stringtemplate-3.2.1/0000755000175000017500000000000011274602746014526 5ustar twernertwernerstringtemplate-3.2.1/LICENSE.txt0000644000175000017500000000262011256235341016342 0ustar twernertwerner[The "BSD licence"] Copyright (c) 2003-2008 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. stringtemplate-3.2.1/target/0000755000175000017500000000000011274602762016012 5ustar twernertwernerstringtemplate-3.2.1/target/classes/0000755000175000017500000000000011274602753017447 5ustar twernertwernerstringtemplate-3.2.1/target/classes/org/0000755000175000017500000000000011274602753020236 5ustar twernertwernerstringtemplate-3.2.1/target/classes/org/antlr/0000755000175000017500000000000011274602753021356 5ustar twernertwernerstringtemplate-3.2.1/target/classes/org/antlr/stringtemplate/0000755000175000017500000000000011274602756024423 5ustar twernertwernerstringtemplate-3.2.1/target/classes/org/antlr/stringtemplate/misc/0000755000175000017500000000000011274602756025356 5ustar twernertwernerstringtemplate-3.2.1/target/classes/org/antlr/stringtemplate/language/0000755000175000017500000000000011274602756026206 5ustar twernertwernerstringtemplate-3.2.1/target/classes/org/antlr/stringtemplate/language/ActionParserTokenTypes.txt0000644000175000017500000000123511274602753033365 0ustar twernertwerner// $ANTLR 2.7.7 (20060906): action.g -> ActionParserTokenTypes.txt$ ActionParser // output token vocab name APPLY=4 MULTI_APPLY=5 ARGS=6 INCLUDE=7 CONDITIONAL="if"=8 VALUE=9 TEMPLATE=10 FUNCTION=11 SINGLEVALUEARG=12 LIST=13 NOTHING=14 SEMI=15 LPAREN=16 RPAREN=17 LITERAL_elseif="elseif"=18 COMMA=19 ID=20 ASSIGN=21 COLON=22 NOT=23 PLUS=24 DOT=25 LITERAL_first="first"=26 LITERAL_rest="rest"=27 LITERAL_last="last"=28 LITERAL_length="length"=29 LITERAL_strip="strip"=30 LITERAL_trunc="trunc"=31 LITERAL_super="super"=32 ANONYMOUS_TEMPLATE=33 STRING=34 INT=35 LBRACK=36 RBRACK=37 DOTDOTDOT=38 TEMPLATE_ARGS=39 NESTED_ANONYMOUS_TEMPLATE=40 ESC_CHAR=41 WS=42 WS_CHAR=43 stringtemplate-3.2.1/target/classes/org/antlr/stringtemplate/language/GroupParserTokenTypes.txt0000644000175000017500000000063211274602753033244 0ustar twernertwerner// $ANTLR 2.7.7 (20060906): group.g -> GroupParserTokenTypes.txt$ GroupParser // output token vocab name LITERAL_group="group"=4 ID=5 COLON=6 LITERAL_implements="implements"=7 COMMA=8 SEMI=9 AT=10 DOT=11 LPAREN=12 RPAREN=13 DEFINED_TO_BE=14 STRING=15 BIGSTRING=16 ASSIGN=17 ANONYMOUS_TEMPLATE=18 LBRACK=19 RBRACK=20 LITERAL_default="default"=21 STAR=22 PLUS=23 OPTIONAL=24 SL_COMMENT=25 ML_COMMENT=26 WS=27 stringtemplate-3.2.1/target/classes/org/antlr/stringtemplate/language/ActionEvaluatorTokenTypes.txt0000644000175000017500000000124111274602753034070 0ustar twernertwerner// $ANTLR 2.7.7 (20060906): eval.g -> ActionEvaluatorTokenTypes.txt$ ActionEvaluator // output token vocab name APPLY=4 MULTI_APPLY=5 ARGS=6 INCLUDE=7 CONDITIONAL="if"=8 VALUE=9 TEMPLATE=10 FUNCTION=11 SINGLEVALUEARG=12 LIST=13 NOTHING=14 SEMI=15 LPAREN=16 RPAREN=17 LITERAL_elseif="elseif"=18 COMMA=19 ID=20 ASSIGN=21 COLON=22 NOT=23 PLUS=24 DOT=25 LITERAL_first="first"=26 LITERAL_rest="rest"=27 LITERAL_last="last"=28 LITERAL_length="length"=29 LITERAL_strip="strip"=30 LITERAL_trunc="trunc"=31 LITERAL_super="super"=32 ANONYMOUS_TEMPLATE=33 STRING=34 INT=35 LBRACK=36 RBRACK=37 DOTDOTDOT=38 TEMPLATE_ARGS=39 NESTED_ANONYMOUS_TEMPLATE=40 ESC_CHAR=41 WS=42 WS_CHAR=43 ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootstringtemplate-3.2.1/target/classes/org/antlr/stringtemplate/language/AngleBracketTemplateLexerTokenTypes.txtstringtemplate-3.2.1/target/classes/org/antlr/stringtemplate/language/AngleBracketTemplateLexerToken0000644000175000017500000000055411274602753034151 0ustar twernertwerner// $ANTLR 2.7.7 (20060906): angle.bracket.template.g -> AngleBracketTemplateLexerTokenTypes.txt$ AngleBracketTemplateLexer // output token vocab name LITERAL=4 NEWLINE=5 ACTION=6 IF=7 ELSEIF=8 ELSE=9 ENDIF=10 REGION_REF=11 REGION_DEF=12 EXPR=13 TEMPLATE=14 IF_EXPR=15 ESC_CHAR=16 ESC=17 HEX=18 SUBTEMPLATE=19 NESTED_PARENS=20 INDENT=21 COMMENT=22 LINE_BREAK=23 stringtemplate-3.2.1/target/classes/org/antlr/stringtemplate/language/TemplateParserTokenTypes.txt0000644000175000017500000000051011274602753033716 0ustar twernertwerner// $ANTLR 2.7.7 (20060906): template.g -> TemplateParserTokenTypes.txt$ TemplateParser // output token vocab name LITERAL=4 NEWLINE=5 ACTION=6 IF=7 ELSEIF=8 ELSE=9 ENDIF=10 REGION_REF=11 REGION_DEF=12 EXPR=13 TEMPLATE=14 IF_EXPR=15 ESC_CHAR=16 ESC=17 HEX=18 SUBTEMPLATE=19 NESTED_PARENS=20 INDENT=21 COMMENT=22 LINE_BREAK=23 stringtemplate-3.2.1/target/classes/org/antlr/stringtemplate/language/InterfaceParserTokenTypes.txt0000644000175000017500000000041011274602753034042 0ustar twernertwerner// $ANTLR 2.7.7 (20060906): interface.g -> InterfaceParserTokenTypes.txt$ InterfaceParser // output token vocab name LITERAL_interface="interface"=4 ID=5 SEMI=6 LITERAL_optional="optional"=7 LPAREN=8 RPAREN=9 COMMA=10 COLON=11 SL_COMMENT=12 ML_COMMENT=13 WS=14 stringtemplate-3.2.1/target/generated-sources/0000755000175000017500000000000011274602746021433 5ustar twernertwernerstringtemplate-3.2.1/target/generated-sources/antlr/0000755000175000017500000000000011274602746022553 5ustar twernertwernerstringtemplate-3.2.1/target/generated-sources/antlr/org/0000755000175000017500000000000011274602746023342 5ustar twernertwernerstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/0000755000175000017500000000000011274602746024462 5ustar twernertwernerstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/0000755000175000017500000000000011274602746027524 5ustar twernertwernerstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/0000755000175000017500000000000011274602752031304 5ustar twernertwerner././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/ActionLexer.javastringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/ActionLexer.ja0000644000175000017500000007017611274602752034050 0ustar twernertwerner// $ANTLR 2.7.7 (20060906): "action.g" -> "ActionLexer.java"$ /* [The "BSD licence"] Copyright (c) 2003-2004 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.language; import org.antlr.stringtemplate.*; import java.util.*; import java.io.InputStream; import antlr.TokenStreamException; import antlr.TokenStreamIOException; import antlr.TokenStreamRecognitionException; import antlr.CharStreamException; import antlr.CharStreamIOException; import antlr.ANTLRException; import java.io.Reader; import java.util.Hashtable; import antlr.CharScanner; import antlr.InputBuffer; import antlr.ByteBuffer; import antlr.CharBuffer; import antlr.Token; import antlr.CommonToken; import antlr.RecognitionException; import antlr.NoViableAltForCharException; import antlr.MismatchedCharException; import antlr.TokenStream; import antlr.ANTLRHashString; import antlr.LexerSharedInputState; import antlr.collections.impl.BitSet; import antlr.SemanticException; public class ActionLexer extends antlr.CharScanner implements ActionParserTokenTypes, TokenStream { public ActionLexer(InputStream in) { this(new ByteBuffer(in)); } public ActionLexer(Reader in) { this(new CharBuffer(in)); } public ActionLexer(InputBuffer ib) { this(new LexerSharedInputState(ib)); } public ActionLexer(LexerSharedInputState state) { super(state); caseSensitiveLiterals = true; setCaseSensitive(true); literals = new Hashtable(); literals.put(new ANTLRHashString("super", this), new Integer(32)); literals.put(new ANTLRHashString("if", this), new Integer(8)); literals.put(new ANTLRHashString("first", this), new Integer(26)); literals.put(new ANTLRHashString("last", this), new Integer(28)); literals.put(new ANTLRHashString("rest", this), new Integer(27)); literals.put(new ANTLRHashString("trunc", this), new Integer(31)); literals.put(new ANTLRHashString("strip", this), new Integer(30)); literals.put(new ANTLRHashString("length", this), new Integer(29)); literals.put(new ANTLRHashString("elseif", this), new Integer(18)); } public Token nextToken() throws TokenStreamException { Token theRetToken=null; tryAgain: for (;;) { Token _token = null; int _ttype = Token.INVALID_TYPE; resetText(); try { // for char stream error handling try { // for lexical error handling switch ( LA(1)) { case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': { mID(true); theRetToken=_returnToken; break; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { mINT(true); theRetToken=_returnToken; break; } case '"': { mSTRING(true); theRetToken=_returnToken; break; } case '{': { mANONYMOUS_TEMPLATE(true); theRetToken=_returnToken; break; } case '[': { mLBRACK(true); theRetToken=_returnToken; break; } case ']': { mRBRACK(true); theRetToken=_returnToken; break; } case '(': { mLPAREN(true); theRetToken=_returnToken; break; } case ')': { mRPAREN(true); theRetToken=_returnToken; break; } case ',': { mCOMMA(true); theRetToken=_returnToken; break; } case '=': { mASSIGN(true); theRetToken=_returnToken; break; } case ':': { mCOLON(true); theRetToken=_returnToken; break; } case '+': { mPLUS(true); theRetToken=_returnToken; break; } case ';': { mSEMI(true); theRetToken=_returnToken; break; } case '!': { mNOT(true); theRetToken=_returnToken; break; } case '\t': case '\n': case '\r': case ' ': { mWS(true); theRetToken=_returnToken; break; } default: if ((LA(1)=='.') && (LA(2)=='.')) { mDOTDOTDOT(true); theRetToken=_returnToken; } else if ((LA(1)=='.') && (true)) { mDOT(true); theRetToken=_returnToken; } else { if (LA(1)==EOF_CHAR) {uponEOF(); _returnToken = makeToken(Token.EOF_TYPE);} else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } } if ( _returnToken==null ) continue tryAgain; // found SKIP token _ttype = _returnToken.getType(); _returnToken.setType(_ttype); return _returnToken; } catch (RecognitionException e) { throw new TokenStreamRecognitionException(e); } } catch (CharStreamException cse) { if ( cse instanceof CharStreamIOException ) { throw new TokenStreamIOException(((CharStreamIOException)cse).io); } else { throw new TokenStreamException(cse.getMessage()); } } } } public final void mID(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = ID; int _saveIndex; { switch ( LA(1)) { case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': { matchRange('a','z'); break; } case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': { matchRange('A','Z'); break; } case '_': { match('_'); break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } { _loop60: do { switch ( LA(1)) { case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': { matchRange('a','z'); break; } case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': { matchRange('A','Z'); break; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { matchRange('0','9'); break; } case '_': { match('_'); break; } case '/': { match('/'); break; } default: { break _loop60; } } } while (true); } _ttype = testLiteralsTable(_ttype); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mINT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = INT; int _saveIndex; { int _cnt63=0; _loop63: do { if (((LA(1) >= '0' && LA(1) <= '9'))) { matchRange('0','9'); } else { if ( _cnt63>=1 ) { break _loop63; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } _cnt63++; } while (true); } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mSTRING(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = STRING; int _saveIndex; _saveIndex=text.length(); match('"'); text.setLength(_saveIndex); { _loop66: do { if ((LA(1)=='\\')) { mESC_CHAR(false,true); } else if ((_tokenSet_0.member(LA(1)))) { matchNot('"'); } else { break _loop66; } } while (true); } _saveIndex=text.length(); match('"'); text.setLength(_saveIndex); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } /** Match escape sequences, optionally translating them for strings, but not * for templates. Do \} only when in {...} templates. */ protected final void mESC_CHAR(boolean _createToken, boolean doEscape ) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = ESC_CHAR; int _saveIndex; char c = '\0'; match('\\'); { if ((LA(1)=='n') && ((LA(2) >= '\u0003' && LA(2) <= '\ufffe'))) { match('n'); if ( inputState.guessing==0 ) { if (doEscape) { text.setLength(_begin); text.append("\n"); } } } else if ((LA(1)=='r') && ((LA(2) >= '\u0003' && LA(2) <= '\ufffe'))) { match('r'); if ( inputState.guessing==0 ) { if (doEscape) { text.setLength(_begin); text.append("\r"); } } } else if ((LA(1)=='t') && ((LA(2) >= '\u0003' && LA(2) <= '\ufffe'))) { match('t'); if ( inputState.guessing==0 ) { if (doEscape) { text.setLength(_begin); text.append("\t"); } } } else if ((LA(1)=='b') && ((LA(2) >= '\u0003' && LA(2) <= '\ufffe'))) { match('b'); if ( inputState.guessing==0 ) { if (doEscape) { text.setLength(_begin); text.append("\b"); } } } else if ((LA(1)=='f') && ((LA(2) >= '\u0003' && LA(2) <= '\ufffe'))) { match('f'); if ( inputState.guessing==0 ) { if (doEscape) { text.setLength(_begin); text.append("\f"); } } } else if (((LA(1) >= '\u0003' && LA(1) <= '\ufffe')) && ((LA(2) >= '\u0003' && LA(2) <= '\ufffe'))) { c = LA(1); matchNot(EOF_CHAR); if ( inputState.guessing==0 ) { if (doEscape) {text.setLength(_begin); text.append(String.valueOf(c));} } } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mANONYMOUS_TEMPLATE(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = ANONYMOUS_TEMPLATE; int _saveIndex; List args=null; StringTemplateToken t = null; _saveIndex=text.length(); match('{'); text.setLength(_saveIndex); { boolean synPredMatched70 = false; if (((_tokenSet_1.member(LA(1))) && (_tokenSet_2.member(LA(2))))) { int _m70 = mark(); synPredMatched70 = true; inputState.guessing++; try { { mTEMPLATE_ARGS(false); } } catch (RecognitionException pe) { synPredMatched70 = false; } rewind(_m70); inputState.guessing--; } if ( synPredMatched70 ) { args=mTEMPLATE_ARGS(false); { if ((_tokenSet_3.member(LA(1))) && ((LA(2) >= '\u0003' && LA(2) <= '\ufffe'))) { _saveIndex=text.length(); mWS_CHAR(false); text.setLength(_saveIndex); } else if (((LA(1) >= '\u0003' && LA(1) <= '\ufffe')) && (true)) { } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } if ( inputState.guessing==0 ) { // create a special token to track args t = new StringTemplateToken(ANONYMOUS_TEMPLATE,new String(text.getBuffer(),_begin,text.length()-_begin),args); _token = t; } } else if (((LA(1) >= '\u0003' && LA(1) <= '\ufffe')) && (true)) { } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } { _loop73: do { if ((LA(1)=='\\') && (LA(2)=='{')) { _saveIndex=text.length(); match('\\'); text.setLength(_saveIndex); match('{'); } else if ((LA(1)=='\\') && (LA(2)=='}')) { _saveIndex=text.length(); match('\\'); text.setLength(_saveIndex); match('}'); } else if ((LA(1)=='\\') && ((LA(2) >= '\u0003' && LA(2) <= '\ufffe'))) { mESC_CHAR(false,false); } else if ((LA(1)=='{')) { mNESTED_ANONYMOUS_TEMPLATE(false); } else if ((_tokenSet_4.member(LA(1)))) { matchNot('}'); } else { break _loop73; } } while (true); } if ( inputState.guessing==0 ) { if ( t!=null ) { t.setText(new String(text.getBuffer(),_begin,text.length()-_begin)); } } _saveIndex=text.length(); match('}'); text.setLength(_saveIndex); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final List mTEMPLATE_ARGS(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { List args=new ArrayList(); int _ttype; Token _token=null; int _begin=text.length(); _ttype = TEMPLATE_ARGS; int _saveIndex; Token a=null; Token a2=null; { switch ( LA(1)) { case '\t': case '\n': case '\r': case ' ': { _saveIndex=text.length(); mWS_CHAR(false); text.setLength(_saveIndex); break; } case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } _saveIndex=text.length(); mID(true); text.setLength(_saveIndex); a=_returnToken; if ( inputState.guessing==0 ) { args.add(a.getText()); } { _loop79: do { if ((_tokenSet_5.member(LA(1))) && (_tokenSet_6.member(LA(2)))) { { switch ( LA(1)) { case '\t': case '\n': case '\r': case ' ': { _saveIndex=text.length(); mWS_CHAR(false); text.setLength(_saveIndex); break; } case ',': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } _saveIndex=text.length(); match(','); text.setLength(_saveIndex); { switch ( LA(1)) { case '\t': case '\n': case '\r': case ' ': { _saveIndex=text.length(); mWS_CHAR(false); text.setLength(_saveIndex); break; } case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } _saveIndex=text.length(); mID(true); text.setLength(_saveIndex); a2=_returnToken; if ( inputState.guessing==0 ) { args.add(a2.getText()); } } else { break _loop79; } } while (true); } { switch ( LA(1)) { case '\t': case '\n': case '\r': case ' ': { _saveIndex=text.length(); mWS_CHAR(false); text.setLength(_saveIndex); break; } case '|': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } _saveIndex=text.length(); match('|'); text.setLength(_saveIndex); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; return args; } protected final void mWS_CHAR(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = WS_CHAR; int _saveIndex; switch ( LA(1)) { case ' ': { match(' '); break; } case '\t': { match('\t'); break; } case '\r': { match('\r'); break; } case '\n': { match('\n'); if ( inputState.guessing==0 ) { newline(); } break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mNESTED_ANONYMOUS_TEMPLATE(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = NESTED_ANONYMOUS_TEMPLATE; int _saveIndex; match('{'); { _loop83: do { if ((LA(1)=='\\') && (LA(2)=='{')) { _saveIndex=text.length(); match('\\'); text.setLength(_saveIndex); match('{'); } else if ((LA(1)=='\\') && (LA(2)=='}')) { _saveIndex=text.length(); match('\\'); text.setLength(_saveIndex); match('}'); } else if ((LA(1)=='\\') && ((LA(2) >= '\u0003' && LA(2) <= '\ufffe'))) { mESC_CHAR(false,false); } else if ((LA(1)=='{')) { mNESTED_ANONYMOUS_TEMPLATE(false); } else if ((_tokenSet_4.member(LA(1)))) { matchNot('}'); } else { break _loop83; } } while (true); } match('}'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mLBRACK(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = LBRACK; int _saveIndex; match('['); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mRBRACK(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = RBRACK; int _saveIndex; match(']'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mLPAREN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = LPAREN; int _saveIndex; match('('); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mRPAREN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = RPAREN; int _saveIndex; match(')'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mCOMMA(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = COMMA; int _saveIndex; match(','); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mDOT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = DOT; int _saveIndex; match('.'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mASSIGN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = ASSIGN; int _saveIndex; match('='); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mCOLON(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = COLON; int _saveIndex; match(':'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mPLUS(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = PLUS; int _saveIndex; match('+'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mSEMI(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = SEMI; int _saveIndex; match(';'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mNOT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = NOT; int _saveIndex; match('!'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mDOTDOTDOT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = DOTDOTDOT; int _saveIndex; match("..."); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mWS(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = WS; int _saveIndex; { int _cnt100=0; _loop100: do { switch ( LA(1)) { case ' ': { match(' '); break; } case '\t': { match('\t'); break; } case '\r': { match('\r'); break; } case '\n': { match('\n'); if ( inputState.guessing==0 ) { newline(); } break; } default: { if ( _cnt100>=1 ) { break _loop100; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } } _cnt100++; } while (true); } if ( inputState.guessing==0 ) { _ttype = Token.SKIP; } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } private static final long[] mk_tokenSet_0() { long[] data = new long[2048]; data[0]=-17179869192L; data[1]=-268435457L; for (int i = 2; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_0 = new BitSet(mk_tokenSet_0()); private static final long[] mk_tokenSet_1() { long[] data = new long[1025]; data[0]=4294977024L; data[1]=576460745995190270L; return data; } public static final BitSet _tokenSet_1 = new BitSet(mk_tokenSet_1()); private static final long[] mk_tokenSet_2() { long[] data = new long[1025]; data[0]=288107235144377856L; data[1]=1729382250602037246L; return data; } public static final BitSet _tokenSet_2 = new BitSet(mk_tokenSet_2()); private static final long[] mk_tokenSet_3() { long[] data = new long[1025]; data[0]=4294977024L; return data; } public static final BitSet _tokenSet_3 = new BitSet(mk_tokenSet_3()); private static final long[] mk_tokenSet_4() { long[] data = new long[2048]; data[0]=-8L; data[1]=-2882303761785552897L; for (int i = 2; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_4 = new BitSet(mk_tokenSet_4()); private static final long[] mk_tokenSet_5() { long[] data = new long[1025]; data[0]=17596481021440L; return data; } public static final BitSet _tokenSet_5 = new BitSet(mk_tokenSet_5()); private static final long[] mk_tokenSet_6() { long[] data = new long[1025]; data[0]=17596481021440L; data[1]=576460745995190270L; return data; } public static final BitSet _tokenSet_6 = new BitSet(mk_tokenSet_6()); } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/ActionParserTokenTypes.txtstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/ActionParserTo0000644000175000017500000000123511274602752034125 0ustar twernertwerner// $ANTLR 2.7.7 (20060906): action.g -> ActionParserTokenTypes.txt$ ActionParser // output token vocab name APPLY=4 MULTI_APPLY=5 ARGS=6 INCLUDE=7 CONDITIONAL="if"=8 VALUE=9 TEMPLATE=10 FUNCTION=11 SINGLEVALUEARG=12 LIST=13 NOTHING=14 SEMI=15 LPAREN=16 RPAREN=17 LITERAL_elseif="elseif"=18 COMMA=19 ID=20 ASSIGN=21 COLON=22 NOT=23 PLUS=24 DOT=25 LITERAL_first="first"=26 LITERAL_rest="rest"=27 LITERAL_last="last"=28 LITERAL_length="length"=29 LITERAL_strip="strip"=30 LITERAL_trunc="trunc"=31 LITERAL_super="super"=32 ANONYMOUS_TEMPLATE=33 STRING=34 INT=35 LBRACK=36 RBRACK=37 DOTDOTDOT=38 TEMPLATE_ARGS=39 NESTED_ANONYMOUS_TEMPLATE=40 ESC_CHAR=41 WS=42 WS_CHAR=43 ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/TemplateParser.smapstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/TemplateParser0000644000175000017500000000324211274602750034156 0ustar twernertwernerSMAP TemplateParser.java G *S G *F + 0 template.g template.g *L 1:3 1:4 1:5 1:6 1:8 1:9 1:10 1:11 1:12 1:13 1:14 1:15 1:16 1:17 1:19 1:20 1:21 1:22 1:23 1:24 1:25 1:26 1:27 1:28 1:29 1:30 1:31 1:32 40:54 42:56 43:57 44:58 45:59 46:60 47:61 48:62 49:63 50:64 53:89 53:90 53:91 53:99 53:137 53:138 53:139 53:140 53:141 53:142 54:96 57:93 57:100 57:101 57:102 57:103 57:104 57:105 57:106 57:107 57:108 57:130 57:131 57:132 57:133 57:134 57:135 57:136 58:94 58:111 58:112 58:113 58:114 60:116 61:117 62:118 64:122 64:123 64:124 64:125 64:126 64:127 68:144 68:145 68:146 68:154 68:155 68:316 68:317 68:318 68:319 68:320 68:321 68:322 68:323 68:324 68:325 68:326 69:148 69:156 69:157 69:158 69:159 71:161 72:162 73:163 74:164 77:149 77:168 77:169 77:170 77:171 79:173 80:174 81:175 82:176 83:177 84:178 85:179 88:181 88:182 90:150 90:183 90:184 90:185 90:186 90:187 90:188 90:199 90:200 90:201 90:202 90:204 90:205 92:190 93:191 94:192 95:193 96:194 97:195 100:197 102:198 105:207 105:208 105:209 105:210 105:226 105:227 105:228 105:229 105:230 107:212 108:213 109:214 110:215 111:216 114:218 115:219 118:232 120:151 120:235 120:236 120:237 120:238 122:240 123:241 124:242 125:243 126:244 127:245 128:246 129:247 130:248 131:249 132:250 133:251 134:252 135:253 136:254 137:255 138:256 139:257 140:258 141:259 142:260 143:261 144:262 145:263 146:264 147:265 148:266 149:267 150:268 151:269 152:270 153:271 154:272 155:273 156:274 157:275 159:277 160:278 161:279 162:280 163:281 164:282 165:283 168:152 168:287 168:288 168:289 168:290 170:292 171:293 172:294 173:295 174:296 175:297 176:298 177:299 178:300 179:301 180:302 181:303 182:304 183:305 184:306 185:307 186:308 187:309 188:310 189:311 190:312 *E ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/ActionParser.javastringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/ActionParser.j0000644000175000017500000013373411274602752034064 0ustar twernertwerner// $ANTLR 2.7.7 (20060906): "action.g" -> "ActionParser.java"$ /* [The "BSD licence"] Copyright (c) 2003-2004 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.language; import org.antlr.stringtemplate.*; import java.util.*; import antlr.TokenBuffer; import antlr.TokenStreamException; import antlr.TokenStreamIOException; import antlr.ANTLRException; import antlr.LLkParser; import antlr.Token; import antlr.TokenStream; import antlr.RecognitionException; import antlr.NoViableAltException; import antlr.MismatchedTokenException; import antlr.SemanticException; import antlr.ParserSharedInputState; import antlr.collections.impl.BitSet; import antlr.collections.AST; import java.util.Hashtable; import antlr.ASTFactory; import antlr.ASTPair; import antlr.collections.impl.ASTArray; /** Parse the individual attribute expressions */ public class ActionParser extends antlr.LLkParser implements ActionParserTokenTypes { protected StringTemplate self = null; public ActionParser(TokenStream lexer, StringTemplate self) { this(lexer, 2); this.self = self; } public void reportError(RecognitionException e) { StringTemplateGroup group = self.getGroup(); if ( group==StringTemplate.defaultGroup ) { self.error("action parse error; template context is "+self.getEnclosingInstanceStackString(), e); } else { self.error("action parse error in group "+self.getGroup().getName()+" line "+self.getGroupFileLine()+"; template context is "+self.getEnclosingInstanceStackString(), e); } } protected ActionParser(TokenBuffer tokenBuf, int k) { super(tokenBuf,k); tokenNames = _tokenNames; buildTokenTypeASTClassMap(); astFactory = new ASTFactory(getTokenTypeToASTClassMap()); } public ActionParser(TokenBuffer tokenBuf) { this(tokenBuf,2); } protected ActionParser(TokenStream lexer, int k) { super(lexer,k); tokenNames = _tokenNames; buildTokenTypeASTClassMap(); astFactory = new ASTFactory(getTokenTypeToASTClassMap()); } public ActionParser(TokenStream lexer) { this(lexer,2); } public ActionParser(ParserSharedInputState state) { super(state,2); tokenNames = _tokenNames; buildTokenTypeASTClassMap(); astFactory = new ASTFactory(getTokenTypeToASTClassMap()); } public final Map action() throws RecognitionException, TokenStreamException { Map opts=null; returnAST = null; ASTPair currentAST = new ASTPair(); org.antlr.stringtemplate.language.StringTemplateAST action_AST = null; try { // for error handling switch ( LA(1)) { case LPAREN: case ID: case LITERAL_first: case LITERAL_rest: case LITERAL_last: case LITERAL_length: case LITERAL_strip: case LITERAL_trunc: case LITERAL_super: case ANONYMOUS_TEMPLATE: case STRING: case INT: case LBRACK: { templatesExpr(); astFactory.addASTChild(currentAST, returnAST); { switch ( LA(1)) { case SEMI: { match(SEMI); opts=optionList(); astFactory.addASTChild(currentAST, returnAST); break; } case EOF: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } action_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; break; } case CONDITIONAL: { org.antlr.stringtemplate.language.StringTemplateAST tmp2_AST = null; tmp2_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp2_AST); match(CONDITIONAL); match(LPAREN); ifCondition(); astFactory.addASTChild(currentAST, returnAST); match(RPAREN); action_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; break; } case LITERAL_elseif: { match(LITERAL_elseif); match(LPAREN); ifCondition(); astFactory.addASTChild(currentAST, returnAST); match(RPAREN); action_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } catch (RecognitionException ex) { if (inputState.guessing==0) { reportError(ex); recover(ex,_tokenSet_0); } else { throw ex; } } returnAST = action_AST; return opts; } public final void templatesExpr() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); org.antlr.stringtemplate.language.StringTemplateAST templatesExpr_AST = null; Token c = null; org.antlr.stringtemplate.language.StringTemplateAST c_AST = null; try { // for error handling boolean synPredMatched10 = false; if (((_tokenSet_1.member(LA(1))) && (_tokenSet_2.member(LA(2))))) { int _m10 = mark(); synPredMatched10 = true; inputState.guessing++; try { { parallelArrayTemplateApplication(); } } catch (RecognitionException pe) { synPredMatched10 = false; } rewind(_m10); inputState.guessing--; } if ( synPredMatched10 ) { parallelArrayTemplateApplication(); astFactory.addASTChild(currentAST, returnAST); templatesExpr_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; } else if ((_tokenSet_1.member(LA(1))) && (_tokenSet_3.member(LA(2)))) { expr(); astFactory.addASTChild(currentAST, returnAST); { _loop14: do { if ((LA(1)==COLON)) { c = LT(1); c_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(c); astFactory.makeASTRoot(currentAST, c_AST); match(COLON); if ( inputState.guessing==0 ) { c_AST.setType(APPLY); } template(); astFactory.addASTChild(currentAST, returnAST); { _loop13: do { if ((LA(1)==COMMA)) { match(COMMA); template(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop13; } } while (true); } } else { break _loop14; } } while (true); } templatesExpr_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; } else { throw new NoViableAltException(LT(1), getFilename()); } } catch (RecognitionException ex) { if (inputState.guessing==0) { reportError(ex); recover(ex,_tokenSet_4); } else { throw ex; } } returnAST = templatesExpr_AST; } public final Map optionList() throws RecognitionException, TokenStreamException { Map opts=new HashMap(); returnAST = null; ASTPair currentAST = new ASTPair(); org.antlr.stringtemplate.language.StringTemplateAST optionList_AST = null; try { // for error handling option(opts); { _loop5: do { if ((LA(1)==COMMA)) { org.antlr.stringtemplate.language.StringTemplateAST tmp9_AST = null; tmp9_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(LT(1)); match(COMMA); option(opts); } else { break _loop5; } } while (true); } } catch (RecognitionException ex) { if (inputState.guessing==0) { reportError(ex); recover(ex,_tokenSet_0); } else { throw ex; } } returnAST = optionList_AST; return opts; } public final void ifCondition() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); org.antlr.stringtemplate.language.StringTemplateAST ifCondition_AST = null; try { // for error handling switch ( LA(1)) { case LPAREN: case ID: case LITERAL_first: case LITERAL_rest: case LITERAL_last: case LITERAL_length: case LITERAL_strip: case LITERAL_trunc: case LITERAL_super: case ANONYMOUS_TEMPLATE: case STRING: case INT: case LBRACK: { ifAtom(); astFactory.addASTChild(currentAST, returnAST); ifCondition_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; break; } case NOT: { org.antlr.stringtemplate.language.StringTemplateAST tmp10_AST = null; tmp10_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp10_AST); match(NOT); ifAtom(); astFactory.addASTChild(currentAST, returnAST); ifCondition_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } catch (RecognitionException ex) { if (inputState.guessing==0) { reportError(ex); recover(ex,_tokenSet_5); } else { throw ex; } } returnAST = ifCondition_AST; } public final void option( Map opts ) throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); org.antlr.stringtemplate.language.StringTemplateAST option_AST = null; Token i = null; org.antlr.stringtemplate.language.StringTemplateAST i_AST = null; org.antlr.stringtemplate.language.StringTemplateAST e_AST = null; Object v=null; try { // for error handling i = LT(1); i_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(i); astFactory.addASTChild(currentAST, i_AST); match(ID); { switch ( LA(1)) { case ASSIGN: { org.antlr.stringtemplate.language.StringTemplateAST tmp11_AST = null; tmp11_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp11_AST); match(ASSIGN); nonAlternatingTemplateExpr(); e_AST = (org.antlr.stringtemplate.language.StringTemplateAST)returnAST; astFactory.addASTChild(currentAST, returnAST); if ( inputState.guessing==0 ) { v=e_AST; } break; } case EOF: case COMMA: { if ( inputState.guessing==0 ) { v=ASTExpr.EMPTY_OPTION; } break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { opts.put(i_AST.getText(),v); } option_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; } catch (RecognitionException ex) { if (inputState.guessing==0) { reportError(ex); recover(ex,_tokenSet_6); } else { throw ex; } } returnAST = option_AST; } public final void nonAlternatingTemplateExpr() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); org.antlr.stringtemplate.language.StringTemplateAST nonAlternatingTemplateExpr_AST = null; Token c = null; org.antlr.stringtemplate.language.StringTemplateAST c_AST = null; try { // for error handling expr(); astFactory.addASTChild(currentAST, returnAST); { _loop35: do { if ((LA(1)==COLON)) { c = LT(1); c_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(c); astFactory.makeASTRoot(currentAST, c_AST); match(COLON); if ( inputState.guessing==0 ) { c_AST.setType(APPLY); } template(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop35; } } while (true); } nonAlternatingTemplateExpr_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; } catch (RecognitionException ex) { if (inputState.guessing==0) { reportError(ex); recover(ex,_tokenSet_7); } else { throw ex; } } returnAST = nonAlternatingTemplateExpr_AST; } public final void parallelArrayTemplateApplication() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); org.antlr.stringtemplate.language.StringTemplateAST parallelArrayTemplateApplication_AST = null; Token c = null; org.antlr.stringtemplate.language.StringTemplateAST c_AST = null; try { // for error handling expr(); astFactory.addASTChild(currentAST, returnAST); { int _cnt17=0; _loop17: do { if ((LA(1)==COMMA)) { match(COMMA); expr(); astFactory.addASTChild(currentAST, returnAST); } else { if ( _cnt17>=1 ) { break _loop17; } else {throw new NoViableAltException(LT(1), getFilename());} } _cnt17++; } while (true); } c = LT(1); c_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(c); astFactory.addASTChild(currentAST, c_AST); match(COLON); anonymousTemplate(); astFactory.addASTChild(currentAST, returnAST); if ( inputState.guessing==0 ) { parallelArrayTemplateApplication_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; parallelArrayTemplateApplication_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.make( (new ASTArray(2)).add((org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(MULTI_APPLY,"MULTI_APPLY")).add(parallelArrayTemplateApplication_AST)); currentAST.root = parallelArrayTemplateApplication_AST; currentAST.child = parallelArrayTemplateApplication_AST!=null &¶llelArrayTemplateApplication_AST.getFirstChild()!=null ? parallelArrayTemplateApplication_AST.getFirstChild() : parallelArrayTemplateApplication_AST; currentAST.advanceChildToEnd(); } parallelArrayTemplateApplication_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; } catch (RecognitionException ex) { if (inputState.guessing==0) { reportError(ex); recover(ex,_tokenSet_4); } else { throw ex; } } returnAST = parallelArrayTemplateApplication_AST; } public final void expr() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); org.antlr.stringtemplate.language.StringTemplateAST expr_AST = null; try { // for error handling primaryExpr(); astFactory.addASTChild(currentAST, returnAST); { _loop22: do { if ((LA(1)==PLUS)) { org.antlr.stringtemplate.language.StringTemplateAST tmp13_AST = null; tmp13_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp13_AST); match(PLUS); primaryExpr(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop22; } } while (true); } expr_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; } catch (RecognitionException ex) { if (inputState.guessing==0) { reportError(ex); recover(ex,_tokenSet_8); } else { throw ex; } } returnAST = expr_AST; } public final void template() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); org.antlr.stringtemplate.language.StringTemplateAST template_AST = null; try { // for error handling { switch ( LA(1)) { case LPAREN: case ID: case LITERAL_super: { namedTemplate(); astFactory.addASTChild(currentAST, returnAST); break; } case ANONYMOUS_TEMPLATE: { anonymousTemplate(); astFactory.addASTChild(currentAST, returnAST); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { template_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; template_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.make( (new ASTArray(2)).add((org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(TEMPLATE)).add(template_AST)); currentAST.root = template_AST; currentAST.child = template_AST!=null &&template_AST.getFirstChild()!=null ? template_AST.getFirstChild() : template_AST; currentAST.advanceChildToEnd(); } template_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; } catch (RecognitionException ex) { if (inputState.guessing==0) { reportError(ex); recover(ex,_tokenSet_8); } else { throw ex; } } returnAST = template_AST; } public final void anonymousTemplate() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); org.antlr.stringtemplate.language.StringTemplateAST anonymousTemplate_AST = null; Token t = null; org.antlr.stringtemplate.language.StringTemplateAST t_AST = null; try { // for error handling t = LT(1); t_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(t); astFactory.addASTChild(currentAST, t_AST); match(ANONYMOUS_TEMPLATE); if ( inputState.guessing==0 ) { StringTemplate anonymous = new StringTemplate(); anonymous.setGroup(self.getGroup()); anonymous.setEnclosingInstance(self); anonymous.setTemplate(t.getText()); anonymous.defineFormalArguments(((StringTemplateToken)t).args); t_AST.setStringTemplate(anonymous); } anonymousTemplate_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; } catch (RecognitionException ex) { if (inputState.guessing==0) { reportError(ex); recover(ex,_tokenSet_8); } else { throw ex; } } returnAST = anonymousTemplate_AST; } public final void ifAtom() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); org.antlr.stringtemplate.language.StringTemplateAST ifAtom_AST = null; try { // for error handling templatesExpr(); astFactory.addASTChild(currentAST, returnAST); ifAtom_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; } catch (RecognitionException ex) { if (inputState.guessing==0) { reportError(ex); recover(ex,_tokenSet_5); } else { throw ex; } } returnAST = ifAtom_AST; } public final void primaryExpr() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); org.antlr.stringtemplate.language.StringTemplateAST primaryExpr_AST = null; try { // for error handling switch ( LA(1)) { case LITERAL_first: case LITERAL_rest: case LITERAL_last: case LITERAL_length: case LITERAL_strip: case LITERAL_trunc: { function(); astFactory.addASTChild(currentAST, returnAST); { _loop31: do { if ((LA(1)==DOT)) { org.antlr.stringtemplate.language.StringTemplateAST tmp14_AST = null; tmp14_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp14_AST); match(DOT); { switch ( LA(1)) { case ID: { org.antlr.stringtemplate.language.StringTemplateAST tmp15_AST = null; tmp15_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp15_AST); match(ID); break; } case LPAREN: { valueExpr(); astFactory.addASTChild(currentAST, returnAST); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } } else { break _loop31; } } while (true); } primaryExpr_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; break; } case LBRACK: { list(); astFactory.addASTChild(currentAST, returnAST); primaryExpr_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; break; } default: boolean synPredMatched25 = false; if (((LA(1)==LPAREN||LA(1)==ID||LA(1)==LITERAL_super) && (_tokenSet_9.member(LA(2))))) { int _m25 = mark(); synPredMatched25 = true; inputState.guessing++; try { { templateInclude(); } } catch (RecognitionException pe) { synPredMatched25 = false; } rewind(_m25); inputState.guessing--; } if ( synPredMatched25 ) { templateInclude(); astFactory.addASTChild(currentAST, returnAST); primaryExpr_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; } else if ((_tokenSet_10.member(LA(1))) && (_tokenSet_11.member(LA(2)))) { atom(); astFactory.addASTChild(currentAST, returnAST); { _loop28: do { if ((LA(1)==DOT)) { org.antlr.stringtemplate.language.StringTemplateAST tmp16_AST = null; tmp16_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp16_AST); match(DOT); { switch ( LA(1)) { case ID: { org.antlr.stringtemplate.language.StringTemplateAST tmp17_AST = null; tmp17_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp17_AST); match(ID); break; } case LPAREN: { valueExpr(); astFactory.addASTChild(currentAST, returnAST); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } } else { break _loop28; } } while (true); } primaryExpr_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; } else if ((LA(1)==LPAREN) && (_tokenSet_1.member(LA(2)))) { valueExpr(); astFactory.addASTChild(currentAST, returnAST); primaryExpr_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; } else { throw new NoViableAltException(LT(1), getFilename()); } } } catch (RecognitionException ex) { if (inputState.guessing==0) { reportError(ex); recover(ex,_tokenSet_12); } else { throw ex; } } returnAST = primaryExpr_AST; } public final void templateInclude() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); org.antlr.stringtemplate.language.StringTemplateAST templateInclude_AST = null; Token id = null; org.antlr.stringtemplate.language.StringTemplateAST id_AST = null; Token qid = null; org.antlr.stringtemplate.language.StringTemplateAST qid_AST = null; try { // for error handling { switch ( LA(1)) { case ID: { id = LT(1); id_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(id); astFactory.addASTChild(currentAST, id_AST); match(ID); argList(); astFactory.addASTChild(currentAST, returnAST); break; } case LITERAL_super: { match(LITERAL_super); match(DOT); qid = LT(1); qid_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(qid); astFactory.addASTChild(currentAST, qid_AST); match(ID); if ( inputState.guessing==0 ) { qid_AST.setText("super."+qid_AST.getText()); } argList(); astFactory.addASTChild(currentAST, returnAST); break; } case LPAREN: { indirectTemplate(); astFactory.addASTChild(currentAST, returnAST); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( inputState.guessing==0 ) { templateInclude_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; templateInclude_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.make( (new ASTArray(2)).add((org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(INCLUDE,"include")).add(templateInclude_AST)); currentAST.root = templateInclude_AST; currentAST.child = templateInclude_AST!=null &&templateInclude_AST.getFirstChild()!=null ? templateInclude_AST.getFirstChild() : templateInclude_AST; currentAST.advanceChildToEnd(); } templateInclude_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; } catch (RecognitionException ex) { if (inputState.guessing==0) { reportError(ex); recover(ex,_tokenSet_12); } else { throw ex; } } returnAST = templateInclude_AST; } public final void atom() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); org.antlr.stringtemplate.language.StringTemplateAST atom_AST = null; try { // for error handling switch ( LA(1)) { case ID: { org.antlr.stringtemplate.language.StringTemplateAST tmp20_AST = null; tmp20_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp20_AST); match(ID); atom_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; break; } case STRING: { org.antlr.stringtemplate.language.StringTemplateAST tmp21_AST = null; tmp21_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp21_AST); match(STRING); atom_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; break; } case INT: { org.antlr.stringtemplate.language.StringTemplateAST tmp22_AST = null; tmp22_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp22_AST); match(INT); atom_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; break; } case ANONYMOUS_TEMPLATE: { org.antlr.stringtemplate.language.StringTemplateAST tmp23_AST = null; tmp23_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp23_AST); match(ANONYMOUS_TEMPLATE); atom_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } catch (RecognitionException ex) { if (inputState.guessing==0) { reportError(ex); recover(ex,_tokenSet_11); } else { throw ex; } } returnAST = atom_AST; } public final void valueExpr() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); org.antlr.stringtemplate.language.StringTemplateAST valueExpr_AST = null; Token eval = null; org.antlr.stringtemplate.language.StringTemplateAST eval_AST = null; try { // for error handling eval = LT(1); eval_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(eval); astFactory.makeASTRoot(currentAST, eval_AST); match(LPAREN); templatesExpr(); astFactory.addASTChild(currentAST, returnAST); match(RPAREN); if ( inputState.guessing==0 ) { eval_AST.setType(VALUE); eval_AST.setText("value"); } valueExpr_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; } catch (RecognitionException ex) { if (inputState.guessing==0) { reportError(ex); recover(ex,_tokenSet_11); } else { throw ex; } } returnAST = valueExpr_AST; } public final void function() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); org.antlr.stringtemplate.language.StringTemplateAST function_AST = null; try { // for error handling { switch ( LA(1)) { case LITERAL_first: { org.antlr.stringtemplate.language.StringTemplateAST tmp25_AST = null; tmp25_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp25_AST); match(LITERAL_first); break; } case LITERAL_rest: { org.antlr.stringtemplate.language.StringTemplateAST tmp26_AST = null; tmp26_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp26_AST); match(LITERAL_rest); break; } case LITERAL_last: { org.antlr.stringtemplate.language.StringTemplateAST tmp27_AST = null; tmp27_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp27_AST); match(LITERAL_last); break; } case LITERAL_length: { org.antlr.stringtemplate.language.StringTemplateAST tmp28_AST = null; tmp28_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp28_AST); match(LITERAL_length); break; } case LITERAL_strip: { org.antlr.stringtemplate.language.StringTemplateAST tmp29_AST = null; tmp29_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp29_AST); match(LITERAL_strip); break; } case LITERAL_trunc: { org.antlr.stringtemplate.language.StringTemplateAST tmp30_AST = null; tmp30_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp30_AST); match(LITERAL_trunc); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } singleArg(); astFactory.addASTChild(currentAST, returnAST); if ( inputState.guessing==0 ) { function_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; function_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.make( (new ASTArray(2)).add((org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(FUNCTION)).add(function_AST)); currentAST.root = function_AST; currentAST.child = function_AST!=null &&function_AST.getFirstChild()!=null ? function_AST.getFirstChild() : function_AST; currentAST.advanceChildToEnd(); } function_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; } catch (RecognitionException ex) { if (inputState.guessing==0) { reportError(ex); recover(ex,_tokenSet_11); } else { throw ex; } } returnAST = function_AST; } public final void list() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); org.antlr.stringtemplate.language.StringTemplateAST list_AST = null; Token lb = null; org.antlr.stringtemplate.language.StringTemplateAST lb_AST = null; try { // for error handling lb = LT(1); lb_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(lb); astFactory.makeASTRoot(currentAST, lb_AST); match(LBRACK); if ( inputState.guessing==0 ) { lb_AST.setType(LIST); lb_AST.setText("value"); } listElement(); astFactory.addASTChild(currentAST, returnAST); { _loop45: do { if ((LA(1)==COMMA)) { match(COMMA); listElement(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop45; } } while (true); } match(RBRACK); list_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; } catch (RecognitionException ex) { if (inputState.guessing==0) { reportError(ex); recover(ex,_tokenSet_12); } else { throw ex; } } returnAST = list_AST; } public final void singleArg() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); org.antlr.stringtemplate.language.StringTemplateAST singleArg_AST = null; try { // for error handling match(LPAREN); nonAlternatingTemplateExpr(); astFactory.addASTChild(currentAST, returnAST); match(RPAREN); if ( inputState.guessing==0 ) { singleArg_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; singleArg_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.make( (new ASTArray(2)).add((org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(SINGLEVALUEARG,"SINGLEVALUEARG")).add(singleArg_AST)); currentAST.root = singleArg_AST; currentAST.child = singleArg_AST!=null &&singleArg_AST.getFirstChild()!=null ? singleArg_AST.getFirstChild() : singleArg_AST; currentAST.advanceChildToEnd(); } singleArg_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; } catch (RecognitionException ex) { if (inputState.guessing==0) { reportError(ex); recover(ex,_tokenSet_11); } else { throw ex; } } returnAST = singleArg_AST; } public final void namedTemplate() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); org.antlr.stringtemplate.language.StringTemplateAST namedTemplate_AST = null; Token qid = null; org.antlr.stringtemplate.language.StringTemplateAST qid_AST = null; try { // for error handling switch ( LA(1)) { case ID: { org.antlr.stringtemplate.language.StringTemplateAST tmp35_AST = null; tmp35_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp35_AST); match(ID); argList(); astFactory.addASTChild(currentAST, returnAST); namedTemplate_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; break; } case LITERAL_super: { match(LITERAL_super); match(DOT); qid = LT(1); qid_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(qid); astFactory.addASTChild(currentAST, qid_AST); match(ID); if ( inputState.guessing==0 ) { qid_AST.setText("super."+qid_AST.getText()); } argList(); astFactory.addASTChild(currentAST, returnAST); namedTemplate_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; break; } case LPAREN: { indirectTemplate(); astFactory.addASTChild(currentAST, returnAST); namedTemplate_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } catch (RecognitionException ex) { if (inputState.guessing==0) { reportError(ex); recover(ex,_tokenSet_8); } else { throw ex; } } returnAST = namedTemplate_AST; } public final void argList() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); org.antlr.stringtemplate.language.StringTemplateAST argList_AST = null; try { // for error handling if ((LA(1)==LPAREN) && (LA(2)==RPAREN)) { match(LPAREN); match(RPAREN); if ( inputState.guessing==0 ) { argList_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; argList_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(ARGS,"ARGS"); currentAST.root = argList_AST; currentAST.child = argList_AST!=null &&argList_AST.getFirstChild()!=null ? argList_AST.getFirstChild() : argList_AST; currentAST.advanceChildToEnd(); } } else { boolean synPredMatched52 = false; if (((LA(1)==LPAREN) && (_tokenSet_1.member(LA(2))))) { int _m52 = mark(); synPredMatched52 = true; inputState.guessing++; try { { singleArg(); } } catch (RecognitionException pe) { synPredMatched52 = false; } rewind(_m52); inputState.guessing--; } if ( synPredMatched52 ) { singleArg(); astFactory.addASTChild(currentAST, returnAST); argList_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; } else if ((LA(1)==LPAREN) && (LA(2)==ID||LA(2)==DOTDOTDOT)) { match(LPAREN); argumentAssignment(); astFactory.addASTChild(currentAST, returnAST); { _loop54: do { if ((LA(1)==COMMA)) { match(COMMA); argumentAssignment(); astFactory.addASTChild(currentAST, returnAST); } else { break _loop54; } } while (true); } match(RPAREN); if ( inputState.guessing==0 ) { argList_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; argList_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.make( (new ASTArray(2)).add((org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(ARGS,"ARGS")).add(argList_AST)); currentAST.root = argList_AST; currentAST.child = argList_AST!=null &&argList_AST.getFirstChild()!=null ? argList_AST.getFirstChild() : argList_AST; currentAST.advanceChildToEnd(); } argList_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; } else { throw new NoViableAltException(LT(1), getFilename()); } } } catch (RecognitionException ex) { if (inputState.guessing==0) { reportError(ex); recover(ex,_tokenSet_12); } else { throw ex; } } returnAST = argList_AST; } /** Match (foo)() and (foo+".terse")() */ public final void indirectTemplate() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); org.antlr.stringtemplate.language.StringTemplateAST indirectTemplate_AST = null; org.antlr.stringtemplate.language.StringTemplateAST e_AST = null; org.antlr.stringtemplate.language.StringTemplateAST args_AST = null; try { // for error handling org.antlr.stringtemplate.language.StringTemplateAST tmp43_AST = null; tmp43_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(LT(1)); match(LPAREN); templatesExpr(); e_AST = (org.antlr.stringtemplate.language.StringTemplateAST)returnAST; org.antlr.stringtemplate.language.StringTemplateAST tmp44_AST = null; tmp44_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(LT(1)); match(RPAREN); argList(); args_AST = (org.antlr.stringtemplate.language.StringTemplateAST)returnAST; if ( inputState.guessing==0 ) { indirectTemplate_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; indirectTemplate_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.make( (new ASTArray(3)).add((org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(VALUE,"value")).add(e_AST).add(args_AST)); currentAST.root = indirectTemplate_AST; currentAST.child = indirectTemplate_AST!=null &&indirectTemplate_AST.getFirstChild()!=null ? indirectTemplate_AST.getFirstChild() : indirectTemplate_AST; currentAST.advanceChildToEnd(); } } catch (RecognitionException ex) { if (inputState.guessing==0) { reportError(ex); recover(ex,_tokenSet_12); } else { throw ex; } } returnAST = indirectTemplate_AST; } public final void listElement() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); org.antlr.stringtemplate.language.StringTemplateAST listElement_AST = null; try { // for error handling switch ( LA(1)) { case LPAREN: case ID: case LITERAL_first: case LITERAL_rest: case LITERAL_last: case LITERAL_length: case LITERAL_strip: case LITERAL_trunc: case LITERAL_super: case ANONYMOUS_TEMPLATE: case STRING: case INT: case LBRACK: { nonAlternatingTemplateExpr(); astFactory.addASTChild(currentAST, returnAST); listElement_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; break; } case COMMA: case RBRACK: { if ( inputState.guessing==0 ) { listElement_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; listElement_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(NOTHING,"NOTHING"); currentAST.root = listElement_AST; currentAST.child = listElement_AST!=null &&listElement_AST.getFirstChild()!=null ? listElement_AST.getFirstChild() : listElement_AST; currentAST.advanceChildToEnd(); } listElement_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } catch (RecognitionException ex) { if (inputState.guessing==0) { reportError(ex); recover(ex,_tokenSet_13); } else { throw ex; } } returnAST = listElement_AST; } public final void argumentAssignment() throws RecognitionException, TokenStreamException { returnAST = null; ASTPair currentAST = new ASTPair(); org.antlr.stringtemplate.language.StringTemplateAST argumentAssignment_AST = null; try { // for error handling switch ( LA(1)) { case ID: { org.antlr.stringtemplate.language.StringTemplateAST tmp45_AST = null; tmp45_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp45_AST); match(ID); org.antlr.stringtemplate.language.StringTemplateAST tmp46_AST = null; tmp46_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(LT(1)); astFactory.makeASTRoot(currentAST, tmp46_AST); match(ASSIGN); nonAlternatingTemplateExpr(); astFactory.addASTChild(currentAST, returnAST); argumentAssignment_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; break; } case DOTDOTDOT: { org.antlr.stringtemplate.language.StringTemplateAST tmp47_AST = null; tmp47_AST = (org.antlr.stringtemplate.language.StringTemplateAST)astFactory.create(LT(1)); astFactory.addASTChild(currentAST, tmp47_AST); match(DOTDOTDOT); argumentAssignment_AST = (org.antlr.stringtemplate.language.StringTemplateAST)currentAST.root; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } catch (RecognitionException ex) { if (inputState.guessing==0) { reportError(ex); recover(ex,_tokenSet_14); } else { throw ex; } } returnAST = argumentAssignment_AST; } public static final String[] _tokenNames = { "<0>", "EOF", "<2>", "NULL_TREE_LOOKAHEAD", "APPLY", "MULTI_APPLY", "ARGS", "INCLUDE", "\"if\"", "VALUE", "TEMPLATE", "FUNCTION", "SINGLEVALUEARG", "LIST", "NOTHING", "SEMI", "LPAREN", "RPAREN", "\"elseif\"", "COMMA", "ID", "ASSIGN", "COLON", "NOT", "PLUS", "DOT", "\"first\"", "\"rest\"", "\"last\"", "\"length\"", "\"strip\"", "\"trunc\"", "\"super\"", "ANONYMOUS_TEMPLATE", "STRING", "INT", "LBRACK", "RBRACK", "DOTDOTDOT", "TEMPLATE_ARGS", "NESTED_ANONYMOUS_TEMPLATE", "ESC_CHAR", "WS", "WS_CHAR" }; protected void buildTokenTypeASTClassMap() { tokenTypeToASTClassMap=null; }; private static final long[] mk_tokenSet_0() { long[] data = { 2L, 0L}; return data; } public static final BitSet _tokenSet_0 = new BitSet(mk_tokenSet_0()); private static final long[] mk_tokenSet_1() { long[] data = { 137372958720L, 0L}; return data; } public static final BitSet _tokenSet_1 = new BitSet(mk_tokenSet_1()); private static final long[] mk_tokenSet_2() { long[] data = { 274862768128L, 0L}; return data; } public static final BitSet _tokenSet_2 = new BitSet(mk_tokenSet_2()); private static final long[] mk_tokenSet_3() { long[] data = { 274867126274L, 0L}; return data; } public static final BitSet _tokenSet_3 = new BitSet(mk_tokenSet_3()); private static final long[] mk_tokenSet_4() { long[] data = { 163842L, 0L}; return data; } public static final BitSet _tokenSet_4 = new BitSet(mk_tokenSet_4()); private static final long[] mk_tokenSet_5() { long[] data = { 131072L, 0L}; return data; } public static final BitSet _tokenSet_5 = new BitSet(mk_tokenSet_5()); private static final long[] mk_tokenSet_6() { long[] data = { 524290L, 0L}; return data; } public static final BitSet _tokenSet_6 = new BitSet(mk_tokenSet_6()); private static final long[] mk_tokenSet_7() { long[] data = { 137439608834L, 0L}; return data; } public static final BitSet _tokenSet_7 = new BitSet(mk_tokenSet_7()); private static final long[] mk_tokenSet_8() { long[] data = { 137443835906L, 0L}; return data; } public static final BitSet _tokenSet_8 = new BitSet(mk_tokenSet_8()); private static final long[] mk_tokenSet_9() { long[] data = { 137406513152L, 0L}; return data; } public static final BitSet _tokenSet_9 = new BitSet(mk_tokenSet_9()); private static final long[] mk_tokenSet_10() { long[] data = { 60130590720L, 0L}; return data; } public static final BitSet _tokenSet_10 = new BitSet(mk_tokenSet_10()); private static final long[] mk_tokenSet_11() { long[] data = { 137494167554L, 0L}; return data; } public static final BitSet _tokenSet_11 = new BitSet(mk_tokenSet_11()); private static final long[] mk_tokenSet_12() { long[] data = { 137460613122L, 0L}; return data; } public static final BitSet _tokenSet_12 = new BitSet(mk_tokenSet_12()); private static final long[] mk_tokenSet_13() { long[] data = { 137439477760L, 0L}; return data; } public static final BitSet _tokenSet_13 = new BitSet(mk_tokenSet_13()); private static final long[] mk_tokenSet_14() { long[] data = { 655360L, 0L}; return data; } public static final BitSet _tokenSet_14 = new BitSet(mk_tokenSet_14()); } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/GroupParserTokenTypes.txtstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/GroupParserTok0000644000175000017500000000063211274602752034157 0ustar twernertwerner// $ANTLR 2.7.7 (20060906): group.g -> GroupParserTokenTypes.txt$ GroupParser // output token vocab name LITERAL_group="group"=4 ID=5 COLON=6 LITERAL_implements="implements"=7 COMMA=8 SEMI=9 AT=10 DOT=11 LPAREN=12 RPAREN=13 DEFINED_TO_BE=14 STRING=15 BIGSTRING=16 ASSIGN=17 ANONYMOUS_TEMPLATE=18 LBRACK=19 RBRACK=20 LITERAL_default="default"=21 STAR=22 PLUS=23 OPTIONAL=24 SL_COMMENT=25 ML_COMMENT=26 WS=27 ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/ActionEvaluatorTokenTypes.txtstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/ActionEvaluato0000644000175000017500000000124111274602752034143 0ustar twernertwerner// $ANTLR 2.7.7 (20060906): eval.g -> ActionEvaluatorTokenTypes.txt$ ActionEvaluator // output token vocab name APPLY=4 MULTI_APPLY=5 ARGS=6 INCLUDE=7 CONDITIONAL="if"=8 VALUE=9 TEMPLATE=10 FUNCTION=11 SINGLEVALUEARG=12 LIST=13 NOTHING=14 SEMI=15 LPAREN=16 RPAREN=17 LITERAL_elseif="elseif"=18 COMMA=19 ID=20 ASSIGN=21 COLON=22 NOT=23 PLUS=24 DOT=25 LITERAL_first="first"=26 LITERAL_rest="rest"=27 LITERAL_last="last"=28 LITERAL_length="length"=29 LITERAL_strip="strip"=30 LITERAL_trunc="trunc"=31 LITERAL_super="super"=32 ANONYMOUS_TEMPLATE=33 STRING=34 INT=35 LBRACK=36 RBRACK=37 DOTDOTDOT=38 TEMPLATE_ARGS=39 NESTED_ANONYMOUS_TEMPLATE=40 ESC_CHAR=41 WS=42 WS_CHAR=43 ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/ActionParser.smapstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/ActionParser.s0000644000175000017500000002247711274602752034076 0ustar twernertwernerSMAP ActionParser.java G *S G *F + 0 action.g action.g *L 1:3 1:4 1:5 1:6 1:8 1:9 1:10 1:11 1:12 1:13 1:14 1:15 1:16 1:17 1:19 1:20 1:21 1:22 1:23 1:24 1:25 1:26 1:27 1:28 1:29 1:30 1:31 1:32 57:57 59:59 60:60 61:61 62:62 64:64 65:65 66:66 67:67 68:68 69:69 70:70 71:71 72:72 75:103 75:104 75:106 75:107 75:108 75:110 75:111 75:173 75:174 75:175 75:176 75:177 75:178 75:179 75:180 75:181 75:182 75:183 75:184 75:185 75:186 75:187 75:188 75:189 76:112 76:113 76:114 76:115 76:116 76:117 76:118 76:119 76:120 76:121 76:122 76:123 76:124 76:125 76:126 76:127 76:129 76:130 76:131 76:132 76:133 76:134 76:141 76:142 76:143 76:144 76:145 77:147 77:150 77:151 77:152 77:153 77:154 77:155 77:156 77:157 77:158 77:159 78:163 78:164 78:165 78:166 78:167 78:168 78:169 79:160 80:170 81:276 81:277 81:279 81:280 81:281 81:283 81:300 81:301 81:302 81:303 81:304 81:305 81:306 81:307 81:308 81:309 81:310 81:311 82:284 82:285 82:286 82:287 82:288 82:289 82:290 82:291 82:292 82:293 82:294 82:295 82:296 82:298 82:299 85:368 85:369 85:370 85:372 85:373 85:374 85:382 85:421 85:422 85:423 85:424 85:425 85:426 85:427 85:428 85:429 85:430 85:431 86:379 89:375 89:376 89:383 89:384 89:385 89:386 90:377 90:388 90:389 90:390 90:391 90:392 90:393 90:394 90:395 90:396 90:397 90:398 90:399 90:411 90:412 90:413 90:414 90:415 91:403 91:404 91:405 91:406 91:407 93:417 93:418 96:191 96:193 96:194 96:195 96:199 96:220 96:259 96:260 96:261 96:262 96:264 96:265 96:266 96:267 96:268 96:269 96:270 96:271 96:272 96:273 96:274 96:420 97:200 97:201 97:202 97:203 97:204 97:205 97:207 97:209 97:210 97:211 97:212 97:213 97:214 97:215 97:216 97:217 97:218 97:219 98:221 98:222 98:223 99:196 99:197 99:224 99:225 99:226 99:227 99:228 99:229 99:230 99:231 99:232 99:233 99:235 99:236 99:237 99:238 99:239 99:240 99:241 99:242 99:243 99:244 99:245 99:246 99:247 99:249 99:250 99:251 99:252 99:253 99:254 99:256 99:257 99:258 103:477 103:479 103:480 103:481 103:485 103:520 103:521 103:522 103:523 103:524 103:525 103:526 103:527 103:528 103:529 103:530 104:482 104:483 104:486 104:487 104:489 104:490 104:491 104:492 104:493 104:494 104:495 104:496 104:497 104:498 104:499 104:501 104:502 104:503 104:504 104:505 104:506 104:507 104:508 104:509 105:510 105:511 105:512 105:514 105:516 105:517 106:513 106:519 109:313 109:315 109:316 109:317 109:319 109:320 109:351 109:352 109:353 109:354 109:355 109:356 109:357 109:358 109:359 109:360 109:361 109:362 109:363 109:364 109:365 109:366 110:321 110:322 110:323 110:324 110:325 110:326 110:327 110:328 110:329 110:330 110:331 110:332 110:333 110:334 110:335 110:336 110:337 111:340 111:341 111:342 111:343 111:344 111:345 111:346 111:347 111:348 114:657 114:659 114:660 114:661 114:663 114:667 114:668 114:669 114:670 114:671 114:672 114:673 114:674 114:675 114:676 114:677 115:664 115:665 115:666 118:532 118:534 118:535 118:536 118:538 118:539 118:540 118:541 118:542 118:543 118:544 118:545 118:546 118:547 118:548 118:549 118:550 118:551 118:552 118:553 118:554 118:556 118:557 118:558 118:559 118:560 118:561 118:562 118:563 118:564 118:565 118:566 118:567 118:568 118:569 121:679 121:681 121:682 121:683 121:685 121:686 121:743 121:764 121:806 121:811 121:812 121:813 121:814 121:815 121:816 121:817 121:818 121:819 121:820 121:821 121:822 121:823 121:824 121:825 121:826 122:744 122:745 122:746 122:747 122:748 122:749 122:751 122:753 122:754 122:755 122:756 122:757 122:758 122:759 122:760 122:761 122:762 122:763 123:765 123:766 123:767 124:768 124:769 124:770 124:771 124:772 124:773 124:774 124:775 124:798 124:799 124:800 124:801 124:803 124:804 124:805 125:777 125:778 125:779 125:780 125:781 125:782 125:783 125:792 125:793 125:794 125:795 125:796 126:786 126:787 126:788 126:789 129:687 129:688 129:689 129:690 129:691 129:692 129:693 129:694 129:695 130:696 130:697 130:698 130:699 130:700 130:701 130:702 130:703 130:726 130:727 130:728 130:729 130:731 130:732 130:733 131:705 131:706 131:707 131:708 131:709 131:710 131:711 131:720 131:721 131:722 131:723 131:724 132:714 132:715 132:716 132:717 135:807 135:808 135:809 135:810 136:736 136:737 136:738 136:739 136:740 139:960 139:962 139:963 139:964 139:968 139:980 139:981 139:982 139:983 139:984 139:985 139:986 139:987 139:988 139:989 139:990 140:965 140:966 140:969 140:970 140:971 140:972 140:973 140:974 140:975 141:976 141:977 144:433 144:435 144:436 144:437 144:441 144:465 144:466 144:467 144:468 144:469 144:470 144:471 144:472 144:473 144:474 144:475 144:979 145:438 145:439 145:442 145:443 145:444 145:445 145:446 145:447 145:448 145:449 145:450 145:451 145:452 145:453 145:455 145:456 145:457 145:458 145:459 145:460 145:462 145:463 145:464 148:992 148:994 148:995 148:996 148:998 148:1066 148:1067 148:1068 148:1069 148:1070 148:1071 148:1072 148:1073 148:1074 148:1075 148:1076 149:1000 149:1001 149:1002 149:1003 149:1004 149:1005 149:1006 149:1049 149:1050 149:1051 149:1052 149:1053 150:1009 150:1010 150:1011 150:1012 150:1013 150:1014 151:1017 151:1018 151:1019 151:1020 151:1021 151:1022 152:1025 152:1026 152:1027 152:1028 152:1029 152:1030 153:1033 153:1034 153:1035 153:1036 153:1037 153:1038 154:1041 154:1042 154:1043 154:1044 154:1045 154:1046 156:1055 156:1056 157:1057 157:1058 157:1059 157:1060 157:1062 157:1063 158:1065 160:571 160:573 160:574 160:575 160:577 160:609 160:610 160:611 160:612 160:613 160:614 160:615 160:616 160:617 160:618 160:619 161:579 161:580 161:581 161:582 161:583 161:584 161:585 161:594 161:595 161:596 161:597 161:598 162:588 162:589 162:590 162:591 164:600 164:601 164:602 164:603 164:605 164:606 165:608 167:1156 167:1158 167:1159 167:1160 167:1164 167:1165 167:1200 167:1201 167:1202 167:1203 167:1204 167:1205 167:1206 167:1207 167:1208 167:1209 167:1210 167:1211 167:1212 167:1213 167:1214 167:1215 168:1166 168:1167 168:1168 168:1169 168:1170 168:1171 168:1172 168:1173 168:1174 169:1161 169:1162 169:1177 169:1178 169:1179 169:1180 169:1181 169:1182 169:1183 169:1184 169:1185 169:1186 169:1188 169:1189 169:1190 170:1193 170:1194 170:1195 170:1196 170:1197 173:621 173:623 173:624 173:625 173:629 173:645 173:646 173:647 173:648 173:649 173:650 173:651 173:652 173:653 173:654 173:655 174:626 174:627 174:630 174:631 174:632 174:633 175:634 176:636 177:637 178:638 179:639 180:640 181:641 185:644 185:899 185:901 185:902 185:903 185:905 185:906 185:907 185:908 185:909 185:910 185:911 185:912 185:943 185:944 185:945 185:946 185:947 185:948 185:949 185:950 185:951 185:952 185:953 185:954 185:955 185:956 185:957 185:958 186:916 186:917 186:918 186:919 186:920 186:921 187:913 187:925 187:926 187:927 187:928 187:929 187:930 188:922 188:934 188:935 188:936 188:937 188:938 188:939 189:931 190:940 191:1078 191:1080 191:1081 191:1082 191:1083 191:1084 191:1086 191:1087 191:1088 191:1089 191:1090 191:1091 191:1092 191:1112 191:1113 191:1114 191:1115 191:1116 191:1117 191:1118 191:1119 191:1120 191:1121 191:1122 192:1094 192:1095 192:1096 192:1097 192:1098 192:1099 192:1100 192:1101 192:1102 192:1103 192:1104 192:1105 192:1106 192:1108 192:1109 193:1110 195:1111 196:1343 196:1345 196:1346 196:1347 196:1349 196:1350 196:1384 196:1385 196:1386 196:1387 196:1388 196:1389 196:1390 196:1391 196:1392 196:1393 196:1394 196:1395 196:1396 196:1397 196:1398 196:1399 197:1351 197:1352 197:1353 197:1354 197:1355 197:1356 197:1357 197:1358 197:1359 197:1360 197:1361 197:1362 197:1363 197:1364 197:1365 197:1366 197:1367 198:1370 198:1371 198:1372 198:1373 198:1374 198:1375 198:1376 198:1378 198:1379 199:1381 201:828 201:830 201:831 201:832 201:838 201:887 201:888 201:889 201:890 201:891 201:892 201:893 201:894 201:895 201:896 201:897 202:833 202:834 202:840 202:841 202:842 202:843 202:844 202:845 202:846 202:847 202:848 202:872 202:873 202:874 202:875 202:876 203:835 203:836 203:851 203:852 203:853 203:854 203:855 203:856 203:857 203:858 203:859 203:860 203:862 203:863 204:866 204:867 204:868 204:869 206:878 206:879 206:880 206:881 206:883 206:884 207:886 210:1303 210:1304 210:1306 210:1307 210:1308 210:1312 210:1331 210:1332 210:1333 210:1334 210:1335 210:1336 210:1337 210:1338 210:1339 210:1340 210:1341 211:1309 211:1310 211:1313 211:1314 211:1315 211:1316 211:1317 211:1318 211:1319 211:1320 211:1321 211:1322 212:1323 212:1324 212:1325 212:1326 212:1328 212:1329 215:1217 215:1219 215:1220 215:1221 215:1223 215:1235 215:1257 215:1286 215:1287 215:1288 215:1289 215:1290 215:1291 215:1292 215:1293 215:1294 215:1295 215:1296 215:1297 215:1298 215:1299 215:1300 215:1301 216:1224 216:1225 216:1226 216:1227 216:1228 216:1229 216:1230 216:1232 216:1233 217:1236 217:1237 217:1238 217:1239 217:1240 217:1241 217:1242 217:1244 217:1246 217:1247 217:1248 217:1249 217:1250 217:1251 217:1252 217:1253 217:1254 217:1255 217:1256 218:1258 218:1259 218:1260 218:1261 218:1262 218:1263 218:1264 218:1265 218:1266 218:1267 218:1268 218:1269 218:1270 218:1271 218:1272 218:1274 218:1275 218:1276 219:1277 219:1278 219:1279 219:1280 219:1282 219:1283 220:1285 222:1124 222:1126 222:1127 222:1128 222:1130 222:1144 222:1145 222:1146 222:1147 222:1148 222:1149 222:1150 222:1151 222:1152 222:1153 222:1154 223:1131 223:1132 223:1133 223:1134 224:1135 224:1136 224:1137 224:1138 224:1140 224:1141 225:1143 227:1401 227:1403 227:1404 227:1405 227:1407 227:1408 227:1433 227:1434 227:1435 227:1436 227:1437 227:1438 227:1439 227:1440 227:1441 227:1442 227:1443 227:1444 227:1445 227:1446 227:1447 227:1448 228:1409 228:1410 228:1411 228:1412 228:1413 228:1414 228:1415 228:1416 228:1417 228:1418 228:1419 228:1420 228:1421 229:1424 229:1425 229:1426 229:1427 229:1428 229:1429 231:1430 *E ././@LongLink0000000000000000000000000000017600000000000011571 Lustar rootrootstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/AngleBracketTemplateLexerTokenTypes.txtstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/AngleBracketTe0000644000175000017500000000055411274602751034045 0ustar twernertwerner// $ANTLR 2.7.7 (20060906): angle.bracket.template.g -> AngleBracketTemplateLexerTokenTypes.txt$ AngleBracketTemplateLexer // output token vocab name LITERAL=4 NEWLINE=5 ACTION=6 IF=7 ELSEIF=8 ELSE=9 ENDIF=10 REGION_REF=11 REGION_DEF=12 EXPR=13 TEMPLATE=14 IF_EXPR=15 ESC_CHAR=16 ESC=17 HEX=18 SUBTEMPLATE=19 NESTED_PARENS=20 INDENT=21 COMMENT=22 LINE_BREAK=23 ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/AngleBracketTemplateLexer.smapstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/AngleBracketTe0000644000175000017500000002013611274602751034043 0ustar twernertwernerSMAP AngleBracketTemplateLexer.java G *S G *F + 0 angle.bracket.template.g angle.bracket.template.g *L 0:122 0:128 0:134 1:3 1:4 1:5 1:6 1:8 1:9 1:10 1:11 1:12 1:13 1:14 1:15 1:16 1:17 1:19 1:20 1:21 1:22 1:23 1:24 1:25 1:26 1:27 1:28 1:29 1:30 1:31 1:32 47:65 48:66 50:68 51:69 52:70 53:71 55:73 56:74 57:75 59:77 60:78 61:79 62:80 64:82 65:83 66:84 67:85 69:87 70:88 71:89 73:91 74:92 75:93 78:163 78:164 78:165 78:166 78:169 78:170 78:228 78:229 78:230 78:231 78:232 78:233 80:172 80:173 80:174 80:184 80:190 80:196 80:202 80:214 80:219 80:220 80:221 80:222 80:224 80:225 80:226 81:176 82:177 85:179 85:180 85:181 85:182 85:183 86:185 86:186 86:187 86:188 86:189 87:191 87:192 87:193 87:194 87:195 88:197 88:198 88:200 89:167 89:203 89:204 89:205 91:207 92:208 93:209 94:210 95:211 96:212 98:215 98:217 100:227 104:235 104:236 104:237 104:238 104:257 104:258 104:259 104:260 104:261 104:262 105:241 105:242 105:243 105:244 105:245 105:246 105:247 105:248 105:249 105:250 105:251 105:252 105:254 105:255 105:256 108:264 108:265 108:266 108:267 108:288 108:289 108:290 108:291 108:292 108:293 109:270 109:271 109:272 109:273 109:280 109:281 109:282 109:283 109:284 109:286 109:287 112:295 112:296 112:297 112:298 112:306 112:331 112:335 112:761 112:762 112:763 112:764 112:766 112:767 112:768 112:769 112:770 112:771 113:300 119:303 119:304 119:305 121:307 121:308 122:309 122:310 122:311 122:313 122:314 122:315 122:316 122:317 122:318 122:319 122:320 122:321 122:322 122:324 122:325 122:326 122:327 122:328 122:329 123:330 124:332 124:333 124:334 125:336 125:394 125:451 125:491 125:531 125:742 125:751 125:752 125:753 125:754 129:338 129:339 129:340 129:341 129:342 129:343 129:344 129:345 129:346 129:347 129:348 129:349 129:350 129:351 129:352 129:353 129:355 129:356 129:357 129:358 129:359 129:360 129:361 129:362 129:363 130:365 130:367 130:368 130:369 130:370 130:371 130:372 130:379 130:380 130:381 130:382 130:383 130:385 130:386 130:387 130:388 130:389 130:391 131:395 131:396 131:397 131:398 131:399 131:400 131:401 131:402 131:403 131:404 131:405 131:406 131:407 131:408 131:409 131:410 131:412 131:413 131:414 131:415 131:416 131:417 131:418 131:419 131:420 132:422 132:424 132:425 132:426 132:427 132:428 132:429 132:436 132:437 132:438 132:439 132:440 132:442 132:443 132:444 132:445 132:446 132:448 133:492 133:493 133:494 133:495 133:496 133:497 133:498 133:499 133:500 134:502 134:504 134:505 134:506 134:507 134:508 134:509 134:516 134:517 134:518 134:519 134:520 134:522 134:523 134:524 134:525 134:526 134:528 135:452 135:453 135:454 135:455 135:456 135:457 135:458 135:459 135:460 136:462 136:464 136:465 136:466 136:467 136:468 136:469 136:476 136:477 136:478 136:479 136:480 136:482 136:483 136:484 136:485 136:486 136:488 140:532 140:533 140:534 140:535 140:536 140:537 140:538 140:540 140:541 140:542 140:543 140:545 140:547 140:548 140:549 140:550 140:552 140:553 140:554 141:556 141:557 141:558 141:559 141:560 141:561 141:562 141:563 141:564 141:565 141:736 141:737 141:738 141:739 141:740 142:568 142:569 142:570 142:571 142:572 144:574 145:575 146:576 148:579 148:581 148:582 148:583 148:584 148:585 148:586 148:593 148:594 148:595 148:596 148:597 148:599 148:600 148:601 148:602 148:603 148:605 148:606 148:607 148:608 149:611 150:613 150:614 150:615 150:648 150:649 150:650 150:651 150:653 150:654 150:655 153:616 153:618 153:620 153:621 153:622 153:623 153:630 153:631 153:632 153:633 153:634 153:636 153:637 153:638 153:642 153:643 153:644 153:645 154:639 154:640 154:641 157:657 157:659 157:660 157:661 157:662 157:663 157:664 157:671 157:672 157:673 157:674 157:675 157:677 157:678 157:679 157:680 157:681 157:683 157:684 157:685 157:686 158:690 158:691 158:692 158:693 158:694 158:698 158:699 158:700 158:701 159:695 159:696 159:697 161:705 161:707 161:708 161:709 161:710 161:711 161:712 161:719 161:720 161:721 161:722 161:723 161:725 161:726 161:727 161:728 161:729 161:731 164:743 164:744 164:745 164:746 164:747 164:748 164:749 164:750 167:758 168:759 173:1042 173:1043 173:1044 173:1045 173:1048 173:1049 173:1050 173:1051 173:1052 173:1053 173:1054 173:1085 173:1106 173:1127 173:1150 173:1153 173:1154 173:1155 173:1156 173:1157 173:1158 173:1159 173:1160 173:1161 173:1162 173:1163 173:1164 173:1165 173:1166 174:1057 174:1058 174:1060 174:1061 174:1062 174:1063 174:1070 174:1071 174:1072 174:1073 174:1074 174:1076 174:1077 175:1080 175:1081 175:1082 176:1086 176:1088 176:1089 176:1090 176:1091 176:1094 176:1095 176:1096 176:1099 176:1100 176:1101 176:1102 176:1103 176:1105 177:1107 177:1109 177:1110 177:1111 177:1112 177:1115 177:1116 177:1117 177:1120 177:1121 177:1122 177:1123 177:1124 177:1126 178:1128 178:1130 178:1131 178:1132 178:1133 178:1136 178:1137 178:1138 178:1141 178:1142 178:1143 178:1144 178:1145 178:1148 179:1151 179:1152 184:1220 184:1221 184:1222 184:1223 184:1225 184:1336 184:1337 184:1338 184:1339 184:1340 184:1341 184:1342 184:1343 184:1344 184:1345 184:1346 185:1226 185:1227 185:1228 185:1229 185:1230 185:1231 185:1232 185:1233 185:1234 185:1235 185:1236 185:1237 185:1238 185:1239 185:1240 185:1242 185:1243 185:1244 186:1247 186:1248 186:1249 187:1251 187:1253 187:1254 187:1255 187:1256 187:1257 187:1258 187:1265 187:1266 187:1267 187:1268 187:1269 187:1271 187:1272 187:1273 187:1274 187:1275 187:1277 187:1278 187:1279 187:1280 188:1283 188:1284 188:1285 188:1286 188:1287 188:1296 188:1302 188:1323 188:1326 188:1327 188:1328 188:1329 188:1331 188:1332 189:1288 189:1289 189:1290 189:1291 189:1292 189:1293 189:1294 189:1295 190:1297 190:1298 190:1299 190:1300 190:1301 191:1303 191:1305 191:1306 191:1307 191:1308 191:1315 191:1316 191:1317 191:1318 191:1319 191:1321 191:1322 192:1324 192:1325 194:1333 198:976 198:977 198:978 198:979 198:982 198:983 198:984 198:985 198:986 198:987 198:988 198:1024 198:1027 198:1028 198:1029 198:1030 198:1031 198:1032 198:1033 198:1034 198:1035 198:1036 198:1037 198:1038 198:1039 198:1040 199:991 199:992 199:994 199:995 199:996 199:997 199:1004 199:1005 199:1006 199:1007 199:1008 199:1010 199:1011 200:1014 200:1015 200:1016 201:1019 201:1020 201:1021 202:1025 202:1026 207:830 207:831 207:832 207:833 207:834 207:845 207:851 207:857 207:863 207:885 207:886 207:887 207:888 207:890 207:891 207:892 207:893 207:894 207:895 207:896 208:840 208:841 208:842 208:843 208:844 209:846 209:847 209:848 209:849 209:850 210:852 210:853 210:854 210:855 210:856 211:858 211:859 211:860 211:861 211:862 212:835 212:836 212:837 212:838 212:864 212:865 212:866 212:867 212:868 212:869 212:870 212:871 212:872 212:873 212:874 212:875 212:876 212:877 212:878 212:879 212:880 212:881 212:882 212:883 213:884 218:1168 218:1169 218:1170 218:1171 218:1173 218:1174 218:1175 218:1176 218:1177 218:1178 218:1179 218:1180 222:1388 222:1389 222:1390 222:1391 222:1393 222:1394 222:1395 222:1396 222:1397 222:1398 222:1401 222:1402 222:1403 222:1404 222:1407 222:1408 222:1409 222:1410 222:1413 222:1414 222:1415 222:1416 222:1417 222:1418 222:1419 222:1420 222:1421 222:1422 222:1423 226:1182 226:1183 226:1184 226:1185 226:1213 226:1214 226:1215 226:1216 226:1217 226:1218 227:1187 227:1188 227:1189 227:1190 227:1191 227:1192 227:1193 227:1194 227:1197 227:1198 227:1199 227:1202 227:1203 227:1204 227:1205 227:1206 227:1207 227:1208 227:1209 227:1210 227:1211 227:1212 231:1348 231:1349 231:1350 231:1351 231:1381 231:1382 231:1383 231:1384 231:1385 231:1386 232:1353 232:1355 232:1356 232:1357 232:1358 232:1359 232:1360 232:1361 232:1364 232:1365 232:1366 232:1369 232:1370 232:1371 232:1372 232:1373 232:1374 232:1375 232:1376 232:1377 232:1378 232:1379 232:1380 236:898 236:899 236:900 236:901 236:969 236:970 236:971 236:972 236:973 236:974 237:903 240:906 241:907 241:908 241:909 241:910 241:911 241:932 241:935 241:936 241:937 241:938 241:940 241:941 242:912 242:914 242:915 242:916 242:917 242:924 242:925 242:926 242:927 242:928 242:930 242:931 243:933 243:934 245:942 245:944 245:946 245:947 245:948 245:949 245:956 245:957 245:958 245:959 245:960 245:962 245:963 245:964 245:966 249:773 249:774 249:775 249:776 249:823 249:824 249:825 249:826 249:827 249:828 250:778 250:780 250:781 250:782 250:783 250:790 250:791 250:792 250:793 250:794 250:797 250:798 250:799 250:800 250:807 250:808 250:809 250:810 250:811 250:813 250:814 250:816 250:817 250:818 250:820 *E ././@LongLink0000000000000000000000000000017700000000000011572 Lustar rootrootstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/AngleBracketTemplateLexerTokenTypes.javastringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/AngleBracketTe0000644000175000017500000000410711274602751034043 0ustar twernertwerner// $ANTLR 2.7.7 (20060906): "angle.bracket.template.g" -> "AngleBracketTemplateLexer.java"$ /* [The "BSD licence"] Copyright (c) 2003-2004 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.language; import org.antlr.stringtemplate.*; import java.io.*; public interface AngleBracketTemplateLexerTokenTypes { int EOF = 1; int NULL_TREE_LOOKAHEAD = 3; int LITERAL = 4; int NEWLINE = 5; int ACTION = 6; int IF = 7; int ELSEIF = 8; int ELSE = 9; int ENDIF = 10; int REGION_REF = 11; int REGION_DEF = 12; int EXPR = 13; int TEMPLATE = 14; int IF_EXPR = 15; int ESC_CHAR = 16; int ESC = 17; int HEX = 18; int SUBTEMPLATE = 19; int NESTED_PARENS = 20; int INDENT = 21; int COMMENT = 22; int LINE_BREAK = 23; } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/DefaultTemplateLexer.smapstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/DefaultTemplat0000644000175000017500000002013211274602750034136 0ustar twernertwernerSMAP DefaultTemplateLexer.java G *S G *F + 0 template.g template.g *L 0:122 0:128 0:134 1:3 1:4 1:5 1:6 1:8 1:9 1:10 1:11 1:12 1:13 1:14 1:15 1:16 1:17 1:19 1:20 1:21 1:22 1:23 1:24 1:25 1:26 1:27 1:28 1:29 1:30 1:31 1:32 206:65 207:66 209:68 210:69 211:70 212:71 214:73 215:74 216:75 218:77 219:78 220:79 221:80 223:82 224:83 225:84 226:85 228:87 229:88 230:89 232:91 233:92 234:93 237:163 237:164 237:165 237:166 237:169 237:170 237:220 237:221 237:222 237:223 237:224 237:225 239:172 239:173 239:174 239:184 239:190 239:194 239:206 239:211 239:212 239:213 239:214 239:216 239:217 239:218 240:176 241:177 244:179 244:180 244:181 244:182 244:183 245:185 245:186 245:187 245:188 245:189 246:191 246:192 246:193 247:167 247:195 247:196 247:197 249:199 250:200 251:201 252:202 253:203 254:204 256:207 256:209 258:219 261:256 261:257 261:258 261:259 261:280 261:281 261:282 261:283 261:284 261:285 262:262 262:263 262:264 262:265 262:272 262:273 262:274 262:275 262:276 262:278 262:279 265:287 265:288 265:289 265:290 265:298 265:323 265:327 265:752 265:753 265:754 265:755 265:757 265:758 265:759 265:760 265:761 265:762 266:292 272:295 272:296 272:297 274:299 274:300 275:301 275:302 275:303 275:305 275:306 275:307 275:308 275:309 275:310 275:311 275:312 275:313 275:314 275:316 275:317 275:318 275:319 275:320 275:321 276:322 277:324 277:325 277:326 278:328 278:386 278:443 278:483 278:523 278:733 278:742 278:743 278:744 278:745 282:330 282:331 282:332 282:333 282:334 282:335 282:336 282:337 282:338 282:339 282:340 282:341 282:342 282:343 282:344 282:345 282:347 282:348 282:349 282:350 282:351 282:352 282:353 282:354 282:355 283:357 283:359 283:360 283:361 283:362 283:363 283:364 283:371 283:372 283:373 283:374 283:375 283:377 283:378 283:379 283:380 283:381 283:383 284:387 284:388 284:389 284:390 284:391 284:392 284:393 284:394 284:395 284:396 284:397 284:398 284:399 284:400 284:401 284:402 284:404 284:405 284:406 284:407 284:408 284:409 284:410 284:411 284:412 285:414 285:416 285:417 285:418 285:419 285:420 285:421 285:428 285:429 285:430 285:431 285:432 285:434 285:435 285:436 285:437 285:438 285:440 286:484 286:485 286:486 286:487 286:488 286:489 286:490 286:491 286:492 287:494 287:496 287:497 287:498 287:499 287:500 287:501 287:508 287:509 287:510 287:511 287:512 287:514 287:515 287:516 287:517 287:518 287:520 288:444 288:445 288:446 288:447 288:448 288:449 288:450 288:451 288:452 289:454 289:456 289:457 289:458 289:459 289:460 289:461 289:468 289:469 289:470 289:471 289:472 289:474 289:475 289:476 289:477 289:478 289:480 293:524 293:525 293:526 293:527 293:528 293:529 293:530 293:532 293:533 293:534 293:535 293:537 293:539 293:540 293:541 293:542 293:544 293:545 293:546 294:548 294:549 294:550 294:551 294:552 294:553 294:554 294:555 294:556 294:557 294:727 294:728 294:729 294:730 294:731 295:560 295:561 295:562 295:563 295:564 296:565 297:566 298:567 300:570 300:572 300:573 300:574 300:575 300:576 300:577 300:584 300:585 300:586 300:587 300:588 300:590 300:591 300:592 300:593 300:594 300:596 300:597 300:598 300:599 301:602 302:604 302:605 302:606 302:639 302:640 302:641 302:642 302:644 302:645 302:646 305:607 305:609 305:611 305:612 305:613 305:614 305:621 305:622 305:623 305:624 305:625 305:627 305:628 305:629 305:633 305:634 305:635 305:636 306:630 306:631 306:632 309:648 309:650 309:651 309:652 309:653 309:654 309:655 309:662 309:663 309:664 309:665 309:666 309:668 309:669 309:670 309:671 309:672 309:674 309:675 309:676 309:677 310:681 310:682 310:683 310:684 310:685 310:689 310:690 310:691 310:692 311:686 311:687 311:688 313:696 313:698 313:699 313:700 313:701 313:702 313:703 313:710 313:711 313:712 313:713 313:714 313:716 313:717 313:718 313:719 313:720 313:722 316:734 316:735 316:736 316:737 316:738 316:739 316:740 316:741 319:749 320:750 325:1033 325:1034 325:1035 325:1036 325:1039 325:1040 325:1041 325:1042 325:1043 325:1044 325:1045 325:1076 325:1097 325:1118 325:1141 325:1144 325:1145 325:1146 325:1147 325:1148 325:1149 325:1150 325:1151 325:1152 325:1153 325:1154 325:1155 325:1156 325:1157 326:1048 326:1049 326:1051 326:1052 326:1053 326:1054 326:1061 326:1062 326:1063 326:1064 326:1065 326:1067 326:1068 327:1071 327:1072 327:1073 328:1077 328:1079 328:1080 328:1081 328:1082 328:1085 328:1086 328:1087 328:1090 328:1091 328:1092 328:1093 328:1094 328:1096 329:1098 329:1100 329:1101 329:1102 329:1103 329:1106 329:1107 329:1108 329:1111 329:1112 329:1113 329:1114 329:1115 329:1117 330:1119 330:1121 330:1122 330:1123 330:1124 330:1127 330:1128 330:1129 330:1132 330:1133 330:1134 330:1135 330:1136 330:1139 331:1142 331:1143 336:1211 336:1212 336:1213 336:1214 336:1216 336:1327 336:1328 336:1329 336:1330 336:1331 336:1332 336:1333 336:1334 336:1335 336:1336 336:1337 337:1217 337:1218 337:1219 337:1220 337:1221 337:1222 337:1223 337:1224 337:1225 337:1226 337:1227 337:1228 337:1229 337:1230 337:1231 337:1233 337:1234 337:1235 338:1238 338:1239 338:1240 339:1242 339:1244 339:1245 339:1246 339:1247 339:1248 339:1249 339:1256 339:1257 339:1258 339:1259 339:1260 339:1262 339:1263 339:1264 339:1265 339:1266 339:1268 339:1269 339:1270 339:1271 340:1274 340:1275 340:1276 340:1277 340:1278 340:1287 340:1293 340:1314 340:1317 340:1318 340:1319 340:1320 340:1322 340:1323 341:1279 341:1280 341:1281 341:1282 341:1283 341:1284 341:1285 341:1286 342:1288 342:1289 342:1290 342:1291 342:1292 343:1294 343:1296 343:1297 343:1298 343:1299 343:1306 343:1307 343:1308 343:1309 343:1310 343:1312 343:1313 344:1315 344:1316 346:1324 350:967 350:968 350:969 350:970 350:973 350:974 350:975 350:976 350:977 350:978 350:979 350:1015 350:1018 350:1019 350:1020 350:1021 350:1022 350:1023 350:1024 350:1025 350:1026 350:1027 350:1028 350:1029 350:1030 350:1031 351:982 351:983 351:985 351:986 351:987 351:988 351:995 351:996 351:997 351:998 351:999 351:1001 351:1002 352:1005 352:1006 352:1007 353:1010 353:1011 353:1012 354:1016 354:1017 359:821 359:822 359:823 359:824 359:825 359:836 359:842 359:848 359:854 359:876 359:877 359:878 359:879 359:881 359:882 359:883 359:884 359:885 359:886 359:887 360:831 360:832 360:833 360:834 360:835 361:837 361:838 361:839 361:840 361:841 362:843 362:844 362:845 362:846 362:847 363:849 363:850 363:851 363:852 363:853 364:826 364:827 364:828 364:829 364:855 364:856 364:857 364:858 364:859 364:860 364:861 364:862 364:863 364:864 364:865 364:866 364:867 364:868 364:869 364:870 364:871 364:872 364:873 364:874 365:875 369:1159 369:1160 369:1161 369:1162 369:1164 369:1165 369:1166 369:1167 369:1168 369:1169 369:1170 369:1171 373:1379 373:1380 373:1381 373:1382 373:1384 373:1385 373:1386 373:1387 373:1388 373:1389 373:1392 373:1393 373:1394 373:1395 373:1398 373:1399 373:1400 373:1401 373:1404 373:1405 373:1406 373:1407 373:1408 373:1409 373:1410 373:1411 373:1412 373:1413 373:1414 377:1173 377:1174 377:1175 377:1176 377:1204 377:1205 377:1206 377:1207 377:1208 377:1209 378:1178 378:1179 378:1180 378:1181 378:1182 378:1183 378:1184 378:1185 378:1188 378:1189 378:1190 378:1193 378:1194 378:1195 378:1196 378:1197 378:1198 378:1199 378:1200 378:1201 378:1202 378:1203 382:1339 382:1340 382:1341 382:1342 382:1372 382:1373 382:1374 382:1375 382:1376 382:1377 383:1344 383:1346 383:1347 383:1348 383:1349 383:1350 383:1351 383:1352 383:1355 383:1356 383:1357 383:1360 383:1361 383:1362 383:1363 383:1364 383:1365 383:1366 383:1367 383:1368 383:1369 383:1370 383:1371 387:227 387:228 387:229 387:230 387:249 387:250 387:251 387:252 387:253 387:254 388:233 388:234 388:235 388:236 388:237 388:238 388:239 388:240 388:241 388:242 388:243 388:244 388:246 388:247 388:248 392:889 392:890 392:891 392:892 392:960 392:961 392:962 392:963 392:964 392:965 393:894 396:897 397:898 397:899 397:900 397:901 397:902 397:923 397:926 397:927 397:928 397:929 397:931 397:932 398:903 398:905 398:906 398:907 398:908 398:915 398:916 398:917 398:918 398:919 398:921 398:922 399:924 399:925 401:933 401:935 401:937 401:938 401:939 401:940 401:947 401:948 401:949 401:950 401:951 401:953 401:954 401:955 401:957 406:764 406:765 406:766 406:767 406:814 406:815 406:816 406:817 406:818 406:819 407:769 407:771 407:772 407:773 407:774 407:781 407:782 407:783 407:784 407:785 407:788 407:789 407:790 407:791 407:798 407:799 407:800 407:801 407:802 407:804 407:805 407:807 407:808 407:809 407:811 *E ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/GroupParser.javastringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/GroupParser.ja0000644000175000017500000003610011274602752034071 0ustar twernertwerner// $ANTLR 2.7.7 (20060906): "group.g" -> "GroupParser.java"$ /* [The "BSD licence"] Copyright (c) 2003-2004 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.language; import org.antlr.stringtemplate.*; import java.util.*; import antlr.TokenBuffer; import antlr.TokenStreamException; import antlr.TokenStreamIOException; import antlr.ANTLRException; import antlr.LLkParser; import antlr.Token; import antlr.TokenStream; import antlr.RecognitionException; import antlr.NoViableAltException; import antlr.MismatchedTokenException; import antlr.SemanticException; import antlr.ParserSharedInputState; import antlr.collections.impl.BitSet; /** Match a group of template definitions beginning * with a group name declaration. Templates are enclosed * in double-quotes or <<...>> quotes for multi-line templates. * Template names have arg lists that indicate the cardinality * of the attribute: present, optional, zero-or-more, one-or-more. * Here is a sample group file: group nfa; // an NFA has edges and states nfa(states,edges) ::= << digraph NFA { rankdir=LR; } >> state(name) ::= "node [shape = circle]; ;" */ public class GroupParser extends antlr.LLkParser implements GroupParserTokenTypes { protected StringTemplateGroup group; public void reportError(RecognitionException e) { if ( group!=null ) { group.error("template group parse error", e); } else { System.err.println("template group parse error: "+e); e.printStackTrace(System.err); } } protected GroupParser(TokenBuffer tokenBuf, int k) { super(tokenBuf,k); tokenNames = _tokenNames; } public GroupParser(TokenBuffer tokenBuf) { this(tokenBuf,3); } protected GroupParser(TokenStream lexer, int k) { super(lexer,k); tokenNames = _tokenNames; } public GroupParser(TokenStream lexer) { this(lexer,3); } public GroupParser(ParserSharedInputState state) { super(state,3); tokenNames = _tokenNames; } public final void group( StringTemplateGroup g ) throws RecognitionException, TokenStreamException { Token name = null; Token s = null; Token i = null; Token i2 = null; this.group = g; try { // for error handling match(LITERAL_group); name = LT(1); match(ID); g.setName(name.getText()); { switch ( LA(1)) { case COLON: { match(COLON); s = LT(1); match(ID); g.setSuperGroup(s.getText()); break; } case LITERAL_implements: case SEMI: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } { switch ( LA(1)) { case LITERAL_implements: { match(LITERAL_implements); i = LT(1); match(ID); g.implementInterface(i.getText()); { _loop5: do { if ((LA(1)==COMMA)) { match(COMMA); i2 = LT(1); match(ID); g.implementInterface(i2.getText()); } else { break _loop5; } } while (true); } break; } case SEMI: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } match(SEMI); { int _cnt7=0; _loop7: do { if ((LA(1)==ID||LA(1)==AT) && (LA(2)==ID||LA(2)==LPAREN||LA(2)==DEFINED_TO_BE) && (LA(3)==ID||LA(3)==DOT||LA(3)==RPAREN)) { template(g); } else if ((LA(1)==ID) && (LA(2)==DEFINED_TO_BE) && (LA(3)==LBRACK)) { mapdef(g); } else { if ( _cnt7>=1 ) { break _loop7; } else {throw new NoViableAltException(LT(1), getFilename());} } _cnt7++; } while (true); } } catch (RecognitionException ex) { reportError(ex); recover(ex,_tokenSet_0); } } public final void template( StringTemplateGroup g ) throws RecognitionException, TokenStreamException { Token scope = null; Token region = null; Token name = null; Token t = null; Token bt = null; Token alias = null; Token target = null; Map formalArgs = null; StringTemplate st = null; boolean ignore = false; String templateName=null; int line = LT(1).getLine(); try { // for error handling if ((LA(1)==ID||LA(1)==AT) && (LA(2)==ID||LA(2)==LPAREN)) { { switch ( LA(1)) { case AT: { match(AT); scope = LT(1); match(ID); match(DOT); region = LT(1); match(ID); templateName=g.getMangledRegionName(scope.getText(),region.getText()); if ( g.isDefinedInThisGroup(templateName) ) { g.error("group "+g.getName()+" line "+line+": redefinition of template region: @"+ scope.getText()+"."+region.getText()); st = new StringTemplate(); // create bogus template to fill in } else { boolean err = false; // @template.region() ::= "..." StringTemplate scopeST = g.lookupTemplate(scope.getText()); if ( scopeST==null ) { g.error("group "+g.getName()+" line "+line+": reference to region within undefined template: "+ scope.getText()); err=true; } if ( !scopeST.containsRegionName(region.getText()) ) { g.error("group "+g.getName()+" line "+line+": template "+scope.getText()+" has no region called "+ region.getText()); err=true; } if ( err ) { st = new StringTemplate(); } else { st = g.defineRegionTemplate(scope.getText(), region.getText(), null, StringTemplate.REGION_EXPLICIT); } } break; } case ID: { name = LT(1); match(ID); templateName = name.getText(); if ( g.isDefinedInThisGroup(templateName) ) { g.error("redefinition of template: "+templateName); st = new StringTemplate(); // create bogus template to fill in } else { st = g.defineTemplate(templateName, null); } break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } if ( st!=null ) {st.setGroupFileLine(line);} match(LPAREN); { switch ( LA(1)) { case ID: { args(st); break; } case RPAREN: { st.defineEmptyFormalArgumentList(); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } match(RPAREN); match(DEFINED_TO_BE); { switch ( LA(1)) { case STRING: { t = LT(1); match(STRING); st.setTemplate(t.getText()); break; } case BIGSTRING: { bt = LT(1); match(BIGSTRING); st.setTemplate(bt.getText()); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } } else if ((LA(1)==ID) && (LA(2)==DEFINED_TO_BE)) { alias = LT(1); match(ID); match(DEFINED_TO_BE); target = LT(1); match(ID); g.defineTemplateAlias(alias.getText(), target.getText()); } else { throw new NoViableAltException(LT(1), getFilename()); } } catch (RecognitionException ex) { reportError(ex); recover(ex,_tokenSet_1); } } public final void mapdef( StringTemplateGroup g ) throws RecognitionException, TokenStreamException { Token name = null; Map m=null; try { // for error handling name = LT(1); match(ID); match(DEFINED_TO_BE); m=map(); if ( g.getMap(name.getText())!=null ) { g.error("redefinition of map: "+name.getText()); } else if ( g.isDefinedInThisGroup(name.getText()) ) { g.error("redefinition of template as map: "+name.getText()); } else { g.defineMap(name.getText(), m); } } catch (RecognitionException ex) { reportError(ex); recover(ex,_tokenSet_1); } } public final void args( StringTemplate st ) throws RecognitionException, TokenStreamException { try { // for error handling arg(st); { _loop14: do { if ((LA(1)==COMMA)) { match(COMMA); arg(st); } else { break _loop14; } } while (true); } } catch (RecognitionException ex) { reportError(ex); recover(ex,_tokenSet_2); } } public final void arg( StringTemplate st ) throws RecognitionException, TokenStreamException { Token name = null; Token s = null; Token bs = null; StringTemplate defaultValue = null; try { // for error handling name = LT(1); match(ID); { if ((LA(1)==ASSIGN) && (LA(2)==STRING)) { match(ASSIGN); s = LT(1); match(STRING); defaultValue=new StringTemplate("$_val_$"); defaultValue.setAttribute("_val_", s.getText()); defaultValue.defineFormalArgument("_val_"); defaultValue.setName("<"+st.getName()+"'s arg "+name.getText()+" default value subtemplate>"); } else if ((LA(1)==ASSIGN) && (LA(2)==ANONYMOUS_TEMPLATE)) { match(ASSIGN); bs = LT(1); match(ANONYMOUS_TEMPLATE); defaultValue=new StringTemplate(st.getGroup(), bs.getText()); defaultValue.setName("<"+st.getName()+"'s arg "+name.getText()+" default value subtemplate>"); } else if ((LA(1)==COMMA||LA(1)==RPAREN)) { } else { throw new NoViableAltException(LT(1), getFilename()); } } st.defineFormalArgument(name.getText(), defaultValue); } catch (RecognitionException ex) { reportError(ex); recover(ex,_tokenSet_3); } } public final Map map() throws RecognitionException, TokenStreamException { Map mapping=new HashMap(); try { // for error handling match(LBRACK); mapPairs(mapping); match(RBRACK); } catch (RecognitionException ex) { reportError(ex); recover(ex,_tokenSet_1); } return mapping; } public final void mapPairs( Map mapping ) throws RecognitionException, TokenStreamException { try { // for error handling switch ( LA(1)) { case STRING: { keyValuePair(mapping); { _loop21: do { if ((LA(1)==COMMA) && (LA(2)==STRING)) { match(COMMA); keyValuePair(mapping); } else { break _loop21; } } while (true); } { switch ( LA(1)) { case COMMA: { match(COMMA); defaultValuePair(mapping); break; } case RBRACK: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } break; } case LITERAL_default: { defaultValuePair(mapping); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } catch (RecognitionException ex) { reportError(ex); recover(ex,_tokenSet_4); } } public final void keyValuePair( Map mapping ) throws RecognitionException, TokenStreamException { Token key = null; StringTemplate v = null; try { // for error handling key = LT(1); match(STRING); match(COLON); v=keyValue(); mapping.put(key.getText(), v); } catch (RecognitionException ex) { reportError(ex); recover(ex,_tokenSet_5); } } public final void defaultValuePair( Map mapping ) throws RecognitionException, TokenStreamException { StringTemplate v = null; try { // for error handling match(LITERAL_default); match(COLON); v=keyValue(); mapping.put(ASTExpr.DEFAULT_MAP_VALUE_NAME, v); } catch (RecognitionException ex) { reportError(ex); recover(ex,_tokenSet_4); } } public final StringTemplate keyValue() throws RecognitionException, TokenStreamException { StringTemplate value=null; Token s1 = null; Token s2 = null; Token k = null; try { // for error handling switch ( LA(1)) { case BIGSTRING: { s1 = LT(1); match(BIGSTRING); value = new StringTemplate(group,s1.getText()); break; } case STRING: { s2 = LT(1); match(STRING); value = new StringTemplate(group,s2.getText()); break; } case ID: { k = LT(1); match(ID); if (!(k.getText().equals("key"))) throw new SemanticException("k.getText().equals(\"key\")"); value = ASTExpr.MAP_KEY_VALUE; break; } case COMMA: case RBRACK: { value = null; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } catch (RecognitionException ex) { reportError(ex); recover(ex,_tokenSet_5); } return value; } public static final String[] _tokenNames = { "<0>", "EOF", "<2>", "NULL_TREE_LOOKAHEAD", "\"group\"", "ID", "COLON", "\"implements\"", "COMMA", "SEMI", "AT", "DOT", "LPAREN", "RPAREN", "DEFINED_TO_BE", "STRING", "BIGSTRING", "ASSIGN", "ANONYMOUS_TEMPLATE", "LBRACK", "RBRACK", "\"default\"", "STAR", "PLUS", "OPTIONAL", "SL_COMMENT", "ML_COMMENT", "WS" }; private static final long[] mk_tokenSet_0() { long[] data = { 2L, 0L}; return data; } public static final BitSet _tokenSet_0 = new BitSet(mk_tokenSet_0()); private static final long[] mk_tokenSet_1() { long[] data = { 1058L, 0L}; return data; } public static final BitSet _tokenSet_1 = new BitSet(mk_tokenSet_1()); private static final long[] mk_tokenSet_2() { long[] data = { 8192L, 0L}; return data; } public static final BitSet _tokenSet_2 = new BitSet(mk_tokenSet_2()); private static final long[] mk_tokenSet_3() { long[] data = { 8448L, 0L}; return data; } public static final BitSet _tokenSet_3 = new BitSet(mk_tokenSet_3()); private static final long[] mk_tokenSet_4() { long[] data = { 1048576L, 0L}; return data; } public static final BitSet _tokenSet_4 = new BitSet(mk_tokenSet_4()); private static final long[] mk_tokenSet_5() { long[] data = { 1048832L, 0L}; return data; } public static final BitSet _tokenSet_5 = new BitSet(mk_tokenSet_5()); } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/InterfaceLexer.javastringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/InterfaceLexer0000644000175000017500000003247211274602752034137 0ustar twernertwerner// $ANTLR 2.7.7 (20060906): "interface.g" -> "InterfaceLexer.java"$ /* [The "BSD licence"] Copyright (c) 2003-2004 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.language; import org.antlr.stringtemplate.*; import java.util.*; import java.io.InputStream; import antlr.TokenStreamException; import antlr.TokenStreamIOException; import antlr.TokenStreamRecognitionException; import antlr.CharStreamException; import antlr.CharStreamIOException; import antlr.ANTLRException; import java.io.Reader; import java.util.Hashtable; import antlr.CharScanner; import antlr.InputBuffer; import antlr.ByteBuffer; import antlr.CharBuffer; import antlr.Token; import antlr.CommonToken; import antlr.RecognitionException; import antlr.NoViableAltForCharException; import antlr.MismatchedCharException; import antlr.TokenStream; import antlr.ANTLRHashString; import antlr.LexerSharedInputState; import antlr.collections.impl.BitSet; import antlr.SemanticException; public class InterfaceLexer extends antlr.CharScanner implements InterfaceParserTokenTypes, TokenStream { public InterfaceLexer(InputStream in) { this(new ByteBuffer(in)); } public InterfaceLexer(Reader in) { this(new CharBuffer(in)); } public InterfaceLexer(InputBuffer ib) { this(new LexerSharedInputState(ib)); } public InterfaceLexer(LexerSharedInputState state) { super(state); caseSensitiveLiterals = true; setCaseSensitive(true); literals = new Hashtable(); literals.put(new ANTLRHashString("interface", this), new Integer(4)); literals.put(new ANTLRHashString("optional", this), new Integer(7)); } public Token nextToken() throws TokenStreamException { Token theRetToken=null; tryAgain: for (;;) { Token _token = null; int _ttype = Token.INVALID_TYPE; resetText(); try { // for char stream error handling try { // for lexical error handling switch ( LA(1)) { case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': { mID(true); theRetToken=_returnToken; break; } case '(': { mLPAREN(true); theRetToken=_returnToken; break; } case ')': { mRPAREN(true); theRetToken=_returnToken; break; } case ',': { mCOMMA(true); theRetToken=_returnToken; break; } case ';': { mSEMI(true); theRetToken=_returnToken; break; } case ':': { mCOLON(true); theRetToken=_returnToken; break; } case '\t': case '\n': case '\u000c': case '\r': case ' ': { mWS(true); theRetToken=_returnToken; break; } default: if ((LA(1)=='/') && (LA(2)=='/')) { mSL_COMMENT(true); theRetToken=_returnToken; } else if ((LA(1)=='/') && (LA(2)=='*')) { mML_COMMENT(true); theRetToken=_returnToken; } else { if (LA(1)==EOF_CHAR) {uponEOF(); _returnToken = makeToken(Token.EOF_TYPE);} else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } } if ( _returnToken==null ) continue tryAgain; // found SKIP token _ttype = _returnToken.getType(); _ttype = testLiteralsTable(_ttype); _returnToken.setType(_ttype); return _returnToken; } catch (RecognitionException e) { throw new TokenStreamRecognitionException(e); } } catch (CharStreamException cse) { if ( cse instanceof CharStreamIOException ) { throw new TokenStreamIOException(((CharStreamIOException)cse).io); } else { throw new TokenStreamException(cse.getMessage()); } } } } public final void mID(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = ID; int _saveIndex; { switch ( LA(1)) { case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': { matchRange('a','z'); break; } case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': { matchRange('A','Z'); break; } case '_': { match('_'); break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } { _loop13: do { switch ( LA(1)) { case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': { matchRange('a','z'); break; } case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': { matchRange('A','Z'); break; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { matchRange('0','9'); break; } case '-': { match('-'); break; } case '_': { match('_'); break; } default: { break _loop13; } } } while (true); } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mLPAREN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = LPAREN; int _saveIndex; match('('); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mRPAREN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = RPAREN; int _saveIndex; match(')'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mCOMMA(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = COMMA; int _saveIndex; match(','); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mSEMI(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = SEMI; int _saveIndex; match(';'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mCOLON(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = COLON; int _saveIndex; match(':'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mSL_COMMENT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = SL_COMMENT; int _saveIndex; match("//"); { _loop22: do { if ((_tokenSet_0.member(LA(1)))) { { match(_tokenSet_0); } } else { break _loop22; } } while (true); } { if ((LA(1)=='\n'||LA(1)=='\r')) { { switch ( LA(1)) { case '\r': { match('\r'); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } match('\n'); } else { } } _ttype = Token.SKIP; newline(); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mML_COMMENT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = ML_COMMENT; int _saveIndex; match("/*"); { _loop28: do { // nongreedy exit test if ((LA(1)=='*') && (LA(2)=='/')) break _loop28; if ((LA(1)=='\n'||LA(1)=='\r') && ((LA(2) >= '\u0000' && LA(2) <= '\ufffe'))) { { switch ( LA(1)) { case '\r': { match('\r'); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } match('\n'); newline(); } else if (((LA(1) >= '\u0000' && LA(1) <= '\ufffe')) && ((LA(2) >= '\u0000' && LA(2) <= '\ufffe'))) { matchNot(EOF_CHAR); } else { break _loop28; } } while (true); } match("*/"); _ttype = Token.SKIP; if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mWS(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = WS; int _saveIndex; { int _cnt32=0; _loop32: do { switch ( LA(1)) { case ' ': { match(' '); break; } case '\t': { match('\t'); break; } case '\u000c': { match('\f'); break; } case '\n': case '\r': { { switch ( LA(1)) { case '\r': { match('\r'); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } match('\n'); newline(); break; } default: { if ( _cnt32>=1 ) { break _loop32; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } } _cnt32++; } while (true); } _ttype = Token.SKIP; if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } private static final long[] mk_tokenSet_0() { long[] data = new long[2048]; data[0]=-9217L; for (int i = 1; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_0 = new BitSet(mk_tokenSet_0()); } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/TemplateParserTokenTypes.txtstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/TemplateParser0000644000175000017500000000051011274602750034151 0ustar twernertwerner// $ANTLR 2.7.7 (20060906): template.g -> TemplateParserTokenTypes.txt$ TemplateParser // output token vocab name LITERAL=4 NEWLINE=5 ACTION=6 IF=7 ELSEIF=8 ELSE=9 ENDIF=10 REGION_REF=11 REGION_DEF=12 EXPR=13 TEMPLATE=14 IF_EXPR=15 ESC_CHAR=16 ESC=17 HEX=18 SUBTEMPLATE=19 NESTED_PARENS=20 INDENT=21 COMMENT=22 LINE_BREAK=23 ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/InterfaceParserTokenTypes.javastringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/InterfaceParse0000644000175000017500000000357211274602752034131 0ustar twernertwerner// $ANTLR 2.7.7 (20060906): "interface.g" -> "InterfaceParser.java"$ /* [The "BSD licence"] Copyright (c) 2003-2004 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.language; import org.antlr.stringtemplate.*; import java.util.*; public interface InterfaceParserTokenTypes { int EOF = 1; int NULL_TREE_LOOKAHEAD = 3; int LITERAL_interface = 4; int ID = 5; int SEMI = 6; int LITERAL_optional = 7; int LPAREN = 8; int RPAREN = 9; int COMMA = 10; int COLON = 11; int SL_COMMENT = 12; int ML_COMMENT = 13; int WS = 14; } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/GroupParserTokenTypes.javastringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/GroupParserTok0000644000175000017500000000415411274602752034162 0ustar twernertwerner// $ANTLR 2.7.7 (20060906): "group.g" -> "GroupParser.java"$ /* [The "BSD licence"] Copyright (c) 2003-2004 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.language; import org.antlr.stringtemplate.*; import java.util.*; public interface GroupParserTokenTypes { int EOF = 1; int NULL_TREE_LOOKAHEAD = 3; int LITERAL_group = 4; int ID = 5; int COLON = 6; int LITERAL_implements = 7; int COMMA = 8; int SEMI = 9; int AT = 10; int DOT = 11; int LPAREN = 12; int RPAREN = 13; int DEFINED_TO_BE = 14; int STRING = 15; int BIGSTRING = 16; int ASSIGN = 17; int ANONYMOUS_TEMPLATE = 18; int LBRACK = 19; int RBRACK = 20; int LITERAL_default = 21; int STAR = 22; int PLUS = 23; int OPTIONAL = 24; int SL_COMMENT = 25; int ML_COMMENT = 26; int WS = 27; } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/DefaultTemplateLexer.javastringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/DefaultTemplat0000644000175000017500000011502611274602750034145 0ustar twernertwerner// $ANTLR 2.7.7 (20060906): "template.g" -> "DefaultTemplateLexer.java"$ /* [The "BSD licence"] Copyright (c) 2003-2004 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.language; import org.antlr.stringtemplate.*; import java.io.*; import java.io.InputStream; import antlr.TokenStreamException; import antlr.TokenStreamIOException; import antlr.TokenStreamRecognitionException; import antlr.CharStreamException; import antlr.CharStreamIOException; import antlr.ANTLRException; import java.io.Reader; import java.util.Hashtable; import antlr.CharScanner; import antlr.InputBuffer; import antlr.ByteBuffer; import antlr.CharBuffer; import antlr.Token; import antlr.CommonToken; import antlr.RecognitionException; import antlr.NoViableAltForCharException; import antlr.MismatchedCharException; import antlr.TokenStream; import antlr.ANTLRHashString; import antlr.LexerSharedInputState; import antlr.collections.impl.BitSet; import antlr.SemanticException; /** Break up an input text stream into chunks of either plain text * or template actions in "$...$". Treat IF and ENDIF tokens * specially. */ public class DefaultTemplateLexer extends antlr.CharScanner implements TemplateParserTokenTypes, TokenStream { protected String currentIndent = null; protected StringTemplate self; public DefaultTemplateLexer(StringTemplate self, Reader r) { this(r); this.self = self; } public void reportError(RecognitionException e) { self.error("$...$ chunk lexer error", e); } protected boolean upcomingELSE(int i) throws CharStreamException { return LA(i)=='$'&&LA(i+1)=='e'&&LA(i+2)=='l'&&LA(i+3)=='s'&&LA(i+4)=='e'&& LA(i+5)=='$'; } protected boolean upcomingENDIF(int i) throws CharStreamException { return LA(i)=='$'&&LA(i+1)=='e'&&LA(i+2)=='n'&&LA(i+3)=='d'&&LA(i+4)=='i'&& LA(i+5)=='f'&&LA(i+6)=='$'; } protected boolean upcomingAtEND(int i) throws CharStreamException { return LA(i)=='$'&&LA(i+1)=='@'&&LA(i+2)=='e'&&LA(i+3)=='n'&&LA(i+4)=='d'&&LA(i+5)=='$'; } protected boolean upcomingNewline(int i) throws CharStreamException { return (LA(i)=='\r'&&LA(i+1)=='\n')||LA(i)=='\n'; } public DefaultTemplateLexer(InputStream in) { this(new ByteBuffer(in)); } public DefaultTemplateLexer(Reader in) { this(new CharBuffer(in)); } public DefaultTemplateLexer(InputBuffer ib) { this(new LexerSharedInputState(ib)); } public DefaultTemplateLexer(LexerSharedInputState state) { super(state); caseSensitiveLiterals = true; setCaseSensitive(true); literals = new Hashtable(); } public Token nextToken() throws TokenStreamException { Token theRetToken=null; tryAgain: for (;;) { Token _token = null; int _ttype = Token.INVALID_TYPE; resetText(); try { // for char stream error handling try { // for lexical error handling switch ( LA(1)) { case '\n': case '\r': { mNEWLINE(true); theRetToken=_returnToken; break; } case '$': { mACTION(true); theRetToken=_returnToken; break; } default: if (((_tokenSet_0.member(LA(1))))&&(LA(1)!='\r'&&LA(1)!='\n')) { mLITERAL(true); theRetToken=_returnToken; } else { if (LA(1)==EOF_CHAR) {uponEOF(); _returnToken = makeToken(Token.EOF_TYPE);} else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } } if ( _returnToken==null ) continue tryAgain; // found SKIP token _ttype = _returnToken.getType(); _ttype = testLiteralsTable(_ttype); _returnToken.setType(_ttype); return _returnToken; } catch (RecognitionException e) { throw new TokenStreamRecognitionException(e); } } catch (CharStreamException cse) { if ( cse instanceof CharStreamIOException ) { throw new TokenStreamIOException(((CharStreamIOException)cse).io); } else { throw new TokenStreamException(cse.getMessage()); } } } } public final void mLITERAL(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = LITERAL; int _saveIndex; Token ind=null; if (!(LA(1)!='\r'&&LA(1)!='\n')) throw new SemanticException("LA(1)!='\\r'&&LA(1)!='\\n'"); { int _cnt11=0; _loop11: do { int loopStartIndex=text.length(); int col=getColumn(); if ((LA(1)=='\\') && (LA(2)=='$')) { _saveIndex=text.length(); match('\\'); text.setLength(_saveIndex); match('$'); } else if ((LA(1)=='\\') && (LA(2)=='\\') && (true) && (true) && (true) && (true) && (true)) { _saveIndex=text.length(); match('\\'); text.setLength(_saveIndex); match('\\'); } else if ((LA(1)=='\\') && (_tokenSet_1.member(LA(2))) && (true) && (true) && (true) && (true) && (true)) { match('\\'); matchNot('$'); } else if ((LA(1)=='\t'||LA(1)==' ') && (true) && (true) && (true) && (true) && (true) && (true)) { mINDENT(true); ind=_returnToken; if ( col==1 && LA(1)=='$' ) { // store indent in ASTExpr not in a literal currentIndent=ind.getText(); text.setLength(loopStartIndex); // reset length to wack text } else currentIndent=null; } else if ((_tokenSet_0.member(LA(1))) && (true) && (true) && (true) && (true) && (true) && (true)) { { match(_tokenSet_0); } } else { if ( _cnt11>=1 ) { break _loop11; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } _cnt11++; } while (true); } if ((new String(text.getBuffer(),_begin,text.length()-_begin)).length()==0) {_ttype = Token.SKIP;} if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mINDENT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = INDENT; int _saveIndex; { int _cnt76=0; _loop76: do { if ((LA(1)==' ') && (true) && (true) && (true) && (true) && (true) && (true)) { match(' '); } else if ((LA(1)=='\t') && (true) && (true) && (true) && (true) && (true) && (true)) { match('\t'); } else { if ( _cnt76>=1 ) { break _loop76; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } _cnt76++; } while (true); } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mNEWLINE(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = NEWLINE; int _saveIndex; { switch ( LA(1)) { case '\r': { match('\r'); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } match('\n'); newline(); currentIndent=null; if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mACTION(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = ACTION; int _saveIndex; int startCol = getColumn(); if ((LA(1)=='$') && (LA(2)=='\\') && (LA(3)=='\\') && (LA(4)=='$') && (_tokenSet_2.member(LA(5))) && (true) && (true)) { mLINE_BREAK(false); _ttype = Token.SKIP; } else if ((LA(1)=='$') && (LA(2)=='\\') && (_tokenSet_3.member(LA(3))) && (_tokenSet_4.member(LA(4))) && (true) && (true) && (true)) { StringBuffer buf = new StringBuffer(); char uc = '\u0000'; _saveIndex=text.length(); match('$'); text.setLength(_saveIndex); { int _cnt16=0; _loop16: do { if ((LA(1)=='\\')) { uc=mESC_CHAR(false); buf.append(uc); } else { if ( _cnt16>=1 ) { break _loop16; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } _cnt16++; } while (true); } _saveIndex=text.length(); match('$'); text.setLength(_saveIndex); text.setLength(_begin); text.append(buf.toString()); _ttype = LITERAL; } else if ((LA(1)=='$') && (LA(2)=='!') && ((LA(3) >= '\u0001' && LA(3) <= '\ufffe')) && ((LA(4) >= '\u0001' && LA(4) <= '\ufffe')) && (true) && (true) && (true)) { mCOMMENT(false); _ttype = Token.SKIP; } else if ((LA(1)=='$') && (_tokenSet_1.member(LA(2))) && ((LA(3) >= '\u0001' && LA(3) <= '\ufffe')) && (true) && (true) && (true) && (true)) { { if ((LA(1)=='$') && (LA(2)=='i') && (LA(3)=='f') && (LA(4)==' '||LA(4)=='(') && (_tokenSet_5.member(LA(5))) && ((LA(6) >= '\u0001' && LA(6) <= '\ufffe')) && ((LA(7) >= '\u0001' && LA(7) <= '\ufffe'))) { _saveIndex=text.length(); match('$'); text.setLength(_saveIndex); match("if"); { _loop19: do { if ((LA(1)==' ')) { _saveIndex=text.length(); match(' '); text.setLength(_saveIndex); } else { break _loop19; } } while (true); } match("("); mIF_EXPR(false); match(")"); _saveIndex=text.length(); match('$'); text.setLength(_saveIndex); _ttype = TemplateParser.IF; { if ((LA(1)=='\n'||LA(1)=='\r')) { { switch ( LA(1)) { case '\r': { _saveIndex=text.length(); match('\r'); text.setLength(_saveIndex); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } _saveIndex=text.length(); match('\n'); text.setLength(_saveIndex); newline(); } else { } } } else if ((LA(1)=='$') && (LA(2)=='e') && (LA(3)=='l') && (LA(4)=='s') && (LA(5)=='e') && (LA(6)=='i') && (LA(7)=='f')) { _saveIndex=text.length(); match('$'); text.setLength(_saveIndex); match("elseif"); { _loop23: do { if ((LA(1)==' ')) { _saveIndex=text.length(); match(' '); text.setLength(_saveIndex); } else { break _loop23; } } while (true); } match("("); mIF_EXPR(false); match(")"); _saveIndex=text.length(); match('$'); text.setLength(_saveIndex); _ttype = TemplateParser.ELSEIF; { if ((LA(1)=='\n'||LA(1)=='\r')) { { switch ( LA(1)) { case '\r': { _saveIndex=text.length(); match('\r'); text.setLength(_saveIndex); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } _saveIndex=text.length(); match('\n'); text.setLength(_saveIndex); newline(); } else { } } } else if ((LA(1)=='$') && (LA(2)=='e') && (LA(3)=='n') && (LA(4)=='d') && (LA(5)=='i') && (LA(6)=='f') && (LA(7)=='$')) { _saveIndex=text.length(); match('$'); text.setLength(_saveIndex); match("endif"); _saveIndex=text.length(); match('$'); text.setLength(_saveIndex); _ttype = TemplateParser.ENDIF; { if (((LA(1)=='\n'||LA(1)=='\r'))&&(startCol==1)) { { switch ( LA(1)) { case '\r': { _saveIndex=text.length(); match('\r'); text.setLength(_saveIndex); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } _saveIndex=text.length(); match('\n'); text.setLength(_saveIndex); newline(); } else { } } } else if ((LA(1)=='$') && (LA(2)=='e') && (LA(3)=='l') && (LA(4)=='s') && (LA(5)=='e') && (LA(6)=='$') && (true)) { _saveIndex=text.length(); match('$'); text.setLength(_saveIndex); match("else"); _saveIndex=text.length(); match('$'); text.setLength(_saveIndex); _ttype = TemplateParser.ELSE; { if ((LA(1)=='\n'||LA(1)=='\r')) { { switch ( LA(1)) { case '\r': { _saveIndex=text.length(); match('\r'); text.setLength(_saveIndex); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } _saveIndex=text.length(); match('\n'); text.setLength(_saveIndex); newline(); } else { } } } else if ((LA(1)=='$') && (LA(2)=='@') && (_tokenSet_6.member(LA(3))) && ((LA(4) >= '\u0001' && LA(4) <= '\ufffe')) && ((LA(5) >= '\u0001' && LA(5) <= '\ufffe')) && ((LA(6) >= '\u0001' && LA(6) <= '\ufffe')) && (true)) { _saveIndex=text.length(); match('$'); text.setLength(_saveIndex); _saveIndex=text.length(); match('@'); text.setLength(_saveIndex); { int _cnt32=0; _loop32: do { if ((_tokenSet_6.member(LA(1)))) { { match(_tokenSet_6); } } else { if ( _cnt32>=1 ) { break _loop32; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } _cnt32++; } while (true); } { switch ( LA(1)) { case '(': { _saveIndex=text.length(); match("()"); text.setLength(_saveIndex); _saveIndex=text.length(); match('$'); text.setLength(_saveIndex); _ttype = TemplateParser.REGION_REF; break; } case '$': { _saveIndex=text.length(); match('$'); text.setLength(_saveIndex); _ttype = TemplateParser.REGION_DEF; String t=new String(text.getBuffer(),_begin,text.length()-_begin); text.setLength(_begin); text.append(t+"::="); { if ((LA(1)=='\n'||LA(1)=='\r') && ((LA(2) >= '\u0001' && LA(2) <= '\ufffe')) && ((LA(3) >= '\u0001' && LA(3) <= '\ufffe')) && (true) && (true) && (true) && (true)) { { switch ( LA(1)) { case '\r': { _saveIndex=text.length(); match('\r'); text.setLength(_saveIndex); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } _saveIndex=text.length(); match('\n'); text.setLength(_saveIndex); newline(); } else if (((LA(1) >= '\u0001' && LA(1) <= '\ufffe')) && ((LA(2) >= '\u0001' && LA(2) <= '\ufffe')) && (true) && (true) && (true) && (true) && (true)) { } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } boolean atLeft = false; { int _cnt39=0; _loop39: do { if ((((LA(1) >= '\u0001' && LA(1) <= '\ufffe')) && ((LA(2) >= '\u0001' && LA(2) <= '\ufffe')) && (true) && (true) && (true) && (true) && (true))&&(!(upcomingAtEND(1)||(upcomingNewline(1)&&upcomingAtEND(2))))) { { if ((LA(1)=='\n'||LA(1)=='\r') && ((LA(2) >= '\u0001' && LA(2) <= '\ufffe')) && (true) && (true) && (true) && (true) && (true)) { { switch ( LA(1)) { case '\r': { match('\r'); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } match('\n'); newline(); atLeft = true; } else if (((LA(1) >= '\u0001' && LA(1) <= '\ufffe')) && ((LA(2) >= '\u0001' && LA(2) <= '\ufffe')) && (true) && (true) && (true) && (true) && (true)) { matchNot(EOF_CHAR); atLeft = false; } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } else { if ( _cnt39>=1 ) { break _loop39; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } _cnt39++; } while (true); } { if ((LA(1)=='\n'||LA(1)=='\r') && ((LA(2) >= '\u0001' && LA(2) <= '\ufffe')) && (true) && (true) && (true) && (true) && (true)) { { switch ( LA(1)) { case '\r': { _saveIndex=text.length(); match('\r'); text.setLength(_saveIndex); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } _saveIndex=text.length(); match('\n'); text.setLength(_saveIndex); newline(); atLeft = true; } else if (((LA(1) >= '\u0001' && LA(1) <= '\ufffe')) && (true) && (true) && (true) && (true) && (true) && (true)) { } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } { if ((LA(1)=='$') && (LA(2)=='@')) { _saveIndex=text.length(); match("$@end$"); text.setLength(_saveIndex); } else if (((LA(1) >= '\u0001' && LA(1) <= '\ufffe')) && (true)) { matchNot(EOF_CHAR); self.error("missing region "+t+" $@end$ tag"); } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } { if (((LA(1)=='\n'||LA(1)=='\r'))&&(atLeft)) { { switch ( LA(1)) { case '\r': { _saveIndex=text.length(); match('\r'); text.setLength(_saveIndex); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } _saveIndex=text.length(); match('\n'); text.setLength(_saveIndex); newline(); } else { } } break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } } else if ((LA(1)=='$') && (_tokenSet_1.member(LA(2))) && ((LA(3) >= '\u0001' && LA(3) <= '\ufffe')) && (true) && (true) && (true) && (true)) { _saveIndex=text.length(); match('$'); text.setLength(_saveIndex); mEXPR(false); _saveIndex=text.length(); match('$'); text.setLength(_saveIndex); } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } ChunkToken t = new ChunkToken(_ttype, new String(text.getBuffer(),_begin,text.length()-_begin), currentIndent); _token = t; } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mLINE_BREAK(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = LINE_BREAK; int _saveIndex; match("$\\\\$"); { switch ( LA(1)) { case '\t': case ' ': { mINDENT(false); break; } case '\n': case '\r': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } { switch ( LA(1)) { case '\r': { match('\r'); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } match('\n'); newline(); { if ((LA(1)=='\t'||LA(1)==' ')) { mINDENT(false); } else { } } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final char mESC_CHAR(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { char uc='\u0000'; int _ttype; Token _token=null; int _begin=text.length(); _ttype = ESC_CHAR; int _saveIndex; Token a=null; Token b=null; Token c=null; Token d=null; if ((LA(1)=='\\') && (LA(2)=='n')) { _saveIndex=text.length(); match("\\n"); text.setLength(_saveIndex); uc = '\n'; } else if ((LA(1)=='\\') && (LA(2)=='r')) { _saveIndex=text.length(); match("\\r"); text.setLength(_saveIndex); uc = '\r'; } else if ((LA(1)=='\\') && (LA(2)=='t')) { _saveIndex=text.length(); match("\\t"); text.setLength(_saveIndex); uc = '\t'; } else if ((LA(1)=='\\') && (LA(2)==' ')) { _saveIndex=text.length(); match("\\ "); text.setLength(_saveIndex); uc = ' '; } else if ((LA(1)=='\\') && (LA(2)=='u')) { _saveIndex=text.length(); match("\\u"); text.setLength(_saveIndex); _saveIndex=text.length(); mHEX(true); text.setLength(_saveIndex); a=_returnToken; _saveIndex=text.length(); mHEX(true); text.setLength(_saveIndex); b=_returnToken; _saveIndex=text.length(); mHEX(true); text.setLength(_saveIndex); c=_returnToken; _saveIndex=text.length(); mHEX(true); text.setLength(_saveIndex); d=_returnToken; uc = (char)Integer.parseInt(a.getText()+b.getText()+c.getText()+d.getText(), 16); } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; return uc; } protected final void mCOMMENT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = COMMENT; int _saveIndex; int startCol = getColumn(); match("$!"); { _loop80: do { // nongreedy exit test if ((LA(1)=='!') && (LA(2)=='$') && (true) && (true) && (true) && (true) && (true)) break _loop80; if ((LA(1)=='\n'||LA(1)=='\r') && ((LA(2) >= '\u0001' && LA(2) <= '\ufffe')) && ((LA(3) >= '\u0001' && LA(3) <= '\ufffe')) && (true) && (true) && (true) && (true)) { { switch ( LA(1)) { case '\r': { match('\r'); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } match('\n'); newline(); } else if (((LA(1) >= '\u0001' && LA(1) <= '\ufffe')) && ((LA(2) >= '\u0001' && LA(2) <= '\ufffe')) && ((LA(3) >= '\u0001' && LA(3) <= '\ufffe')) && (true) && (true) && (true) && (true)) { matchNot(EOF_CHAR); } else { break _loop80; } } while (true); } match("!$"); { if (((LA(1)=='\n'||LA(1)=='\r'))&&(startCol==1)) { { switch ( LA(1)) { case '\r': { match('\r'); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } match('\n'); newline(); } else { } } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mIF_EXPR(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = IF_EXPR; int _saveIndex; { int _cnt64=0; _loop64: do { switch ( LA(1)) { case '\\': { mESC(false); break; } case '\n': case '\r': { { switch ( LA(1)) { case '\r': { match('\r'); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } match('\n'); newline(); break; } case '{': { mSUBTEMPLATE(false); break; } case '(': { mNESTED_PARENS(false); break; } default: if ((_tokenSet_7.member(LA(1)))) { matchNot(')'); } else { if ( _cnt64>=1 ) { break _loop64; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } } _cnt64++; } while (true); } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mEXPR(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = EXPR; int _saveIndex; { int _cnt52=0; _loop52: do { switch ( LA(1)) { case '\\': { mESC(false); break; } case '\n': case '\r': { { switch ( LA(1)) { case '\r': { match('\r'); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } match('\n'); newline(); break; } case '{': { mSUBTEMPLATE(false); break; } default: if ((LA(1)=='+'||LA(1)=='=') && (LA(2)=='"'||LA(2)=='<')) { { switch ( LA(1)) { case '=': { match('='); break; } case '+': { match('+'); break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } mTEMPLATE(false); } else if ((LA(1)=='+'||LA(1)=='=') && (LA(2)=='{')) { { switch ( LA(1)) { case '=': { match('='); break; } case '+': { match('+'); break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } mSUBTEMPLATE(false); } else if ((LA(1)=='+'||LA(1)=='=') && (_tokenSet_8.member(LA(2)))) { { switch ( LA(1)) { case '=': { match('='); break; } case '+': { match('+'); break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } { match(_tokenSet_8); } } else if ((_tokenSet_9.member(LA(1)))) { matchNot('$'); } else { if ( _cnt52>=1 ) { break _loop52; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } } _cnt52++; } while (true); } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mESC(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = ESC; int _saveIndex; match('\\'); matchNot(EOF_CHAR); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mSUBTEMPLATE(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = SUBTEMPLATE; int _saveIndex; match('{'); { _loop70: do { switch ( LA(1)) { case '{': { mSUBTEMPLATE(false); break; } case '\\': { mESC(false); break; } default: if ((_tokenSet_10.member(LA(1)))) { matchNot('}'); } else { break _loop70; } } } while (true); } match('}'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mTEMPLATE(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = TEMPLATE; int _saveIndex; switch ( LA(1)) { case '"': { match('"'); { _loop55: do { if ((LA(1)=='\\')) { mESC(false); } else if ((_tokenSet_11.member(LA(1)))) { matchNot('"'); } else { break _loop55; } } while (true); } match('"'); break; } case '<': { match("<<"); { if ((LA(1)=='\n'||LA(1)=='\r') && ((LA(2) >= '\u0001' && LA(2) <= '\ufffe')) && ((LA(3) >= '\u0001' && LA(3) <= '\ufffe')) && ((LA(4) >= '\u0001' && LA(4) <= '\ufffe')) && (true) && (true) && (true)) { { switch ( LA(1)) { case '\r': { _saveIndex=text.length(); match('\r'); text.setLength(_saveIndex); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } _saveIndex=text.length(); match('\n'); text.setLength(_saveIndex); newline(); } else if (((LA(1) >= '\u0001' && LA(1) <= '\ufffe')) && ((LA(2) >= '\u0001' && LA(2) <= '\ufffe')) && ((LA(3) >= '\u0001' && LA(3) <= '\ufffe')) && (true) && (true) && (true) && (true)) { } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } { _loop60: do { // nongreedy exit test if ((LA(1)=='>') && (LA(2)=='>') && ((LA(3) >= '\u0001' && LA(3) <= '\ufffe')) && (true) && (true) && (true) && (true)) break _loop60; if (((LA(1)=='\r') && (LA(2)=='\n') && ((LA(3) >= '\u0001' && LA(3) <= '\ufffe')) && ((LA(4) >= '\u0001' && LA(4) <= '\ufffe')) && ((LA(5) >= '\u0001' && LA(5) <= '\ufffe')) && (true) && (true))&&(LA(3)=='>'&&LA(4)=='>')) { _saveIndex=text.length(); match('\r'); text.setLength(_saveIndex); _saveIndex=text.length(); match('\n'); text.setLength(_saveIndex); newline(); } else if (((LA(1)=='\n') && ((LA(2) >= '\u0001' && LA(2) <= '\ufffe')) && ((LA(3) >= '\u0001' && LA(3) <= '\ufffe')) && ((LA(4) >= '\u0001' && LA(4) <= '\ufffe')) && (true) && (true) && (true))&&(LA(2)=='>'&&LA(3)=='>')) { _saveIndex=text.length(); match('\n'); text.setLength(_saveIndex); newline(); } else if ((LA(1)=='\n'||LA(1)=='\r') && ((LA(2) >= '\u0001' && LA(2) <= '\ufffe')) && ((LA(3) >= '\u0001' && LA(3) <= '\ufffe')) && ((LA(4) >= '\u0001' && LA(4) <= '\ufffe')) && (true) && (true) && (true)) { { switch ( LA(1)) { case '\r': { match('\r'); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } match('\n'); newline(); } else if (((LA(1) >= '\u0001' && LA(1) <= '\ufffe')) && ((LA(2) >= '\u0001' && LA(2) <= '\ufffe')) && ((LA(3) >= '\u0001' && LA(3) <= '\ufffe')) && ((LA(4) >= '\u0001' && LA(4) <= '\ufffe')) && (true) && (true) && (true)) { matchNot(EOF_CHAR); } else { break _loop60; } } while (true); } match(">>"); break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mNESTED_PARENS(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = NESTED_PARENS; int _saveIndex; match('('); { int _cnt73=0; _loop73: do { switch ( LA(1)) { case '(': { mNESTED_PARENS(false); break; } case '\\': { mESC(false); break; } default: if ((_tokenSet_12.member(LA(1)))) { matchNot(')'); } else { if ( _cnt73>=1 ) { break _loop73; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } } _cnt73++; } while (true); } match(')'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mHEX(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = HEX; int _saveIndex; switch ( LA(1)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { matchRange('0','9'); break; } case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': { matchRange('A','F'); break; } case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': { matchRange('a','f'); break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } private static final long[] mk_tokenSet_0() { long[] data = new long[2048]; data[0]=-68719485954L; for (int i = 1; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_0 = new BitSet(mk_tokenSet_0()); private static final long[] mk_tokenSet_1() { long[] data = new long[2048]; data[0]=-68719476738L; for (int i = 1; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_1 = new BitSet(mk_tokenSet_1()); private static final long[] mk_tokenSet_2() { long[] data = new long[1025]; data[0]=4294977024L; return data; } public static final BitSet _tokenSet_2 = new BitSet(mk_tokenSet_2()); private static final long[] mk_tokenSet_3() { long[] data = new long[1025]; data[0]=4294967296L; data[1]=14707067533131776L; return data; } public static final BitSet _tokenSet_3 = new BitSet(mk_tokenSet_3()); private static final long[] mk_tokenSet_4() { long[] data = new long[1025]; data[0]=287948969894477824L; data[1]=541434314878L; return data; } public static final BitSet _tokenSet_4 = new BitSet(mk_tokenSet_4()); private static final long[] mk_tokenSet_5() { long[] data = new long[2048]; data[0]=-2199023255554L; for (int i = 1; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_5 = new BitSet(mk_tokenSet_5()); private static final long[] mk_tokenSet_6() { long[] data = new long[2048]; data[0]=-1168231104514L; for (int i = 1; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_6 = new BitSet(mk_tokenSet_6()); private static final long[] mk_tokenSet_7() { long[] data = new long[2048]; data[0]=-3298534892546L; data[1]=-576460752571858945L; for (int i = 2; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_7 = new BitSet(mk_tokenSet_7()); private static final long[] mk_tokenSet_8() { long[] data = new long[2048]; data[0]=-1152921521786716162L; data[1]=-576460752303423489L; for (int i = 2; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_8 = new BitSet(mk_tokenSet_8()); private static final long[] mk_tokenSet_9() { long[] data = new long[2048]; data[0]=-2305851874026202114L; data[1]=-576460752571858945L; for (int i = 2; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_9 = new BitSet(mk_tokenSet_9()); private static final long[] mk_tokenSet_10() { long[] data = new long[2048]; data[0]=-2L; data[1]=-2882303761785552897L; for (int i = 2; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_10 = new BitSet(mk_tokenSet_10()); private static final long[] mk_tokenSet_11() { long[] data = new long[2048]; data[0]=-17179869186L; data[1]=-268435457L; for (int i = 2; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_11 = new BitSet(mk_tokenSet_11()); private static final long[] mk_tokenSet_12() { long[] data = new long[2048]; data[0]=-3298534883330L; data[1]=-268435457L; for (int i = 2; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_12 = new BitSet(mk_tokenSet_12()); } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/ActionLexer.smapstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/ActionLexer.sm0000644000175000017500000001166011274602752034066 0ustar twernertwernerSMAP ActionLexer.java G *S G *F + 0 action.g action.g *L 0:110 0:118 0:124 0:130 0:136 0:142 0:148 0:154 0:160 0:166 0:172 0:178 0:184 0:190 0:196 0:202 0:206 1:3 1:4 1:5 1:6 1:8 1:9 1:10 1:11 1:12 1:13 1:14 1:15 1:16 1:17 1:19 1:20 1:21 1:22 1:23 1:24 1:25 1:26 1:27 1:28 1:29 1:30 1:31 1:32 241:234 241:235 241:236 241:237 241:324 241:325 241:326 241:327 241:328 241:329 241:330 245:240 245:241 245:242 245:243 245:244 245:245 245:246 245:247 245:248 245:249 245:252 245:253 245:254 245:255 245:256 245:257 245:258 245:259 245:260 245:263 245:264 245:265 245:268 245:269 245:270 245:271 245:272 245:274 245:275 245:276 245:277 245:278 245:279 245:280 245:281 245:282 245:283 245:284 245:285 245:286 245:289 245:290 245:291 245:292 245:293 245:294 245:295 245:296 245:297 245:300 245:301 245:302 245:303 245:304 245:307 245:308 245:309 245:312 245:313 245:314 245:317 245:318 245:319 245:320 245:321 245:322 245:323 248:332 248:333 248:334 248:335 248:338 248:339 248:340 248:341 248:342 248:343 248:344 248:345 248:346 248:348 248:349 248:350 248:351 248:352 248:353 248:354 248:355 248:356 250:358 250:359 250:360 250:361 250:384 250:385 250:386 250:387 250:388 250:389 251:363 251:364 251:365 251:366 251:367 251:368 251:369 251:370 251:371 251:372 251:373 251:374 251:375 251:376 251:377 251:379 251:380 251:381 251:382 251:383 254:453 254:454 254:455 254:456 254:552 254:553 254:554 254:555 254:556 254:557 255:458 256:459 259:462 259:463 259:464 260:466 260:467 260:468 260:469 260:470 260:471 260:473 260:475 260:476 260:477 260:478 260:479 260:480 260:481 260:482 260:483 260:485 260:486 260:487 260:488 260:489 260:491 260:492 260:493 260:494 260:504 260:506 260:507 260:508 260:509 261:497 262:499 263:500 264:501 268:512 268:513 268:514 268:515 268:516 268:517 268:518 268:519 268:520 268:521 268:522 268:523 268:524 268:525 268:526 268:527 268:528 268:529 268:530 268:531 268:532 268:533 268:534 268:535 268:536 268:537 268:538 268:540 268:541 269:542 270:544 271:545 272:546 274:549 274:550 274:551 278:559 278:560 278:561 278:562 278:563 278:700 278:701 278:702 278:703 278:704 278:705 278:706 279:564 279:568 279:569 279:570 279:571 279:572 279:573 279:593 279:594 279:595 279:596 279:597 279:599 279:600 279:601 279:602 279:603 279:604 280:565 280:606 280:607 280:608 280:609 280:611 280:612 280:613 280:614 280:615 280:616 280:623 280:624 280:625 280:626 280:627 280:629 280:630 280:631 280:633 280:634 280:635 280:636 280:637 280:638 280:658 280:659 280:660 280:661 280:662 280:664 280:665 280:666 280:667 280:668 280:669 280:671 280:672 280:673 280:674 280:676 280:677 281:679 281:680 281:681 281:682 281:683 281:684 281:691 281:692 281:693 281:694 281:695 281:697 281:698 281:699 285:749 285:750 285:751 285:752 285:786 285:787 285:788 285:789 285:790 285:791 286:754 286:755 286:756 286:757 286:758 286:759 286:760 286:761 286:762 286:763 286:764 286:765 286:766 286:767 286:768 286:769 286:770 286:771 286:772 286:773 286:774 286:775 286:776 286:777 286:778 286:779 286:780 286:781 286:783 286:784 286:785 293:391 293:394 293:395 293:396 293:397 293:398 293:399 293:446 293:447 293:448 293:449 293:450 293:451 294:392 294:402 295:393 295:409 295:415 295:421 295:427 295:433 295:440 295:441 295:442 295:443 296:404 296:405 296:406 296:407 297:410 297:411 297:412 297:413 298:416 298:417 298:418 298:419 299:422 299:423 299:424 299:425 300:428 300:429 300:430 300:431 301:400 301:434 301:435 301:436 301:437 301:438 305:793 305:794 305:795 305:796 305:798 305:799 305:800 305:801 305:802 305:803 305:804 306:806 306:807 306:808 306:809 306:811 306:812 306:813 306:814 306:815 306:816 306:817 307:819 307:820 307:821 307:822 307:824 307:825 307:826 307:827 307:828 307:829 307:830 308:832 308:833 308:834 308:835 308:837 308:838 308:839 308:840 308:841 308:842 308:843 309:845 309:846 309:847 309:848 309:850 309:851 309:852 309:853 309:854 309:855 309:856 310:858 310:859 310:860 310:861 310:863 310:864 310:865 310:866 310:867 310:868 310:869 311:871 311:872 311:873 311:874 311:876 311:877 311:878 311:879 311:880 311:881 311:882 312:884 312:885 312:886 312:887 312:889 312:890 312:891 312:892 312:893 312:894 312:895 313:897 313:898 313:899 313:900 313:902 313:903 313:904 313:905 313:906 313:907 313:908 314:910 314:911 314:912 314:913 314:915 314:916 314:917 314:918 314:919 314:920 314:921 315:923 315:924 315:925 315:926 315:928 315:929 315:930 315:931 315:932 315:933 315:934 316:936 316:937 316:938 316:939 316:941 316:942 316:943 316:944 316:945 316:946 316:947 318:949 318:950 318:951 318:952 318:955 318:956 318:957 318:958 318:959 318:960 318:961 318:964 318:965 318:966 318:969 318:970 318:971 318:974 318:975 318:976 318:977 318:978 318:982 318:983 318:984 318:985 318:986 318:987 318:988 318:989 318:990 318:991 318:993 318:994 318:995 318:996 318:997 318:998 322:708 322:709 322:710 322:711 322:713 322:737 322:738 322:739 322:740 322:741 322:742 322:743 322:744 322:745 322:746 322:747 323:714 323:715 323:716 323:719 323:720 323:721 323:724 323:725 323:726 323:729 323:730 323:731 323:732 323:733 *E ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/ActionEvaluator.javastringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/ActionEvaluato0000644000175000017500000007003111274602752034146 0ustar twernertwerner// $ANTLR 2.7.7 (20060906): "eval.g" -> "ActionEvaluator.java"$ /* [The "BSD licence"] Copyright (c) 2003-2004 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.language; import org.antlr.stringtemplate.*; import java.util.*; import java.io.*; import java.lang.reflect.*; import antlr.TreeParser; import antlr.Token; import antlr.collections.AST; import antlr.RecognitionException; import antlr.ANTLRException; import antlr.NoViableAltException; import antlr.MismatchedTokenException; import antlr.SemanticException; import antlr.collections.impl.BitSet; import antlr.ASTPair; import antlr.collections.impl.ASTArray; public class ActionEvaluator extends antlr.TreeParser implements ActionEvaluatorTokenTypes { public static class NameValuePair { public String name; public Object value; }; protected StringTemplate self = null; protected StringTemplateWriter out = null; protected ASTExpr chunk = null; /** Create an evaluator using attributes from self */ public ActionEvaluator(StringTemplate self, ASTExpr chunk, StringTemplateWriter out) { this.self = self; this.chunk = chunk; this.out = out; } public void reportError(RecognitionException e) { self.error("eval tree parse error", e); } public ActionEvaluator() { tokenNames = _tokenNames; } public final int action(AST _t) throws RecognitionException { int numCharsWritten=0; org.antlr.stringtemplate.language.StringTemplateAST action_AST_in = (_t == ASTNULL) ? null : (org.antlr.stringtemplate.language.StringTemplateAST)_t; Object e=null; try { // for error handling e=expr(_t); _t = _retTree; numCharsWritten = chunk.writeAttribute(self,e,out); } catch (RecognitionException ex) { reportError(ex); if (_t!=null) {_t = _t.getNextSibling();} } _retTree = _t; return numCharsWritten; } public final Object expr(AST _t) throws RecognitionException { Object value=null; org.antlr.stringtemplate.language.StringTemplateAST expr_AST_in = (_t == ASTNULL) ? null : (org.antlr.stringtemplate.language.StringTemplateAST)_t; Object a=null, b=null, e=null; Map argumentContext=null; try { // for error handling if (_t==null) _t=ASTNULL; switch ( _t.getType()) { case PLUS: { AST __t3 = _t; org.antlr.stringtemplate.language.StringTemplateAST tmp1_AST_in = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,PLUS); _t = _t.getFirstChild(); a=expr(_t); _t = _retTree; b=expr(_t); _t = _retTree; value = chunk.add(a,b); _t = __t3; _t = _t.getNextSibling(); break; } case APPLY: case MULTI_APPLY: { value=templateApplication(_t); _t = _retTree; break; } case ID: case DOT: case ANONYMOUS_TEMPLATE: case STRING: case INT: { value=attribute(_t); _t = _retTree; break; } case INCLUDE: { value=templateInclude(_t); _t = _retTree; break; } case FUNCTION: { value=function(_t); _t = _retTree; break; } case LIST: { value=list(_t); _t = _retTree; break; } case VALUE: { AST __t4 = _t; org.antlr.stringtemplate.language.StringTemplateAST tmp2_AST_in = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,VALUE); _t = _t.getFirstChild(); e=expr(_t); _t = _retTree; _t = __t4; _t = _t.getNextSibling(); StringWriter buf = new StringWriter(); StringTemplateWriter sw = self.getGroup().getStringTemplateWriter(buf); int n = chunk.writeAttribute(self,e,sw); if ( n > 0 ) { value = buf.toString(); } break; } default: { throw new NoViableAltException(_t); } } } catch (RecognitionException ex) { reportError(ex); if (_t!=null) {_t = _t.getNextSibling();} } _retTree = _t; return value; } /** Apply template(s) to an attribute; can be applied to another apply * result. */ public final Object templateApplication(AST _t) throws RecognitionException { Object value=null; org.antlr.stringtemplate.language.StringTemplateAST templateApplication_AST_in = (_t == ASTNULL) ? null : (org.antlr.stringtemplate.language.StringTemplateAST)_t; org.antlr.stringtemplate.language.StringTemplateAST anon = null; Object a=null; Vector templatesToApply=new Vector(); List attributes = new ArrayList(); try { // for error handling if (_t==null) _t=ASTNULL; switch ( _t.getType()) { case APPLY: { AST __t14 = _t; org.antlr.stringtemplate.language.StringTemplateAST tmp3_AST_in = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,APPLY); _t = _t.getFirstChild(); a=expr(_t); _t = _retTree; { int _cnt16=0; _loop16: do { if (_t==null) _t=ASTNULL; if ((_t.getType()==TEMPLATE)) { template(_t,templatesToApply); _t = _retTree; } else { if ( _cnt16>=1 ) { break _loop16; } else {throw new NoViableAltException(_t);} } _cnt16++; } while (true); } value = chunk.applyListOfAlternatingTemplates(self,a,templatesToApply); _t = __t14; _t = _t.getNextSibling(); break; } case MULTI_APPLY: { AST __t17 = _t; org.antlr.stringtemplate.language.StringTemplateAST tmp4_AST_in = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,MULTI_APPLY); _t = _t.getFirstChild(); { int _cnt19=0; _loop19: do { if (_t==null) _t=ASTNULL; if ((_tokenSet_0.member(_t.getType()))) { a=expr(_t); _t = _retTree; attributes.add(a); } else { if ( _cnt19>=1 ) { break _loop19; } else {throw new NoViableAltException(_t);} } _cnt19++; } while (true); } org.antlr.stringtemplate.language.StringTemplateAST tmp5_AST_in = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,COLON); _t = _t.getNextSibling(); anon = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,ANONYMOUS_TEMPLATE); _t = _t.getNextSibling(); StringTemplate anonymous = anon.getStringTemplate(); templatesToApply.addElement(anonymous); value = chunk.applyTemplateToListOfAttributes(self, attributes, anon.getStringTemplate()); _t = __t17; _t = _t.getNextSibling(); break; } default: { throw new NoViableAltException(_t); } } } catch (RecognitionException ex) { reportError(ex); if (_t!=null) {_t = _t.getNextSibling();} } _retTree = _t; return value; } public final Object attribute(AST _t) throws RecognitionException { Object value=null; org.antlr.stringtemplate.language.StringTemplateAST attribute_AST_in = (_t == ASTNULL) ? null : (org.antlr.stringtemplate.language.StringTemplateAST)_t; org.antlr.stringtemplate.language.StringTemplateAST prop = null; org.antlr.stringtemplate.language.StringTemplateAST i3 = null; org.antlr.stringtemplate.language.StringTemplateAST i = null; org.antlr.stringtemplate.language.StringTemplateAST s = null; org.antlr.stringtemplate.language.StringTemplateAST at = null; Object obj = null; Object propName = null; Object e = null; try { // for error handling if (_t==null) _t=ASTNULL; switch ( _t.getType()) { case DOT: { AST __t33 = _t; org.antlr.stringtemplate.language.StringTemplateAST tmp6_AST_in = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,DOT); _t = _t.getFirstChild(); obj=expr(_t); _t = _retTree; { if (_t==null) _t=ASTNULL; switch ( _t.getType()) { case ID: { prop = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,ID); _t = _t.getNextSibling(); propName = prop.getText(); break; } case VALUE: { AST __t35 = _t; org.antlr.stringtemplate.language.StringTemplateAST tmp7_AST_in = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,VALUE); _t = _t.getFirstChild(); e=expr(_t); _t = _retTree; _t = __t35; _t = _t.getNextSibling(); if (e!=null) {propName=e;} break; } default: { throw new NoViableAltException(_t); } } } _t = __t33; _t = _t.getNextSibling(); value = chunk.getObjectProperty(self,obj,propName); break; } case ID: { i3 = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,ID); _t = _t.getNextSibling(); value=self.getAttribute(i3.getText()); break; } case INT: { i = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,INT); _t = _t.getNextSibling(); value=new Integer(i.getText()); break; } case STRING: { s = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,STRING); _t = _t.getNextSibling(); value=s.getText(); break; } case ANONYMOUS_TEMPLATE: { at = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,ANONYMOUS_TEMPLATE); _t = _t.getNextSibling(); value=at.getText(); if ( at.getText()!=null ) { StringTemplate valueST =new StringTemplate(self.getGroup(), at.getText()); valueST.setEnclosingInstance(self); valueST.setName(""); value = valueST; } break; } default: { throw new NoViableAltException(_t); } } } catch (RecognitionException ex) { reportError(ex); if (_t!=null) {_t = _t.getNextSibling();} } _retTree = _t; return value; } public final Object templateInclude(AST _t) throws RecognitionException { Object value=null; org.antlr.stringtemplate.language.StringTemplateAST templateInclude_AST_in = (_t == ASTNULL) ? null : (org.antlr.stringtemplate.language.StringTemplateAST)_t; org.antlr.stringtemplate.language.StringTemplateAST id = null; org.antlr.stringtemplate.language.StringTemplateAST a1 = null; org.antlr.stringtemplate.language.StringTemplateAST a2 = null; StringTemplateAST args = null; String name = null; Object n = null; try { // for error handling AST __t10 = _t; org.antlr.stringtemplate.language.StringTemplateAST tmp8_AST_in = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,INCLUDE); _t = _t.getFirstChild(); { if (_t==null) _t=ASTNULL; switch ( _t.getType()) { case ID: { id = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,ID); _t = _t.getNextSibling(); a1 = (org.antlr.stringtemplate.language.StringTemplateAST)_t; if ( _t==null ) throw new MismatchedTokenException(); _t = _t.getNextSibling(); name=id.getText(); args=a1; break; } case VALUE: { AST __t12 = _t; org.antlr.stringtemplate.language.StringTemplateAST tmp9_AST_in = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,VALUE); _t = _t.getFirstChild(); n=expr(_t); _t = _retTree; a2 = (org.antlr.stringtemplate.language.StringTemplateAST)_t; if ( _t==null ) throw new MismatchedTokenException(); _t = _t.getNextSibling(); _t = __t12; _t = _t.getNextSibling(); if (n!=null) {name=n.toString();} args=a2; break; } default: { throw new NoViableAltException(_t); } } } _t = __t10; _t = _t.getNextSibling(); if ( name!=null ) { value = chunk.getTemplateInclude(self, name, args); } } catch (RecognitionException ex) { reportError(ex); if (_t!=null) {_t = _t.getNextSibling();} } _retTree = _t; return value; } public final Object function(AST _t) throws RecognitionException { Object value=null; org.antlr.stringtemplate.language.StringTemplateAST function_AST_in = (_t == ASTNULL) ? null : (org.antlr.stringtemplate.language.StringTemplateAST)_t; Object a; try { // for error handling AST __t21 = _t; org.antlr.stringtemplate.language.StringTemplateAST tmp10_AST_in = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,FUNCTION); _t = _t.getFirstChild(); { if (_t==null) _t=ASTNULL; switch ( _t.getType()) { case LITERAL_first: { org.antlr.stringtemplate.language.StringTemplateAST tmp11_AST_in = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,LITERAL_first); _t = _t.getNextSibling(); a=singleFunctionArg(_t); _t = _retTree; value=chunk.first(a); break; } case LITERAL_rest: { org.antlr.stringtemplate.language.StringTemplateAST tmp12_AST_in = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,LITERAL_rest); _t = _t.getNextSibling(); a=singleFunctionArg(_t); _t = _retTree; value=chunk.rest(a); break; } case LITERAL_last: { org.antlr.stringtemplate.language.StringTemplateAST tmp13_AST_in = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,LITERAL_last); _t = _t.getNextSibling(); a=singleFunctionArg(_t); _t = _retTree; value=chunk.last(a); break; } case LITERAL_length: { org.antlr.stringtemplate.language.StringTemplateAST tmp14_AST_in = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,LITERAL_length); _t = _t.getNextSibling(); a=singleFunctionArg(_t); _t = _retTree; value=chunk.length(a); break; } case LITERAL_strip: { org.antlr.stringtemplate.language.StringTemplateAST tmp15_AST_in = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,LITERAL_strip); _t = _t.getNextSibling(); a=singleFunctionArg(_t); _t = _retTree; value=chunk.strip(a); break; } case LITERAL_trunc: { org.antlr.stringtemplate.language.StringTemplateAST tmp16_AST_in = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,LITERAL_trunc); _t = _t.getNextSibling(); a=singleFunctionArg(_t); _t = _retTree; value=chunk.trunc(a); break; } default: { throw new NoViableAltException(_t); } } } _t = __t21; _t = _t.getNextSibling(); } catch (RecognitionException ex) { reportError(ex); if (_t!=null) {_t = _t.getNextSibling();} } _retTree = _t; return value; } /** create a new list of expressions as a new multi-value attribute */ public final Object list(AST _t) throws RecognitionException { Object value=null; org.antlr.stringtemplate.language.StringTemplateAST list_AST_in = (_t == ASTNULL) ? null : (org.antlr.stringtemplate.language.StringTemplateAST)_t; Object e = null; List elements = new ArrayList(); try { // for error handling AST __t6 = _t; org.antlr.stringtemplate.language.StringTemplateAST tmp17_AST_in = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,LIST); _t = _t.getFirstChild(); { int _cnt8=0; _loop8: do { if (_t==null) _t=ASTNULL; switch ( _t.getType()) { case APPLY: case MULTI_APPLY: case INCLUDE: case VALUE: case FUNCTION: case LIST: case ID: case PLUS: case DOT: case ANONYMOUS_TEMPLATE: case STRING: case INT: { e=expr(_t); _t = _retTree; if ( e!=null ) { elements.add(e); } break; } case NOTHING: { org.antlr.stringtemplate.language.StringTemplateAST tmp18_AST_in = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,NOTHING); _t = _t.getNextSibling(); List nullSingleton = new ArrayList() {{add(null);}}; elements.add(nullSingleton.iterator()); // add a blank break; } default: { if ( _cnt8>=1 ) { break _loop8; } else {throw new NoViableAltException(_t);} } } _cnt8++; } while (true); } _t = __t6; _t = _t.getNextSibling(); value = new Cat(elements); } catch (RecognitionException ex) { reportError(ex); if (_t!=null) {_t = _t.getNextSibling();} } _retTree = _t; return value; } public final void template(AST _t, Vector templatesToApply ) throws RecognitionException { org.antlr.stringtemplate.language.StringTemplateAST template_AST_in = (_t == ASTNULL) ? null : (org.antlr.stringtemplate.language.StringTemplateAST)_t; org.antlr.stringtemplate.language.StringTemplateAST t = null; org.antlr.stringtemplate.language.StringTemplateAST args = null; org.antlr.stringtemplate.language.StringTemplateAST anon = null; org.antlr.stringtemplate.language.StringTemplateAST args2 = null; Map argumentContext = null; Object n = null; try { // for error handling AST __t26 = _t; org.antlr.stringtemplate.language.StringTemplateAST tmp19_AST_in = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,TEMPLATE); _t = _t.getFirstChild(); { if (_t==null) _t=ASTNULL; switch ( _t.getType()) { case ID: { t = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,ID); _t = _t.getNextSibling(); args = (org.antlr.stringtemplate.language.StringTemplateAST)_t; if ( _t==null ) throw new MismatchedTokenException(); _t = _t.getNextSibling(); String templateName = t.getText(); StringTemplateGroup group = self.getGroup(); StringTemplate embedded = group.getEmbeddedInstanceOf(self, templateName); if ( embedded!=null ) { embedded.setArgumentsAST(args); templatesToApply.addElement(embedded); } break; } case ANONYMOUS_TEMPLATE: { anon = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,ANONYMOUS_TEMPLATE); _t = _t.getNextSibling(); StringTemplate anonymous = anon.getStringTemplate(); // to properly see overridden templates, always set // anonymous' group to be self's group anonymous.setGroup(self.getGroup()); templatesToApply.addElement(anonymous); break; } case VALUE: { AST __t28 = _t; org.antlr.stringtemplate.language.StringTemplateAST tmp20_AST_in = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,VALUE); _t = _t.getFirstChild(); n=expr(_t); _t = _retTree; args2 = (org.antlr.stringtemplate.language.StringTemplateAST)_t; if ( _t==null ) throw new MismatchedTokenException(); _t = _t.getNextSibling(); StringTemplate embedded = null; if ( n!=null ) { String templateName = n.toString(); StringTemplateGroup group = self.getGroup(); embedded = group.getEmbeddedInstanceOf(self, templateName); if ( embedded!=null ) { embedded.setArgumentsAST(args2); templatesToApply.addElement(embedded); } } _t = __t28; _t = _t.getNextSibling(); break; } default: { throw new NoViableAltException(_t); } } } _t = __t26; _t = _t.getNextSibling(); } catch (RecognitionException ex) { reportError(ex); if (_t!=null) {_t = _t.getNextSibling();} } _retTree = _t; } public final Object singleFunctionArg(AST _t) throws RecognitionException { Object value=null; org.antlr.stringtemplate.language.StringTemplateAST singleFunctionArg_AST_in = (_t == ASTNULL) ? null : (org.antlr.stringtemplate.language.StringTemplateAST)_t; try { // for error handling AST __t24 = _t; org.antlr.stringtemplate.language.StringTemplateAST tmp21_AST_in = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,SINGLEVALUEARG); _t = _t.getFirstChild(); value=expr(_t); _t = _retTree; _t = __t24; _t = _t.getNextSibling(); } catch (RecognitionException ex) { reportError(ex); if (_t!=null) {_t = _t.getNextSibling();} } _retTree = _t; return value; } public final boolean ifCondition(AST _t) throws RecognitionException { boolean value=false; org.antlr.stringtemplate.language.StringTemplateAST ifCondition_AST_in = (_t == ASTNULL) ? null : (org.antlr.stringtemplate.language.StringTemplateAST)_t; Object a=null, b=null; try { // for error handling if (_t==null) _t=ASTNULL; switch ( _t.getType()) { case APPLY: case MULTI_APPLY: case INCLUDE: case VALUE: case FUNCTION: case LIST: case ID: case PLUS: case DOT: case ANONYMOUS_TEMPLATE: case STRING: case INT: { a=ifAtom(_t); _t = _retTree; value = chunk.testAttributeTrue(a); break; } case NOT: { AST __t30 = _t; org.antlr.stringtemplate.language.StringTemplateAST tmp22_AST_in = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,NOT); _t = _t.getFirstChild(); a=ifAtom(_t); _t = _retTree; _t = __t30; _t = _t.getNextSibling(); value = !chunk.testAttributeTrue(a); break; } default: { throw new NoViableAltException(_t); } } } catch (RecognitionException ex) { reportError(ex); if (_t!=null) {_t = _t.getNextSibling();} } _retTree = _t; return value; } public final Object ifAtom(AST _t) throws RecognitionException { Object value=null; org.antlr.stringtemplate.language.StringTemplateAST ifAtom_AST_in = (_t == ASTNULL) ? null : (org.antlr.stringtemplate.language.StringTemplateAST)_t; try { // for error handling value=expr(_t); _t = _retTree; } catch (RecognitionException ex) { reportError(ex); if (_t!=null) {_t = _t.getNextSibling();} } _retTree = _t; return value; } /** self is assumed to be the enclosing context as foo(x=y) must find y in * the template that encloses the ref to foo(x=y). We must pass in * the embedded template (the one invoked) so we can check formal args * in rawSetArgumentAttribute. */ public final Map argList(AST _t, StringTemplate embedded, Map initialContext ) throws RecognitionException { Map argumentContext=null; org.antlr.stringtemplate.language.StringTemplateAST argList_AST_in = (_t == ASTNULL) ? null : (org.antlr.stringtemplate.language.StringTemplateAST)_t; argumentContext = initialContext; if ( argumentContext==null ) { argumentContext=new HashMap(); } try { // for error handling if (_t==null) _t=ASTNULL; switch ( _t.getType()) { case ARGS: { AST __t37 = _t; org.antlr.stringtemplate.language.StringTemplateAST tmp23_AST_in = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,ARGS); _t = _t.getFirstChild(); { _loop39: do { if (_t==null) _t=ASTNULL; if ((_t.getType()==ASSIGN||_t.getType()==DOTDOTDOT)) { argumentAssignment(_t,embedded,argumentContext); _t = _retTree; } else { break _loop39; } } while (true); } _t = __t37; _t = _t.getNextSibling(); break; } case SINGLEVALUEARG: { singleTemplateArg(_t,embedded,argumentContext); _t = _retTree; break; } default: { throw new NoViableAltException(_t); } } } catch (RecognitionException ex) { reportError(ex); if (_t!=null) {_t = _t.getNextSibling();} } _retTree = _t; return argumentContext; } public final void argumentAssignment(AST _t, StringTemplate embedded, Map argumentContext ) throws RecognitionException { org.antlr.stringtemplate.language.StringTemplateAST argumentAssignment_AST_in = (_t == ASTNULL) ? null : (org.antlr.stringtemplate.language.StringTemplateAST)_t; org.antlr.stringtemplate.language.StringTemplateAST arg = null; Object e = null; try { // for error handling if (_t==null) _t=ASTNULL; switch ( _t.getType()) { case ASSIGN: { AST __t43 = _t; org.antlr.stringtemplate.language.StringTemplateAST tmp24_AST_in = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,ASSIGN); _t = _t.getFirstChild(); arg = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,ID); _t = _t.getNextSibling(); e=expr(_t); _t = _retTree; _t = __t43; _t = _t.getNextSibling(); if ( e!=null ) { self.rawSetArgumentAttribute(embedded,argumentContext,arg.getText(),e); } break; } case DOTDOTDOT: { org.antlr.stringtemplate.language.StringTemplateAST tmp25_AST_in = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,DOTDOTDOT); _t = _t.getNextSibling(); embedded.setPassThroughAttributes(true); break; } default: { throw new NoViableAltException(_t); } } } catch (RecognitionException ex) { reportError(ex); if (_t!=null) {_t = _t.getNextSibling();} } _retTree = _t; } public final void singleTemplateArg(AST _t, StringTemplate embedded, Map argumentContext ) throws RecognitionException { org.antlr.stringtemplate.language.StringTemplateAST singleTemplateArg_AST_in = (_t == ASTNULL) ? null : (org.antlr.stringtemplate.language.StringTemplateAST)_t; Object e = null; try { // for error handling AST __t41 = _t; org.antlr.stringtemplate.language.StringTemplateAST tmp26_AST_in = (org.antlr.stringtemplate.language.StringTemplateAST)_t; match(_t,SINGLEVALUEARG); _t = _t.getFirstChild(); e=expr(_t); _t = _retTree; _t = __t41; _t = _t.getNextSibling(); if ( e!=null ) { String soleArgName = null; // find the sole defined formal argument for embedded boolean error = false; Map formalArgs = embedded.getFormalArguments(); if ( formalArgs!=null ) { Set argNames = formalArgs.keySet(); if ( argNames.size()==1 ) { soleArgName = (String)argNames.toArray()[0]; //System.out.println("sole formal arg of "+embedded.getName()+" is "+soleArgName); } else { error=true; } } else { error=true; } if ( error ) { self.error("template "+embedded.getName()+ " must have exactly one formal arg in template context "+ self.getEnclosingInstanceStackString()); } else { self.rawSetArgumentAttribute(embedded,argumentContext,soleArgName,e); } } } catch (RecognitionException ex) { reportError(ex); if (_t!=null) {_t = _t.getNextSibling();} } _retTree = _t; } public static final String[] _tokenNames = { "<0>", "EOF", "<2>", "NULL_TREE_LOOKAHEAD", "APPLY", "MULTI_APPLY", "ARGS", "INCLUDE", "\"if\"", "VALUE", "TEMPLATE", "FUNCTION", "SINGLEVALUEARG", "LIST", "NOTHING", "SEMI", "LPAREN", "RPAREN", "\"elseif\"", "COMMA", "ID", "ASSIGN", "COLON", "NOT", "PLUS", "DOT", "\"first\"", "\"rest\"", "\"last\"", "\"length\"", "\"strip\"", "\"trunc\"", "\"super\"", "ANONYMOUS_TEMPLATE", "STRING", "INT", "LBRACK", "RBRACK", "DOTDOTDOT", "TEMPLATE_ARGS", "NESTED_ANONYMOUS_TEMPLATE", "ESC_CHAR", "WS", "WS_CHAR" }; private static final long[] mk_tokenSet_0() { long[] data = { 60180933296L, 0L}; return data; } public static final BitSet _tokenSet_0 = new BitSet(mk_tokenSet_0()); } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/InterfaceParser.javastringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/InterfaceParse0000644000175000017500000001407311274602752034127 0ustar twernertwerner// $ANTLR 2.7.7 (20060906): "interface.g" -> "InterfaceParser.java"$ /* [The "BSD licence"] Copyright (c) 2003-2004 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.language; import org.antlr.stringtemplate.*; import java.util.*; import antlr.TokenBuffer; import antlr.TokenStreamException; import antlr.TokenStreamIOException; import antlr.ANTLRException; import antlr.LLkParser; import antlr.Token; import antlr.TokenStream; import antlr.RecognitionException; import antlr.NoViableAltException; import antlr.MismatchedTokenException; import antlr.SemanticException; import antlr.ParserSharedInputState; import antlr.collections.impl.BitSet; /** Match an ST group interface. Just a list of template names with args. * Here is a sample interface file: * * interface nfa; * nfa(states,edges); * optional state(name); */ public class InterfaceParser extends antlr.LLkParser implements InterfaceParserTokenTypes { protected StringTemplateGroupInterface groupI; public void reportError(RecognitionException e) { if ( groupI!=null ) { groupI.error("template group interface parse error", e); } else { System.err.println("template group interface parse error: "+e); e.printStackTrace(System.err); } } protected InterfaceParser(TokenBuffer tokenBuf, int k) { super(tokenBuf,k); tokenNames = _tokenNames; } public InterfaceParser(TokenBuffer tokenBuf) { this(tokenBuf,3); } protected InterfaceParser(TokenStream lexer, int k) { super(lexer,k); tokenNames = _tokenNames; } public InterfaceParser(TokenStream lexer) { this(lexer,3); } public InterfaceParser(ParserSharedInputState state) { super(state,3); tokenNames = _tokenNames; } public final void groupInterface( StringTemplateGroupInterface groupI ) throws RecognitionException, TokenStreamException { Token name = null; this.groupI = groupI; try { // for error handling match(LITERAL_interface); name = LT(1); match(ID); groupI.setName(name.getText()); match(SEMI); { int _cnt3=0; _loop3: do { if ((LA(1)==ID||LA(1)==LITERAL_optional)) { template(groupI); } else { if ( _cnt3>=1 ) { break _loop3; } else {throw new NoViableAltException(LT(1), getFilename());} } _cnt3++; } while (true); } } catch (RecognitionException ex) { reportError(ex); recover(ex,_tokenSet_0); } } public final void template( StringTemplateGroupInterface groupI ) throws RecognitionException, TokenStreamException { Token opt = null; Token name = null; LinkedHashMap formalArgs = new LinkedHashMap(); // leave blank if no args String templateName=null; try { // for error handling { switch ( LA(1)) { case LITERAL_optional: { opt = LT(1); match(LITERAL_optional); break; } case ID: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } name = LT(1); match(ID); match(LPAREN); { switch ( LA(1)) { case ID: { formalArgs=args(); break; } case RPAREN: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } match(RPAREN); match(SEMI); templateName = name.getText(); groupI.defineTemplate(templateName, formalArgs, opt!=null); } catch (RecognitionException ex) { reportError(ex); recover(ex,_tokenSet_1); } } public final LinkedHashMap args() throws RecognitionException, TokenStreamException { LinkedHashMap args=new LinkedHashMap(); Token a = null; Token b = null; try { // for error handling a = LT(1); match(ID); args.put(a.getText(), new FormalArgument(a.getText())); { _loop9: do { if ((LA(1)==COMMA)) { match(COMMA); b = LT(1); match(ID); args.put(b.getText(), new FormalArgument(b.getText())); } else { break _loop9; } } while (true); } } catch (RecognitionException ex) { reportError(ex); recover(ex,_tokenSet_2); } return args; } public static final String[] _tokenNames = { "<0>", "EOF", "<2>", "NULL_TREE_LOOKAHEAD", "\"interface\"", "ID", "SEMI", "\"optional\"", "LPAREN", "RPAREN", "COMMA", "COLON", "SL_COMMENT", "ML_COMMENT", "WS" }; private static final long[] mk_tokenSet_0() { long[] data = { 2L, 0L}; return data; } public static final BitSet _tokenSet_0 = new BitSet(mk_tokenSet_0()); private static final long[] mk_tokenSet_1() { long[] data = { 162L, 0L}; return data; } public static final BitSet _tokenSet_1 = new BitSet(mk_tokenSet_1()); private static final long[] mk_tokenSet_2() { long[] data = { 512L, 0L}; return data; } public static final BitSet _tokenSet_2 = new BitSet(mk_tokenSet_2()); } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/InterfaceParser.smapstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/InterfaceParse0000644000175000017500000000166111274602752034126 0ustar twernertwernerSMAP InterfaceParser.java G *S G *F + 0 interface.g interface.g *L 1:3 1:4 1:5 1:6 1:8 1:9 1:10 1:11 1:12 1:13 1:14 1:15 1:16 1:17 1:19 1:20 1:21 1:22 1:23 1:24 1:25 1:26 1:27 1:28 1:29 1:30 1:31 1:32 48:58 50:60 51:61 52:62 53:63 54:64 55:65 56:66 57:67 58:68 61:93 61:94 61:95 61:98 61:100 61:120 61:121 61:122 61:123 61:124 61:125 63:97 63:101 63:102 63:103 63:104 63:105 64:107 64:108 64:109 64:110 64:111 64:112 64:113 64:114 64:115 64:117 64:118 64:119 67:127 67:128 67:129 67:138 67:183 67:184 67:185 67:186 67:187 67:188 68:134 69:135 72:131 72:132 72:140 72:141 72:142 72:143 72:144 72:151 72:152 72:153 72:154 72:155 72:157 72:158 72:159 72:161 72:162 72:163 72:164 72:171 72:172 72:173 72:174 72:175 72:177 72:178 74:180 75:181 79:190 79:191 79:196 79:215 79:216 79:217 79:218 79:219 79:220 79:221 80:193 80:197 80:198 80:199 81:194 81:200 81:201 81:202 81:203 81:204 81:205 81:206 81:207 81:208 81:209 81:210 81:211 81:213 81:214 *E ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/ActionParserTokenTypes.javastringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/ActionParserTo0000644000175000017500000000471111274602752034127 0ustar twernertwerner// $ANTLR 2.7.7 (20060906): "action.g" -> "ActionParser.java"$ /* [The "BSD licence"] Copyright (c) 2003-2004 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.language; import org.antlr.stringtemplate.*; import java.util.*; public interface ActionParserTokenTypes { int EOF = 1; int NULL_TREE_LOOKAHEAD = 3; int APPLY = 4; int MULTI_APPLY = 5; int ARGS = 6; int INCLUDE = 7; int CONDITIONAL = 8; int VALUE = 9; int TEMPLATE = 10; int FUNCTION = 11; int SINGLEVALUEARG = 12; int LIST = 13; int NOTHING = 14; int SEMI = 15; int LPAREN = 16; int RPAREN = 17; int LITERAL_elseif = 18; int COMMA = 19; int ID = 20; int ASSIGN = 21; int COLON = 22; int NOT = 23; int PLUS = 24; int DOT = 25; int LITERAL_first = 26; int LITERAL_rest = 27; int LITERAL_last = 28; int LITERAL_length = 29; int LITERAL_strip = 30; int LITERAL_trunc = 31; int LITERAL_super = 32; int ANONYMOUS_TEMPLATE = 33; int STRING = 34; int INT = 35; int LBRACK = 36; int RBRACK = 37; int DOTDOTDOT = 38; int TEMPLATE_ARGS = 39; int NESTED_ANONYMOUS_TEMPLATE = 40; int ESC_CHAR = 41; int WS = 42; int WS_CHAR = 43; } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/GroupLexer.javastringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/GroupLexer.jav0000644000175000017500000005733511274602752034117 0ustar twernertwerner// $ANTLR 2.7.7 (20060906): "group.g" -> "GroupLexer.java"$ /* [The "BSD licence"] Copyright (c) 2003-2004 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.language; import org.antlr.stringtemplate.*; import java.util.*; import java.io.InputStream; import antlr.TokenStreamException; import antlr.TokenStreamIOException; import antlr.TokenStreamRecognitionException; import antlr.CharStreamException; import antlr.CharStreamIOException; import antlr.ANTLRException; import java.io.Reader; import java.util.Hashtable; import antlr.CharScanner; import antlr.InputBuffer; import antlr.ByteBuffer; import antlr.CharBuffer; import antlr.Token; import antlr.CommonToken; import antlr.RecognitionException; import antlr.NoViableAltForCharException; import antlr.MismatchedCharException; import antlr.TokenStream; import antlr.ANTLRHashString; import antlr.LexerSharedInputState; import antlr.collections.impl.BitSet; import antlr.SemanticException; public class GroupLexer extends antlr.CharScanner implements GroupParserTokenTypes, TokenStream { public GroupLexer(InputStream in) { this(new ByteBuffer(in)); } public GroupLexer(Reader in) { this(new CharBuffer(in)); } public GroupLexer(InputBuffer ib) { this(new LexerSharedInputState(ib)); } public GroupLexer(LexerSharedInputState state) { super(state); caseSensitiveLiterals = true; setCaseSensitive(true); literals = new Hashtable(); literals.put(new ANTLRHashString("default", this), new Integer(21)); literals.put(new ANTLRHashString("group", this), new Integer(4)); literals.put(new ANTLRHashString("implements", this), new Integer(7)); } public Token nextToken() throws TokenStreamException { Token theRetToken=null; tryAgain: for (;;) { Token _token = null; int _ttype = Token.INVALID_TYPE; resetText(); try { // for char stream error handling try { // for lexical error handling switch ( LA(1)) { case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': { mID(true); theRetToken=_returnToken; break; } case '"': { mSTRING(true); theRetToken=_returnToken; break; } case '<': { mBIGSTRING(true); theRetToken=_returnToken; break; } case '{': { mANONYMOUS_TEMPLATE(true); theRetToken=_returnToken; break; } case '@': { mAT(true); theRetToken=_returnToken; break; } case '(': { mLPAREN(true); theRetToken=_returnToken; break; } case ')': { mRPAREN(true); theRetToken=_returnToken; break; } case '[': { mLBRACK(true); theRetToken=_returnToken; break; } case ']': { mRBRACK(true); theRetToken=_returnToken; break; } case ',': { mCOMMA(true); theRetToken=_returnToken; break; } case '.': { mDOT(true); theRetToken=_returnToken; break; } case ';': { mSEMI(true); theRetToken=_returnToken; break; } case '*': { mSTAR(true); theRetToken=_returnToken; break; } case '+': { mPLUS(true); theRetToken=_returnToken; break; } case '=': { mASSIGN(true); theRetToken=_returnToken; break; } case '?': { mOPTIONAL(true); theRetToken=_returnToken; break; } case '\t': case '\n': case '\u000c': case '\r': case ' ': { mWS(true); theRetToken=_returnToken; break; } default: if ((LA(1)==':') && (LA(2)==':')) { mDEFINED_TO_BE(true); theRetToken=_returnToken; } else if ((LA(1)=='/') && (LA(2)=='/')) { mSL_COMMENT(true); theRetToken=_returnToken; } else if ((LA(1)=='/') && (LA(2)=='*')) { mML_COMMENT(true); theRetToken=_returnToken; } else if ((LA(1)==':') && (true)) { mCOLON(true); theRetToken=_returnToken; } else { if (LA(1)==EOF_CHAR) {uponEOF(); _returnToken = makeToken(Token.EOF_TYPE);} else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } } if ( _returnToken==null ) continue tryAgain; // found SKIP token _ttype = _returnToken.getType(); _returnToken.setType(_ttype); return _returnToken; } catch (RecognitionException e) { throw new TokenStreamRecognitionException(e); } } catch (CharStreamException cse) { if ( cse instanceof CharStreamIOException ) { throw new TokenStreamIOException(((CharStreamIOException)cse).io); } else { throw new TokenStreamException(cse.getMessage()); } } } } public final void mID(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = ID; int _saveIndex; { switch ( LA(1)) { case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': { matchRange('a','z'); break; } case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': { matchRange('A','Z'); break; } case '_': { match('_'); break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } { _loop29: do { switch ( LA(1)) { case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': { matchRange('a','z'); break; } case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': { matchRange('A','Z'); break; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { matchRange('0','9'); break; } case '-': { match('-'); break; } case '_': { match('_'); break; } default: { break _loop29; } } } while (true); } _ttype = testLiteralsTable(_ttype); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mSTRING(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = STRING; int _saveIndex; _saveIndex=text.length(); match('"'); text.setLength(_saveIndex); { _loop32: do { if ((LA(1)=='\\') && (LA(2)=='"')) { _saveIndex=text.length(); match('\\'); text.setLength(_saveIndex); match('"'); } else if ((LA(1)=='\\') && (_tokenSet_0.member(LA(2)))) { match('\\'); matchNot('"'); } else if ((_tokenSet_1.member(LA(1)))) { matchNot('"'); } else { break _loop32; } } while (true); } _saveIndex=text.length(); match('"'); text.setLength(_saveIndex); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mBIGSTRING(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = BIGSTRING; int _saveIndex; _saveIndex=text.length(); match("<<"); text.setLength(_saveIndex); { if ((LA(1)=='\n'||LA(1)=='\r') && ((LA(2) >= '\u0000' && LA(2) <= '\ufffe'))) { { switch ( LA(1)) { case '\r': { _saveIndex=text.length(); match('\r'); text.setLength(_saveIndex); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } _saveIndex=text.length(); match('\n'); text.setLength(_saveIndex); newline(); } else if (((LA(1) >= '\u0000' && LA(1) <= '\ufffe')) && ((LA(2) >= '\u0000' && LA(2) <= '\ufffe'))) { } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } { _loop38: do { // nongreedy exit test if ((LA(1)=='>') && (LA(2)=='>')) break _loop38; if (((LA(1)=='\r') && (LA(2)=='\n'))&&(LA(3)=='>'&&LA(4)=='>')) { _saveIndex=text.length(); match('\r'); text.setLength(_saveIndex); _saveIndex=text.length(); match('\n'); text.setLength(_saveIndex); newline(); } else if (((LA(1)=='\n') && ((LA(2) >= '\u0000' && LA(2) <= '\ufffe')))&&(LA(2)=='>'&&LA(3)=='>')) { _saveIndex=text.length(); match('\n'); text.setLength(_saveIndex); newline(); } else if ((LA(1)=='\n'||LA(1)=='\r') && ((LA(2) >= '\u0000' && LA(2) <= '\ufffe'))) { { switch ( LA(1)) { case '\r': { match('\r'); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } match('\n'); newline(); } else if ((LA(1)=='\\') && (LA(2)=='>')) { _saveIndex=text.length(); match('\\'); text.setLength(_saveIndex); match('>'); } else if (((LA(1) >= '\u0000' && LA(1) <= '\ufffe')) && ((LA(2) >= '\u0000' && LA(2) <= '\ufffe'))) { matchNot(EOF_CHAR); } else { break _loop38; } } while (true); } _saveIndex=text.length(); match(">>"); text.setLength(_saveIndex); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mANONYMOUS_TEMPLATE(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = ANONYMOUS_TEMPLATE; int _saveIndex; List args=null; StringTemplateToken t = null; _saveIndex=text.length(); match('{'); text.setLength(_saveIndex); { _loop42: do { // nongreedy exit test if ((LA(1)=='}') && (true)) break _loop42; if ((LA(1)=='\n'||LA(1)=='\r') && ((LA(2) >= '\u0000' && LA(2) <= '\ufffe'))) { { switch ( LA(1)) { case '\r': { match('\r'); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } match('\n'); newline(); } else if ((LA(1)=='\\') && (LA(2)=='}')) { _saveIndex=text.length(); match('\\'); text.setLength(_saveIndex); match('}'); } else if (((LA(1) >= '\u0000' && LA(1) <= '\ufffe')) && ((LA(2) >= '\u0000' && LA(2) <= '\ufffe'))) { matchNot(EOF_CHAR); } else { break _loop42; } } while (true); } _saveIndex=text.length(); match('}'); text.setLength(_saveIndex); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mAT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = AT; int _saveIndex; match('@'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mLPAREN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = LPAREN; int _saveIndex; match('('); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mRPAREN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = RPAREN; int _saveIndex; match(')'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mLBRACK(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = LBRACK; int _saveIndex; match('['); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mRBRACK(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = RBRACK; int _saveIndex; match(']'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mCOMMA(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = COMMA; int _saveIndex; match(','); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mDOT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = DOT; int _saveIndex; match('.'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mDEFINED_TO_BE(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = DEFINED_TO_BE; int _saveIndex; match("::="); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mSEMI(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = SEMI; int _saveIndex; match(';'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mCOLON(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = COLON; int _saveIndex; match(':'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mSTAR(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = STAR; int _saveIndex; match('*'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mPLUS(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = PLUS; int _saveIndex; match('+'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mASSIGN(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = ASSIGN; int _saveIndex; match('='); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mOPTIONAL(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = OPTIONAL; int _saveIndex; match('?'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mSL_COMMENT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = SL_COMMENT; int _saveIndex; match("//"); { _loop60: do { if ((_tokenSet_2.member(LA(1)))) { { match(_tokenSet_2); } } else { break _loop60; } } while (true); } { if ((LA(1)=='\n'||LA(1)=='\r')) { { switch ( LA(1)) { case '\r': { match('\r'); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } match('\n'); } else { } } _ttype = Token.SKIP; newline(); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mML_COMMENT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = ML_COMMENT; int _saveIndex; match("/*"); { _loop66: do { // nongreedy exit test if ((LA(1)=='*') && (LA(2)=='/')) break _loop66; if ((LA(1)=='\n'||LA(1)=='\r') && ((LA(2) >= '\u0000' && LA(2) <= '\ufffe'))) { { switch ( LA(1)) { case '\r': { match('\r'); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } match('\n'); newline(); } else if (((LA(1) >= '\u0000' && LA(1) <= '\ufffe')) && ((LA(2) >= '\u0000' && LA(2) <= '\ufffe'))) { matchNot(EOF_CHAR); } else { break _loop66; } } while (true); } match("*/"); _ttype = Token.SKIP; if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mWS(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = WS; int _saveIndex; { int _cnt70=0; _loop70: do { switch ( LA(1)) { case ' ': { match(' '); break; } case '\t': { match('\t'); break; } case '\u000c': { match('\f'); break; } case '\n': case '\r': { { switch ( LA(1)) { case '\r': { match('\r'); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } match('\n'); newline(); break; } default: { if ( _cnt70>=1 ) { break _loop70; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } } _cnt70++; } while (true); } _ttype = Token.SKIP; if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } private static final long[] mk_tokenSet_0() { long[] data = new long[2048]; data[0]=-17179869185L; for (int i = 1; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_0 = new BitSet(mk_tokenSet_0()); private static final long[] mk_tokenSet_1() { long[] data = new long[2048]; data[0]=-17179869185L; data[1]=-268435457L; for (int i = 2; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_1 = new BitSet(mk_tokenSet_1()); private static final long[] mk_tokenSet_2() { long[] data = new long[2048]; data[0]=-9217L; for (int i = 1; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_2 = new BitSet(mk_tokenSet_2()); } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/ActionEvaluatorTokenTypes.javastringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/ActionEvaluato0000644000175000017500000000477311274602752034160 0ustar twernertwerner// $ANTLR 2.7.7 (20060906): "eval.g" -> "ActionEvaluator.java"$ /* [The "BSD licence"] Copyright (c) 2003-2004 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.language; import org.antlr.stringtemplate.*; import java.util.*; import java.io.*; import java.lang.reflect.*; public interface ActionEvaluatorTokenTypes { int EOF = 1; int NULL_TREE_LOOKAHEAD = 3; int APPLY = 4; int MULTI_APPLY = 5; int ARGS = 6; int INCLUDE = 7; int CONDITIONAL = 8; int VALUE = 9; int TEMPLATE = 10; int FUNCTION = 11; int SINGLEVALUEARG = 12; int LIST = 13; int NOTHING = 14; int SEMI = 15; int LPAREN = 16; int RPAREN = 17; int LITERAL_elseif = 18; int COMMA = 19; int ID = 20; int ASSIGN = 21; int COLON = 22; int NOT = 23; int PLUS = 24; int DOT = 25; int LITERAL_first = 26; int LITERAL_rest = 27; int LITERAL_last = 28; int LITERAL_length = 29; int LITERAL_strip = 30; int LITERAL_trunc = 31; int LITERAL_super = 32; int ANONYMOUS_TEMPLATE = 33; int STRING = 34; int INT = 35; int LBRACK = 36; int RBRACK = 37; int DOTDOTDOT = 38; int TEMPLATE_ARGS = 39; int NESTED_ANONYMOUS_TEMPLATE = 40; int ESC_CHAR = 41; int WS = 42; int WS_CHAR = 43; } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/GroupParser.smapstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/GroupParser.sm0000644000175000017500000000653411274602752034126 0ustar twernertwernerSMAP GroupParser.java G *S G *F + 0 group.g group.g *L 1:3 1:4 1:5 1:6 1:8 1:9 1:10 1:11 1:12 1:13 1:14 1:15 1:16 1:17 1:19 1:20 1:21 1:22 1:23 1:24 1:25 1:26 1:27 1:28 1:29 1:30 1:31 1:32 62:72 64:74 65:75 66:76 67:77 68:78 69:79 70:80 71:81 72:82 75:107 75:108 75:109 75:119 75:198 75:199 75:200 75:201 75:202 75:203 76:116 79:111 79:120 79:121 79:122 79:123 80:112 80:125 80:126 80:127 80:128 80:129 80:130 80:131 80:139 80:140 80:141 80:142 80:143 81:113 81:146 81:147 81:148 81:149 81:150 81:151 81:152 81:174 81:175 81:176 81:177 81:178 82:114 82:153 82:154 82:155 82:156 82:157 82:158 82:159 82:160 82:161 82:162 82:163 82:164 82:166 82:167 84:180 85:182 85:183 85:184 85:185 85:186 85:187 85:188 85:189 85:190 85:191 85:192 85:193 85:195 85:196 85:197 88:205 88:206 88:207 88:224 88:336 88:344 88:345 88:346 88:347 88:349 88:350 88:351 88:352 88:353 88:354 89:217 90:218 91:219 92:220 93:221 96:209 96:210 96:225 96:227 96:228 96:229 96:230 96:231 96:232 96:233 96:234 96:235 96:286 96:287 96:288 96:289 96:290 98:237 99:238 100:239 101:240 102:241 103:242 104:243 105:244 106:245 107:246 108:247 109:248 110:249 111:250 112:251 113:252 114:253 115:254 116:255 117:256 118:257 119:258 120:259 121:260 122:261 123:262 124:263 125:264 126:265 127:266 129:211 129:270 129:271 129:272 129:273 129:274 131:276 132:277 133:278 134:279 135:280 136:281 137:282 140:292 141:293 142:295 142:296 142:297 142:298 142:301 142:302 142:303 142:306 142:307 142:308 142:309 142:310 143:312 144:313 145:212 145:315 145:316 145:317 145:318 145:319 145:320 145:330 145:331 145:332 145:333 145:334 146:213 146:323 146:324 146:325 146:326 146:327 149:214 149:215 149:337 149:338 149:339 149:340 149:341 149:342 150:343 153:388 153:389 153:390 153:393 153:408 153:409 153:410 153:411 153:412 153:413 154:394 154:395 154:396 154:397 154:398 154:399 154:400 154:401 154:402 154:403 154:404 154:406 154:407 157:415 157:416 157:417 157:426 157:458 157:459 157:460 157:461 157:462 157:463 158:423 161:419 161:427 161:428 162:420 162:430 162:431 162:432 162:433 162:440 162:449 162:451 162:452 162:453 162:454 164:435 165:436 166:437 167:438 169:421 169:441 169:442 169:443 169:444 171:446 172:447 175:457 187:356 187:357 187:358 187:365 187:381 187:382 187:383 187:384 187:385 187:386 188:362 191:360 191:366 191:367 192:368 192:369 194:371 195:372 196:373 197:374 198:375 199:376 200:377 201:378 202:379 206:465 206:466 206:469 206:473 206:474 206:475 206:476 206:477 206:478 206:479 207:470 207:471 207:472 210:481 210:482 210:483 210:486 210:487 210:529 210:530 210:531 210:532 210:533 210:534 210:535 210:536 210:537 210:538 210:539 211:488 211:489 211:490 211:491 211:492 211:493 211:494 211:495 211:496 211:497 211:498 211:499 211:500 211:502 211:503 212:505 212:506 212:507 212:508 212:509 212:516 212:517 212:518 212:519 212:520 213:524 213:525 213:526 216:563 216:564 216:565 216:571 216:576 216:577 216:578 216:579 216:580 216:581 217:568 220:572 220:573 220:574 221:575 224:541 224:542 224:543 224:550 224:556 224:557 224:558 224:559 224:560 224:561 225:547 228:545 228:551 228:552 228:553 228:554 228:555 231:583 231:584 231:590 231:591 231:621 231:622 231:623 231:624 231:625 231:626 231:627 231:628 231:629 231:630 231:631 231:632 232:586 232:592 232:593 232:594 232:595 232:596 233:587 233:599 233:600 233:601 233:602 233:603 234:588 234:606 234:607 234:608 234:609 234:610 234:611 235:612 236:615 236:616 236:617 236:618 *E ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/AngleBracketTemplateLexer.javastringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/AngleBracketTe0000644000175000017500000011613411274602751034047 0ustar twernertwerner// $ANTLR 2.7.7 (20060906): "angle.bracket.template.g" -> "AngleBracketTemplateLexer.java"$ /* [The "BSD licence"] Copyright (c) 2003-2004 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.language; import org.antlr.stringtemplate.*; import java.io.*; import java.io.InputStream; import antlr.TokenStreamException; import antlr.TokenStreamIOException; import antlr.TokenStreamRecognitionException; import antlr.CharStreamException; import antlr.CharStreamIOException; import antlr.ANTLRException; import java.io.Reader; import java.util.Hashtable; import antlr.CharScanner; import antlr.InputBuffer; import antlr.ByteBuffer; import antlr.CharBuffer; import antlr.Token; import antlr.CommonToken; import antlr.RecognitionException; import antlr.NoViableAltForCharException; import antlr.MismatchedCharException; import antlr.TokenStream; import antlr.ANTLRHashString; import antlr.LexerSharedInputState; import antlr.collections.impl.BitSet; import antlr.SemanticException; /** Break up an input text stream into chunks of either plain text * or template actions in "<...>". Treat IF and ENDIF tokens * specially. */ public class AngleBracketTemplateLexer extends antlr.CharScanner implements AngleBracketTemplateLexerTokenTypes, TokenStream { protected String currentIndent = null; protected StringTemplate self; public AngleBracketTemplateLexer(StringTemplate self, Reader r) { this(r); this.self = self; } public void reportError(RecognitionException e) { self.error("<...> chunk lexer error", e); } protected boolean upcomingELSE(int i) throws CharStreamException { return LA(i)=='<'&&LA(i+1)=='e'&&LA(i+2)=='l'&&LA(i+3)=='s'&&LA(i+4)=='e'&& LA(i+5)=='>'; } protected boolean upcomingENDIF(int i) throws CharStreamException { return LA(i)=='<'&&LA(i+1)=='e'&&LA(i+2)=='n'&&LA(i+3)=='d'&&LA(i+4)=='i'&& LA(i+5)=='f'&&LA(i+6)=='>'; } protected boolean upcomingAtEND(int i) throws CharStreamException { return LA(i)=='<'&&LA(i+1)=='@'&&LA(i+2)=='e'&&LA(i+3)=='n'&&LA(i+4)=='d'&&LA(i+5)=='>'; } protected boolean upcomingNewline(int i) throws CharStreamException { return (LA(i)=='\r'&&LA(i+1)=='\n')||LA(i)=='\n'; } public AngleBracketTemplateLexer(InputStream in) { this(new ByteBuffer(in)); } public AngleBracketTemplateLexer(Reader in) { this(new CharBuffer(in)); } public AngleBracketTemplateLexer(InputBuffer ib) { this(new LexerSharedInputState(ib)); } public AngleBracketTemplateLexer(LexerSharedInputState state) { super(state); caseSensitiveLiterals = true; setCaseSensitive(true); literals = new Hashtable(); } public Token nextToken() throws TokenStreamException { Token theRetToken=null; tryAgain: for (;;) { Token _token = null; int _ttype = Token.INVALID_TYPE; resetText(); try { // for char stream error handling try { // for lexical error handling switch ( LA(1)) { case '\n': case '\r': { mNEWLINE(true); theRetToken=_returnToken; break; } case '<': { mACTION(true); theRetToken=_returnToken; break; } default: if (((_tokenSet_0.member(LA(1))))&&(LA(1)!='\r'&&LA(1)!='\n')) { mLITERAL(true); theRetToken=_returnToken; } else { if (LA(1)==EOF_CHAR) {uponEOF(); _returnToken = makeToken(Token.EOF_TYPE);} else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } } if ( _returnToken==null ) continue tryAgain; // found SKIP token _ttype = _returnToken.getType(); _ttype = testLiteralsTable(_ttype); _returnToken.setType(_ttype); return _returnToken; } catch (RecognitionException e) { throw new TokenStreamRecognitionException(e); } } catch (CharStreamException cse) { if ( cse instanceof CharStreamIOException ) { throw new TokenStreamIOException(((CharStreamIOException)cse).io); } else { throw new TokenStreamException(cse.getMessage()); } } } } public final void mLITERAL(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = LITERAL; int _saveIndex; Token ind=null; if (!(LA(1)!='\r'&&LA(1)!='\n')) throw new SemanticException("LA(1)!='\\r'&&LA(1)!='\\n'"); { int _cnt5=0; _loop5: do { int loopStartIndex=text.length(); int col=getColumn(); if ((LA(1)=='\\') && (LA(2)=='<')) { _saveIndex=text.length(); match('\\'); text.setLength(_saveIndex); match('<'); } else if ((LA(1)=='\\') && (LA(2)=='>') && (true) && (true) && (true) && (true) && (true)) { _saveIndex=text.length(); match('\\'); text.setLength(_saveIndex); match('>'); } else if ((LA(1)=='\\') && (LA(2)=='\\') && (true) && (true) && (true) && (true) && (true)) { _saveIndex=text.length(); match('\\'); text.setLength(_saveIndex); match('\\'); } else if ((LA(1)=='\\') && (_tokenSet_1.member(LA(2))) && (true) && (true) && (true) && (true) && (true)) { match('\\'); { match(_tokenSet_1); } } else if ((LA(1)=='\t'||LA(1)==' ') && (true) && (true) && (true) && (true) && (true) && (true)) { mINDENT(true); ind=_returnToken; if ( col==1 && LA(1)=='<' ) { // store indent in ASTExpr not in a literal currentIndent=ind.getText(); text.setLength(loopStartIndex); // reset length to wack text } else currentIndent=null; } else if ((_tokenSet_0.member(LA(1))) && (true) && (true) && (true) && (true) && (true) && (true)) { { match(_tokenSet_0); } } else { if ( _cnt5>=1 ) { break _loop5; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } _cnt5++; } while (true); } if ((new String(text.getBuffer(),_begin,text.length()-_begin)).length()==0) {_ttype = Token.SKIP;} if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mINDENT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = INDENT; int _saveIndex; { int _cnt8=0; _loop8: do { if ((LA(1)==' ') && (true) && (true) && (true) && (true) && (true) && (true)) { match(' '); } else if ((LA(1)=='\t') && (true) && (true) && (true) && (true) && (true) && (true)) { match('\t'); } else { if ( _cnt8>=1 ) { break _loop8; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } _cnt8++; } while (true); } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mNEWLINE(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = NEWLINE; int _saveIndex; { switch ( LA(1)) { case '\r': { match('\r'); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } match('\n'); newline(); currentIndent=null; if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } public final void mACTION(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = ACTION; int _saveIndex; int startCol = getColumn(); if ((LA(1)=='<') && (LA(2)=='\\') && (LA(3)=='\\') && (LA(4)=='>') && (_tokenSet_2.member(LA(5))) && (true) && (true)) { mLINE_BREAK(false); _ttype = Token.SKIP; } else if ((LA(1)=='<') && (LA(2)=='\\') && (_tokenSet_3.member(LA(3))) && (_tokenSet_4.member(LA(4))) && (true) && (true) && (true)) { StringBuffer buf = new StringBuffer(); char uc = '\u0000'; _saveIndex=text.length(); match('<'); text.setLength(_saveIndex); { int _cnt13=0; _loop13: do { if ((LA(1)=='\\')) { uc=mESC_CHAR(false); buf.append(uc); } else { if ( _cnt13>=1 ) { break _loop13; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } _cnt13++; } while (true); } _saveIndex=text.length(); match('>'); text.setLength(_saveIndex); text.setLength(_begin); text.append(buf.toString()); _ttype = LITERAL; } else if ((LA(1)=='<') && (LA(2)=='!') && ((LA(3) >= '\u0001' && LA(3) <= '\ufffe')) && ((LA(4) >= '\u0001' && LA(4) <= '\ufffe')) && (true) && (true) && (true)) { mCOMMENT(false); _ttype = Token.SKIP; } else if ((LA(1)=='<') && (_tokenSet_5.member(LA(2))) && ((LA(3) >= '\u0001' && LA(3) <= '\ufffe')) && (true) && (true) && (true) && (true)) { { if ((LA(1)=='<') && (LA(2)=='i') && (LA(3)=='f') && (LA(4)==' '||LA(4)=='(') && (_tokenSet_6.member(LA(5))) && ((LA(6) >= '\u0001' && LA(6) <= '\ufffe')) && ((LA(7) >= '\u0001' && LA(7) <= '\ufffe'))) { _saveIndex=text.length(); match('<'); text.setLength(_saveIndex); match("if"); { _loop16: do { if ((LA(1)==' ')) { _saveIndex=text.length(); match(' '); text.setLength(_saveIndex); } else { break _loop16; } } while (true); } match("("); mIF_EXPR(false); match(")"); _saveIndex=text.length(); match('>'); text.setLength(_saveIndex); _ttype = TemplateParser.IF; { if ((LA(1)=='\n'||LA(1)=='\r')) { { switch ( LA(1)) { case '\r': { _saveIndex=text.length(); match('\r'); text.setLength(_saveIndex); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } _saveIndex=text.length(); match('\n'); text.setLength(_saveIndex); newline(); } else { } } } else if ((LA(1)=='<') && (LA(2)=='e') && (LA(3)=='l') && (LA(4)=='s') && (LA(5)=='e') && (LA(6)=='i') && (LA(7)=='f')) { _saveIndex=text.length(); match('<'); text.setLength(_saveIndex); match("elseif"); { _loop20: do { if ((LA(1)==' ')) { _saveIndex=text.length(); match(' '); text.setLength(_saveIndex); } else { break _loop20; } } while (true); } match("("); mIF_EXPR(false); match(")"); _saveIndex=text.length(); match('>'); text.setLength(_saveIndex); _ttype = TemplateParser.ELSEIF; { if ((LA(1)=='\n'||LA(1)=='\r')) { { switch ( LA(1)) { case '\r': { _saveIndex=text.length(); match('\r'); text.setLength(_saveIndex); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } _saveIndex=text.length(); match('\n'); text.setLength(_saveIndex); newline(); } else { } } } else if ((LA(1)=='<') && (LA(2)=='e') && (LA(3)=='n') && (LA(4)=='d') && (LA(5)=='i') && (LA(6)=='f') && (LA(7)=='>')) { _saveIndex=text.length(); match('<'); text.setLength(_saveIndex); match("endif"); _saveIndex=text.length(); match('>'); text.setLength(_saveIndex); _ttype = TemplateParser.ENDIF; { if (((LA(1)=='\n'||LA(1)=='\r'))&&(startCol==1)) { { switch ( LA(1)) { case '\r': { _saveIndex=text.length(); match('\r'); text.setLength(_saveIndex); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } _saveIndex=text.length(); match('\n'); text.setLength(_saveIndex); newline(); } else { } } } else if ((LA(1)=='<') && (LA(2)=='e') && (LA(3)=='l') && (LA(4)=='s') && (LA(5)=='e') && (LA(6)=='>') && (true)) { _saveIndex=text.length(); match('<'); text.setLength(_saveIndex); match("else"); _saveIndex=text.length(); match('>'); text.setLength(_saveIndex); _ttype = TemplateParser.ELSE; { if ((LA(1)=='\n'||LA(1)=='\r')) { { switch ( LA(1)) { case '\r': { _saveIndex=text.length(); match('\r'); text.setLength(_saveIndex); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } _saveIndex=text.length(); match('\n'); text.setLength(_saveIndex); newline(); } else { } } } else if ((LA(1)=='<') && (LA(2)=='@') && (_tokenSet_7.member(LA(3))) && ((LA(4) >= '\u0001' && LA(4) <= '\ufffe')) && ((LA(5) >= '\u0001' && LA(5) <= '\ufffe')) && ((LA(6) >= '\u0001' && LA(6) <= '\ufffe')) && (true)) { _saveIndex=text.length(); match('<'); text.setLength(_saveIndex); _saveIndex=text.length(); match('@'); text.setLength(_saveIndex); { int _cnt29=0; _loop29: do { if ((_tokenSet_7.member(LA(1)))) { { match(_tokenSet_7); } } else { if ( _cnt29>=1 ) { break _loop29; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } _cnt29++; } while (true); } { switch ( LA(1)) { case '(': { _saveIndex=text.length(); match("()"); text.setLength(_saveIndex); _saveIndex=text.length(); match('>'); text.setLength(_saveIndex); _ttype = TemplateParser.REGION_REF; break; } case '>': { _saveIndex=text.length(); match('>'); text.setLength(_saveIndex); _ttype = TemplateParser.REGION_DEF; String t=new String(text.getBuffer(),_begin,text.length()-_begin); text.setLength(_begin); text.append(t+"::="); { if ((LA(1)=='\n'||LA(1)=='\r') && ((LA(2) >= '\u0001' && LA(2) <= '\ufffe')) && ((LA(3) >= '\u0001' && LA(3) <= '\ufffe')) && (true) && (true) && (true) && (true)) { { switch ( LA(1)) { case '\r': { _saveIndex=text.length(); match('\r'); text.setLength(_saveIndex); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } _saveIndex=text.length(); match('\n'); text.setLength(_saveIndex); newline(); } else if (((LA(1) >= '\u0001' && LA(1) <= '\ufffe')) && ((LA(2) >= '\u0001' && LA(2) <= '\ufffe')) && (true) && (true) && (true) && (true) && (true)) { } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } boolean atLeft = false; { int _cnt36=0; _loop36: do { if ((((LA(1) >= '\u0001' && LA(1) <= '\ufffe')) && ((LA(2) >= '\u0001' && LA(2) <= '\ufffe')) && (true) && (true) && (true) && (true) && (true))&&(!(upcomingAtEND(1)||(upcomingNewline(1)&&upcomingAtEND(2))))) { { if ((LA(1)=='\n'||LA(1)=='\r') && ((LA(2) >= '\u0001' && LA(2) <= '\ufffe')) && (true) && (true) && (true) && (true) && (true)) { { switch ( LA(1)) { case '\r': { match('\r'); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } match('\n'); newline(); atLeft = true; } else if (((LA(1) >= '\u0001' && LA(1) <= '\ufffe')) && ((LA(2) >= '\u0001' && LA(2) <= '\ufffe')) && (true) && (true) && (true) && (true) && (true)) { matchNot(EOF_CHAR); atLeft = false; } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } else { if ( _cnt36>=1 ) { break _loop36; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } _cnt36++; } while (true); } { if ((LA(1)=='\n'||LA(1)=='\r') && ((LA(2) >= '\u0001' && LA(2) <= '\ufffe')) && (true) && (true) && (true) && (true) && (true)) { { switch ( LA(1)) { case '\r': { _saveIndex=text.length(); match('\r'); text.setLength(_saveIndex); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } _saveIndex=text.length(); match('\n'); text.setLength(_saveIndex); newline(); atLeft = true; } else if (((LA(1) >= '\u0001' && LA(1) <= '\ufffe')) && (true) && (true) && (true) && (true) && (true) && (true)) { } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } { if ((LA(1)=='<') && (LA(2)=='@')) { _saveIndex=text.length(); match("<@end>"); text.setLength(_saveIndex); } else if (((LA(1) >= '\u0001' && LA(1) <= '\ufffe')) && (true)) { matchNot(EOF_CHAR); self.error("missing region "+t+" <@end> tag"); } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } { if (((LA(1)=='\n'||LA(1)=='\r'))&&(atLeft)) { { switch ( LA(1)) { case '\r': { _saveIndex=text.length(); match('\r'); text.setLength(_saveIndex); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } _saveIndex=text.length(); match('\n'); text.setLength(_saveIndex); newline(); } else { } } break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } } else if ((LA(1)=='<') && (_tokenSet_5.member(LA(2))) && ((LA(3) >= '\u0001' && LA(3) <= '\ufffe')) && (true) && (true) && (true) && (true)) { _saveIndex=text.length(); match('<'); text.setLength(_saveIndex); mEXPR(false); _saveIndex=text.length(); match('>'); text.setLength(_saveIndex); } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } ChunkToken t = new ChunkToken(_ttype, new String(text.getBuffer(),_begin,text.length()-_begin), currentIndent); _token = t; } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mLINE_BREAK(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = LINE_BREAK; int _saveIndex; match("<\\\\>"); { switch ( LA(1)) { case '\t': case ' ': { mINDENT(false); break; } case '\n': case '\r': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } { switch ( LA(1)) { case '\r': { match('\r'); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } match('\n'); newline(); { if ((LA(1)=='\t'||LA(1)==' ')) { mINDENT(false); } else { } } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final char mESC_CHAR(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { char uc='\u0000'; int _ttype; Token _token=null; int _begin=text.length(); _ttype = ESC_CHAR; int _saveIndex; Token a=null; Token b=null; Token c=null; Token d=null; if ((LA(1)=='\\') && (LA(2)=='n')) { _saveIndex=text.length(); match("\\n"); text.setLength(_saveIndex); uc = '\n'; } else if ((LA(1)=='\\') && (LA(2)=='r')) { _saveIndex=text.length(); match("\\r"); text.setLength(_saveIndex); uc = '\r'; } else if ((LA(1)=='\\') && (LA(2)=='t')) { _saveIndex=text.length(); match("\\t"); text.setLength(_saveIndex); uc = '\t'; } else if ((LA(1)=='\\') && (LA(2)==' ')) { _saveIndex=text.length(); match("\\ "); text.setLength(_saveIndex); uc = ' '; } else if ((LA(1)=='\\') && (LA(2)=='u')) { _saveIndex=text.length(); match("\\u"); text.setLength(_saveIndex); _saveIndex=text.length(); mHEX(true); text.setLength(_saveIndex); a=_returnToken; _saveIndex=text.length(); mHEX(true); text.setLength(_saveIndex); b=_returnToken; _saveIndex=text.length(); mHEX(true); text.setLength(_saveIndex); c=_returnToken; _saveIndex=text.length(); mHEX(true); text.setLength(_saveIndex); d=_returnToken; uc = (char)Integer.parseInt(a.getText()+b.getText()+c.getText()+d.getText(), 16); } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; return uc; } protected final void mCOMMENT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = COMMENT; int _saveIndex; int startCol = getColumn(); match("') && (true) && (true) && (true) && (true) && (true)) break _loop74; if ((LA(1)=='\n'||LA(1)=='\r') && ((LA(2) >= '\u0001' && LA(2) <= '\ufffe')) && ((LA(3) >= '\u0001' && LA(3) <= '\ufffe')) && (true) && (true) && (true) && (true)) { { switch ( LA(1)) { case '\r': { match('\r'); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } match('\n'); newline(); } else if (((LA(1) >= '\u0001' && LA(1) <= '\ufffe')) && ((LA(2) >= '\u0001' && LA(2) <= '\ufffe')) && ((LA(3) >= '\u0001' && LA(3) <= '\ufffe')) && (true) && (true) && (true) && (true)) { matchNot(EOF_CHAR); } else { break _loop74; } } while (true); } match("!>"); { if (((LA(1)=='\n'||LA(1)=='\r'))&&(startCol==1)) { { switch ( LA(1)) { case '\r': { match('\r'); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } match('\n'); newline(); } else { } } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mIF_EXPR(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = IF_EXPR; int _saveIndex; { int _cnt61=0; _loop61: do { switch ( LA(1)) { case '\\': { mESC(false); break; } case '\n': case '\r': { { switch ( LA(1)) { case '\r': { match('\r'); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } match('\n'); newline(); break; } case '{': { mSUBTEMPLATE(false); break; } case '(': { mNESTED_PARENS(false); break; } default: if ((_tokenSet_8.member(LA(1)))) { matchNot(')'); } else { if ( _cnt61>=1 ) { break _loop61; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } } _cnt61++; } while (true); } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mEXPR(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = EXPR; int _saveIndex; { int _cnt49=0; _loop49: do { switch ( LA(1)) { case '\\': { mESC(false); break; } case '\n': case '\r': { { switch ( LA(1)) { case '\r': { match('\r'); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } match('\n'); newline(); break; } case '{': { mSUBTEMPLATE(false); break; } default: if ((LA(1)=='+'||LA(1)=='=') && (LA(2)=='"'||LA(2)=='<')) { { switch ( LA(1)) { case '=': { match('='); break; } case '+': { match('+'); break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } mTEMPLATE(false); } else if ((LA(1)=='+'||LA(1)=='=') && (LA(2)=='{')) { { switch ( LA(1)) { case '=': { match('='); break; } case '+': { match('+'); break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } mSUBTEMPLATE(false); } else if ((LA(1)=='+'||LA(1)=='=') && (_tokenSet_9.member(LA(2)))) { { switch ( LA(1)) { case '=': { match('='); break; } case '+': { match('+'); break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } { match(_tokenSet_9); } } else if ((_tokenSet_10.member(LA(1)))) { matchNot('>'); } else { if ( _cnt49>=1 ) { break _loop49; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } } _cnt49++; } while (true); } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mESC(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = ESC; int _saveIndex; match('\\'); matchNot(EOF_CHAR); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mSUBTEMPLATE(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = SUBTEMPLATE; int _saveIndex; match('{'); { _loop67: do { switch ( LA(1)) { case '{': { mSUBTEMPLATE(false); break; } case '\\': { mESC(false); break; } default: if ((_tokenSet_11.member(LA(1)))) { matchNot('}'); } else { break _loop67; } } } while (true); } match('}'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mTEMPLATE(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = TEMPLATE; int _saveIndex; switch ( LA(1)) { case '"': { match('"'); { _loop52: do { if ((LA(1)=='\\')) { mESC(false); } else if ((_tokenSet_12.member(LA(1)))) { matchNot('"'); } else { break _loop52; } } while (true); } match('"'); break; } case '<': { match("<<"); { if ((LA(1)=='\n'||LA(1)=='\r') && ((LA(2) >= '\u0001' && LA(2) <= '\ufffe')) && ((LA(3) >= '\u0001' && LA(3) <= '\ufffe')) && ((LA(4) >= '\u0001' && LA(4) <= '\ufffe')) && (true) && (true) && (true)) { { switch ( LA(1)) { case '\r': { _saveIndex=text.length(); match('\r'); text.setLength(_saveIndex); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } _saveIndex=text.length(); match('\n'); text.setLength(_saveIndex); newline(); } else if (((LA(1) >= '\u0001' && LA(1) <= '\ufffe')) && ((LA(2) >= '\u0001' && LA(2) <= '\ufffe')) && ((LA(3) >= '\u0001' && LA(3) <= '\ufffe')) && (true) && (true) && (true) && (true)) { } else { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } { _loop57: do { // nongreedy exit test if ((LA(1)=='>') && (LA(2)=='>') && ((LA(3) >= '\u0001' && LA(3) <= '\ufffe')) && (true) && (true) && (true) && (true)) break _loop57; if (((LA(1)=='\r') && (LA(2)=='\n') && ((LA(3) >= '\u0001' && LA(3) <= '\ufffe')) && ((LA(4) >= '\u0001' && LA(4) <= '\ufffe')) && ((LA(5) >= '\u0001' && LA(5) <= '\ufffe')) && (true) && (true))&&(LA(3)=='>'&&LA(4)=='>')) { _saveIndex=text.length(); match('\r'); text.setLength(_saveIndex); _saveIndex=text.length(); match('\n'); text.setLength(_saveIndex); newline(); } else if (((LA(1)=='\n') && ((LA(2) >= '\u0001' && LA(2) <= '\ufffe')) && ((LA(3) >= '\u0001' && LA(3) <= '\ufffe')) && ((LA(4) >= '\u0001' && LA(4) <= '\ufffe')) && (true) && (true) && (true))&&(LA(2)=='>'&&LA(3)=='>')) { _saveIndex=text.length(); match('\n'); text.setLength(_saveIndex); newline(); } else if ((LA(1)=='\n'||LA(1)=='\r') && ((LA(2) >= '\u0001' && LA(2) <= '\ufffe')) && ((LA(3) >= '\u0001' && LA(3) <= '\ufffe')) && ((LA(4) >= '\u0001' && LA(4) <= '\ufffe')) && (true) && (true) && (true)) { { switch ( LA(1)) { case '\r': { match('\r'); break; } case '\n': { break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } match('\n'); newline(); } else if (((LA(1) >= '\u0001' && LA(1) <= '\ufffe')) && ((LA(2) >= '\u0001' && LA(2) <= '\ufffe')) && ((LA(3) >= '\u0001' && LA(3) <= '\ufffe')) && ((LA(4) >= '\u0001' && LA(4) <= '\ufffe')) && (true) && (true) && (true)) { matchNot(EOF_CHAR); } else { break _loop57; } } while (true); } match(">>"); break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mNESTED_PARENS(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = NESTED_PARENS; int _saveIndex; match('('); { int _cnt70=0; _loop70: do { switch ( LA(1)) { case '(': { mNESTED_PARENS(false); break; } case '\\': { mESC(false); break; } default: if ((_tokenSet_13.member(LA(1)))) { matchNot(')'); } else { if ( _cnt70>=1 ) { break _loop70; } else {throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn());} } } _cnt70++; } while (true); } match(')'); if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } protected final void mHEX(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = HEX; int _saveIndex; switch ( LA(1)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { matchRange('0','9'); break; } case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': { matchRange('A','F'); break; } case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': { matchRange('a','f'); break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; } private static final long[] mk_tokenSet_0() { long[] data = new long[2048]; data[0]=-1152921504606856194L; for (int i = 1; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_0 = new BitSet(mk_tokenSet_0()); private static final long[] mk_tokenSet_1() { long[] data = new long[2048]; data[0]=-5764607523034234882L; for (int i = 1; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_1 = new BitSet(mk_tokenSet_1()); private static final long[] mk_tokenSet_2() { long[] data = new long[1025]; data[0]=4294977024L; return data; } public static final BitSet _tokenSet_2 = new BitSet(mk_tokenSet_2()); private static final long[] mk_tokenSet_3() { long[] data = new long[1025]; data[0]=4294967296L; data[1]=14707067533131776L; return data; } public static final BitSet _tokenSet_3 = new BitSet(mk_tokenSet_3()); private static final long[] mk_tokenSet_4() { long[] data = new long[1025]; data[0]=4899634919602388992L; data[1]=541434314878L; return data; } public static final BitSet _tokenSet_4 = new BitSet(mk_tokenSet_4()); private static final long[] mk_tokenSet_5() { long[] data = new long[2048]; data[0]=-4611686018427387906L; for (int i = 1; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_5 = new BitSet(mk_tokenSet_5()); private static final long[] mk_tokenSet_6() { long[] data = new long[2048]; data[0]=-2199023255554L; for (int i = 1; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_6 = new BitSet(mk_tokenSet_6()); private static final long[] mk_tokenSet_7() { long[] data = new long[2048]; data[0]=-4611687117939015682L; for (int i = 1; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_7 = new BitSet(mk_tokenSet_7()); private static final long[] mk_tokenSet_8() { long[] data = new long[2048]; data[0]=-3298534892546L; data[1]=-576460752571858945L; for (int i = 2; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_8 = new BitSet(mk_tokenSet_8()); private static final long[] mk_tokenSet_9() { long[] data = new long[2048]; data[0]=-1152921521786716162L; data[1]=-576460752303423489L; for (int i = 2; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_9 = new BitSet(mk_tokenSet_9()); private static final long[] mk_tokenSet_10() { long[] data = new long[2048]; data[0]=-6917537823734113282L; data[1]=-576460752571858945L; for (int i = 2; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_10 = new BitSet(mk_tokenSet_10()); private static final long[] mk_tokenSet_11() { long[] data = new long[2048]; data[0]=-2L; data[1]=-2882303761785552897L; for (int i = 2; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_11 = new BitSet(mk_tokenSet_11()); private static final long[] mk_tokenSet_12() { long[] data = new long[2048]; data[0]=-17179869186L; data[1]=-268435457L; for (int i = 2; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_12 = new BitSet(mk_tokenSet_12()); private static final long[] mk_tokenSet_13() { long[] data = new long[2048]; data[0]=-3298534883330L; data[1]=-268435457L; for (int i = 2; i<=1022; i++) { data[i]=-1L; } data[1023]=9223372036854775807L; return data; } public static final BitSet _tokenSet_13 = new BitSet(mk_tokenSet_13()); } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/GroupLexer.smapstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/GroupLexer.sma0000644000175000017500000001062511274602752034106 0ustar twernertwernerSMAP GroupLexer.java G *S G *F + 0 group.g group.g *L 0:104 0:110 0:116 0:122 0:128 0:134 0:140 0:146 0:152 0:158 0:164 0:170 0:176 0:182 0:188 0:194 0:201 0:207 0:211 0:215 0:219 1:3 1:4 1:5 1:6 1:8 1:9 1:10 1:11 1:12 1:13 1:14 1:15 1:16 1:17 1:19 1:20 1:21 1:22 1:23 1:24 1:25 1:26 1:27 1:28 1:29 1:30 1:31 1:32 247:247 247:248 247:249 247:250 247:337 247:338 247:339 247:340 247:341 247:342 247:343 251:253 251:254 251:255 251:256 251:257 251:258 251:259 251:260 251:261 251:262 251:265 251:266 251:267 251:268 251:269 251:270 251:271 251:272 251:273 251:276 251:277 251:278 251:281 251:282 251:283 251:284 251:285 251:287 251:288 251:289 251:290 251:291 251:292 251:293 251:294 251:295 251:296 251:297 251:298 251:299 251:302 251:303 251:304 251:305 251:306 251:307 251:308 251:309 251:310 251:313 251:314 251:315 251:316 251:317 251:320 251:321 251:322 251:325 251:326 251:327 251:330 251:331 251:332 251:333 251:334 251:335 251:336 254:345 254:346 254:347 254:348 254:378 254:379 254:380 254:381 254:382 254:383 255:350 255:351 255:352 255:353 255:354 255:355 255:356 255:357 255:358 255:359 255:360 255:361 255:362 255:363 255:364 255:365 255:366 255:367 255:368 255:369 255:370 255:371 255:373 255:374 255:375 255:376 255:377 258:385 258:386 258:387 258:388 258:485 258:486 258:487 258:488 258:489 258:490 259:390 259:391 259:392 260:394 260:396 260:397 260:398 260:399 260:400 260:401 260:408 260:409 260:410 260:411 260:412 260:414 260:415 260:416 260:417 260:418 260:420 260:421 260:422 260:423 261:426 261:427 261:428 261:429 261:430 261:439 261:445 261:466 261:472 261:475 261:476 261:477 261:478 261:480 261:481 262:431 262:432 262:433 262:434 262:435 262:436 262:437 262:438 263:440 263:441 263:442 263:443 263:444 264:446 264:448 264:449 264:450 264:451 264:458 264:459 264:460 264:461 264:462 264:464 264:465 265:467 265:468 265:469 265:470 265:471 266:473 266:474 268:482 268:483 268:484 271:492 271:493 271:494 271:495 271:548 271:549 271:550 271:551 271:552 271:553 272:497 273:498 276:501 276:502 276:503 277:504 277:505 277:506 277:507 277:508 277:529 277:535 277:538 277:539 277:540 277:541 277:543 277:544 278:509 278:511 278:512 278:513 278:514 278:521 278:522 278:523 278:524 278:525 278:527 278:528 279:530 279:531 279:532 279:533 279:534 280:536 280:537 282:545 282:546 282:547 286:555 286:556 286:557 286:558 286:560 286:561 286:562 286:563 286:564 286:565 286:566 287:568 287:569 287:570 287:571 287:573 287:574 287:575 287:576 287:577 287:578 287:579 288:581 288:582 288:583 288:584 288:586 288:587 288:588 288:589 288:590 288:591 288:592 289:594 289:595 289:596 289:597 289:599 289:600 289:601 289:602 289:603 289:604 289:605 290:607 290:608 290:609 290:610 290:612 290:613 290:614 290:615 290:616 290:617 290:618 291:620 291:621 291:622 291:623 291:625 291:626 291:627 291:628 291:629 291:630 291:631 292:633 292:634 292:635 292:636 292:638 292:639 292:640 292:641 292:642 292:643 292:644 293:646 293:647 293:648 293:649 293:651 293:652 293:653 293:654 293:655 293:656 293:657 294:659 294:660 294:661 294:662 294:664 294:665 294:666 294:667 294:668 294:669 294:670 295:672 295:673 295:674 295:675 295:677 295:678 295:679 295:680 295:681 295:682 295:683 296:685 296:686 296:687 296:688 296:690 296:691 296:692 296:693 296:694 296:695 296:696 297:698 297:699 297:700 297:701 297:703 297:704 297:705 297:706 297:707 297:708 297:709 298:711 298:712 298:713 298:714 298:716 298:717 298:718 298:719 298:720 298:721 298:722 299:724 299:725 299:726 299:727 299:729 299:730 299:731 299:732 299:733 299:734 299:735 302:737 302:738 302:739 302:740 302:783 302:784 302:785 302:786 302:787 302:788 303:742 304:743 304:744 304:745 304:746 304:748 304:750 304:751 304:752 304:753 304:755 304:756 304:758 304:760 304:761 304:762 304:763 304:770 304:771 304:772 304:773 304:774 304:776 304:777 304:779 305:782 309:790 309:791 309:792 309:793 309:833 309:834 309:835 309:836 309:837 309:838 310:795 311:796 311:797 311:798 311:799 311:800 311:821 311:824 311:825 311:826 311:827 311:829 311:830 315:801 315:803 315:804 315:805 315:806 315:813 315:814 315:815 315:816 315:817 315:819 315:820 316:822 316:823 318:831 319:832 323:840 323:841 323:842 323:843 323:846 323:847 323:848 323:849 323:850 323:851 323:852 323:888 323:889 323:890 323:891 323:892 323:893 323:894 323:895 323:897 323:898 323:899 323:900 323:901 323:902 324:855 324:856 324:857 325:860 325:861 325:862 326:865 326:866 326:868 326:869 326:870 326:871 326:878 326:879 326:880 326:881 326:882 326:884 326:885 328:896 *E ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/TemplateParserTokenTypes.javastringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/TemplateParser0000644000175000017500000000404311274602750034156 0ustar twernertwerner// $ANTLR 2.7.7 (20060906): "template.g" -> "TemplateParser.java"$ /* [The "BSD licence"] Copyright (c) 2003-2004 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.language; import org.antlr.stringtemplate.*; import java.io.*; public interface TemplateParserTokenTypes { int EOF = 1; int NULL_TREE_LOOKAHEAD = 3; int LITERAL = 4; int NEWLINE = 5; int ACTION = 6; int IF = 7; int ELSEIF = 8; int ELSE = 9; int ENDIF = 10; int REGION_REF = 11; int REGION_DEF = 12; int EXPR = 13; int TEMPLATE = 14; int IF_EXPR = 15; int ESC_CHAR = 16; int ESC = 17; int HEX = 18; int SUBTEMPLATE = 19; int NESTED_PARENS = 20; int INDENT = 21; int COMMENT = 22; int LINE_BREAK = 23; } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/InterfaceParserTokenTypes.txtstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/InterfaceParse0000644000175000017500000000041011274602752034115 0ustar twernertwerner// $ANTLR 2.7.7 (20060906): interface.g -> InterfaceParserTokenTypes.txt$ InterfaceParser // output token vocab name LITERAL_interface="interface"=4 ID=5 SEMI=6 LITERAL_optional="optional"=7 LPAREN=8 RPAREN=9 COMMA=10 COLON=11 SL_COMMENT=12 ML_COMMENT=13 WS=14 ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/ActionEvaluator.smapstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/ActionEvaluato0000644000175000017500000001410211274602752034143 0ustar twernertwernerSMAP ActionEvaluator.java G *S G *F + 0 eval.g eval.g *L 1:3 1:4 1:5 1:6 1:8 1:9 1:10 1:11 1:12 1:13 1:14 1:15 1:16 1:17 1:19 1:20 1:21 1:22 1:23 1:24 1:25 1:26 1:27 1:28 1:29 1:30 1:31 1:32 1:33 1:34 44:52 45:53 46:54 47:55 49:57 50:58 51:59 53:61 54:62 55:63 56:64 57:65 58:66 60:68 61:69 62:70 65:75 65:76 65:83 65:87 65:88 65:89 65:90 65:91 65:92 65:93 65:94 66:80 69:84 69:85 69:86 72:96 72:97 72:105 72:106 72:107 72:179 72:180 72:181 72:182 72:183 72:184 72:185 72:186 72:187 72:188 72:189 72:190 72:191 73:101 74:102 77:108 77:109 77:110 77:111 77:112 77:113 77:114 77:115 77:116 77:117 77:118 77:119 77:120 78:123 78:124 78:125 78:126 78:127 79:130 79:131 79:132 79:133 79:134 79:135 79:136 79:137 80:140 80:141 80:142 80:143 81:146 81:147 81:148 81:149 82:152 82:153 82:154 82:155 83:158 83:159 83:160 83:161 83:162 83:163 83:164 83:165 83:166 83:167 86:169 87:170 88:171 89:172 90:173 91:174 92:175 97:575 97:576 97:577 97:585 97:640 97:641 97:642 97:643 97:644 97:645 97:646 97:647 98:581 99:582 102:586 102:587 102:588 102:589 102:637 102:638 103:591 103:592 103:593 103:594 103:595 103:596 103:597 103:598 103:599 103:600 103:601 103:602 103:603 103:604 103:605 103:606 103:607 103:608 103:609 103:610 103:629 103:630 103:631 103:632 103:633 103:634 103:635 103:636 105:612 106:613 107:614 109:618 109:619 109:620 109:621 109:622 111:624 112:625 116:639 119:412 119:413 119:425 119:473 119:474 119:475 119:476 119:477 119:478 119:479 119:480 120:420 121:421 122:422 125:426 125:427 125:428 125:429 125:466 125:467 127:416 127:417 127:431 127:432 127:433 127:434 127:435 127:436 127:437 127:438 127:439 127:440 127:460 127:461 127:462 127:463 127:464 128:441 130:418 130:444 130:445 130:446 130:447 130:448 130:449 130:450 130:451 130:452 130:453 130:454 130:455 130:456 131:457 136:469 137:470 138:471 145:193 145:196 145:197 145:207 145:208 145:209 145:279 145:280 145:281 145:282 145:283 145:284 145:285 145:286 145:287 145:288 145:289 145:290 145:291 146:194 146:202 147:195 147:203 148:204 151:210 151:211 151:212 151:213 151:214 151:215 151:216 151:217 151:235 151:236 152:219 152:220 152:221 152:222 152:223 152:224 152:225 152:226 152:227 152:228 152:229 152:231 152:232 152:233 153:234 155:239 155:240 155:241 155:242 155:243 155:244 155:246 155:247 155:248 155:249 155:250 155:251 155:252 155:253 155:254 155:255 155:256 155:257 155:259 155:260 155:261 155:262 155:263 155:264 155:275 155:276 156:200 156:265 156:266 156:267 158:269 159:270 160:271 161:272 162:273 167:482 167:483 167:490 167:566 167:567 167:568 167:569 167:570 167:571 167:572 167:573 168:487 171:491 171:492 171:493 171:494 171:564 171:565 172:496 172:497 172:498 172:499 172:500 172:501 172:502 172:503 172:504 172:505 172:558 172:559 172:560 172:561 172:562 173:508 173:509 173:510 173:511 173:512 173:513 173:514 173:515 174:518 174:519 174:520 174:521 174:522 174:523 174:524 174:525 175:528 175:529 175:530 175:531 175:532 175:533 175:534 175:535 176:538 176:539 176:540 176:541 176:542 176:543 176:544 176:545 177:548 177:549 177:550 177:551 177:552 177:553 177:554 177:555 183:747 183:748 183:752 183:761 183:762 183:763 183:764 183:765 183:766 183:767 183:768 184:753 184:754 184:755 184:756 184:757 184:758 184:759 184:760 187:649 187:650 187:651 187:663 187:739 187:740 187:741 187:742 187:743 187:744 187:745 188:659 189:660 192:664 192:665 192:666 192:667 192:737 192:738 193:654 193:655 193:669 193:670 193:671 193:672 193:673 193:674 193:675 193:676 193:677 193:678 193:731 193:732 193:733 193:734 193:735 195:680 196:681 197:682 198:683 199:684 200:685 201:686 204:656 204:690 204:691 204:692 204:693 204:694 206:696 207:697 208:698 209:699 210:700 213:657 213:704 213:705 213:706 213:707 213:708 213:709 213:710 213:711 213:712 213:713 213:714 213:727 213:728 215:716 216:717 217:718 218:719 219:720 220:721 221:722 222:723 223:724 224:725 231:770 231:771 231:778 231:779 231:780 231:812 231:813 231:814 231:815 231:816 231:817 231:818 231:819 231:820 231:821 231:822 231:823 231:824 232:775 235:781 235:782 235:783 235:784 235:785 235:786 235:787 235:788 235:789 235:790 235:791 235:792 235:793 235:794 235:795 235:796 236:799 236:800 236:801 236:802 236:803 236:804 236:805 236:806 236:807 236:808 236:809 239:826 239:827 239:831 239:834 239:835 239:836 239:837 239:838 239:839 239:840 239:841 240:832 240:833 243:293 243:294 243:308 243:309 243:310 243:398 243:399 243:400 243:401 243:402 243:403 243:404 243:405 243:406 243:407 243:408 243:409 243:410 244:303 245:304 246:305 249:311 249:312 249:313 249:314 249:315 249:316 249:317 249:318 249:349 249:350 250:297 250:320 250:321 250:322 250:323 250:324 250:325 250:326 250:327 250:343 250:344 250:345 250:346 250:347 255:330 255:331 255:332 255:333 255:334 255:335 255:336 255:337 255:338 255:339 255:340 258:351 260:298 260:354 260:355 260:356 260:357 260:358 262:360 265:299 265:364 265:365 265:366 265:367 265:368 265:369 267:300 267:372 267:373 267:374 267:375 267:376 269:378 272:301 272:382 272:383 272:384 272:385 272:386 274:388 275:389 276:390 277:391 278:392 279:393 280:394 289:843 289:848 289:849 289:850 289:851 289:861 289:862 289:863 289:894 289:895 289:896 289:897 289:898 289:899 289:900 289:901 289:902 289:903 289:904 289:905 289:906 290:844 290:855 291:845 291:856 292:846 292:857 293:847 293:858 297:864 297:865 297:866 297:867 297:868 297:869 297:870 297:871 297:872 297:873 297:874 297:875 297:876 297:877 297:878 297:879 297:880 297:882 297:883 297:884 297:885 298:888 298:889 298:890 298:891 301:962 301:963 301:964 301:971 301:1009 301:1010 301:1011 301:1012 301:1013 301:1014 301:1015 302:968 305:972 305:973 305:974 305:975 305:976 305:977 305:978 305:979 307:981 308:982 309:983 310:984 311:985 312:986 313:987 314:988 315:989 316:990 317:991 318:992 319:993 320:994 321:995 322:996 323:997 324:998 325:999 326:1000 327:1001 328:1002 329:1003 330:1004 331:1005 332:1006 333:1007 337:908 337:909 337:910 337:918 337:919 337:920 337:949 337:950 337:951 337:952 337:953 337:954 337:955 337:956 337:957 337:958 337:959 337:960 338:915 341:913 341:921 341:922 341:923 341:924 341:925 341:926 341:927 341:928 341:929 341:930 341:931 341:932 341:933 343:935 344:936 345:937 347:941 347:942 347:943 347:944 347:945 347:946 *E ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/InterfaceLexer.smapstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/InterfaceLexer0000644000175000017500000000413511274602752034132 0ustar twernertwernerSMAP InterfaceLexer.java G *S G *F + 0 interface.g interface.g *L 0:103 0:109 0:115 0:121 0:127 0:133 0:140 0:146 0:150 1:3 1:4 1:5 1:6 1:8 1:9 1:10 1:11 1:12 1:13 1:14 1:15 1:16 1:17 1:19 1:20 1:21 1:22 1:23 1:24 1:25 1:26 1:27 1:28 1:29 1:30 1:31 1:32 92:179 92:180 92:181 92:182 92:185 92:186 92:187 92:188 92:189 92:190 92:191 92:192 92:193 92:194 92:197 92:198 92:199 92:200 92:201 92:202 92:203 92:204 92:205 92:208 92:209 92:210 92:213 92:214 92:215 92:216 92:217 92:219 92:220 92:221 92:222 92:223 92:224 92:225 92:226 92:227 92:228 92:229 92:230 92:231 92:234 92:235 92:236 92:237 92:238 92:239 92:240 92:241 92:242 92:245 92:246 92:247 92:248 92:249 92:252 92:253 92:254 92:257 92:258 92:259 92:262 92:263 92:264 92:265 92:266 92:267 92:268 92:269 92:270 92:271 92:272 92:273 92:274 95:276 95:277 95:278 95:279 95:281 95:282 95:283 95:284 95:285 95:286 95:287 96:289 96:290 96:291 96:292 96:294 96:295 96:296 96:297 96:298 96:299 96:300 97:302 97:303 97:304 97:305 97:307 97:308 97:309 97:310 97:311 97:312 97:313 98:315 98:316 98:317 98:318 98:320 98:321 98:322 98:323 98:324 98:325 98:326 99:328 99:329 99:330 99:331 99:333 99:334 99:335 99:336 99:337 99:338 99:339 102:341 102:342 102:343 102:344 102:387 102:388 102:389 102:390 102:391 102:392 103:346 104:347 104:348 104:349 104:350 104:352 104:354 104:355 104:356 104:357 104:359 104:360 104:362 104:364 104:365 104:366 104:367 104:374 104:375 104:376 104:377 104:378 104:380 104:381 104:383 105:386 109:394 109:395 109:396 109:397 109:437 109:438 109:439 109:440 109:441 109:442 110:399 111:400 111:401 111:402 111:403 111:404 111:425 111:428 111:429 111:430 111:431 111:433 111:434 115:405 115:407 115:408 115:409 115:410 115:417 115:418 115:419 115:420 115:421 115:423 115:424 116:426 116:427 118:435 119:436 123:444 123:445 123:446 123:447 123:450 123:451 123:452 123:453 123:454 123:455 123:456 123:492 123:493 123:494 123:495 123:496 123:497 123:498 123:499 123:501 123:502 123:503 123:504 123:505 123:506 124:459 124:460 124:461 125:464 125:465 125:466 126:469 126:470 126:472 126:473 126:474 126:475 126:482 126:483 126:484 126:485 126:486 126:488 126:489 128:500 *E ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootstringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/TemplateParser.javastringtemplate-3.2.1/target/generated-sources/antlr/org/antlr/stringtemplate/language/TemplateParser0000644000175000017500000002321711274602750034162 0ustar twernertwerner// $ANTLR 2.7.7 (20060906): "template.g" -> "TemplateParser.java"$ /* [The "BSD licence"] Copyright (c) 2003-2004 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.language; import org.antlr.stringtemplate.*; import java.io.*; import antlr.TokenBuffer; import antlr.TokenStreamException; import antlr.TokenStreamIOException; import antlr.ANTLRException; import antlr.LLkParser; import antlr.Token; import antlr.TokenStream; import antlr.RecognitionException; import antlr.NoViableAltException; import antlr.MismatchedTokenException; import antlr.SemanticException; import antlr.ParserSharedInputState; import antlr.collections.impl.BitSet; /** A parser used to break up a single template into chunks, text literals * and attribute expressions. */ public class TemplateParser extends antlr.LLkParser implements TemplateParserTokenTypes { protected StringTemplate self; public void reportError(RecognitionException e) { StringTemplateGroup group = self.getGroup(); if ( group==StringTemplate.defaultGroup ) { self.error("template parse error; template context is "+self.getEnclosingInstanceStackString(), e); } else { self.error("template parse error in group "+self.getGroup().getName()+" line "+self.getGroupFileLine()+"; template context is "+self.getEnclosingInstanceStackString(), e); } } protected TemplateParser(TokenBuffer tokenBuf, int k) { super(tokenBuf,k); tokenNames = _tokenNames; } public TemplateParser(TokenBuffer tokenBuf) { this(tokenBuf,1); } protected TemplateParser(TokenStream lexer, int k) { super(lexer,k); tokenNames = _tokenNames; } public TemplateParser(TokenStream lexer) { this(lexer,1); } public TemplateParser(ParserSharedInputState state) { super(state,1); tokenNames = _tokenNames; } public final void template( StringTemplate self ) throws RecognitionException, TokenStreamException { Token s = null; Token nl = null; this.self = self; try { // for error handling { _loop3: do { switch ( LA(1)) { case LITERAL: { s = LT(1); match(LITERAL); self.addChunk(new StringRef(self,s.getText())); break; } case NEWLINE: { nl = LT(1); match(NEWLINE); if ( LA(1)!=ELSE && LA(1)!=ENDIF ) { self.addChunk(new NewlineRef(self,nl.getText())); } break; } case ACTION: case IF: case REGION_REF: case REGION_DEF: { action(self); break; } default: { break _loop3; } } } while (true); } } catch (RecognitionException ex) { reportError(ex); recover(ex,_tokenSet_0); } } public final void action( StringTemplate self ) throws RecognitionException, TokenStreamException { Token a = null; Token i = null; Token ei = null; Token rr = null; Token rd = null; try { // for error handling switch ( LA(1)) { case ACTION: { a = LT(1); match(ACTION); String indent = ((ChunkToken)a).getIndentation(); ASTExpr c = self.parseAction(a.getText()); c.setIndentation(indent); self.addChunk(c); break; } case IF: { i = LT(1); match(IF); ConditionalExpr c = (ConditionalExpr)self.parseAction(i.getText()); // create and precompile the subtemplate StringTemplate subtemplate = new StringTemplate(self.getGroup(), null); subtemplate.setEnclosingInstance(self); subtemplate.setName(i.getText()+"_subtemplate"); self.addChunk(c); template(subtemplate); if ( c!=null ) c.setSubtemplate(subtemplate); { _loop6: do { if ((LA(1)==ELSEIF)) { ei = LT(1); match(ELSEIF); ASTExpr ec = self.parseAction(ei.getText()); // create and precompile the subtemplate StringTemplate elseIfSubtemplate = new StringTemplate(self.getGroup(), null); elseIfSubtemplate.setEnclosingInstance(self); elseIfSubtemplate.setName(ei.getText()+"_subtemplate"); template(elseIfSubtemplate); if ( c!=null ) c.addElseIfSubtemplate(ec, elseIfSubtemplate); } else { break _loop6; } } while (true); } { switch ( LA(1)) { case ELSE: { match(ELSE); // create and precompile the subtemplate StringTemplate elseSubtemplate = new StringTemplate(self.getGroup(), null); elseSubtemplate.setEnclosingInstance(self); elseSubtemplate.setName("else_subtemplate"); template(elseSubtemplate); if ( c!=null ) c.setElseSubtemplate(elseSubtemplate); break; } case ENDIF: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } match(ENDIF); break; } case REGION_REF: { rr = LT(1); match(REGION_REF); // define implicit template and // convert <@r()> to String regionName = rr.getText(); String mangledRef = null; boolean err = false; // watch out for <@super.r()>; that does NOT def implicit region // convert to if ( regionName.startsWith("super.") ) { //System.out.println("super region ref "+regionName); String regionRef = regionName.substring("super.".length(),regionName.length()); String templateScope = self.getGroup().getUnMangledTemplateName(self.getName()); StringTemplate scopeST = self.getGroup().lookupTemplate(templateScope); if ( scopeST==null ) { self.getGroup().error("reference to region within undefined template: "+ templateScope); err=true; } if ( !scopeST.containsRegionName(regionRef) ) { self.getGroup().error("template "+templateScope+" has no region called "+ regionRef); err=true; } else { mangledRef = self.getGroup().getMangledRegionName(templateScope,regionRef); mangledRef = "super."+mangledRef; } } else { //System.out.println("region ref "+regionName); StringTemplate regionST = self.getGroup().defineImplicitRegionTemplate(self,regionName); mangledRef = regionST.getName(); } if ( !err ) { // treat as regular action: mangled template include String indent = ((ChunkToken)rr).getIndentation(); ASTExpr c = self.parseAction(mangledRef+"()"); c.setIndentation(indent); self.addChunk(c); } break; } case REGION_DEF: { rd = LT(1); match(REGION_DEF); String combinedNameTemplateStr = rd.getText(); int indexOfDefSymbol = combinedNameTemplateStr.indexOf("::="); if ( indexOfDefSymbol>=1 ) { String regionName = combinedNameTemplateStr.substring(0,indexOfDefSymbol); String template = combinedNameTemplateStr.substring(indexOfDefSymbol+3, combinedNameTemplateStr.length()); StringTemplate regionST = self.getGroup().defineRegionTemplate(self, regionName, template, StringTemplate.REGION_EMBEDDED); // treat as regular action: mangled template include String indent = ((ChunkToken)rd).getIndentation(); ASTExpr c = self.parseAction(regionST.getName()+"()"); c.setIndentation(indent); self.addChunk(c); } else { self.error("embedded region definition screwed up"); } break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } catch (RecognitionException ex) { reportError(ex); recover(ex,_tokenSet_1); } } public static final String[] _tokenNames = { "<0>", "EOF", "<2>", "NULL_TREE_LOOKAHEAD", "LITERAL", "NEWLINE", "ACTION", "IF", "ELSEIF", "ELSE", "ENDIF", "REGION_REF", "REGION_DEF", "EXPR", "TEMPLATE", "IF_EXPR", "ESC_CHAR", "ESC", "HEX", "SUBTEMPLATE", "NESTED_PARENS", "INDENT", "COMMENT", "LINE_BREAK" }; private static final long[] mk_tokenSet_0() { long[] data = { 1792L, 0L}; return data; } public static final BitSet _tokenSet_0 = new BitSet(mk_tokenSet_0()); private static final long[] mk_tokenSet_1() { long[] data = { 8176L, 0L}; return data; } public static final BitSet _tokenSet_1 = new BitSet(mk_tokenSet_1()); } stringtemplate-3.2.1/target/maven-archiver/0000755000175000017500000000000011274602762020721 5ustar twernertwernerstringtemplate-3.2.1/target/maven-archiver/pom.properties0000644000175000017500000000016311274602762023632 0ustar twernertwerner#Generated by Maven #Thu Nov 05 09:05:54 PST 2009 version=3.3-SNAPSHOT groupId=org.antlr artifactId=stringtemplate stringtemplate-3.2.1/target/surefire-reports/0000755000175000017500000000000011274602761021331 5ustar twernertwerner././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootstringtemplate-3.2.1/target/surefire-reports/TEST-org.antlr.stringtemplate.test.TestStringTemplate.xmlstringtemplate-3.2.1/target/surefire-reports/TEST-org.antlr.stringtemplate.test.TestStringTemplate.x0000644000175000017500000012574311274602761034041 0ustar twernertwerner stringtemplate-3.2.1/target/surefire-reports/org.antlr.stringtemplate.test.TestStringTemplate.txt0000644000175000017500000000044711274602761033625 0ustar twernertwerner------------------------------------------------------------------------------- Test set: org.antlr.stringtemplate.test.TestStringTemplate ------------------------------------------------------------------------------- Tests run: 315, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.656 sec stringtemplate-3.2.1/target/test-classes/0000755000175000017500000000000011274602756020427 5ustar twernertwernerstringtemplate-3.2.1/target/test-classes/org/0000755000175000017500000000000011274602756021216 5ustar twernertwernerstringtemplate-3.2.1/target/test-classes/org/antlr/0000755000175000017500000000000011274602756022336 5ustar twernertwernerstringtemplate-3.2.1/target/test-classes/org/antlr/stringtemplate/0000755000175000017500000000000011274602756025400 5ustar twernertwernerstringtemplate-3.2.1/target/test-classes/org/antlr/stringtemplate/test/0000755000175000017500000000000011274602760026352 5ustar twernertwernerstringtemplate-3.2.1/target/test-classes/org/antlr/stringtemplate/test/TestStringTemplate.java0000644000175000017500000062071711274602756033041 0ustar twernertwerner/* [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.test; import junit.framework.TestCase; import org.antlr.stringtemplate.*; import org.antlr.stringtemplate.language.AngleBracketTemplateLexer; import org.antlr.stringtemplate.language.DefaultTemplateLexer; import java.io.*; import java.text.SimpleDateFormat; import java.util.*; public class TestStringTemplate extends TestCase { static final String newline = System.getProperty("line.separator"); static class ErrorBuffer implements StringTemplateErrorListener { StringBuffer errorOutput = new StringBuffer(500); int n = 0; public void error(String msg, Throwable e) { n++; if ( n>1 ) { errorOutput.append('\n'); } if ( e!=null ) { StringWriter duh = new StringWriter(); e.printStackTrace(new PrintWriter(duh)); errorOutput.append(msg+": "+duh.toString()); } else { errorOutput.append(msg); } } public void warning(String msg) { n++; errorOutput.append(msg); } public boolean equals(Object o) { String me = toString(); String them = o.toString(); return me.equals(them); } public String toString() { return errorOutput.toString(); } } public void testInterfaceFileFormat() throws Exception { String groupI = "interface test;" +newline+ "t();" +newline+ "bold(item);"+newline+ "optional duh(a,b,c);"+newline; StringTemplateGroupInterface I = new StringTemplateGroupInterface(new StringReader(groupI)); String expecting = "interface test;\n" + "t();\n" + "bold(item);\n" + "optional duh(a, b, c);\n"; assertEquals(expecting,I.toString()); } public void testNoGroupLoader() throws Exception { // this also tests the group loader StringTemplateErrorListener errors = new ErrorBuffer(); String tmpdir = System.getProperty("java.io.tmpdir"); String templates = "group testG implements blort;" +newline+ "t() ::= <>" +newline+ "bold(item) ::= <>"+newline+ "duh(a,b,c) ::= <>"+newline; writeFile(tmpdir, "testG.stg", templates); /*StringTemplateGroup group =*/ new StringTemplateGroup(new FileReader(tmpdir+"/testG.stg"), errors); String expecting = "no group loader registered"; assertEquals(expecting,errors.toString()); } public void testCannotFindInterfaceFile() throws Exception { // this also tests the group loader StringTemplateErrorListener errors = new ErrorBuffer(); String tmpdir = System.getProperty("java.io.tmpdir"); StringTemplateGroup.registerGroupLoader(new PathGroupLoader(tmpdir,errors)); String templates = "group testG implements blort;" +newline+ "t() ::= <>" +newline+ "bold(item) ::= <>"+newline+ "duh(a,b,c) ::= <>"+newline; writeFile(tmpdir, "testG.stg", templates); /*StringTemplateGroup group =*/ new StringTemplateGroup(new FileReader(tmpdir+"/testG.stg"), errors); String expecting = "no such interface file blort.sti"; assertEquals(expecting,errors.toString()); } public void testMultiDirGroupLoading() throws Exception { // this also tests the group loader StringTemplateErrorListener errors = new ErrorBuffer(); String tmpdir = System.getProperty("java.io.tmpdir"); if ( !(new File(tmpdir+"/sub").exists()) ) { if ( !(new File(tmpdir+"/sub").mkdir()) ) { // create a subdir System.err.println("can't make subdir in test"); return; } } StringTemplateGroup.registerGroupLoader( new PathGroupLoader(tmpdir+":"+tmpdir+"/sub",errors) ); String templates = "group testG2;" +newline+ "t() ::= <>" +newline+ "bold(item) ::= <>"+newline+ "duh(a,b,c) ::= <>"+newline; writeFile(tmpdir+"/sub", "testG2.stg", templates); StringTemplateGroup group = StringTemplateGroup.loadGroup("testG2"); String expecting = "group testG2;\n" + "bold(item) ::= <>\n" + "duh(a,b,c) ::= <>\n" + "t() ::= <>\n"; assertEquals(expecting,group.toString()); } public void testGroupSatisfiesSingleInterface() throws Exception { // this also tests the group loader StringTemplateErrorListener errors = new ErrorBuffer(); String tmpdir = System.getProperty("java.io.tmpdir"); StringTemplateGroup.registerGroupLoader(new PathGroupLoader(tmpdir,errors)); String groupI = "interface testI;" +newline+ "t();" +newline+ "bold(item);"+newline+ "optional duh(a,b,c);"+newline; writeFile(tmpdir, "testI.sti", groupI); String templates = "group testG implements testI;" +newline+ "t() ::= <>" +newline+ "bold(item) ::= <>"+newline+ "duh(a,b,c) ::= <>"+newline; writeFile(tmpdir, "testG.stg", templates); /*StringTemplateGroup group =*/ new StringTemplateGroup(new FileReader(tmpdir+"/testG.stg"), errors); String expecting = ""; // should be no errors assertEquals(expecting,errors.toString()); } public void testGroupExtendsSuperGroup() throws Exception { // this also tests the group loader StringTemplateErrorListener errors = new ErrorBuffer(); String tmpdir = System.getProperty("java.io.tmpdir"); StringTemplateGroup.registerGroupLoader( new PathGroupLoader(tmpdir,errors) ); String superGroup = "group superG;" +newline+ "bold(item) ::= <<*$item$*>>;\n"+newline; writeFile(tmpdir, "superG.stg", superGroup); String templates = "group testG : superG;" +newline+ "main(x) ::= <<$bold(x)$>>"+newline; writeFile(tmpdir, "testG.stg", templates); StringTemplateGroup group = new StringTemplateGroup(new FileReader(tmpdir+"/testG.stg"), DefaultTemplateLexer.class, errors); StringTemplate st = group.getInstanceOf("main"); st.setAttribute("x", "foo"); String expecting = "*foo*"; assertEquals(expecting, st.toString()); } public void testGroupExtendsSuperGroupWithAngleBrackets() throws Exception { // this also tests the group loader StringTemplateErrorListener errors = new ErrorBuffer(); String tmpdir = System.getProperty("java.io.tmpdir"); StringTemplateGroup.registerGroupLoader( new PathGroupLoader(tmpdir,errors) ); String superGroup = "group superG;" +newline+ "bold(item) ::= <<**>>;\n"+newline; writeFile(tmpdir, "superG.stg", superGroup); String templates = "group testG : superG;" +newline+ "main(x) ::= \"\""+newline; writeFile(tmpdir, "testG.stg", templates); StringTemplateGroup group = new StringTemplateGroup(new FileReader(tmpdir+"/testG.stg"), errors); StringTemplate st = group.getInstanceOf("main"); st.setAttribute("x", "foo"); String expecting = "*foo*"; assertEquals(expecting, st.toString()); } public void testMissingInterfaceTemplate() throws Exception { // this also tests the group loader StringTemplateErrorListener errors = new ErrorBuffer(); String tmpdir = System.getProperty("java.io.tmpdir"); StringTemplateGroup.registerGroupLoader(new PathGroupLoader(tmpdir,errors)); String groupI = "interface testI;" +newline+ "t();" +newline+ "bold(item);"+newline+ "optional duh(a,b,c);"+newline; writeFile(tmpdir, "testI.sti", groupI); String templates = "group testG implements testI;" +newline+ "t() ::= <>" +newline+ "duh(a,b,c) ::= <>"+newline; writeFile(tmpdir, "testG.stg", templates); /*StringTemplateGroup group =*/ new StringTemplateGroup(new FileReader(tmpdir+"/testG.stg"), errors); String expecting = "group testG does not satisfy interface testI: missing templates [bold]"; assertEquals(expecting, errors.toString()); } public void testMissingOptionalInterfaceTemplate() throws Exception { // this also tests the group loader StringTemplateErrorListener errors = new ErrorBuffer(); String tmpdir = System.getProperty("java.io.tmpdir"); StringTemplateGroup.registerGroupLoader(new PathGroupLoader(tmpdir,errors)); String groupI = "interface testI;" +newline+ "t();" +newline+ "bold(item);"+newline+ "optional duh(a,b,c);"+newline; writeFile(tmpdir, "testI.sti", groupI); String templates = "group testG implements testI;" +newline+ "t() ::= <>" +newline+ "bold(item) ::= <>"; writeFile(tmpdir, "testG.stg", templates); /*StringTemplateGroup group =*/ new StringTemplateGroup(new FileReader(tmpdir+"/testG.stg"), errors); String expecting = ""; // should be NO errors assertEquals(expecting, errors.toString()); } public void testMismatchedInterfaceTemplate() throws Exception { // this also tests the group loader StringTemplateErrorListener errors = new ErrorBuffer(); String tmpdir = System.getProperty("java.io.tmpdir"); StringTemplateGroup.registerGroupLoader(new PathGroupLoader(tmpdir,errors)); String groupI = "interface testI;" +newline+ "t();" +newline+ "bold(item);"+newline+ "optional duh(a,b,c);"+newline; writeFile(tmpdir, "testI.sti", groupI); String templates = "group testG implements testI;" +newline+ "t() ::= <>" +newline+ "bold(item) ::= <>"+newline+ "duh(a,c) ::= <>"+newline; writeFile(tmpdir, "testG.stg", templates); /*StringTemplateGroup group =*/ new StringTemplateGroup(new FileReader(tmpdir+"/testG.stg"), errors); String expecting = "group testG does not satisfy interface testI: mismatched arguments on these templates [optional duh(a, b, c)]"; assertEquals(expecting,errors.toString()); } public void testGroupFileFormat() throws Exception { String templates = "group test;" +newline+ "t() ::= \"literal template\"" +newline+ "bold(item) ::= \"$item$\""+newline+ "duh() ::= <<"+newline+"xx"+newline+">>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class); String expecting = "group test;" +newline+ "bold(item) ::= <<$item$>>" +newline+ "duh() ::= <>" +newline+ "t() ::= <>"+newline; assertEquals(expecting,group.toString()); StringTemplate a = group.getInstanceOf("t"); expecting = "literal template"; assertEquals(expecting,a.toString()); StringTemplate b = group.getInstanceOf("bold"); b.setAttribute("item", "dork"); expecting = "dork"; assertEquals(expecting,b.toString()); } public void testEscapedTemplateDelimiters() throws Exception { String templates = "group test;" +newline+ "t() ::= <<$\"literal\":{a|$a$\\}}$ template\n>>" +newline+ "bold(item) ::= <<$item$>>"+newline+ "duh() ::= <<"+newline+"xx"+newline+">>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class); String expecting = "group test;" +newline+ "bold(item) ::= <<$item$>>" +newline+ "duh() ::= <>" +newline+ "t() ::= <<$\"literal\":{a|$a$\\}}$ template>>"+newline; assertEquals(expecting,group.toString()); StringTemplate b = group.getInstanceOf("bold"); b.setAttribute("item", "dork"); expecting = "dork"; assertEquals(expecting,b.toString()); StringTemplate a = group.getInstanceOf("t"); expecting = "literal} template"; assertEquals(expecting,a.toString()); } /** Check syntax and setAttribute-time errors */ public void testTemplateParameterDecls() throws Exception { String templates = "group test;" +newline+ "t() ::= \"no args but ref $foo$\"" +newline+ "t2(item) ::= \"decl but not used is ok\""+newline + "t3(a,b,c,d) ::= <<$a$ $d$>>"+newline+ "t4(a,b,c,d) ::= <<$a$ $b$ $c$ $d$>>"+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class); // check setting unknown arg in empty formal list StringTemplate a = group.getInstanceOf("t"); String error = null; try { a.setAttribute("foo", "x"); // want NoSuchElementException } catch (NoSuchElementException e) { error = e.getMessage(); } String expecting = "no such attribute: foo in template context [t]"; assertEquals(expecting,error); // check setting known arg a = group.getInstanceOf("t2"); a.setAttribute("item", "x"); // shouldn't get exception // check setting unknown arg in nonempty list of formal args a = group.getInstanceOf("t3"); a.setAttribute("b", "x"); } public void testTemplateRedef() throws Exception { String templates = "group test;" +newline+ "a() ::= \"x\"" +newline+ "b() ::= \"y\"" +newline+ "a() ::= \"z\"" +newline; StringTemplateErrorListener errors = new ErrorBuffer(); /*StringTemplateGroup group =*/ new StringTemplateGroup(new StringReader(templates), errors); String expecting = "redefinition of template: a"; assertEquals(expecting,errors.toString()); } public void testMissingInheritedAttribute() throws Exception { String templates = "group test;" +newline+ "page(title,font) ::= <<"+newline + ""+newline + ""+newline + "$title$
"+newline + "$body()$"+newline + ""+newline + ""+newline + ">>"+newline + "body() ::= \"my body\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class); StringTemplate t = group.getInstanceOf("page"); t.setAttribute("title","my title"); t.setAttribute("font","Helvetica"); // body() will see it t.toString(); // should be no problem } public void testFormalArgumentAssignment() throws Exception { String templates = "group test;" +newline+ "page() ::= <<$body(font=\"Times\")$>>"+newline + "body(font) ::= \"my body\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class); StringTemplate t = group.getInstanceOf("page"); String expecting = "my body"; assertEquals(expecting, t.toString()); } public void testUndefinedArgumentAssignment() throws Exception { String templates = "group test;" +newline+ "page(x) ::= <<$body(font=x)$>>"+newline + "body() ::= \"my body\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class); StringTemplate t = group.getInstanceOf("page"); t.setAttribute("x","Times"); String error = ""; try { t.toString(); } catch (NoSuchElementException iae) { error = iae.getMessage(); } String expecting = "template body has no such attribute: font in template context [page ]"; assertEquals(expecting, error); } public void testFormalArgumentAssignmentInApply() throws Exception { String templates = "group test;" +newline+ "page(name) ::= <<$name:bold(font=\"Times\")$>>"+newline + "bold(font) ::= \"$it$\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class); StringTemplate t = group.getInstanceOf("page"); t.setAttribute("name", "Ter"); String expecting = "Ter"; assertEquals(expecting, t.toString()); } public void testUndefinedArgumentAssignmentInApply() throws Exception { String templates = "group test;" +newline+ "page(name,x) ::= <<$name:bold(font=x)$>>"+newline + "bold() ::= \"$it$\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class); StringTemplate t = group.getInstanceOf("page"); t.setAttribute("x","Times"); t.setAttribute("name", "Ter"); String error = ""; try { t.toString(); } catch (NoSuchElementException iae) { error = iae.getMessage(); } String expecting = "template bold has no such attribute: font in template context [page ]"; assertEquals(expecting,error); } public void testUndefinedAttributeReference() throws Exception { String templates = "group test;" +newline+ "page() ::= <<$bold()$>>"+newline + "bold() ::= \"$name$\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class); StringTemplate t = group.getInstanceOf("page"); String error = ""; try { t.toString(); } catch (NoSuchElementException iae) { error = iae.getMessage(); } String expecting = "no such attribute: name in template context [page bold]"; assertEquals(expecting,error); } public void testUndefinedDefaultAttributeReference() throws Exception { String templates = "group test;" +newline+ "page() ::= <<$bold()$>>"+newline + "bold() ::= \"$it$\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class); StringTemplate t = group.getInstanceOf("page"); String error = ""; try { t.toString(); } catch (NoSuchElementException nse) { error = nse.getMessage(); } String expecting = "no such attribute: it in template context [page bold]"; assertEquals(expecting,error); } public void testAngleBracketsWithGroupFile() throws Exception { String templates = "group test;" +newline+ "a(s) ::= \" : break;}>\""+newline + "b(t) ::= \"\"" +newline+ "c(t) ::= << >>" +newline; // mainly testing to ensure we don't get parse errors of above StringTemplateGroup group = new StringTemplateGroup( new StringReader(templates)); StringTemplate t = group.getInstanceOf("a"); t.setAttribute("s","Test"); String expecting = "case 1 : Test break;"; assertEquals(expecting, t.toString()); } public void testAngleBracketsNoGroup() throws Exception { StringTemplate st =new StringTemplate( "Tokens : ;", AngleBracketTemplateLexer.class); st.setAttribute("rules", "A"); st.setAttribute("rules", "B"); String expecting = "Tokens : A|B ;"; assertEquals(expecting, st.toString()); } public void testRegionRef() throws Exception { String templates = "group test;" +newline+ "a() ::= \"X$@r()$Y\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class); StringTemplate st = group.getInstanceOf("a"); String result = st.toString(); String expecting = "XY"; assertEquals(expecting, result); } public void testEmbeddedRegionRef() throws Exception { String templates = "group test;" +newline+ "a() ::= \"X$@r$blort$@end$Y\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class); StringTemplate st = group.getInstanceOf("a"); String result = st.toString(); String expecting = "XblortY"; assertEquals(expecting, result); } public void testRegionRefAngleBrackets() throws Exception { String templates = "group test;" +newline+ "a() ::= \"X<@r()>Y\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("a"); String result = st.toString(); String expecting = "XY"; assertEquals(expecting, result); } public void testEmbeddedRegionRefAngleBrackets() throws Exception { String templates = "group test;" +newline+ "a() ::= \"X<@r>blort<@end>Y\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("a"); String result = st.toString(); String expecting = "XblortY"; assertEquals(expecting, result); } // FIXME: This test fails due to inserted white space... public void testEmbeddedRegionRefWithNewlinesAngleBrackets() throws Exception { String templates = "group test;" +newline+ "a() ::= \"X<@r>" +newline+ "blort" +newline+ "<@end>" +newline+ "Y\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("a"); String result = st.toString(); String expecting = "XblortY"; assertEquals(expecting, result); } public void testRegionRefWithDefAngleBrackets() throws Exception { String templates = "group test;" +newline+ "a() ::= \"X<@r()>Y\"" +newline+ "@a.r() ::= \"foo\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("a"); String result = st.toString(); String expecting = "XfooY"; assertEquals(expecting, result); } public void testRegionRefWithDefInConditional() throws Exception { String templates = "group test;" +newline+ "a(v) ::= \"XA<@r()>BY\"" +newline+ "@a.r() ::= \"foo\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("a"); st.setAttribute("v", "true"); String result = st.toString(); String expecting = "XAfooBY"; assertEquals(expecting, result); } public void testRegionRefWithImplicitDefInConditional() throws Exception { String templates = "group test;" +newline+ "a(v) ::= \"XA<@r>yo<@end>BY\"" +newline+ "@a.r() ::= \"foo\"" +newline; StringTemplateErrorListener errors = new ErrorBuffer(); StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), errors); StringTemplate st = group.getInstanceOf("a"); st.setAttribute("v", "true"); String result = st.toString(); String expecting = "XAyoBY"; assertEquals(expecting, result); String err_result = errors.toString(); String err_expecting = "group test line 3: redefinition of template region: @a.r"; assertEquals(err_expecting,err_result); } public void testRegionOverride() throws Exception { String templates1 = "group super;" +newline+ "a() ::= \"X<@r()>Y\"" + "@a.r() ::= \"foo\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates1)); String templates2 = "group sub;" +newline+ "@a.r() ::= \"foo\"" +newline; StringTemplateGroup subGroup = new StringTemplateGroup(new StringReader(templates2), AngleBracketTemplateLexer.class, null, group); StringTemplate st = subGroup.getInstanceOf("a"); String result = st.toString(); String expecting = "XfooY"; assertEquals(expecting, result); } public void testRegionOverrideRefSuperRegion() throws Exception { String templates1 = "group super;" +newline+ "a() ::= \"X<@r()>Y\"" + "@a.r() ::= \"foo\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates1)); String templates2 = "group sub;" +newline+ "@a.r() ::= \"A<@super.r()>B\"" +newline; StringTemplateGroup subGroup = new StringTemplateGroup(new StringReader(templates2), AngleBracketTemplateLexer.class, null, group); StringTemplate st = subGroup.getInstanceOf("a"); String result = st.toString(); String expecting = "XAfooBY"; assertEquals(expecting, result); } public void testRegionOverrideRefSuperRegion3Levels() throws Exception { // Bug: This was causing infinite recursion: // getInstanceOf(super::a) // getInstanceOf(sub::a) // getInstanceOf(subsub::a) // getInstanceOf(subsub::region__a__r) // getInstanceOf(subsub::super.region__a__r) // getInstanceOf(subsub::super.region__a__r) // getInstanceOf(subsub::super.region__a__r) // ... // Somehow, the ref to super in subsub is not moving up the chain // to the @super.r(); oh, i introduced a bug when i put setGroup // into STG.getInstanceOf()! String templates1 = "group super;" +newline+ "a() ::= \"X<@r()>Y\"" + "@a.r() ::= \"foo\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates1)); String templates2 = "group sub;" +newline+ "@a.r() ::= \"<@super.r()>2\"" +newline; StringTemplateGroup subGroup = new StringTemplateGroup(new StringReader(templates2), AngleBracketTemplateLexer.class, null, group); String templates3 = "group subsub;" +newline+ "@a.r() ::= \"<@super.r()>3\"" +newline; StringTemplateGroup subSubGroup = new StringTemplateGroup(new StringReader(templates3), AngleBracketTemplateLexer.class, null, subGroup); StringTemplate st = subSubGroup.getInstanceOf("a"); String result = st.toString(); String expecting = "Xfoo23Y"; assertEquals(expecting, result); } public void testRegionOverrideRefSuperImplicitRegion() throws Exception { String templates1 = "group super;" +newline+ "a() ::= \"X<@r>foo<@end>Y\""+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates1)); String templates2 = "group sub;" +newline+ "@a.r() ::= \"A<@super.r()>\"" +newline; StringTemplateGroup subGroup = new StringTemplateGroup(new StringReader(templates2), AngleBracketTemplateLexer.class, null, group); StringTemplate st = subGroup.getInstanceOf("a"); String result = st.toString(); String expecting = "XAfooY"; assertEquals(expecting, result); } public void testEmbeddedRegionRedefError() throws Exception { // cannot define an embedded template within group String templates = "group test;" +newline+ "a() ::= \"X<@r>dork<@end>Y\"" + "@a.r() ::= \"foo\"" +newline; StringTemplateErrorListener errors = new ErrorBuffer(); StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), errors); StringTemplate st = group.getInstanceOf("a"); st.toString(); String result = errors.toString(); String expecting = "group test line 2: redefinition of template region: @a.r"; assertEquals(expecting, result); } public void testImplicitRegionRedefError() throws Exception { // cannot define an implicitly-defined template more than once String templates = "group test;" +newline+ "a() ::= \"X<@r()>Y\"" +newline+ "@a.r() ::= \"foo\"" +newline+ "@a.r() ::= \"bar\"" +newline; StringTemplateErrorListener errors = new ErrorBuffer(); StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), errors); StringTemplate st = group.getInstanceOf("a"); st.toString(); String result = errors.toString(); String expecting = "group test line 4: redefinition of template region: @a.r"; assertEquals(expecting, result); } public void testImplicitOverriddenRegionRedefError() throws Exception { String templates1 = "group super;" +newline+ "a() ::= \"X<@r()>Y\"" + "@a.r() ::= \"foo\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates1)); String templates2 = "group sub;" +newline+ "@a.r() ::= \"foo\"" +newline+ "@a.r() ::= \"bar\"" +newline; StringTemplateErrorListener errors = new ErrorBuffer(); StringTemplateGroup subGroup = new StringTemplateGroup(new StringReader(templates2), AngleBracketTemplateLexer.class, errors, group); /*StringTemplate st =*/ subGroup.getInstanceOf("a"); String result = errors.toString(); String expecting = "group sub line 3: redefinition of template region: @a.r"; assertEquals(expecting, result); } public void testUnknownRegionDefError() throws Exception { // cannot define an implicitly-defined template more than once String templates = "group test;" +newline+ "a() ::= \"X<@r()>Y\"" +newline+ "@a.q() ::= \"foo\"" +newline; StringTemplateErrorListener errors = new ErrorBuffer(); StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), errors); StringTemplate st = group.getInstanceOf("a"); st.toString(); String result = errors.toString(); String expecting = "group test line 3: template a has no region called q"; assertEquals(expecting, result); } public void testSuperRegionRefError() throws Exception { String templates1 = "group super;" +newline+ "a() ::= \"X<@r()>Y\"" + "@a.r() ::= \"foo\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates1)); String templates2 = "group sub;" +newline+ "@a.r() ::= \"A<@super.q()>B\"" +newline; StringTemplateErrorListener errors = new ErrorBuffer(); StringTemplateGroup subGroup = new StringTemplateGroup(new StringReader(templates2), AngleBracketTemplateLexer.class, errors, group); /*StringTemplate st =*/ subGroup.getInstanceOf("a"); String result = errors.toString(); String expecting = "template a has no region called q"; assertEquals(expecting, result); } public void testMissingEndRegionError() throws Exception { // cannot define an implicitly-defined template more than once String templates = "group test;" +newline+ "a() ::= \"X$@r$foo\"" +newline; StringTemplateErrorListener errors = new ErrorBuffer(); StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class, errors, null); StringTemplate st = group.getInstanceOf("a"); st.toString(); String result = errors.toString(); String expecting = "missing region r $@end$ tag"; assertEquals(expecting, result); } public void testMissingEndRegionErrorAngleBrackets() throws Exception { // cannot define an implicitly-defined template more than once String templates = "group test;" +newline+ "a() ::= \"X<@r>foo\"" +newline; StringTemplateErrorListener errors = new ErrorBuffer(); StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), errors); StringTemplate st = group.getInstanceOf("a"); st.toString(); String result = errors.toString(); String expecting = "missing region r <@end> tag"; assertEquals(expecting, result); } public void testSimpleInheritance() throws Exception { // make a bold template in the super group that you can inherit from sub StringTemplateGroup supergroup = new StringTemplateGroup("super"); StringTemplateGroup subgroup = new StringTemplateGroup("sub"); /*StringTemplate bold =*/ supergroup.defineTemplate("bold", "$it$"); subgroup.setSuperGroup(supergroup); StringTemplateErrorListener errors = new ErrorBuffer(); subgroup.setErrorListener(errors); supergroup.setErrorListener(errors); StringTemplate duh = new StringTemplate(subgroup, "$name:bold()$"); duh.setAttribute("name", "Terence"); String expecting = "Terence"; assertEquals(expecting,duh.toString()); } public void testOverrideInheritance() throws Exception { // make a bold template in the super group and one in sub group StringTemplateGroup supergroup = new StringTemplateGroup("super"); StringTemplateGroup subgroup = new StringTemplateGroup("sub"); supergroup.defineTemplate("bold", "$it$"); subgroup.defineTemplate("bold", "$it$"); subgroup.setSuperGroup(supergroup); StringTemplateErrorListener errors = new ErrorBuffer(); subgroup.setErrorListener(errors); supergroup.setErrorListener(errors); StringTemplate duh = new StringTemplate(subgroup, "$name:bold()$"); duh.setAttribute("name", "Terence"); String expecting = "Terence"; assertEquals(expecting,duh.toString()); } public void testMultiLevelInheritance() throws Exception { // must loop up two levels to find bold() StringTemplateGroup rootgroup = new StringTemplateGroup("root"); StringTemplateGroup level1 = new StringTemplateGroup("level1"); StringTemplateGroup level2 = new StringTemplateGroup("level2"); rootgroup.defineTemplate("bold", "$it$"); level1.setSuperGroup(rootgroup); level2.setSuperGroup(level1); StringTemplateErrorListener errors = new ErrorBuffer(); rootgroup.setErrorListener(errors); level1.setErrorListener(errors); level2.setErrorListener(errors); StringTemplate duh = new StringTemplate(level2, "$name:bold()$"); duh.setAttribute("name", "Terence"); String expecting = "Terence"; assertEquals(expecting,duh.toString()); } public void testComplicatedInheritance() throws Exception { // in super: decls invokes labels // in sub: overridden decls which calls super.decls // overridden labels // Bug: didn't see the overridden labels. In other words, // the overridden decls called super which called labels, but // didn't get the subgroup overridden labels--it calls the // one in the superclass. Ouput was "DL" not "DSL"; didn't // invoke sub's labels(). String basetemplates = "group base;" +newline+ "decls() ::= \"D\""+newline+ "labels() ::= \"L\"" +newline ; StringTemplateGroup base = new StringTemplateGroup(new StringReader(basetemplates)); String subtemplates = "group sub;" +newline+ "decls() ::= \"\""+newline+ "labels() ::= \"SL\"" +newline ; StringTemplateGroup sub = new StringTemplateGroup(new StringReader(subtemplates)); sub.setSuperGroup(base); StringTemplate st = sub.getInstanceOf("decls"); String expecting = "DSL"; String result = st.toString(); assertEquals(expecting, result); } public void test3LevelSuperRef() throws Exception { String templates1 = "group super;" +newline+ "r() ::= \"foo\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates1)); String templates2 = "group sub;" +newline+ "r() ::= \"2\"" +newline; StringTemplateGroup subGroup = new StringTemplateGroup(new StringReader(templates2), AngleBracketTemplateLexer.class, null, group); String templates3 = "group subsub;" +newline+ "r() ::= \"3\"" +newline; StringTemplateGroup subSubGroup = new StringTemplateGroup(new StringReader(templates3), AngleBracketTemplateLexer.class, null, subGroup); StringTemplate st = subSubGroup.getInstanceOf("r"); String result = st.toString(); String expecting = "foo23"; assertEquals(expecting, result); } public void testExprInParens() throws Exception { // specify a template to apply to an attribute // Use a template group so we can specify the start/stop chars StringTemplateGroup group = new StringTemplateGroup("dummy", "."); /*StringTemplate bold =*/ group.defineTemplate("bold", "$it$"); StringTemplate duh = new StringTemplate(group, "$(\"blort: \"+(list)):bold()$"); duh.setAttribute("list", "a"); duh.setAttribute("list", "b"); duh.setAttribute("list", "c"); // System.out.println(duh); String expecting = "blort: abc"; assertEquals(expecting, duh.toString()); } public void testMultipleAdditions() throws Exception { // specify a template to apply to an attribute // Use a template group so we can specify the start/stop chars StringTemplateGroup group = new StringTemplateGroup("dummy", "."); group.defineTemplate("link", "$title$"); StringTemplate duh = new StringTemplate(group, "$link(url=\"/member/view?ID=\"+ID+\"&x=y\"+foo, title=\"the title\")$"); duh.setAttribute("ID", "3321"); duh.setAttribute("foo", "fubar"); String expecting = "the title"; assertEquals(expecting, duh.toString()); } public void testCollectionAttributes() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); /*StringTemplate bold =*/ group.defineTemplate("bold", "$it$"); StringTemplate t = new StringTemplate(group, "$data$, $data:bold()$, "+ "$list:bold():bold()$, $array$, $a2$, $a3$, $a4$"); Vector v = new Vector(); v.addElement("1"); v.addElement("2"); v.addElement("3"); List list = new ArrayList(); list.add("a"); list.add("b"); list.add("c"); t.setAttribute("data", v); t.setAttribute("list", list); t.setAttribute("array", new String[] {"x","y"}); t.setAttribute("a2", new int[] {10,20}); t.setAttribute("a3", new float[] {1.2f,1.3f}); t.setAttribute("a4", new double[] {8.7,9.2}); //System.out.println(t); String expecting="123, 123, "+ "abc, xy, 1020, 1.21.3, 8.79.2"; assertEquals(expecting, t.toString()); } public void testParenthesizedExpression() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); /*StringTemplate bold =*/ group.defineTemplate("bold", "$it$"); StringTemplate t = new StringTemplate(group, "$(f+l):bold()$"); t.setAttribute("f", "Joe"); t.setAttribute("l", "Schmoe"); //System.out.println(t); String expecting="JoeSchmoe"; assertEquals(expecting, t.toString()); } public void testApplyTemplateNameExpression() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); /* StringTemplate bold =*/ group.defineTemplate("foobar", "foo$attr$bar"); StringTemplate t = new StringTemplate(group, "$data:(name+\"bar\")()$"); t.setAttribute("data", "Ter"); t.setAttribute("data", "Tom"); t.setAttribute("name", "foo"); //System.out.println(t); String expecting="fooTerbarfooTombar"; assertEquals(expecting, t.toString()); } public void testApplyTemplateNameTemplateEval() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); /*StringTemplate foobar =*/ group.defineTemplate("foobar", "foo$it$bar"); /*StringTemplate a =*/ group.defineTemplate("a", "$it$bar"); StringTemplate t = new StringTemplate(group, "$data:(\"foo\":a())()$"); t.setAttribute("data", "Ter"); t.setAttribute("data", "Tom"); //System.out.println(t); String expecting="fooTerbarfooTombar"; assertEquals(expecting, t.toString()); } public void testTemplateNameExpression() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); /*StringTemplate foo =*/ group.defineTemplate("foo", "hi there!"); StringTemplate t = new StringTemplate(group, "$(name)()$"); t.setAttribute("name", "foo"); //System.out.println(t); String expecting="hi there!"; assertEquals(expecting, t.toString()); } public void testMissingEndDelimiter() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplateErrorListener errors = new ErrorBuffer(); group.setErrorListener(errors); /*StringTemplate t =*/ new StringTemplate(group, "stuff $a then more junk etc..."); String expectingError="problem parsing template 'anonymous': line 1:31: expecting '$', found ''"; //System.out.println("error: '"+errors+"'"); //System.out.println("expecting: '"+expectingError+"'"); assertTrue(errors.toString().startsWith(expectingError)); } public void testSetButNotRefd() throws Exception { StringTemplate.setLintMode(true); StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplate t = new StringTemplate(group, "$a$ then $b$ and $c$ refs."); t.setAttribute("a", "Terence"); t.setAttribute("b", "Terence"); t.setAttribute("cc", "Terence"); // oops...should be 'c' StringTemplateErrorListener errors = new ErrorBuffer(); group.setErrorListener(errors); String expectingError="anonymous: set but not used: cc"; /*String result =*/ t.toString(); // result is irrelevant //System.out.println("result error: '"+errors+"'"); //System.out.println("expecting: '"+expectingError+"'"); StringTemplate.setLintMode(false); assertEquals(expectingError,errors.toString()); } public void testNullTemplateApplication() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplateErrorListener errors = new ErrorBuffer(); group.setErrorListener(errors); StringTemplate t = new StringTemplate(group, "$names:bold(x=it)$"); t.setAttribute("names", "Terence"); String error = null; try { t.toString(); } catch (IllegalArgumentException iae) { error = iae.getMessage(); } String expecting = "Can't find template bold.st; context is [anonymous]; group hierarchy is [test]" ; assertEquals(expecting,error); } public void testNullTemplateToMultiValuedApplication() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplateErrorListener errors = new ErrorBuffer(); group.setErrorListener(errors); StringTemplate t = new StringTemplate(group, "$names:bold(x=it)$"); t.setAttribute("names", "Terence"); t.setAttribute("names", "Tom"); //System.out.println(t); String error = null; try { t.toString(); } catch (IllegalArgumentException iae) { error = iae.getMessage(); } String expecting = "Can't find template bold.st; context is [anonymous]; group hierarchy is [test]"; // bold not found...empty string assertEquals(expecting,error); } public void testChangingAttrValueTemplateApplicationToVector() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); /*StringTemplate bold =*/ group.defineTemplate("bold", "$x$"); StringTemplate t = new StringTemplate(group, "$names:bold(x=it)$"); t.setAttribute("names", "Terence"); t.setAttribute("names", "Tom"); //System.out.println("'"+t.toString()+"'"); String expecting="TerenceTom"; assertEquals(expecting, t.toString()); } public void testChangingAttrValueRepeatedTemplateApplicationToVector() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", "."); /*StringTemplate bold =*/ group.defineTemplate("bold", "$item$"); /*StringTemplate italics =*/ group.defineTemplate("italics", "$it$"); StringTemplate members = new StringTemplate(group, "$members:bold(item=it):italics(it=it)$"); members.setAttribute("members", "Jim"); members.setAttribute("members", "Mike"); members.setAttribute("members", "Ashar"); //System.out.println("members="+members); String expecting = "JimMikeAshar"; assertEquals(expecting,members.toString()); } public void testAlternatingTemplateApplication() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", "."); /*StringTemplate listItem =*/ group.defineTemplate("listItem", "
  • $it$
  • "); /*StringTemplate bold =*/ group.defineTemplate("bold", "$it$"); /*StringTemplate italics =*/ group.defineTemplate("italics", "$it$"); StringTemplate item = new StringTemplate(group, "$item:bold(),italics():listItem()$"); item.setAttribute("item", "Jim"); item.setAttribute("item", "Mike"); item.setAttribute("item", "Ashar"); //System.out.println("ITEM="+item); String expecting = "
  • Jim
  • Mike
  • Ashar
  • "; assertEquals(item.toString(), expecting); } public void testExpressionAsRHSOfAssignment() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); /*StringTemplate hostname =*/ group.defineTemplate("hostname", "$machine$.jguru.com"); /*StringTemplate bold =*/ group.defineTemplate("bold", "$x$"); StringTemplate t = new StringTemplate(group, "$bold(x=hostname(machine=\"www\"))$"); String expecting="www.jguru.com"; assertEquals(expecting, t.toString()); } public void testTemplateApplicationAsRHSOfAssignment() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); /*StringTemplate hostname =*/ group.defineTemplate("hostname", "$machine$.jguru.com"); /*StringTemplate bold =*/ group.defineTemplate("bold", "$x$"); /*StringTemplate italics =*/ group.defineTemplate("italics", "$it$"); StringTemplate t = new StringTemplate(group, "$bold(x=hostname(machine=\"www\"):italics())$"); String expecting="www.jguru.com"; assertEquals(expecting, t.toString()); } public void testParameterAndAttributeScoping() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); /*StringTemplate italics =*/ group.defineTemplate("italics", "$x$"); /*StringTemplate bold =*/ group.defineTemplate("bold", "$x$"); StringTemplate t = new StringTemplate(group, "$bold(x=italics(x=name))$"); t.setAttribute("name", "Terence"); //System.out.println(t); String expecting="Terence"; assertEquals(expecting, t.toString()); } public void testComplicatedSeparatorExpr() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); /*StringTemplate bold =*/ group.defineTemplate("bulletSeparator", "$foo$
  • "); // make separator a complicated expression with args passed to included template StringTemplate t = new StringTemplate(group, "
      $name; separator=bulletSeparator(foo=\" \")+\" \"$
    "); t.setAttribute("name", "Ter"); t.setAttribute("name", "Tom"); t.setAttribute("name", "Mel"); //System.out.println(t); String expecting = "
      Ter
    •  Tom
    •  Mel
    "; assertEquals(expecting, t.toString()); } public void testAttributeRefButtedUpAgainstEndifAndWhitespace() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplate a = new StringTemplate(group, "$if (!firstName)$$email$$endif$"); a.setAttribute("email", "parrt@jguru.com"); String expecting = "parrt@jguru.com"; assertEquals(a.toString(), expecting); } public void testStringCatenationOnSingleValuedAttributeViaTemplateLiteral() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); /*StringTemplate bold =*/ group.defineTemplate("bold", "$it$"); //StringTemplate a = new StringTemplate(group, "$\" Parr\":bold()$"); StringTemplate b = new StringTemplate(group, "$bold(it={$name$ Parr})$"); //a.setAttribute("name", "Terence"); b.setAttribute("name", "Terence"); String expecting = "Terence Parr"; //assertEquals(a.toString(), expecting); assertEquals(b.toString(), expecting); } public void testStringCatenationOpOnArg() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); /*StringTemplate bold =*/ group.defineTemplate("bold", "$it$"); StringTemplate b = new StringTemplate(group, "$bold(it=name+\" Parr\")$"); //a.setAttribute("name", "Terence"); b.setAttribute("name", "Terence"); String expecting = "Terence Parr"; //assertEquals(expecting, a.toString()); assertEquals(expecting, b.toString()); } public void testStringCatenationOpOnArgWithEqualsInString() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); /*StringTemplate bold =*/ group.defineTemplate("bold", "$it$"); StringTemplate b = new StringTemplate(group, "$bold(it=name+\" Parr=\")$"); //a.setAttribute("name", "Terence"); b.setAttribute("name", "Terence"); String expecting = "Terence Parr="; //assertEquals(expecting, a.toString()); assertEquals(expecting, b.toString()); } public void testApplyingTemplateFromDiskWithPrecompiledIF() throws Exception { // Create a temporary working directory File tmpDir = new File(System.getProperty("java.io.tmpdir")); File tmpWorkDir; int counter = (new Random()).nextInt() & 65535;; do { counter++; StringBuffer name = new StringBuffer("st-junit-"); name.append(counter); tmpWorkDir = new File(tmpDir, name.toString()); } while (tmpWorkDir.exists()); tmpWorkDir.mkdirs(); // write the template files first to /tmp File pageFile = new File(tmpWorkDir,"page.st"); FileWriter fw = new FileWriter(pageFile); fw.write(""+newline); //fw.write(" PeerScope: $title$"+newline); fw.write(""+newline); fw.write(""+newline); fw.write("$if(member)$User: $member:terse()$$endif$"+newline); fw.write(""+newline); fw.write(""+newline); fw.close(); File terseFile = new File(tmpWorkDir,"terse.st"); fw = new FileWriter(terseFile); fw.write("$it.firstName$ $it.lastName$ ($it.email$)"+newline); fw.close(); // specify a template to apply to an attribute // Use a template group so we can specify the start/stop chars StringTemplateGroup group = new StringTemplateGroup("dummy", tmpWorkDir.toString()); StringTemplate a = group.getInstanceOf("page"); a.setAttribute("member", new Connector()); String expecting = ""+newline+ ""+newline+ ""+newline+ "User: Terence Parr (parrt@jguru.com)"+newline+ ""+newline+ ""; //System.out.println("'"+a+"'"); assertEquals(expecting, a.toString()); // Cleanup the temp folder. pageFile.delete(); terseFile.delete(); tmpWorkDir.delete(); } public void testMultiValuedAttributeWithAnonymousTemplateUsingIndexVariableI() throws Exception { StringTemplateGroup tgroup = new StringTemplateGroup("dummy", "."); StringTemplate t = new StringTemplate(tgroup, " List:"+newline+" "+newline+"foo"+newline+newline+ "$names:{
    $i$. $it$"+newline+ "}$"); t.setAttribute("names", "Terence"); t.setAttribute("names", "Jim"); t.setAttribute("names", "Sriram"); //System.out.println(t); String expecting = " List:"+newline+ " "+newline+ "foo"+newline+newline+ "
    1. Terence"+newline+ "
    2. Jim"+newline+ "
    3. Sriram"+newline; assertEquals(expecting, t.toString()); } public void testFindTemplateInCLASSPATH() throws Exception { // Look for templates in CLASSPATH as resources StringTemplateGroup mgroup = new StringTemplateGroup("method stuff", AngleBracketTemplateLexer.class); StringTemplate m = mgroup.getInstanceOf("org/antlr/stringtemplate/test/method"); // "method.st" references body() so "body.st" will be loaded too m.setAttribute("visibility", "public"); m.setAttribute("name", "foobar"); m.setAttribute("returnType", "void"); m.setAttribute("statements", "i=1;"); // body inherits these from method m.setAttribute("statements", "x=i;"); String expecting = "public void foobar() {"+newline+ "\t// start of a body"+newline+ "\ti=1;"+newline+ "\tx=i;"+newline+ "\t// end of a body"+newline+ "}"; //System.out.println(m); assertEquals(expecting, m.toString()); } public void testApplyTemplateToSingleValuedAttribute() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); /*StringTemplate bold =*/ group.defineTemplate("bold", "$x$"); StringTemplate name = new StringTemplate(group, "$name:bold(x=name)$"); name.setAttribute("name", "Terence"); assertEquals("Terence",name.toString()); } public void testStringLiteralAsAttribute() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); /*StringTemplate bold =*/ group.defineTemplate("bold", "$it$"); StringTemplate name = new StringTemplate(group, "$\"Terence\":bold()$"); assertEquals("Terence",name.toString()); } public void testApplyTemplateToSingleValuedAttributeWithDefaultAttribute() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); /*StringTemplate bold =*/ group.defineTemplate("bold", "$it$"); StringTemplate name = new StringTemplate(group, "$name:bold()$"); name.setAttribute("name", "Terence"); assertEquals("Terence",name.toString()); } public void testApplyAnonymousTemplateToSingleValuedAttribute() throws Exception { // specify a template to apply to an attribute // Use a template group so we can specify the start/stop chars StringTemplateGroup group = new StringTemplateGroup("dummy", "."); StringTemplate item = new StringTemplate(group, "$item:{
  • $it$
  • }$"); item.setAttribute("item", "Terence"); assertEquals("
  • Terence
  • ",item.toString()); } public void testApplyAnonymousTemplateToMultiValuedAttribute() throws Exception { // specify a template to apply to an attribute // Use a template group so we can specify the start/stop chars StringTemplateGroup group = new StringTemplateGroup("dummy", "."); StringTemplate list = new StringTemplate(group, "
      $items$
    "); // demonstrate setting arg to anonymous subtemplate StringTemplate item = new StringTemplate(group, "$item:{
  • $it$
  • }; separator=\",\"$"); item.setAttribute("item", "Terence"); item.setAttribute("item", "Jim"); item.setAttribute("item", "John"); list.setAttribute("items", item); // nested template String expecting = "
    • Terence
    • ,
    • Jim
    • ,
    • John
    "; assertEquals(expecting,list.toString()); } public void testApplyAnonymousTemplateToAggregateAttribute() throws Exception { StringTemplate st = new StringTemplate("$items:{$it.lastName$, $it.firstName$\n}$"); // also testing wacky spaces in aggregate spec st.setAttribute("items.{ firstName ,lastName}", "Ter", "Parr"); st.setAttribute("items.{firstName, lastName }", "Tom", "Burns"); String expecting = "Parr, Ter"+newline + "Burns, Tom"+newline; assertEquals(expecting, st.toString()); } public void testRepeatedApplicationOfTemplateToSingleValuedAttribute() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", "."); /*StringTemplate search =*/ group.defineTemplate("bold", "$it$"); StringTemplate item = new StringTemplate(group, "$item:bold():bold()$"); item.setAttribute("item", "Jim"); assertEquals("Jim", item.toString()); } public void testRepeatedApplicationOfTemplateToMultiValuedAttributeWithSeparator() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", "."); /*StringTemplate search =*/ group.defineTemplate("bold", "$it$"); StringTemplate item = new StringTemplate(group, "$item:bold():bold(); separator=\",\"$"); item.setAttribute("item", "Jim"); item.setAttribute("item", "Mike"); item.setAttribute("item", "Ashar"); // first application of template must yield another vector! //System.out.println("ITEM="+item); String expecting = "Jim,Mike,Ashar"; assertEquals(item.toString(), expecting); } // ### NEED A TEST OF obj ASSIGNED TO ARG? public void testMultiValuedAttributeWithSeparator() throws Exception { StringTemplate query; // if column can be multi-valued, specify a separator StringTemplateGroup group = new StringTemplateGroup("dummy", ".", AngleBracketTemplateLexer.class); query = new StringTemplate(group, "SELECT FROM ;"); query.setAttribute("column", "name"); query.setAttribute("column", "email"); query.setAttribute("table", "User"); // uncomment next line to make "DISTINCT" appear in output // query.setAttribute("distince", "DISTINCT"); // System.out.println(query); assertEquals("SELECT name, email FROM User;",query.toString()); } public void testSingleValuedAttributes() throws Exception { // all attributes are single-valued: StringTemplate query = new StringTemplate("SELECT $column$ FROM $table$;"); query.setAttribute("column", "name"); query.setAttribute("table", "User"); // System.out.println(query); assertEquals("SELECT name FROM User;",query.toString()); } public void testIFTemplate() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", ".", AngleBracketTemplateLexer.class); StringTemplate t = new StringTemplate(group, "SELECT FROM PERSON "+ "WHERE ID=;"); t.setAttribute("column", "name"); t.setAttribute("cond", "true"); t.setAttribute("id", "231"); assertEquals("SELECT name FROM PERSON WHERE ID=231;",t.toString()); } public void testIFCondWithParensTemplate() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", ".", AngleBracketTemplateLexer.class); StringTemplate t = new StringTemplate(group, " =;"); HashMap map = new HashMap(); map.put("int","0"); t.setAttribute("map", map); t.setAttribute("prop", "x"); t.setAttribute("type", "int"); assertEquals("int x=0;",t.toString()); } public void testIFCondWithParensDollarDelimsTemplate() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", "."); StringTemplate t = new StringTemplate(group, "$if(map.(type))$$type$ $prop$=$map.(type)$;$endif$"); HashMap map = new HashMap(); map.put("int","0"); t.setAttribute("map", map); t.setAttribute("prop", "x"); t.setAttribute("type", "int"); assertEquals("int x=0;",t.toString()); } /** As of 2.0, you can test a boolean value */ public void testIFBoolean() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", "."); StringTemplate t = new StringTemplate(group, "$if(b)$x$endif$ $if(!b)$y$endif$"); t.setAttribute("b", new Boolean(true)); assertEquals(t.toString(), "x "); t = t.getInstanceOf(); t.setAttribute("b", new Boolean(false)); assertEquals(" y", t.toString()); } public void testNestedIFTemplate() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", ".", AngleBracketTemplateLexer.class); StringTemplate t = new StringTemplate(group, "ack"+newline+ "foo"+newline+ "stuff"+newline+ "no"+newline+ "junk"+newline+ "" ); t.setAttribute("a", "blort"); // leave b as null //System.out.println("t="+t); String expecting = "ackfoo"+newline+ "stuff"+newline+ "junk"; assertEquals(expecting, t.toString()); } public void testIFConditionWithTemplateApplication() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", "."); StringTemplate t = new StringTemplate(group, "$if(names:{$it$})$Fail!$endif$ $if(!names:{$it$})$Works!$endif$"); t.setAttribute("b", new Boolean(true)); assertEquals(t.toString(), " Works!"); } public class Connector { public int getID() { return 1; } public String getFirstName() { return "Terence"; } public String getLastName() { return "Parr"; } public String getEmail() { return "parrt@jguru.com"; } public String getBio() { return "Superhero by night..."; } /** As of 2.0, booleans work as you expect. In 1.x, * a missing value simulated a boolean. */ public boolean getCanEdit() { return false; } } public class Connector2 { public int getID() { return 2; } public String getFirstName() { return "Tom"; } public String getLastName() { return "Burns"; } public String getEmail() { return "tombu@jguru.com"; } public String getBio() { return "Superhero by day..."; } public Boolean getCanEdit() { return new Boolean(true); } } public void testObjectPropertyReference() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", "."); StringTemplate t = new StringTemplate( group, "Name: $p.firstName$ $p.lastName$
    "+newline+ "Email: $p.email$
    "+newline+ "$p.bio$" ); t.setAttribute("p", new Connector()); //System.out.println("t is "+t.toString()); String expecting = "Name: Terence Parr
    "+newline+ "Email: parrt@jguru.com
    "+newline+ "Superhero by night..."; assertEquals(expecting, t.toString()); } public void testApplyRepeatedAnonymousTemplateWithForeignTemplateRefToMultiValuedAttribute() throws Exception { // specify a template to apply to an attribute // Use a template group so we can specify the start/stop chars StringTemplateGroup group = new StringTemplateGroup("dummy", "."); group.defineTemplate("link", "$title$"); StringTemplate duh = new StringTemplate(group, "start|$p:{$link(url=\"/member/view?ID=\"+it.ID, title=it.firstName)$ $if(it.canEdit)$canEdit$endif$}:"+ "{$it$
    \n}$|end"); duh.setAttribute("p", new Connector()); duh.setAttribute("p", new Connector2()); //System.out.println(duh); String expecting = "start|Terence
    "+newline+ "Tom canEdit
    "+newline+ "|end"; assertEquals(expecting,duh.toString()); } public static class Tree { protected List children = new LinkedList(); protected String text; public Tree(String t) { text = t; } public String getText() { return text; } public void addChild(Tree c) { children.add(c); } public Tree getFirstChild() { if ( children.size()==0 ) { return null; } return (Tree)children.get(0); } public List getChildren() { return children; } } public void testRecursion() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", ".", AngleBracketTemplateLexer.class); group.defineTemplate("tree", ""+ "( )" + "" + "" + ""); StringTemplate tree = group.getInstanceOf("tree"); // build ( a b (c d) e ) Tree root = new Tree("a"); root.addChild(new Tree("b")); Tree subtree = new Tree("c"); subtree.addChild(new Tree("d")); root.addChild(subtree); root.addChild(new Tree("e")); tree.setAttribute("it", root); String expecting = "( a b ( c d ) e )"; assertEquals(expecting, tree.toString()); } public void testNestedAnonymousTemplates() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", "."); StringTemplate t = new StringTemplate( group, "$A:{" + newline + "$it:{" + newline + "$it$" + newline + "}$" + newline + "}$" ); t.setAttribute("A", "parrt"); String expecting = newline + "" + newline + "parrt" + newline + "" + newline; assertEquals(expecting, t.toString()); } public void testAnonymousTemplateAccessToEnclosingAttributes() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", "."); StringTemplate t = new StringTemplate( group, "$A:{" + newline + "$it:{" + newline + "$it$, $B$" + newline + "}$" + newline + "}$" ); t.setAttribute("A", "parrt"); t.setAttribute("B", "tombu"); String expecting = newline + "" + newline + "parrt, tombu" + newline + "" + newline; assertEquals(expecting, t.toString()); } public void testNestedAnonymousTemplatesAgain() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", "."); StringTemplate t = new StringTemplate( group, "
    "+newline + "$names:{$it:{}$}$"+newline + "
    $it:{$it$}$
    "+newline ); t.setAttribute("names", "parrt"); t.setAttribute("names", "tombu"); String expecting = "" + newline + "" + newline + "
    parrt
    tombu
    " + newline; assertEquals(expecting, t.toString()); } public void testEscapes() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", "."); group.defineTemplate("foo", "$x$ && $it$"); StringTemplate t = new StringTemplate( group, "$A:foo(x=\"dog\\\"\\\"\")$" // $A:foo("dog\"\"")$ ); StringTemplate u = new StringTemplate( group, "$A:foo(x=\"dog\\\"g\")$" // $A:foo(x="dog\"g")$ ); StringTemplate v = new StringTemplate( group, // $A:{$attr:foo(x="\{dog\}\"")$ is cool}$ "$A:{$it:foo(x=\"\\{dog\\}\\\"\")$ is cool}$" ); t.setAttribute("A", "ick"); u.setAttribute("A", "ick"); v.setAttribute("A", "ick"); //System.out.println("t is '"+t.toString()+"'"); //System.out.println("u is '"+u.toString()+"'"); //System.out.println("v is '"+v.toString()+"'"); String expecting = "dog\"\" && ick"; assertEquals(expecting, t.toString()); expecting = "dog\"g && ick"; assertEquals(expecting,u.toString()); expecting = "{dog}\" && ick is cool"; assertEquals(expecting,v.toString()); } public void testEscapesOutsideExpressions() throws Exception { StringTemplate b = new StringTemplate("It\\'s ok...\\$; $a:{\\'hi\\', $it$}$"); b.setAttribute("a", "Ter"); String expecting ="It\\'s ok...$; \\'hi\\', Ter"; String result = b.toString(); assertEquals(expecting, result); } public void testElseClause() throws Exception { StringTemplate e = new StringTemplate( "$if(title)$"+newline + "foo"+newline + "$else$"+newline + "bar"+newline + "$endif$" ); e.setAttribute("title", "sample"); String expecting = "foo"; assertEquals(expecting, e.toString()); e = e.getInstanceOf(); expecting = "bar"; assertEquals(expecting, e.toString()); } public void testElseIfClause() throws Exception { StringTemplate e = new StringTemplate( "$if(x)$"+newline + "foo"+newline + "$elseif(y)$"+newline + "bar"+newline + "$endif$" ); e.setAttribute("y", "yep"); String expecting = "bar"; assertEquals(expecting, e.toString()); } public void testElseIfClauseAngleBrackets() throws Exception { StringTemplate e = new StringTemplate( ""+newline + "foo"+newline + ""+newline + "bar"+newline + "", AngleBracketTemplateLexer.class ); e.setAttribute("y", "yep"); String expecting = "bar"; assertEquals(expecting, e.toString()); } public void testElseIfClause2() throws Exception { StringTemplate e = new StringTemplate( "$if(x)$"+newline + "foo"+newline + "$elseif(y)$"+newline + "bar"+newline + "$elseif(z)$"+newline + "blort"+newline + "$endif$" ); e.setAttribute("z", "yep"); String expecting = "blort"; assertEquals(expecting, e.toString()); } public void testElseIfClauseAndElse() throws Exception { StringTemplate e = new StringTemplate( "$if(x)$"+newline + "foo"+newline + "$elseif(y)$"+newline + "bar"+newline + "$elseif(z)$"+newline + "z"+newline + "$else$"+newline + "blort"+newline + "$endif$" ); String expecting = "blort"; assertEquals(expecting, e.toString()); } public void testNestedIF() throws Exception { StringTemplate e = new StringTemplate( "$if(title)$"+newline + "foo"+newline + "$else$"+newline + "$if(header)$"+newline + "bar"+newline + "$else$"+newline + "blort"+newline + "$endif$"+newline + "$endif$" ); e.setAttribute("title", "sample"); String expecting = "foo"; assertEquals(expecting, e.toString()); e = e.getInstanceOf(); e.setAttribute("header", "more"); expecting = "bar"; assertEquals(expecting, e.toString()); e = e.getInstanceOf(); expecting = "blort"; assertEquals(expecting, e.toString()); } public void testEmbeddedMultiLineIF() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplate main = new StringTemplate(group, "$sub$"); StringTemplate sub = new StringTemplate(group, "begin" + newline + "$if(foo)$" + newline + "$foo$" + newline + "$else$" +newline + "blort" + newline + "$endif$" + newline ); sub.setAttribute("foo", "stuff"); main.setAttribute("sub", sub); String expecting = "begin"+newline+ "stuff"; assertEquals(expecting, main.toString()); main = new StringTemplate(group, "$sub$"); sub = sub.getInstanceOf(); main.setAttribute("sub", sub); expecting = "begin"+newline+ "blort"; assertEquals(expecting, main.toString()); } public void testSimpleIndentOfAttributeList() throws Exception { String templates = "group test;" +newline+ "list(names) ::= <<" + " $names; separator=\"\n\"$"+newline+ ">>"+newline; StringTemplateErrorListener errors = new ErrorBuffer(); StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class, errors); StringTemplate t = group.getInstanceOf("list"); t.setAttribute("names", "Terence"); t.setAttribute("names", "Jim"); t.setAttribute("names", "Sriram"); String expecting = " Terence"+newline+ " Jim"+newline+ " Sriram"; assertEquals(expecting, t.toString()); } public void testIndentOfMultilineAttributes() throws Exception { String templates = "group test;" +newline+ "list(names) ::= <<" + " $names; separator=\"\n\"$"+newline+ ">>"+newline; StringTemplateErrorListener errors = new ErrorBuffer(); StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class, errors); StringTemplate t = group.getInstanceOf("list"); t.setAttribute("names", "Terence\nis\na\nmaniac"); t.setAttribute("names", "Jim"); t.setAttribute("names", "Sriram\nis\ncool"); String expecting = " Terence"+newline+ " is"+newline+ " a"+newline+ " maniac"+newline+ " Jim"+newline+ " Sriram"+newline+ " is"+newline+ " cool"; assertEquals(expecting, t.toString()); } public void testIndentOfMultipleBlankLines() throws Exception { String templates = "group test;" +newline+ "list(names) ::= <<" + " $names$"+newline+ ">>"+newline; StringTemplateErrorListener errors = new ErrorBuffer(); StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class, errors); StringTemplate t = group.getInstanceOf("list"); t.setAttribute("names", "Terence\n\nis a maniac"); String expecting = " Terence"+newline+ ""+newline+ // no indent on blank line " is a maniac"; assertEquals(expecting, t.toString()); } public void testIndentBetweenLeftJustifiedLiterals() throws Exception { String templates = "group test;" +newline+ "list(names) ::= <<" + "Before:"+newline + " $names; separator=\"\\n\"$"+newline+ "after" +newline+ ">>"+newline; StringTemplateErrorListener errors = new ErrorBuffer(); StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class, errors); StringTemplate t = group.getInstanceOf("list"); t.setAttribute("names", "Terence"); t.setAttribute("names", "Jim"); t.setAttribute("names", "Sriram"); String expecting = "Before:" +newline+ " Terence"+newline+ " Jim"+newline+ " Sriram"+newline+ "after"; assertEquals(expecting, t.toString()); } public void testNestedIndent() throws Exception { String templates = "group test;" +newline+ "method(name,stats) ::= <<" + "void $name$() {"+newline + "\t$stats; separator=\"\\n\"$"+newline+ "}" +newline+ ">>"+newline+ "ifstat(expr,stats) ::= <<"+newline + "if ($expr$) {"+newline + " $stats; separator=\"\\n\"$"+newline + "}" + ">>"+newline + "assign(lhs,expr) ::= <<$lhs$=$expr$;>>"+newline ; StringTemplateErrorListener errors = new ErrorBuffer(); StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class, errors); StringTemplate t = group.getInstanceOf("method"); t.setAttribute("name", "foo"); StringTemplate s1 = group.getInstanceOf("assign"); s1.setAttribute("lhs", "x"); s1.setAttribute("expr", "0"); StringTemplate s2 = group.getInstanceOf("ifstat"); s2.setAttribute("expr", "x>0"); StringTemplate s2a = group.getInstanceOf("assign"); s2a.setAttribute("lhs", "y"); s2a.setAttribute("expr", "x+y"); StringTemplate s2b = group.getInstanceOf("assign"); s2b.setAttribute("lhs", "z"); s2b.setAttribute("expr", "4"); s2.setAttribute("stats", s2a); s2.setAttribute("stats", s2b); t.setAttribute("stats", s1); t.setAttribute("stats", s2); String expecting = "void foo() {"+newline+ "\tx=0;"+newline+ "\tif (x>0) {"+newline+ "\t y=x+y;"+newline+ "\t z=4;"+newline+ "\t}"+newline+ "}"; assertEquals(expecting, t.toString()); } public void testAlternativeWriter() throws Exception { final StringBuffer buf = new StringBuffer(); StringTemplateWriter w = new StringTemplateWriter() { public void pushIndentation(String indent) { } public String popIndentation() { return null; } public void pushAnchorPoint() { } public void popAnchorPoint() { } public void setLineWidth(int lineWidth) { } public int write(String str, String wrap) throws IOException { return 0; } public int write(String str) throws IOException { buf.append(str); // just pass thru return str.length(); } public int writeWrapSeparator(String wrap) throws IOException { return 0; } public int writeSeparator(String str) throws IOException { return write(str); } }; StringTemplateGroup group = new StringTemplateGroup("test"); group.defineTemplate("bold", "$x$"); StringTemplate name = new StringTemplate(group, "$name:bold(x=name)$"); name.setAttribute("name", "Terence"); name.write(w); assertEquals("Terence", buf.toString()); } public void testApplyAnonymousTemplateToMapAndSet() throws Exception { StringTemplate st = new StringTemplate("$items:{
  • $it$
  • }$"); Map m = new LinkedHashMap(); m.put("a", "1"); m.put("b", "2"); m.put("c", "3"); st.setAttribute("items", m); String expecting = "
  • 1
  • 2
  • 3
  • "; assertEquals(expecting, st.toString()); st = st.getInstanceOf(); Set s = new HashSet(); s.add("1"); s.add("2"); s.add("3"); st.setAttribute("items", s); expecting = "
  • 3
  • 2
  • 1
  • "; assertEquals(expecting, st.toString()); } public void testDumpMapAndSet() throws Exception { StringTemplate st = new StringTemplate("$items; separator=\",\"$"); Map m = new LinkedHashMap(); m.put("a", "1"); m.put("b", "2"); m.put("c", "3"); st.setAttribute("items", m); String expecting = "1,2,3"; assertEquals(expecting, st.toString()); st = st.getInstanceOf(); Set s = new HashSet(); s.add("1"); s.add("2"); s.add("3"); st.setAttribute("items", s); expecting = "3,2,1"; assertEquals(expecting, st.toString()); } public class Connector3 { public int[] getValues() { return new int[] {1,2,3}; } public Map getStuff() { Map m = new LinkedHashMap(); m.put("a","1"); m.put("b","2"); return m; } } public void testApplyAnonymousTemplateToArrayAndMapProperty() throws Exception { StringTemplate st = new StringTemplate("$x.values:{
  • $it$
  • }$"); st.setAttribute("x", new Connector3()); String expecting = "
  • 1
  • 2
  • 3
  • "; assertEquals(expecting, st.toString()); st = new StringTemplate("$x.stuff:{
  • $it$
  • }$"); st.setAttribute("x", new Connector3()); expecting = "
  • 1
  • 2
  • "; assertEquals(expecting, st.toString()); } public void testSuperTemplateRef() throws Exception { // you can refer to a template defined in a super group via super.t() StringTemplateGroup group = new StringTemplateGroup("super"); StringTemplateGroup subGroup = new StringTemplateGroup("sub"); subGroup.setSuperGroup(group); group.defineTemplate("page", "$font()$:text"); group.defineTemplate("font", "Helvetica"); subGroup.defineTemplate("font", "$super.font()$ and Times"); StringTemplate st = subGroup.getInstanceOf("page"); String expecting = "Helvetica and Times:text"; assertEquals(expecting, st.toString()); } public void testApplySuperTemplateRef() throws Exception { StringTemplateGroup group = new StringTemplateGroup("super"); StringTemplateGroup subGroup = new StringTemplateGroup("sub"); subGroup.setSuperGroup(group); group.defineTemplate("bold", "$it$"); subGroup.defineTemplate("bold", "$it$"); subGroup.defineTemplate("page", "$name:super.bold()$"); StringTemplate st = subGroup.getInstanceOf("page"); st.setAttribute("name", "Ter"); String expecting = "Ter"; assertEquals(expecting, st.toString()); } public void testLazyEvalOfSuperInApplySuperTemplateRef() throws Exception { StringTemplateGroup group = new StringTemplateGroup("base"); StringTemplateGroup subGroup = new StringTemplateGroup("sub"); subGroup.setSuperGroup(group); group.defineTemplate("bold", "$it$"); subGroup.defineTemplate("bold", "$it$"); // this is the same as testApplySuperTemplateRef() test // 'cept notice that here the supergroup defines page // As long as you create the instance via the subgroup, // "super." will evaluate lazily (i.e., not statically // during template compilation) to the templates // getGroup().superGroup value. If I create instance // of page in group not subGroup, however, I will get // an error as superGroup is null for group "group". group.defineTemplate("page", "$name:super.bold()$"); StringTemplate st = subGroup.getInstanceOf("page"); st.setAttribute("name", "Ter"); String error = null; try { st.toString(); } catch (IllegalArgumentException iae) { error = iae.getMessage(); } String expectingError = "base has no super group; invalid template: super.bold"; assertEquals(expectingError, error); } public void testTemplatePolymorphism() throws Exception { StringTemplateGroup group = new StringTemplateGroup("super"); StringTemplateGroup subGroup = new StringTemplateGroup("sub"); subGroup.setSuperGroup(group); // bold is defined in both super and sub // if you create an instance of page via the subgroup, // then bold() should evaluate to the subgroup not the super // even though page is defined in the super. Just like polymorphism. group.defineTemplate("bold", "$it$"); group.defineTemplate("page", "$name:bold()$"); subGroup.defineTemplate("bold", "$it$"); StringTemplate st = subGroup.getInstanceOf("page"); st.setAttribute("name", "Ter"); String expecting = "Ter"; assertEquals(expecting, st.toString()); } public void testListOfEmbeddedTemplateSeesEnclosingAttributes() throws Exception { String templates = "group test;" +newline+ "output(cond,items) ::= <>" +newline+ "mybody() ::= <<$font()$stuff>>" +newline+ "font() ::= <<$if(cond)$this$else$that$endif$>>" ; StringTemplateErrorListener errors = new ErrorBuffer(); StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class, errors); StringTemplate outputST = group.getInstanceOf("output"); StringTemplate bodyST1 = group.getInstanceOf("mybody"); StringTemplate bodyST2 = group.getInstanceOf("mybody"); StringTemplate bodyST3 = group.getInstanceOf("mybody"); outputST.setAttribute("items", bodyST1); outputST.setAttribute("items", bodyST2); outputST.setAttribute("items", bodyST3); String expecting = "page: thatstuffthatstuffthatstuff"; assertEquals(expecting, outputST.toString()); } public void testInheritArgumentFromRecursiveTemplateApplication() throws Exception { // do not inherit attributes through formal args String templates = "group test;" +newline+ "block(stats) ::= \"\"" + "ifstat(stats) ::= \"IF true then \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate b = group.getInstanceOf("block"); b.setAttribute("stats", group.getInstanceOf("ifstat")); b.setAttribute("stats", group.getInstanceOf("ifstat")); String expecting = "IF true then IF true then "; String result = b.toString(); //System.err.println("result='"+result+"'"); assertEquals(expecting, result); } public void testDeliberateRecursiveTemplateApplication() throws Exception { // This test will cause infinite loop. block contains a stat which // contains the same block. Must be in lintMode to detect String templates = "group test;" +newline+ "block(stats) ::= \"\"" + "ifstat(stats) ::= \"IF true then \""+newline ; StringTemplate.setLintMode(true); StringTemplate.resetTemplateCounter(); StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate b = group.getInstanceOf("block"); StringTemplate ifstat = group.getInstanceOf("ifstat"); b.setAttribute("stats", ifstat); // block has if stat ifstat.setAttribute("stats", b); // but make "if" contain block String expectingError = "infinite recursion to referenced in ; stack trace:"+newline + ", attributes=[stats=]>"+newline + ", attributes=[stats=], references=[stats]>"+newline + " (start of recursive cycle)"+newline + "..."; // note that attributes attribute doesn't show up in ifstat() because // recursion detection traps the problem before it writes out the // infinitely-recursive template; I set the attributes attribute right // before I render. String errors = ""; try { /*String result =*/ b.toString(); } catch (IllegalStateException ise) { errors = ise.getMessage(); } //System.err.println("errors="+errors+"'"); //System.err.println("expecting="+expectingError+"'"); StringTemplate.setLintMode(false); assertEquals(expectingError, errors); } public void testImmediateTemplateAsAttributeLoop() throws Exception { // even though block has a stats value that refers to itself, // there is no recursion because each instance of block hides // the stats value from above since it's a formal arg. String templates = "group test;" +newline+ "block(stats) ::= \"{}\"" ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate b = group.getInstanceOf("block"); b.setAttribute("stats", group.getInstanceOf("block")); String expecting ="{{}}"; String result = b.toString(); //System.err.println(result); assertEquals(expecting, result); } public void testTemplateAlias() throws Exception { String templates = "group test;" +newline+ "page(name) ::= \"name is \"" + "other ::= page"+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate b = group.getInstanceOf("other"); // alias for page b.setAttribute("name", "Ter"); String expecting ="name is Ter"; String result = b.toString(); assertEquals(expecting, result); } public void testTemplateGetPropertyGetsAttribute() throws Exception { // This test will cause infinite loop if missing attribute no // properly caught in getAttribute String templates = "group test;"+newline+ "Cfile(funcs) ::= <<"+newline + "#include \\"+newline+ "();}; separator=\"\\n\">"+newline+ ""+newline+ ">>"+newline + "func(name,args,body) ::= <<"+newline+ "public void () {}"+newline + ">>"+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate b = group.getInstanceOf("Cfile"); StringTemplate f1 = group.getInstanceOf("func"); StringTemplate f2 = group.getInstanceOf("func"); f1.setAttribute("name", "f"); f1.setAttribute("args", ""); f1.setAttribute("body", "i=1;"); f2.setAttribute("name", "g"); f2.setAttribute("args", "int arg"); f2.setAttribute("body", "y=1;"); b.setAttribute("funcs",f1); b.setAttribute("funcs",f2); String expecting = "#include " +newline+ "public void f();"+newline+ "public void g(int arg);" +newline+ "public void f() {i=1;}"+newline+ "public void g(int arg) {y=1;}"; assertEquals(expecting,b.toString()); } public static class Decl { String name; String type; public Decl(String name, String type) {this.name=name; this.type=type;} public String getName() {return name;} public String getType() {return type;} } public void testComplicatedIndirectTemplateApplication() throws Exception { String templates = "group Java;"+newline + ""+newline + "file(variables) ::= <<" + "}; separator=\"\\n\">"+newline + ">>"+newline+ "intdecl(decl) ::= \"int = 0;\""+newline + "intarray(decl) ::= \"int[] = null;\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate f = group.getInstanceOf("file"); f.setAttribute("variables.{decl,format}", new Decl("i","int"), "intdecl"); f.setAttribute("variables.{decl,format}", new Decl("a","int-array"), "intarray"); //System.out.println("f='"+f+"'"); String expecting = "int i = 0;" +newline+ "int[] a = null;"; assertEquals(expecting, f.toString()); } public void testIndirectTemplateApplication() throws Exception { String templates = "group dork;"+newline + ""+newline + "test(name) ::= <<" + "<(name)()>"+newline + ">>"+newline+ "first() ::= \"the first\""+newline + "second() ::= \"the second\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate f = group.getInstanceOf("test"); f.setAttribute("name", "first"); String expecting = "the first"; assertEquals(expecting, f.toString()); } public void testIndirectTemplateWithArgsApplication() throws Exception { String templates = "group dork;"+newline + ""+newline + "test(name) ::= <<" + "<(name)(a=\"foo\")>"+newline + ">>"+newline+ "first(a) ::= \"the first: \""+newline + "second(a) ::= \"the second \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate f = group.getInstanceOf("test"); f.setAttribute("name", "first"); String expecting = "the first: foo"; assertEquals(f.toString(), expecting); } public void testNullIndirectTemplateApplication() throws Exception { String templates = "group dork;"+newline + ""+newline + "test(names,t) ::= <<" + ""+newline + // t null be must be defined else error: null attr w/o formal def ">>"+newline+ "ind() ::= \"[]\""+newline; ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate f = group.getInstanceOf("test"); f.setAttribute("names", "me"); f.setAttribute("names", "you"); String expecting = ""; assertEquals(expecting, f.toString()); } public void testNullIndirectTemplate() throws Exception { String templates = "group dork;"+newline + ""+newline + "test(name) ::= <<" + "<(name)()>"+newline + ">>"+newline+ "first() ::= \"the first\""+newline + "second() ::= \"the second\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate f = group.getInstanceOf("test"); //f.setAttribute("name", "first"); String expecting = ""; assertEquals(expecting, f.toString()); } public void testHashMapPropertyFetch() throws Exception { StringTemplate a = new StringTemplate("$stuff.prop$"); HashMap map = new HashMap(); a.setAttribute("stuff", map); map.put("prop", "Terence"); String results = a.toString(); //System.out.println(results); String expecting = "Terence"; assertEquals(expecting, results); } public void testHashMapPropertyFetchEmbeddedStringTemplate() throws Exception { StringTemplate a = new StringTemplate("$stuff.prop$"); HashMap map = new HashMap(); a.setAttribute("stuff", map); a.setAttribute("title", "ST rocks"); map.put("prop", new StringTemplate("embedded refers to $title$")); String results = a.toString(); //System.out.println(results); String expecting = "embedded refers to ST rocks"; assertEquals(expecting, results); } public void testEmbeddedComments() throws Exception { StringTemplate st = new StringTemplate( "Foo $! ignore !$bar" +newline ); String expecting ="Foo bar"+newline; String result = st.toString(); assertEquals(expecting, result); st = new StringTemplate( "Foo $! ignore" +newline+ " and a line break!$" +newline+ "bar" +newline ); expecting ="Foo "+newline+"bar"+newline; result = st.toString(); assertEquals(expecting, result); st = new StringTemplate( "$! start of line $ and $! ick" +newline+ "!$boo"+newline ); expecting ="boo"+newline; result = st.toString(); assertEquals(expecting, result); st = new StringTemplate( "$! start of line !$" +newline+ "$! another to ignore !$" +newline+ "$! ick" +newline+ "!$boo"+newline ); expecting ="boo"+newline; result = st.toString(); assertEquals(expecting, result); st = new StringTemplate( "$! back !$$! to back !$" +newline+ // can't detect; leaves \n "$! ick" +newline+ "!$boo"+newline ); expecting =newline+"boo"+newline; result = st.toString(); assertEquals(expecting, result); } public void testEmbeddedCommentsAngleBracketed() throws Exception { StringTemplate st = new StringTemplate( "Foo bar" +newline, AngleBracketTemplateLexer.class ); String expecting ="Foo bar"+newline; String result = st.toString(); assertEquals(expecting, result); st = new StringTemplate( "Foo " +newline+ "bar" +newline, AngleBracketTemplateLexer.class ); expecting ="Foo "+newline+"bar"+newline; result = st.toString(); assertEquals(expecting, result); st = new StringTemplate( "boo"+newline, AngleBracketTemplateLexer.class ); expecting ="boo"+newline; result = st.toString(); assertEquals(expecting, result); st = new StringTemplate( "" + "" + "boo"+newline, AngleBracketTemplateLexer.class ); expecting ="boo"+newline; result = st.toString(); //System.out.println(result); assertEquals(expecting, result); st = new StringTemplate( "" +newline+ // can't detect; leaves \n "boo"+newline, AngleBracketTemplateLexer.class ); expecting =newline+"boo"+newline; result = st.toString(); assertEquals(expecting, result); } public void testLineBreak() throws Exception { StringTemplate st = new StringTemplate( "Foo <\\\\>"+newline+ " \t bar" +newline, AngleBracketTemplateLexer.class ); StringWriter sw = new StringWriter(); st.write(new AutoIndentWriter(sw,"\n")); // force \n as newline String result = sw.toString(); String expecting ="Foo bar"+newline; // expect \n in output assertEquals(expecting, result); } public void testLineBreak2() throws Exception { StringTemplate st = new StringTemplate( "Foo <\\\\> "+newline+ " \t bar" +newline, AngleBracketTemplateLexer.class ); StringWriter sw = new StringWriter(); st.write(new AutoIndentWriter(sw,"\n")); // force \n as newline String result = sw.toString(); String expecting ="Foo bar"+newline; // expect \n in output assertEquals(expecting, result); } public void testLineBreakNoWhiteSpace() throws Exception { StringTemplate st = new StringTemplate( "Foo <\\\\>"+newline+ "bar" +newline, AngleBracketTemplateLexer.class ); StringWriter sw = new StringWriter(); st.write(new AutoIndentWriter(sw,"\n")); // force \n as newline String result = sw.toString(); String expecting ="Foo bar"+newline; // expect \n in output assertEquals(expecting, result); } public void testLineBreakDollar() throws Exception { StringTemplate st = new StringTemplate( "Foo $\\\\$"+newline+ " \t bar" +newline, DefaultTemplateLexer.class ); StringWriter sw = new StringWriter(); st.write(new AutoIndentWriter(sw,"\n")); // force \n as newline String result = sw.toString(); String expecting ="Foo bar"+newline; // expect \n in output assertEquals(expecting, result); } public void testLineBreakDollar2() throws Exception { StringTemplate st = new StringTemplate( "Foo $\\\\$ "+newline+ " \t bar" +newline, DefaultTemplateLexer.class ); StringWriter sw = new StringWriter(); st.write(new AutoIndentWriter(sw,"\n")); // force \n as newline String result = sw.toString(); String expecting ="Foo bar"+newline; // expect \n in output assertEquals(expecting, result); } public void testLineBreakNoWhiteSpaceDollar() throws Exception { StringTemplate st = new StringTemplate( "Foo $\\\\$"+newline+ "bar" +newline, DefaultTemplateLexer.class ); StringWriter sw = new StringWriter(); st.write(new AutoIndentWriter(sw,"\n")); // force \n as newline String result = sw.toString(); String expecting ="Foo bar"+newline; // expect \n in output assertEquals(expecting, result); } public void testCharLiterals() throws Exception { StringTemplate st = new StringTemplate( "Foo <\\r\\n><\\n><\\t> bar" +newline, AngleBracketTemplateLexer.class ); StringWriter sw = new StringWriter(); st.write(new AutoIndentWriter(sw,"\n")); // force \n as newline String result = sw.toString(); String expecting ="Foo \n\n\t bar"+newline; // expect \n in output assertEquals(expecting, result); st = new StringTemplate( "Foo $\\n$$\\t$ bar" +newline); sw = new StringWriter(); st.write(new AutoIndentWriter(sw,"\n")); // force \n as newline expecting ="Foo \n\t bar"+newline; // expect \n in output result = sw.toString(); assertEquals(expecting, result); st = new StringTemplate( "Foo$\\ $bar$\\n$"); sw = new StringWriter(); st.write(new AutoIndentWriter(sw,"\n")); // force \n as newline result = sw.toString(); expecting ="Foo bar\n"; // force \n assertEquals(expecting, result); } public void testNewlineNormalizationInTemplateString() throws Exception { StringTemplate st = new StringTemplate( "Foo\r\n"+ "Bar\n", AngleBracketTemplateLexer.class ); StringWriter sw = new StringWriter(); st.write(new AutoIndentWriter(sw,"\n")); // force \n as newline String result = sw.toString(); String expecting ="Foo\nBar\n"; // expect \n in output assertEquals(expecting, result); } public void testNewlineNormalizationInTemplateStringPC() throws Exception { StringTemplate st = new StringTemplate( "Foo\r\n"+ "Bar\n", AngleBracketTemplateLexer.class ); StringWriter sw = new StringWriter(); st.write(new AutoIndentWriter(sw,"\r\n")); // force \r\n as newline String result = sw.toString(); String expecting ="Foo\r\nBar\r\n"; // expect \r\n in output assertEquals(expecting, result); } public void testNewlineNormalizationInAttribute() throws Exception { StringTemplate st = new StringTemplate( "Foo\r\n"+ "\n", AngleBracketTemplateLexer.class ); st.setAttribute("name", "a\nb\r\nc"); StringWriter sw = new StringWriter(); st.write(new AutoIndentWriter(sw,"\n")); // force \n as newline String result = sw.toString(); String expecting ="Foo\na\nb\nc\n"; // expect \n in output assertEquals(expecting, result); } public void testUnicodeLiterals() throws Exception { StringTemplate st = new StringTemplate( "Foo <\\uFEA5\\n\\u00C2> bar" +newline, AngleBracketTemplateLexer.class ); String expecting ="Foo \ufea5"+newline+"\u00C2 bar"+newline; String result = st.toString(); assertEquals(expecting, result); st = new StringTemplate( "Foo $\\uFEA5\\n\\u00C2$ bar" +newline); expecting ="Foo \ufea5"+newline+"\u00C2 bar"+newline; result = st.toString(); assertEquals(expecting, result); st = new StringTemplate( "Foo$\\ $bar$\\n$"); expecting ="Foo bar"+newline; result = st.toString(); assertEquals(expecting, result); } public void testEmptyIteratedValueGetsSeparator() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplateErrorListener errors = new ErrorBuffer(); group.setErrorListener(errors); StringTemplate t = new StringTemplate(group, "$names; separator=\",\"$"); t.setAttribute("names", "Terence"); t.setAttribute("names", ""); t.setAttribute("names", ""); t.setAttribute("names", "Tom"); t.setAttribute("names", "Frank"); t.setAttribute("names", ""); // empty values get separator still String expecting="Terence,,,Tom,Frank,"; String result = t.toString(); assertEquals(expecting, result); } public void testMissingIteratedConditionalValueGetsNOSeparator() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplateErrorListener errors = new ErrorBuffer(); group.setErrorListener(errors); StringTemplate t = new StringTemplate(group, "$users:{$if(it.ok)$$it.name$$endif$}; separator=\",\"$"); t.setAttribute("users.{name,ok}", "Terence", new Boolean(true)); t.setAttribute("users.{name,ok}", "Tom", new Boolean(false)); t.setAttribute("users.{name,ok}", "Frank", new Boolean(true)); t.setAttribute("users.{name,ok}", "Johnny", new Boolean(false)); // empty conditional values get no separator String expecting="Terence,Frank"; String result = t.toString(); assertEquals(expecting, result); } public void testMissingIteratedConditionalValueGetsNOSeparator2() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplateErrorListener errors = new ErrorBuffer(); group.setErrorListener(errors); StringTemplate t = new StringTemplate(group, "$users:{$if(it.ok)$$it.name$$endif$}; separator=\",\"$"); t.setAttribute("users.{name,ok}", "Terence", new Boolean(true)); t.setAttribute("users.{name,ok}", "Tom", new Boolean(false)); t.setAttribute("users.{name,ok}", "Frank", new Boolean(false)); t.setAttribute("users.{name,ok}", "Johnny", new Boolean(false)); // empty conditional values get no separator String expecting="Terence"; String result = t.toString(); assertEquals(expecting, result); } public void testMissingIteratedDoubleConditionalValueGetsNOSeparator() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplateErrorListener errors = new ErrorBuffer(); group.setErrorListener(errors); StringTemplate t = new StringTemplate(group, "$users:{$if(it.ok)$$it.name$$endif$$if(it.ok)$$it.name$$endif$}; separator=\",\"$"); t.setAttribute("users.{name,ok}", "Terence", new Boolean(false)); t.setAttribute("users.{name,ok}", "Tom", new Boolean(true)); t.setAttribute("users.{name,ok}", "Frank", new Boolean(true)); t.setAttribute("users.{name,ok}", "Johnny", new Boolean(true)); // empty conditional values get no separator String expecting="TomTom,FrankFrank,JohnnyJohnny"; String result = t.toString(); assertEquals(expecting, result); } public void testIteratedConditionalWithEmptyElseValueGetsSeparator() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplateErrorListener errors = new ErrorBuffer(); group.setErrorListener(errors); StringTemplate t = new StringTemplate(group, "$users:{$if(it.ok)$$it.name$$else$$endif$}; separator=\",\"$"); t.setAttribute("users.{name,ok}", "Terence", new Boolean(true)); t.setAttribute("users.{name,ok}", "Tom", new Boolean(false)); t.setAttribute("users.{name,ok}", "Frank", new Boolean(true)); t.setAttribute("users.{name,ok}", "Johnny", new Boolean(false)); // empty conditional values get no separator String expecting="Terence,,Frank,"; String result = t.toString(); assertEquals(expecting, result); } public void testWhiteSpaceAtEndOfTemplate() throws Exception { StringTemplateGroup group = new StringTemplateGroup("group"); StringTemplate pageST = group.getInstanceOf("org/antlr/stringtemplate/test/page"); StringTemplate listST = group.getInstanceOf("org/antlr/stringtemplate/test/users_list"); // users.list references row.st which has a single blank line at the end. // I.e., there are 2 \n in a row at the end // ST should eat all whitespace at end listST.setAttribute("users", new Connector()); listST.setAttribute("users", new Connector2()); pageST.setAttribute("title", "some title"); pageST.setAttribute("body", listST); String expecting ="some title" +newline+ "Terence parrt@jguru.comTom tombu@jguru.com"; String result = pageST.toString(); //System.out.println("'"+result+"'"); assertEquals(expecting, result); } static class Duh { public List users = new ArrayList(); } public void testSizeZeroButNonNullListGetsNoOutput() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplateErrorListener errors = new ErrorBuffer(); group.setErrorListener(errors); StringTemplate t = new StringTemplate(group, "begin\n" + "$duh.users:{name: $it$}; separator=\", \"$\n" + "end\n"); t.setAttribute("duh", new Duh()); String expecting="begin\nend\n"; String result = t.toString(); assertEquals(expecting, result); } public void testNullListGetsNoOutput() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplateErrorListener errors = new ErrorBuffer(); group.setErrorListener(errors); StringTemplate t = new StringTemplate(group, "begin\n" + "$users:{name: $it$}; separator=\", \"$\n" + "end\n"); //t.setAttribute("users", new Duh()); String expecting="begin\nend\n"; String result = t.toString(); assertEquals(expecting, result); } public void testEmptyListGetsNoOutput() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplateErrorListener errors = new ErrorBuffer(); group.setErrorListener(errors); StringTemplate t = new StringTemplate(group, "begin\n" + "$users:{name: $it$}; separator=\", \"$\n" + "end\n"); t.setAttribute("users", new ArrayList()); String expecting="begin\nend\n"; String result = t.toString(); assertEquals(expecting, result); } public void testEmptyListNoIteratorGetsNoOutput() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplateErrorListener errors = new ErrorBuffer(); group.setErrorListener(errors); StringTemplate t = new StringTemplate(group, "begin\n" + "$users; separator=\", \"$\n" + "end\n"); t.setAttribute("users", new ArrayList()); String expecting="begin\nend\n"; String result = t.toString(); assertEquals(expecting, result); } public void testEmptyExprAsFirstLineGetsNoOutput() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplateErrorListener errors = new ErrorBuffer(); group.setErrorListener(errors); group.defineTemplate("bold", "$it$"); StringTemplate t = new StringTemplate(group, "$users$\n" + "end\n"); String expecting="end\n"; String result = t.toString(); assertEquals(expecting, result); } public void testSizeZeroOnLineByItselfGetsNoOutput() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplateErrorListener errors = new ErrorBuffer(); group.setErrorListener(errors); StringTemplate t = new StringTemplate(group, "begin\n"+ "$name$\n"+ "$users:{name: $it$}$\n"+ "$users:{name: $it$}; separator=\", \"$\n"+ "end\n"); String expecting="begin\nend\n"; String result = t.toString(); assertEquals(expecting, result); } public void testSizeZeroOnLineWithIndentGetsNoOutput() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplateErrorListener errors = new ErrorBuffer(); group.setErrorListener(errors); StringTemplate t = new StringTemplate(group, "begin\n"+ " $name$\n"+ " $users:{name: $it$}$\n"+ " $users:{name: $it$$\\n$}$\n"+ "end\n"); String expecting="begin\nend\n"; String result = t.toString(); assertEquals(expecting, result); } public void testSimpleAutoIndent() throws Exception { StringTemplate a = new StringTemplate( "$title$: {\n" + " $name; separator=\"\n\"$\n" + "}"); a.setAttribute("title", "foo"); a.setAttribute("name", "Terence"); a.setAttribute("name", "Frank"); String results = a.toString(); //System.out.println(results); String expecting = "foo: {\n" + " Terence\n" + " Frank\n" + "}"; assertEquals(results, expecting); } public void testComputedPropertyName() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplateErrorListener errors = new ErrorBuffer(); group.setErrorListener(errors); StringTemplate t = new StringTemplate(group, "variable property $propName$=$v.(propName)$"); t.setAttribute("v", new Decl("i","int")); t.setAttribute("propName", "type"); String expecting="variable property type=int"; String result = t.toString(); assertEquals("", errors.toString()); assertEquals(expecting, result); } public void testNonNullButEmptyIteratorTestsFalse() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplate t = new StringTemplate(group, "$if(users)$\n" + "Users: $users:{$it.name$ }$\n" + "$endif$"); t.setAttribute("users", new LinkedList()); String expecting=""; String result = t.toString(); assertEquals(expecting, result); } public void testDoNotInheritAttributesThroughFormalArgs() throws Exception { String templates = "group test;" +newline+ "method(name) ::= \"\"" +newline+ "stat(name) ::= \"x=y; // \""+newline ; // name is not visible in stat because of the formal arg called name. // somehow, it must be set. StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate b = group.getInstanceOf("method"); b.setAttribute("name", "foo"); String expecting = "x=y; // "; String result = b.toString(); //System.err.println("result='"+result+"'"); assertEquals(expecting, result); } public void testArgEvaluationContext() throws Exception { String templates = "group test;" +newline+ "method(name) ::= \"\"" +newline+ "stat(name) ::= \"x=y; // \""+newline ; // attribute name is not visible in stat because of the formal // arg called name in template stat. However, we can set it's value // with an explicit name=name. This looks weird, but makes total // sense as the rhs is evaluated in the context of method and the lhs // is evaluated in the context of stat's arg list. StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate b = group.getInstanceOf("method"); b.setAttribute("name", "foo"); String expecting = "x=y; // foo"; String result = b.toString(); //System.err.println("result='"+result+"'"); assertEquals(expecting, result); } public void testPassThroughAttributes() throws Exception { String templates = "group test;" +newline+ "method(name) ::= \"\"" +newline+ "stat(name) ::= \"x=y; // \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate b = group.getInstanceOf("method"); b.setAttribute("name", "foo"); String expecting = "x=y; // foo"; String result = b.toString(); //System.err.println("result='"+result+"'"); assertEquals(expecting, result); } public void testPassThroughAttributes2() throws Exception { String templates = "group test;" +newline+ "method(name) ::= <<"+newline+ "" +newline+ ">>"+newline+ "stat(name,value) ::= \"x=; // \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate b = group.getInstanceOf("method"); b.setAttribute("name", "foo"); String expecting = "x=34; // foo"; String result = b.toString(); //System.err.println("result='"+result+"'"); assertEquals(expecting, result); } public void testDefaultArgument() throws Exception { String templates = "group test;" +newline+ "method(name) ::= <<"+newline+ "" +newline+ ">>"+newline+ "stat(name,value=\"99\") ::= \"x=; // \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate b = group.getInstanceOf("method"); b.setAttribute("name", "foo"); String expecting = "x=99; // foo"; String result = b.toString(); //System.err.println("result='"+result+"'"); assertEquals(expecting, result); } public void testDefaultArgument2() throws Exception { String templates = "group test;" +newline+ "stat(name,value=\"99\") ::= \"x=; // \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate b = group.getInstanceOf("stat"); b.setAttribute("name", "foo"); String expecting = "x=99; // foo"; String result = b.toString(); //System.err.println("result='"+result+"'"); assertEquals(expecting, result); } public void testDefaultArgumentManuallySet() throws Exception { class Field { public String name = "parrt"; public int n = 0; public String toString() { return "Field"; } } String templates = "group test;" +newline+ "method(fields) ::= <<"+newline+ "}>" +newline+ ">>"+newline+ "stat(f,value={}) ::= \"x=; // \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate m = group.getInstanceOf("method"); m.setAttribute("fields", new Field()); String expecting = "x=parrt; // parrt"; String result = m.toString(); assertEquals(expecting, result); } /** This fails because checkNullAttributeAgainstFormalArguments looks * for a formal argument at the current level not of the original embedded * template. We have defined it all the way in the embedded, but there is * no value so we try to look upwards ala dynamic scoping. When it reaches * the top, it doesn't find a value but it will miss the * formal argument down in the embedded. * * By definition, though, the formal parameter exists if we have * a default value. look up the value to see if it's null without * checking checkNullAttributeAgainstFormalArguments. */ public void testDefaultArgumentImplicitlySet() throws Exception { class Field { public String name = "parrt"; public int n = 0; public String toString() { return "Field"; } } String templates = "group test;" +newline+ "method(fields) ::= <<"+newline+ "}>" +newline+ ">>"+newline+ "stat(f,value={}) ::= \"x=; // \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate m = group.getInstanceOf("method"); m.setAttribute("fields", new Field()); String expecting = "x=parrt; // parrt"; String result = m.toString(); assertEquals(expecting, result); } /* FIX THIS public void testDefaultArgumentImplicitlySet2() throws Exception { class Field { public String name = "parrt"; public int n = 0; public String toString() { return "Field"; } } String templates = "group test;" +newline+ "method(fields) ::= <<"+newline+ "}>" +newline+ // THIS SHOULD BE ERROR; >1 arg? ">>"+newline+ "stat(f,value={}) ::= \"x=; // \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate m = group.getInstanceOf("method"); m.setAttribute("fields", new Field()); String expecting = "x=parrt; // parrt"; String result = m.toString(); assertEquals(expecting, result); } */ public void testDefaultArgumentAsTemplate() throws Exception { String templates = "group test;" +newline+ "method(name,size) ::= <<"+newline+ "" +newline+ ">>"+newline+ "stat(name,value={}) ::= \"x=; // \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate b = group.getInstanceOf("method"); b.setAttribute("name", "foo"); b.setAttribute("size", "2"); String expecting = "x=foo; // foo"; String result = b.toString(); //System.err.println("result='"+result+"'"); assertEquals(expecting, result); } public void testDefaultArgumentAsTemplate2() throws Exception { String templates = "group test;" +newline+ "method(name,size) ::= <<"+newline+ "" +newline+ ">>"+newline+ "stat(name,value={ [] }) ::= \"x=; // \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate b = group.getInstanceOf("method"); b.setAttribute("name", "foo"); b.setAttribute("size", "2"); String expecting = "x= [foo] ; // foo"; String result = b.toString(); //System.err.println("result='"+result+"'"); assertEquals(expecting, result); } public void testDoNotUseDefaultArgument() throws Exception { String templates = "group test;" +newline+ "method(name) ::= <<"+newline+ "" +newline+ ">>"+newline+ "stat(name,value=\"99\") ::= \"x=; // \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate b = group.getInstanceOf("method"); b.setAttribute("name", "foo"); String expecting = "x=34; // foo"; String result = b.toString(); assertEquals(expecting, result); } public void testDefaultArgumentInParensToEvalEarly() throws Exception { class Counter { int n = 0; public String toString() { return String.valueOf(n++); } } String templates = "group test;" +newline+ "A(x) ::= \"\""+newline+ "B(y={<(x)>}) ::= \" \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate b = group.getInstanceOf("A"); b.setAttribute("x", new Counter()); String expecting = "0 1 2 0"; String result = b.toString(); //System.err.println("result='"+result+"'"); assertEquals(expecting, result); } public void testArgumentsAsTemplates() throws Exception { String templates = "group test;" +newline+ "method(name,size) ::= <<"+newline+ "})>" +newline+ ">>"+newline+ "stat(value) ::= \"x=;\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate b = group.getInstanceOf("method"); b.setAttribute("name", "foo"); b.setAttribute("size", "34"); String expecting = "x=34;"; String result = b.toString(); assertEquals(expecting, result); } public void testTemplateArgumentEvaluatedInSurroundingContext() throws Exception { String templates = "group test;" +newline+ "file(m,size) ::= \"\""+newline+ "method(name) ::= <<"+newline+ ".0})>" +newline+ ">>"+newline+ "stat(value) ::= \"x=;\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate f = group.getInstanceOf("file"); f.setAttribute("size", "34"); StringTemplate m = group.getInstanceOf("method"); m.setAttribute("name", "foo"); f.setAttribute("m", m); String expecting = "x=34.0;"; String result = m.toString(); assertEquals(expecting, result); } public void testArgumentsAsTemplatesDefaultDelimiters() throws Exception { String templates = "group test;" +newline+ "method(name,size) ::= <<"+newline+ "$stat(value={$size$})$" +newline+ ">>"+newline+ "stat(value) ::= \"x=$value$;\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class); StringTemplate b = group.getInstanceOf("method"); b.setAttribute("name", "foo"); b.setAttribute("size", "34"); String expecting = "x=34;"; String result = b.toString(); assertEquals(expecting, result); } public void testDefaultArgsWhenNotInvoked() throws Exception { String templates = "group test;" +newline+ "b(name=\"foo\") ::= \"..\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate b = group.getInstanceOf("b"); String expecting = ".foo."; String result = b.toString(); assertEquals(expecting, result); } public class DateRenderer implements AttributeRenderer { public String toString(Object o) { SimpleDateFormat f = new SimpleDateFormat ("yyyy.MM.dd"); return f.format(((Calendar)o).getTime()); } public String toString(Object o, String formatString) { return toString(o); } } public class DateRenderer2 implements AttributeRenderer { public String toString(Object o) { SimpleDateFormat f = new SimpleDateFormat ("MM/dd/yyyy"); return f.format(((Calendar)o).getTime()); } public String toString(Object o, String formatString) { return toString(o); } } public class DateRenderer3 implements AttributeRenderer { public String toString(Object o) { SimpleDateFormat f = new SimpleDateFormat ("MM/dd/yyyy"); return f.format(((Calendar)o).getTime()); } public String toString(Object o, String formatString) { SimpleDateFormat f = new SimpleDateFormat (formatString); return f.format(((Calendar)o).getTime()); } } public class StringRenderer implements AttributeRenderer { public String toString(Object o) { return (String)o; } public String toString(Object o, String formatString) { if ( formatString.equals("upper") ) { return ((String)o).toUpperCase(); } return toString(o); } } public void testRendererForST() throws Exception { StringTemplate st =new StringTemplate( "date: ", AngleBracketTemplateLexer.class); st.setAttribute("created", new GregorianCalendar(2005, 07-1, 05)); st.registerRenderer(GregorianCalendar.class, new DateRenderer()); String expecting = "date: 2005.07.05"; String result = st.toString(); assertEquals(expecting, result); } public void testRendererWithFormat() throws Exception { StringTemplate st =new StringTemplate( "date: ", AngleBracketTemplateLexer.class); st.setAttribute("created", new GregorianCalendar(2005, 07-1, 05)); st.registerRenderer(GregorianCalendar.class, new DateRenderer3()); String expecting = "date: 2005.07.05"; String result = st.toString(); assertEquals(expecting, result); } public void testRendererWithFormatAndList() throws Exception { StringTemplate st =new StringTemplate( "The names: ", AngleBracketTemplateLexer.class); st.setAttribute("names", "ter"); st.setAttribute("names", "tom"); st.setAttribute("names", "sriram"); st.registerRenderer(String.class, new StringRenderer()); String expecting = "The names: TERTOMSRIRAM"; String result = st.toString(); assertEquals(expecting, result); } public void testRendererWithFormatAndSeparator() throws Exception { StringTemplate st =new StringTemplate( "The names: ", AngleBracketTemplateLexer.class); st.setAttribute("names", "ter"); st.setAttribute("names", "tom"); st.setAttribute("names", "sriram"); st.registerRenderer(String.class, new StringRenderer()); String expecting = "The names: TER and TOM and SRIRAM"; String result = st.toString(); assertEquals(expecting, result); } public void testRendererWithFormatAndSeparatorAndNull() throws Exception { StringTemplate st =new StringTemplate( "The names: ", AngleBracketTemplateLexer.class); List names = new ArrayList(); names.add("ter"); names.add(null); names.add("sriram"); st.setAttribute("names", names); st.registerRenderer(String.class, new StringRenderer()); String expecting = "The names: TER and N/A and SRIRAM"; String result = st.toString(); assertEquals(expecting, result); } public void testEmbeddedRendererSeesEnclosing() throws Exception { // st is embedded in outer; set renderer on outer, st should // still see it. StringTemplate outer =new StringTemplate( "X: ", AngleBracketTemplateLexer.class); StringTemplate st =new StringTemplate( "date: ", AngleBracketTemplateLexer.class); st.setAttribute("created", new GregorianCalendar(2005, 07-1, 05)); outer.setAttribute("x", st); outer.registerRenderer(GregorianCalendar.class, new DateRenderer()); String expecting = "X: date: 2005.07.05"; String result = outer.toString(); assertEquals(expecting, result); } public void testRendererForGroup() throws Exception { String templates = "group test;" +newline+ "dateThing(created) ::= \"date: \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("dateThing"); st.setAttribute("created", new GregorianCalendar(2005, 07-1, 05)); group.registerRenderer(GregorianCalendar.class, new DateRenderer()); String expecting = "date: 2005.07.05"; String result = st.toString(); assertEquals(expecting, result); } public void testOverriddenRenderer() throws Exception { String templates = "group test;" +newline+ "dateThing(created) ::= \"date: \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("dateThing"); st.setAttribute("created", new GregorianCalendar(2005, 07-1, 05)); group.registerRenderer(GregorianCalendar.class, new DateRenderer()); st.registerRenderer(GregorianCalendar.class, new DateRenderer2()); String expecting = "date: 07/05/2005"; String result = st.toString(); assertEquals(expecting, result); } public void testMap() throws Exception { String templates = "group test;" +newline+ "typeInit ::= [\"int\":\"0\", \"float\":\"0.0\"] "+newline+ "var(type,name) ::= \" = ;\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("var"); st.setAttribute("type", "int"); st.setAttribute("name", "x"); String expecting = "int x = 0;"; String result = st.toString(); assertEquals(expecting, result); } public void testMapValuesAreTemplates() throws Exception { String templates = "group test;" +newline+ "typeInit ::= [\"int\":\"0\", \"float\":\"0.0\"] "+newline+ "var(type,w,name) ::= \" = ;\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("var"); st.setAttribute("w", "L"); st.setAttribute("type", "int"); st.setAttribute("name", "x"); String expecting = "int x = 0L;"; String result = st.toString(); assertEquals(expecting, result); } public void testMapKeyLookupViaTemplate() throws Exception { // ST doesn't do a toString on .(key) values, it just uses the value // of key rather than key itself as the key. But, if you compute a // key via a template String templates = "group test;" +newline+ "typeInit ::= [\"int\":\"0\", \"float\":\"0.0\"] "+newline+ "var(type,w,name) ::= \" = ;\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("var"); st.setAttribute("w", "L"); st.setAttribute("type", new StringTemplate("int")); st.setAttribute("name", "x"); String expecting = "int x = 0L;"; String result = st.toString(); assertEquals(expecting, result); } public void testMapMissingDefaultValueIsEmpty() throws Exception { String templates = "group test;" +newline+ "typeInit ::= [\"int\":\"0\", \"float\":\"0.0\"] "+newline+ "var(type,w,name) ::= \" = ;\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("var"); st.setAttribute("w", "L"); st.setAttribute("type", "double"); // double not in typeInit map st.setAttribute("name", "x"); String expecting = "double x = ;"; // weird, but tests default value is key String result = st.toString(); assertEquals(expecting, result); } public void testMapHiddenByFormalArg() throws Exception { String templates = "group test;" +newline+ "typeInit ::= [\"int\":\"0\", \"float\":\"0.0\"] "+newline+ "var(typeInit,type,name) ::= \" = ;\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("var"); st.setAttribute("type", "int"); st.setAttribute("name", "x"); String expecting = "int x = ;"; String result = st.toString(); assertEquals(expecting, result); } public void testMapEmptyValueAndAngleBracketStrings() throws Exception { String templates = "group test;" +newline+ "typeInit ::= [\"int\":\"0\", \"float\":, \"double\":<<0.0L>>] "+newline+ "var(type,name) ::= \" = ;\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("var"); st.setAttribute("type", "float"); st.setAttribute("name", "x"); String expecting = "float x = ;"; String result = st.toString(); assertEquals(expecting, result); } public void testMapDefaultValue() throws Exception { String templates = "group test;" +newline+ "typeInit ::= [\"int\":\"0\", default:\"null\"] "+newline+ "var(type,name) ::= \" = ;\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("var"); st.setAttribute("type", "UserRecord"); st.setAttribute("name", "x"); String expecting = "UserRecord x = null;"; String result = st.toString(); assertEquals(expecting, result); } public void testMapEmptyDefaultValue() throws Exception { String templates = "group test;" +newline+ "typeInit ::= [\"int\":\"0\", default:] "+newline+ "var(type,name) ::= \" = ;\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("var"); st.setAttribute("type", "UserRecord"); st.setAttribute("name", "x"); String expecting = "UserRecord x = ;"; String result = st.toString(); assertEquals(expecting, result); } public void testMapDefaultValueIsKey() throws Exception { String templates = "group test;" +newline+ "typeInit ::= [\"int\":\"0\", default:key] "+newline+ "var(type,name) ::= \" = ;\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("var"); st.setAttribute("type", "UserRecord"); st.setAttribute("name", "x"); String expecting = "UserRecord x = UserRecord;"; String result = st.toString(); assertEquals(expecting, result); } /** * Test that a map can have only the default entry. *

    * Bug ref: JIRA bug ST-15 (Fixed) */ public void testMapDefaultStringAsKey() throws Exception { String templates = "group test;" +newline+ "typeInit ::= [\"default\":\"foo\"] "+newline+ "var(type,name) ::= \" = ;\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("var"); st.setAttribute("type", "default"); st.setAttribute("name", "x"); String expecting = "default x = foo;"; String result = st.toString(); assertEquals(expecting, result); } /** * Test that a map can return a string with the word: default. *

    * Bug ref: JIRA bug ST-15 (Fixed) */ public void testMapDefaultIsDefaultString() throws Exception { String templates = "group test;" +newline+ "map ::= [default: \"default\"] "+newline+ "t1() ::= \"\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("t1"); String expecting = "default"; String result = st.toString(); assertEquals(expecting, result); } public void testMapViaEnclosingTemplates() throws Exception { String templates = "group test;" +newline+ "typeInit ::= [\"int\":\"0\", \"float\":\"0.0\"] "+newline+ "intermediate(type,name) ::= \"\""+newline+ "var(type,name) ::= \" = ;\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("intermediate"); st.setAttribute("type", "int"); st.setAttribute("name", "x"); String expecting = "int x = 0;"; String result = st.toString(); assertEquals(expecting, result); } public void testMapViaEnclosingTemplates2() throws Exception { String templates = "group test;" +newline+ "typeInit ::= [\"int\":\"0\", \"float\":\"0.0\"] "+newline+ "intermediate(stuff) ::= \"\""+newline+ "var(type,name) ::= \" = ;\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate interm = group.getInstanceOf("intermediate"); StringTemplate var = group.getInstanceOf("var"); var.setAttribute("type", "int"); var.setAttribute("name", "x"); interm.setAttribute("stuff", var); String expecting = "int x = 0;"; String result = interm.toString(); assertEquals(expecting, result); } public void testEmptyGroupTemplate() throws Exception { String templates = "group test;" +newline+ "foo() ::= \"\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate a = group.getInstanceOf("foo"); String expecting = ""; String result = a.toString(); assertEquals(expecting, result); } public void testEmptyStringAndEmptyAnonTemplateAsParameterUsingAngleBracketLexer() throws Exception { String templates = "group test;" +newline+ "top() ::= <<>>"+newline+ "x(a,b) ::= \"a=, b=\""+newline; ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate a = group.getInstanceOf("top"); String expecting = "a=, b="; String result = a.toString(); assertEquals(expecting, result); } public void testEmptyStringAndEmptyAnonTemplateAsParameterUsingDollarLexer() throws Exception { String templates = "group test;" +newline+ "top() ::= <<$x(a=\"\", b={})$>>"+newline+ "x(a,b) ::= \"a=$a$, b=$b$\""+newline; ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class); StringTemplate a = group.getInstanceOf("top"); String expecting = "a=, b="; String result = a.toString(); assertEquals(expecting, result); } /** * FIXME: Dannish does not work if typed directly in with default file * encoding on windows. The character needs to be escaped as bellow. * Please correct to escape the correct charcter. */ public void test8BitEuroChars() throws Exception { StringTemplate e = new StringTemplate( "Danish: \u0143 char" ); e = e.getInstanceOf(); String expecting = "Danish: \u0143 char"; assertEquals(expecting, e.toString()); } public void test16BitUnicodeChar() throws Exception { StringTemplate e = new StringTemplate( "DINGBAT CIRCLED SANS-SERIF DIGIT ONE: \u2780" ); e = e.getInstanceOf(); String expecting = "DINGBAT CIRCLED SANS-SERIF DIGIT ONE: \u2780"; assertEquals(expecting, e.toString()); } public void testFirstOp() throws Exception { StringTemplate e = new StringTemplate( "$first(names)$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("names", "Sriram"); String expecting = "Ter"; assertEquals(expecting, e.toString()); } public void testTruncOp() throws Exception { StringTemplate e = new StringTemplate( "$trunc(names); separator=\", \"$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("names", "Sriram"); String expecting = "Ter, Tom"; assertEquals(expecting, e.toString()); } public void testRestOp() throws Exception { StringTemplate e = new StringTemplate( "$rest(names); separator=\", \"$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("names", "Sriram"); String expecting = "Tom, Sriram"; assertEquals(expecting, e.toString()); } public void testRestOpEmptyList() throws Exception { StringTemplate e = new StringTemplate( "$rest(names); separator=\", \"$" ); e = e.getInstanceOf(); e.setAttribute("names", new ArrayList()); String expecting = ""; assertEquals(expecting, e.toString()); } public void testReUseOfRestResult() throws Exception { String templates = "group test;" +newline+ "a(names) ::= \"\""+newline+ "b(x) ::= \", \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate e = group.getInstanceOf("a"); List names = new ArrayList(); names.add("Ter"); names.add("Tom"); e.setAttribute("names", names); String expecting = "Tom, Tom"; assertEquals(expecting, e.toString()); } public void testLastOp() throws Exception { StringTemplate e = new StringTemplate( "$last(names)$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("names", "Sriram"); String expecting = "Sriram"; assertEquals(expecting, e.toString()); } public void testCombinedOp() throws Exception { // replace first of yours with first of mine StringTemplate e = new StringTemplate( "$[first(mine),rest(yours)]; separator=\", \"$" ); e = e.getInstanceOf(); e.setAttribute("mine", "1"); e.setAttribute("mine", "2"); e.setAttribute("mine", "3"); e.setAttribute("yours", "a"); e.setAttribute("yours", "b"); String expecting = "1, b"; assertEquals(expecting, e.toString()); } public void testCatListAndSingleAttribute() throws Exception { // replace first of yours with first of mine StringTemplate e = new StringTemplate( "$[mine,yours]; separator=\", \"$" ); e = e.getInstanceOf(); e.setAttribute("mine", "1"); e.setAttribute("mine", "2"); e.setAttribute("mine", "3"); e.setAttribute("yours", "a"); String expecting = "1, 2, 3, a"; assertEquals(expecting, e.toString()); } public void testReUseOfCat() throws Exception { String templates = "group test;" +newline+ "a(mine,yours) ::= \"\""+newline+ "b(x) ::= \", \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate e = group.getInstanceOf("a"); List mine = new ArrayList(); mine.add("Ter"); mine.add("Tom"); e.setAttribute("mine", mine); List yours = new ArrayList(); yours.add("Foo"); e.setAttribute("yours", yours); String expecting = "TerTomFoo, TerTomFoo"; assertEquals(expecting, e.toString()); } public void testCatListAndEmptyAttributes() throws Exception { // + is overloaded to be cat strings and cat lists so the // two operands (from left to right) determine which way it // goes. In this case, x+mine is a list so everything from their // to the right becomes list cat. StringTemplate e = new StringTemplate( "$[x,mine,y,yours,z]; separator=\", \"$" ); e = e.getInstanceOf(); e.setAttribute("mine", "1"); e.setAttribute("mine", "2"); e.setAttribute("mine", "3"); e.setAttribute("yours", "a"); String expecting = "1, 2, 3, a"; assertEquals(expecting, e.toString()); } public void testNestedOp() throws Exception { StringTemplate e = new StringTemplate( "$first(rest(names))$" // gets 2nd element ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("names", "Sriram"); String expecting = "Tom"; assertEquals(expecting, e.toString()); } public void testFirstWithOneAttributeOp() throws Exception { StringTemplate e = new StringTemplate( "$first(names)$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); String expecting = "Ter"; assertEquals(expecting, e.toString()); } public void testLastWithOneAttributeOp() throws Exception { StringTemplate e = new StringTemplate( "$last(names)$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); String expecting = "Ter"; assertEquals(expecting, e.toString()); } public void testLastWithLengthOneListAttributeOp() throws Exception { StringTemplate e = new StringTemplate( "$last(names)$" ); e = e.getInstanceOf(); e.setAttribute("names", new ArrayList() {{add("Ter");}}); String expecting = "Ter"; assertEquals(expecting, e.toString()); } public void testRestWithOneAttributeOp() throws Exception { StringTemplate e = new StringTemplate( "$rest(names)$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); String expecting = ""; assertEquals(expecting, e.toString()); } public void testRestWithLengthOneListAttributeOp() throws Exception { StringTemplate e = new StringTemplate( "$rest(names)$" ); e = e.getInstanceOf(); e.setAttribute("names", new ArrayList() {{add("Ter");}}); String expecting = ""; assertEquals(expecting, e.toString()); } public void testRepeatedRestOp() throws Exception { StringTemplate e = new StringTemplate( "$rest(names)$, $rest(names)$" // gets 2nd element ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); String expecting = "Tom, Tom"; assertEquals(expecting, e.toString()); } /** If an iterator is sent into ST, it must be cannot be reset after each * use so repeated refs yield empty values. This would * work if we passed in a List not an iterator. Avoid sending in iterators * if you ref it twice. */ public void testRepeatedIteratedAttrFromArg() throws Exception { String templates = "group test;" +newline+ "root(names) ::= \"$other(names)$\""+newline+ "other(x) ::= \"$x$, $x$\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class); StringTemplate e = group.getInstanceOf("root"); List names = new ArrayList(); names.add("Ter"); names.add("Tom"); e.setAttribute("names", names.iterator()); String expecting = "TerTom, "; // This does not give TerTom twice!! assertEquals(expecting, e.toString()); } /** FIXME: BUG! Iterator is not reset from first to second $x$ * Either reset the iterator or pass an attribute that knows to get * the iterator each time. Seems like first, tail do not * have same problem as they yield objects. * * Maybe make a RestIterator like I have CatIterator. */ /* public void testRepeatedRestOpAsArg() throws Exception { String templates = "group test;" +newline+ "root(names) ::= \"$other(rest(names))$\""+newline+ "other(x) ::= \"$x$, $x$\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class); StringTemplate e = group.getInstanceOf("root"); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); String expecting = "Tom, Tom"; assertEquals(expecting, e.toString()); } */ public void testIncomingLists() throws Exception { StringTemplate e = new StringTemplate( "$rest(names)$, $rest(names)$" // gets 2nd element ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); String expecting = "Tom, Tom"; assertEquals(expecting, e.toString()); } public void testIncomingListsAreNotModified() throws Exception { StringTemplate e = new StringTemplate( "$names; separator=\", \"$" // gets 2nd element ); e = e.getInstanceOf(); List names = new ArrayList(); names.add("Ter"); names.add("Tom"); e.setAttribute("names", names); e.setAttribute("names", "Sriram"); String expecting = "Ter, Tom, Sriram"; assertEquals(expecting, e.toString()); assertEquals(names.size(), 2); } public void testIncomingListsAreNotModified2() throws Exception { StringTemplate e = new StringTemplate( "$names; separator=\", \"$" // gets 2nd element ); e = e.getInstanceOf(); List names = new ArrayList(); names.add("Ter"); names.add("Tom"); e.setAttribute("names", "Sriram"); // single element first now e.setAttribute("names", names); String expecting = "Sriram, Ter, Tom"; assertEquals(expecting, e.toString()); assertEquals(names.size(), 2); } public void testIncomingArraysAreOk() throws Exception { StringTemplate e = new StringTemplate( "$names; separator=\", \"$" // gets 2nd element ); e = e.getInstanceOf(); e.setAttribute("names", new String[] {"Ter","Tom"}); e.setAttribute("names", "Sriram"); String expecting = "Ter, Tom, Sriram"; assertEquals(expecting, e.toString()); } public void testMultipleRefsToListAttribute() throws Exception { String templates = "group test;" +newline+ "f(x) ::= \" \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate e = group.getInstanceOf("f"); e.setAttribute("x", "Ter"); e.setAttribute("x", "Tom"); String expecting = "TerTom TerTom"; assertEquals(expecting, e.toString()); } public void testApplyTemplateWithSingleFormalArgs() throws Exception { String templates = "group test;" +newline+ "test(names) ::= << >>"+newline+ "bold(item) ::= <<**>>"+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate e = group.getInstanceOf("test"); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); String expecting = "*Ter*, *Tom* "; String result = e.toString(); assertEquals(expecting, result); } public void testApplyTemplateWithNoFormalArgs() throws Exception { String templates = "group test;" +newline+ "test(names) ::= << >>"+newline+ "bold() ::= <<**>>"+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), AngleBracketTemplateLexer.class); StringTemplate e = group.getInstanceOf("test"); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); String expecting = "*Ter*, *Tom* "; String result = e.toString(); assertEquals(expecting, result); } public void testAnonTemplateArgs() throws Exception { StringTemplate e = new StringTemplate( "$names:{n| $n$}; separator=\", \"$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); String expecting = "Ter, Tom"; assertEquals(expecting, e.toString()); } public void testAnonTemplateWithArgHasNoITArg() throws Exception { StringTemplate e = new StringTemplate( "$names:{n| $n$:$it$}; separator=\", \"$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); String error = null; try { e.toString(); } catch (NoSuchElementException nse) { error = nse.getMessage(); } String expecting = "no such attribute: it in template context [anonymous anonymous]"; assertEquals(error, expecting); } public void testAnonTemplateArgs2() throws Exception { StringTemplate e = new StringTemplate( "$names:{n| .$n$.}:{ n | _$n$_}; separator=\", \"$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); String expecting = "_.Ter._, _.Tom._"; assertEquals(expecting, e.toString()); } public void testFirstWithCatAttribute() throws Exception { StringTemplate e = new StringTemplate( "$first([names,phones])$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("phones", "1"); e.setAttribute("phones", "2"); String expecting = "Ter"; assertEquals(expecting, e.toString()); } public void testFirstWithListOfMaps() throws Exception { StringTemplate e = new StringTemplate( "$first(maps).Ter$" ); e = e.getInstanceOf(); final Map m1 = new HashMap(); final Map m2 = new HashMap(); m1.put("Ter", "x5707"); e.setAttribute("maps", m1); m2.put("Tom", "x5332"); e.setAttribute("maps", m2); String expecting = "x5707"; assertEquals(expecting, e.toString()); e = e.getInstanceOf(); List list = new ArrayList() {{add(m1); add(m2);}}; e.setAttribute("maps", list); expecting = "x5707"; assertEquals(expecting, e.toString()); } // this FAILS! /* public void testFirstWithListOfMaps2() throws Exception { StringTemplate e = new StringTemplate( "$first(maps):{ m | $m.Ter$ }$" ); final Map m1 = new HashMap(); final Map m2 = new HashMap(); m1.put("Ter", "x5707"); e.setAttribute("maps", m1); m2.put("Tom", "x5332"); e.setAttribute("maps", m2); String expecting = "x5707"; assertEquals(expecting, e.toString()); e = e.getInstanceOf(); List list = new ArrayList() {{add(m1); add(m2);}}; e.setAttribute("maps", list); expecting = "x5707"; assertEquals(expecting, e.toString()); } */ public void testJustCat() throws Exception { StringTemplate e = new StringTemplate( "$[names,phones]$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("phones", "1"); e.setAttribute("phones", "2"); String expecting = "TerTom12"; assertEquals(expecting, e.toString()); } public void testCat2Attributes() throws Exception { StringTemplate e = new StringTemplate( "$[names,phones]; separator=\", \"$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("phones", "1"); e.setAttribute("phones", "2"); String expecting = "Ter, Tom, 1, 2"; assertEquals(expecting, e.toString()); } public void testCat2AttributesWithApply() throws Exception { StringTemplate e = new StringTemplate( "$[names,phones]:{a|$a$.}$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("phones", "1"); e.setAttribute("phones", "2"); String expecting = "Ter.Tom.1.2."; assertEquals(expecting, e.toString()); } public void testCat3Attributes() throws Exception { StringTemplate e = new StringTemplate( "$[names,phones,salaries]; separator=\", \"$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("phones", "1"); e.setAttribute("phones", "2"); e.setAttribute("salaries", "big"); e.setAttribute("salaries", "huge"); String expecting = "Ter, Tom, 1, 2, big, huge"; assertEquals(expecting, e.toString()); } public void testCatWithTemplateApplicationAsElement() throws Exception { StringTemplate e = new StringTemplate( "$[names:{$it$!},phones]; separator=\", \"$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("phones" , "1"); e.setAttribute("phones", "2"); String expecting = "Ter!, Tom!, 1, 2"; assertEquals(expecting, e.toString()); } public void testCatWithIFAsElement() throws Exception { StringTemplate e = new StringTemplate( "$[{$if(names)$doh$endif$},phones]; separator=\", \"$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("phones" , "1"); e.setAttribute("phones", "2"); String expecting = "doh, 1, 2"; assertEquals(expecting, e.toString()); } public void testCatWithNullTemplateApplicationAsElement() throws Exception { StringTemplate e = new StringTemplate( "$[names:{$it$!},\"foo\"]:{x}; separator=\", \"$" ); e = e.getInstanceOf(); e.setAttribute("phones", "1"); e.setAttribute("phones", "2"); String expecting = "x"; // only one since template application gives nothing assertEquals(expecting, e.toString()); } public void testCatWithNestedTemplateApplicationAsElement() throws Exception { StringTemplate e = new StringTemplate( "$[names, [\"foo\",\"bar\"]:{$it$!},phones]; separator=\", \"$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("phones", "1"); e.setAttribute("phones", "2"); String expecting = "Ter, Tom, foo!, bar!, 1, 2"; assertEquals(expecting, e.toString()); } public void testListAsTemplateArgument() throws Exception { String templates = "group test;" +newline+ "test(names,phones) ::= \"\""+newline+ "foo(items) ::= \"*}>\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), AngleBracketTemplateLexer.class); StringTemplate e = group.getInstanceOf("test"); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("phones", "1"); e.setAttribute("phones", "2"); String expecting = "*Ter**Tom**1**2*"; String result = e.toString(); assertEquals(expecting, result); } public void testSingleExprTemplateArgument() throws Exception { String templates = "group test;" +newline+ "test(name) ::= \"\""+newline+ "bold(item) ::= \"**\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), AngleBracketTemplateLexer.class); StringTemplate e = group.getInstanceOf("test"); e.setAttribute("name", "Ter"); String expecting = "*Ter*"; String result = e.toString(); assertEquals(expecting, result); } public void testSingleExprTemplateArgumentInApply() throws Exception { // when you specify a single arg on a template application // it overrides the setting of the iterated value "it" to that // same single formal arg. Your arg hides the implicitly set "it". String templates = "group test;" +newline+ "test(names,x) ::= \"\""+newline+ "bold(item) ::= \"**\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), AngleBracketTemplateLexer.class); StringTemplate e = group.getInstanceOf("test"); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("x", "ick"); String expecting = "*ick**ick*"; String result = e.toString(); assertEquals(expecting, result); } public void testSoleFormalTemplateArgumentInMultiApply() throws Exception { String templates = "group test;" +newline+ "test(names) ::= \"\""+newline+ "bold(x) ::= \"**\""+newline+ "italics(y) ::= \"__\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), AngleBracketTemplateLexer.class); StringTemplate e = group.getInstanceOf("test"); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); String expecting = "*Ter*_Tom_"; String result = e.toString(); assertEquals(expecting, result); } public void testSingleExprTemplateArgumentError() throws Exception { String templates = "group test;" +newline+ "test(name) ::= \"\""+newline+ "bold(item,ick) ::= \"**\""+newline ; StringTemplateErrorListener errors = new ErrorBuffer(); StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), AngleBracketTemplateLexer.class, errors); StringTemplate e = group.getInstanceOf("test"); e.setAttribute("name", "Ter"); /*String result =*/ e.toString(); String expecting = "template bold must have exactly one formal arg in template context [test ]"; assertEquals(errors.toString(), expecting); } public void testInvokeIndirectTemplateWithSingleFormalArgs() throws Exception { String templates = "group test;" +newline+ "test(templateName,arg) ::= \"<(templateName)(arg)>\""+newline+ "bold(x) ::= <<**>>"+newline+ "italics(y) ::= <<__>>"+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate e = group.getInstanceOf("test"); e.setAttribute("templateName", "italics"); e.setAttribute("arg", "Ter"); String expecting = "_Ter_"; String result = e.toString(); assertEquals(expecting, result); } public void testParallelAttributeIteration() throws Exception { StringTemplate e = new StringTemplate( "$names,phones,salaries:{n,p,s | $n$@$p$: $s$\n}$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("phones", "1"); e.setAttribute("phones", "2"); e.setAttribute("salaries", "big"); e.setAttribute("salaries", "huge"); String expecting = "Ter@1: big"+newline+"Tom@2: huge"+newline; assertEquals(expecting, e.toString()); } public void testParallelAttributeIterationWithNullValue() throws Exception { StringTemplate e = new StringTemplate( "$names,phones,salaries:{n,p,s | $n$@$p$: $s$\n}$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("names", "Sriram"); e.setAttribute("phones", new ArrayList() {{add("1"); add(null); add("3");}}); e.setAttribute("salaries", "big"); e.setAttribute("salaries", "huge"); e.setAttribute("salaries", "enormous"); String expecting = "Ter@1: big"+newline+ "Tom@: huge"+newline+ "Sriram@3: enormous"+newline; assertEquals(expecting, e.toString()); } public void testParallelAttributeIterationHasI() throws Exception { StringTemplate e = new StringTemplate( "$names,phones,salaries:{n,p,s | $i0$. $n$@$p$: $s$\n}$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("phones", "1"); e.setAttribute("phones", "2"); e.setAttribute("salaries", "big"); e.setAttribute("salaries", "huge"); String expecting = "0. Ter@1: big"+newline+"1. Tom@2: huge"+newline; assertEquals(expecting, e.toString()); } public void testParallelAttributeIterationWithDifferentSizes() throws Exception { StringTemplate e = new StringTemplate( "$names,phones,salaries:{n,p,s | $n$@$p$: $s$}; separator=\", \"$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("names", "Sriram"); e.setAttribute("phones", "1"); e.setAttribute("phones", "2"); e.setAttribute("salaries", "big"); String expecting = "Ter@1: big, Tom@2: , Sriram@: "; assertEquals(expecting, e.toString()); } public void testParallelAttributeIterationWithSingletons() throws Exception { StringTemplate e = new StringTemplate( "$names,phones,salaries:{n,p,s | $n$@$p$: $s$}; separator=\", \"$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("phones", "1"); e.setAttribute("salaries", "big"); String expecting = "Ter@1: big"; assertEquals(expecting, e.toString()); } public void testParallelAttributeIterationWithMismatchArgListSizes() throws Exception { StringTemplateErrorListener errors = new ErrorBuffer(); StringTemplate e = new StringTemplate( "$names,phones,salaries:{n,p | $n$@$p$}; separator=\", \"$" ); e.setErrorListener(errors); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("phones", "1"); e.setAttribute("phones", "2"); e.setAttribute("salaries", "big"); String expecting = "Ter@1, Tom@2"; assertEquals(expecting, e.toString()); String errorExpecting = "number of arguments [n, p] mismatch between attribute list and anonymous template in context [anonymous]"; assertEquals(errorExpecting, errors.toString()); } public void testParallelAttributeIterationWithMissingArgs() throws Exception { StringTemplateErrorListener errors = new ErrorBuffer(); StringTemplate e = new StringTemplate( "$names,phones,salaries:{$n$@$p$}; separator=\", \"$" ); e.setErrorListener(errors); e = e.getInstanceOf(); e.setAttribute("names", "Tom"); e.setAttribute("phones", "2"); e.setAttribute("salaries", "big"); e.toString(); // generate the error String errorExpecting = "missing arguments in anonymous template in context [anonymous]"; assertEquals(errorExpecting, errors.toString()); } public void testParallelAttributeIterationWithDifferentSizesTemplateRefInsideToo() throws Exception { String templates = "group test;" +newline+ "page(names,phones,salaries) ::= "+newline+ " <<$names,phones,salaries:{n,p,s | $value(n)$@$value(p)$: $value(s)$}; separator=\", \"$>>"+newline + "value(x=\"n/a\") ::= \"$x$\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class); StringTemplate p = group.getInstanceOf("page"); p.setAttribute("names", "Ter"); p.setAttribute("names", "Tom"); p.setAttribute("names", "Sriram"); p.setAttribute("phones", "1"); p.setAttribute("phones", "2"); p.setAttribute("salaries", "big"); String expecting = "Ter@1: big, Tom@2: n/a, Sriram@n/a: n/a"; assertEquals(expecting, p.toString()); } public void testAnonTemplateOnLeftOfApply() throws Exception { StringTemplate e = new StringTemplate( "${foo}:{($it$)}$" ); String expecting = "(foo)"; assertEquals(expecting, e.toString()); } public void testOverrideThroughConditional() throws Exception { String templates = "group base;" +newline+ "body(ick) ::= \"ick\"" + "f() ::= \"foo\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); String templates2 = "group sub;" +newline+ "f() ::= \"bar\""+newline ; StringTemplateGroup subgroup = new StringTemplateGroup(new StringReader(templates2), AngleBracketTemplateLexer.class, null, group); StringTemplate b = subgroup.getInstanceOf("body"); String expecting ="bar"; String result = b.toString(); assertEquals(expecting, result); } public static class NonPublicProperty { } public void testNonPublicPropertyAccess() throws Exception { StringTemplate st = new StringTemplate("$x.foo$:$x.bar$"); Object o = new Object() { public int foo = 9; public int getBar() { return 34; } }; st.setAttribute("x", o); String expecting = "9:34"; assertEquals(expecting, st.toString()); } public void testIndexVar() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", "."); StringTemplate t = new StringTemplate( group, "$A:{$i$. $it$}; separator=\"\\n\"$" ); t.setAttribute("A", "parrt"); t.setAttribute("A", "tombu"); String expecting = "1. parrt" +newline+ "2. tombu"; assertEquals(expecting, t.toString()); } public void testIndex0Var() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", "."); StringTemplate t = new StringTemplate( group, "$A:{$i0$. $it$}; separator=\"\\n\"$" ); t.setAttribute("A", "parrt"); t.setAttribute("A", "tombu"); String expecting = "0. parrt" +newline+ "1. tombu"; assertEquals(expecting, t.toString()); } public void testIndexVarWithMultipleExprs() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", "."); StringTemplate t = new StringTemplate( group, "$A,B:{a,b|$i$. $a$@$b$}; separator=\"\\n\"$" ); t.setAttribute("A", "parrt"); t.setAttribute("A", "tombu"); t.setAttribute("B", "x5707"); t.setAttribute("B", "x5000"); String expecting = "1. parrt@x5707" +newline+ "2. tombu@x5000"; assertEquals(expecting, t.toString()); } public void testIndex0VarWithMultipleExprs() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", "."); StringTemplate t = new StringTemplate( group, "$A,B:{a,b|$i0$. $a$@$b$}; separator=\"\\n\"$" ); t.setAttribute("A", "parrt"); t.setAttribute("A", "tombu"); t.setAttribute("B", "x5707"); t.setAttribute("B", "x5000"); String expecting = "0. parrt@x5707" +newline+ "1. tombu@x5000"; assertEquals(expecting, t.toString()); } public void testArgumentContext() throws Exception { // t is referenced within foo and so will be evaluated in that // context. it can therefore see name. StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplate main = group.defineTemplate("main", "$foo(t={Hi, $name$}, name=\"parrt\")$"); /*StringTemplate foo =*/ group.defineTemplate("foo", "$t$"); String expecting="Hi, parrt"; assertEquals(expecting, main.toString()); } public void testNoDotsInAttributeNames() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", "."); StringTemplate t = new StringTemplate(group, "$user.Name$"); String error=null; try { t.setAttribute("user.Name", "Kunle"); } catch (IllegalArgumentException e) { error = e.getMessage(); } String expecting = "cannot have '.' in attribute names"; assertEquals(expecting,error); } public void testNoDotsInTemplateNames() throws Exception { StringTemplateErrorListener errors = new ErrorBuffer(); String templates = "group test;" +newline+ "a.b() ::= <>"+newline; /*StringTemplateGroup group =*/ new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class, errors); String expecting = "template group parse error: line 2:1: unexpected token:"; assertTrue(errors.toString().startsWith(expecting)); } public void testLineWrap() throws Exception { String templates = "group test;" +newline+ "array(values) ::= < };>>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate a = group.getInstanceOf("array"); a.setAttribute("values", new int[] {3,9,20,2,1,4,6,32,5,6,77,888,2,1,6,32,5,6,77, 4,9,20,2,1,4,63,9,20,2,1,4,6,32,5,6,77,6,32,5,6,77, 3,9,20,2,1,4,6,32,5,6,77,888,1,6,32,5}); String expecting = "int[] a = { 3,9,20,2,1,4,6,32,5,6,77,888,\n" + "2,1,6,32,5,6,77,4,9,20,2,1,4,63,9,20,2,1,\n" + "4,6,32,5,6,77,6,32,5,6,77,3,9,20,2,1,4,6,\n" + "32,5,6,77,888,1,6,32,5 };"; assertEquals(expecting,a.toString(40)); } public void testLineWrapWithNormalizedNewlines() throws Exception { String templates = "group test;" +newline+ "array(values) ::= < };>>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate a = group.getInstanceOf("array"); a.setAttribute("values", new int[] {3,9,20,2,1,4,6,32,5,6,77,888,2,1,6,32,5,6,77, 4,9,20,2,1,4,63,9,20,2,1,4,6,32,5,6,77,6,32,5,6,77, 3,9,20,2,1,4,6,32,5,6,77,888,1,6,32,5}); String expecting = "int[] a = { 3,9,20,2,1,4,6,32,5,6,77,888,\n" + // wrap is \r\n, normalize to \n "2,1,6,32,5,6,77,4,9,20,2,1,4,63,9,20,2,1,\n" + "4,6,32,5,6,77,6,32,5,6,77,3,9,20,2,1,4,6,\n" + "32,5,6,77,888,1,6,32,5 };"; StringWriter sw = new StringWriter(); StringTemplateWriter stw = new AutoIndentWriter(sw,"\n"); // force \n as newline stw.setLineWidth(40); a.write(stw); String result = sw.toString(); assertEquals(expecting, result); } public void testLineWrapAnchored() throws Exception { String templates = "group test;" +newline+ "array(values) ::= < };>>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate a = group.getInstanceOf("array"); a.setAttribute("values", new int[] {3,9,20,2,1,4,6,32,5,6,77,888,2,1,6,32,5,6,77, 4,9,20,2,1,4,63,9,20,2,1,4,6,32,5,6,77,6,32,5,6,77, 3,9,20,2,1,4,6,32,5,6,77,888,1,6,32,5}); String expecting = "int[] a = { 3,9,20,2,1,4,6,32,5,6,77,888,\n" + " 2,1,6,32,5,6,77,4,9,20,2,1,4,\n" + " 63,9,20,2,1,4,6,32,5,6,77,6,\n" + " 32,5,6,77,3,9,20,2,1,4,6,32,\n" + " 5,6,77,888,1,6,32,5 };"; assertEquals(expecting, a.toString(40)); } public void testSubtemplatesAnchorToo() throws Exception { String templates = "group test;" +newline+ "array(values) ::= <<{ }>>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); final StringTemplate x = new StringTemplate(group, "<\\n>{ }<\\n>"); x.setAttribute("stuff", "1"); x.setAttribute("stuff", "2"); x.setAttribute("stuff", "3"); StringTemplate a = group.getInstanceOf("array"); a.setAttribute("values", new ArrayList() {{ add("a"); add(x); add("b"); }}); String expecting = "{ a, \n" + " { 1,\n" + " 2,\n" + " 3 }\n" + " , b }"; assertEquals(expecting, a.toString(40)); } public void testFortranLineWrap() throws Exception { String templates = "group test;" +newline+ "func(args) ::= << FUNCTION line( )>>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate a = group.getInstanceOf("func"); a.setAttribute("args", new String[] {"a","b","c","d","e","f"}); String expecting = " FUNCTION line( a,b,c,d,\n" + " ce,f )"; assertEquals(expecting, a.toString(30)); } public void testLineWrapWithDiffAnchor() throws Exception { String templates = "group test;" +newline+ "array(values) ::= <}; anchor> };>>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate a = group.getInstanceOf("array"); a.setAttribute("values", new int[] {3,9,20,2,1,4,6,32,5,6,77,888,2,1,6,32,5,6,77, 4,9,20,2,1,4,63,9,20,2,1,4,6}); String expecting = "int[] a = { 1,9,2,3,9,20,2,1,4,\n" + " 6,32,5,6,77,888,2,\n" + " 1,6,32,5,6,77,4,9,\n" + " 20,2,1,4,63,9,20,2,\n" + " 1,4,6 };"; assertEquals(expecting, a.toString(30)); } public void testLineWrapEdgeCase() throws Exception { String templates = "group test;" +newline+ "duh(chars) ::= <<>>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate a = group.getInstanceOf("duh"); a.setAttribute("chars", new String[] {"a","b","c","d","e"}); // lineWidth==3 implies that we can have 3 characters at most String expecting = "abc\n"+ "de"; assertEquals(expecting, a.toString(3)); } public void testLineWrapLastCharIsNewline() throws Exception { String templates = "group test;" +newline+ "duh(chars) ::= <<>>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate a = group.getInstanceOf("duh"); a.setAttribute("chars", new String[] {"a","b","\n","d","e"}); // don't do \n if it's last element anyway String expecting = "ab\n"+ "de"; assertEquals(expecting,a.toString(3)); } public void testLineWrapCharAfterWrapIsNewline() throws Exception { String templates = "group test;" +newline+ "duh(chars) ::= <<>>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate a = group.getInstanceOf("duh"); a.setAttribute("chars", new String[] {"a","b","c","\n","d","e"}); // Once we wrap, we must dump chars as we see them. A newline right // after a wrap is just an "unfortunate" event. People will expect // a newline if it's in the data. String expecting = "abc\n" + "\n" + "de"; assertEquals(expecting, a.toString(3)); } public void testLineWrapForAnonTemplate() throws Exception { String templates = "group test;" +newline+ "duh(data) ::= <]}; wrap>!>>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate a = group.getInstanceOf("duh"); a.setAttribute("data", new int[] {1,2,3,4,5,6,7,8,9}); String expecting = "![1][2][3]\n" + // width=9 is the 3 char; don't break til after ] "[4][5][6]\n" + "[7][8][9]!"; assertEquals(expecting,a.toString(9)); } public void testLineWrapForAnonTemplateAnchored() throws Exception { String templates = "group test;" +newline+ "duh(data) ::= <]}; anchor, wrap>!>>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate a = group.getInstanceOf("duh"); a.setAttribute("data", new int[] {1,2,3,4,5,6,7,8,9}); String expecting = "![1][2][3]\n" + " [4][5][6]\n" + " [7][8][9]!"; assertEquals(expecting, a.toString(9)); } public void testLineWrapForAnonTemplateComplicatedWrap() throws Exception { String templates = "group test;" +newline+ "top(s) ::= << .>>"+ "str(data) ::= <]}; wrap=\"!+\\n!\">!>>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate t = group.getInstanceOf("top"); StringTemplate s = group.getInstanceOf("str"); s.setAttribute("data", new int[] {1,2,3,4,5,6,7,8,9}); t.setAttribute("s", s); String expecting = " ![1][2]!+\n" + " ![3][4]!+\n" + " ![5][6]!+\n" + " ![7][8]!+\n" + " ![9]!."; assertEquals(expecting,t.toString(9)); } public void testIndentBeyondLineWidth() throws Exception { String templates = "group test;" +newline+ "duh(chars) ::= << >>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate a = group.getInstanceOf("duh"); a.setAttribute("chars", new String[] {"a","b","c","d","e"}); // String expecting = " a\n" + " b\n" + " c\n" + " d\n" + " e"; assertEquals(expecting, a.toString(2)); } public void testIndentedExpr() throws Exception { String templates = "group test;" +newline+ "duh(chars) ::= << >>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate a = group.getInstanceOf("duh"); a.setAttribute("chars", new String[] {"a","b","c","d","e"}); // String expecting = " ab\n" + " cd\n" + " e"; // width=4 spaces + 2 char. assertEquals(expecting, a.toString(6)); } public void testNestedIndentedExpr() throws Exception { String templates = "group test;" +newline+ "top(d) ::= << !>>"+newline+ "duh(chars) ::= << >>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate top = group.getInstanceOf("top"); StringTemplate duh = group.getInstanceOf("duh"); duh.setAttribute("chars", new String[] {"a","b","c","d","e"}); top.setAttribute("d", duh); String expecting = " ab\n" + " cd\n" + " e!"; // width=4 spaces + 2 char. assertEquals(expecting, top.toString(6)); } public void testNestedWithIndentAndTrackStartOfExpr() throws Exception { String templates = "group test;" +newline+ "top(d) ::= << !>>"+newline+ "duh(chars) ::= <>>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate top = group.getInstanceOf("top"); StringTemplate duh = group.getInstanceOf("duh"); duh.setAttribute("chars", new String[] {"a","b","c","d","e"}); top.setAttribute("d", duh); // String expecting = " x: ab\n" + " cd\n" + " e!"; assertEquals(expecting, top.toString(7)); } public void testLineDoesNotWrapDueToLiteral() throws Exception { String templates = "group test;" +newline+ "m(args,body) ::= <) throws Ick { }>>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate a = group.getInstanceOf("m"); a.setAttribute("args", new String[] {"a", "b", "c"}); a.setAttribute("body", "i=3;"); // make it wrap because of ") throws Ick { " literal int n = "public void foo(a, b, c".length(); String expecting = "public void foo(a, b, c) throws Ick { i=3; }"; assertEquals(expecting, a.toString(n)); } public void testSingleValueWrap() throws Exception { String templates = "group test;" +newline+ "m(args,body) ::= <<{ }>>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate m = group.getInstanceOf("m"); m.setAttribute("body", "i=3;"); // make it wrap because of ") throws Ick { " literal String expecting = "{ \n"+ " i=3; }"; assertEquals(expecting, m.toString(2)); } public void testLineWrapInNestedExpr() throws Exception { String templates = "group test;" +newline+ "top(arrays) ::= <done>>"+newline+ "array(values) ::= < };<\\n\\>>>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate top = group.getInstanceOf("top"); StringTemplate a = group.getInstanceOf("array"); a.setAttribute("values", new int[] {3,9,20,2,1,4,6,32,5,6,77,888,2,1,6,32,5,6,77, 4,9,20,2,1,4,63,9,20,2,1,4,6,32,5,6,77,6,32,5,6,77, 3,9,20,2,1,4,6,32,5,6,77,888,1,6,32,5}); top.setAttribute("arrays", a); top.setAttribute("arrays", a); // add twice String expecting = "Arrays: int[] a = { 3,9,20,2,1,4,6,32,5,\n" + " 6,77,888,2,1,6,32,5,\n" + " 6,77,4,9,20,2,1,4,63,\n" + " 9,20,2,1,4,6,32,5,6,\n" + " 77,6,32,5,6,77,3,9,20,\n" + " 2,1,4,6,32,5,6,77,888,\n" + " 1,6,32,5 };\n" + "int[] a = { 3,9,20,2,1,4,6,32,5,6,77,888,\n" + " 2,1,6,32,5,6,77,4,9,20,2,1,4,\n" + " 63,9,20,2,1,4,6,32,5,6,77,6,\n" + " 32,5,6,77,3,9,20,2,1,4,6,32,\n" + " 5,6,77,888,1,6,32,5 };\n" + "done"; assertEquals(expecting, top.toString(40)); } public void testBackslash() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplate t = group.defineTemplate("t", "\\"); String expecting="\\"; assertEquals(expecting, t.toString()); } public void testBackslash2() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplate t = group.defineTemplate("t", "\\ "); String expecting="\\ "; assertEquals(expecting, t.toString()); } public void testEscapeEscape() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplate t = group.defineTemplate("t", "\\\\$v$"); t.setAttribute("v", "Joe"); //System.out.println(t); String expecting="\\Joe"; assertEquals(expecting, t.toString()); } public void testEscapeEscapeNestedAngle() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test", AngleBracketTemplateLexer.class); StringTemplate t = group.defineTemplate("t", "}>"); t.setAttribute("v", "Joe"); //System.out.println(t); String expecting="\\Joe"; assertEquals(expecting, t.toString()); } public void testListOfIntArrays() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test", AngleBracketTemplateLexer.class); StringTemplate t = group.defineTemplate("t", ""); group.defineTemplate("array", "[]"); group.defineTemplate("element", ""); List data = new ArrayList(); data.add(new int[] {1,2,3}); data.add(new int[] {10,20,30}); t.setAttribute("data", data); //System.out.println(t); String expecting="[1,2,3][10,20,30]"; assertEquals(expecting, t.toString()); } // Test null option public void testNullOptionSingleNullValue() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test", AngleBracketTemplateLexer.class); StringTemplate t = group.defineTemplate("t", ""); //System.out.println(t); String expecting="0"; assertEquals(expecting, t.toString()); } public void testNullOptionHasEmptyNullValue() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test", AngleBracketTemplateLexer.class); StringTemplate t = group.defineTemplate("t", ""); List data = new ArrayList(); data.add(null); data.add(new Integer(1)); t.setAttribute("data", data); String expecting=", 1"; assertEquals(expecting, t.toString()); } public void testNullOptionSingleNullValueInList() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test", AngleBracketTemplateLexer.class); StringTemplate t = group.defineTemplate("t", ""); List data = new ArrayList(); data.add(null); t.setAttribute("data", data); //System.out.println(t); String expecting="0"; assertEquals(expecting, t.toString()); } public void testNullValueInList() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test", AngleBracketTemplateLexer.class); StringTemplate t = group.defineTemplate("t", ""); List data = new ArrayList(); data.add(null); data.add(new Integer(1)); data.add(null); data.add(new Integer(3)); data.add(new Integer(4)); data.add(null); t.setAttribute("data", data); //System.out.println(t); String expecting="-1, 1, -1, 3, 4, -1"; assertEquals(expecting, t.toString()); } public void testNullValueInListNoNullOption() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test", AngleBracketTemplateLexer.class); StringTemplate t = group.defineTemplate("t", ""); List data = new ArrayList(); data.add(null); data.add(new Integer(1)); data.add(null); data.add(new Integer(3)); data.add(new Integer(4)); data.add(null); t.setAttribute("data", data); //System.out.println(t); String expecting="1, 3, 4"; assertEquals(expecting, t.toString()); } public void testNullValueInListWithTemplateApply() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test", AngleBracketTemplateLexer.class); StringTemplate t = group.defineTemplate("t", ""); group.defineTemplate("array", ""); List data = new ArrayList(); data.add(new Integer(0)); data.add(null); data.add(new Integer(2)); data.add(null); t.setAttribute("data", data); String expecting="0, -1, 2, -1"; assertEquals(expecting, t.toString()); } public void testNullValueInListWithTemplateApplyNullFirstValue() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test", AngleBracketTemplateLexer.class); StringTemplate t = group.defineTemplate("t", ""); group.defineTemplate("array", ""); List data = new ArrayList(); data.add(null); data.add(new Integer(0)); data.add(null); data.add(new Integer(2)); t.setAttribute("data", data); String expecting="-1, 0, -1, 2"; assertEquals(expecting, t.toString()); } public void testNullSingleValueInListWithTemplateApply() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test", AngleBracketTemplateLexer.class); StringTemplate t = group.defineTemplate("t", ""); group.defineTemplate("array", ""); List data = new ArrayList(); data.add(null); t.setAttribute("data", data); String expecting="-1"; assertEquals(expecting, t.toString()); } public void testNullSingleValueWithTemplateApply() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test", AngleBracketTemplateLexer.class); StringTemplate t = group.defineTemplate("t", ""); group.defineTemplate("array", ""); String expecting="-1"; assertEquals(expecting, t.toString()); } public void testLengthOp() throws Exception { StringTemplate e = new StringTemplate( "$length(names)$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("names", "Sriram"); String expecting = "3"; assertEquals(expecting, e.toString()); } public void testLengthOpWithMap() throws Exception { StringTemplate e = new StringTemplate( "$length(names)$" ); e = e.getInstanceOf(); Map m = new HashMap(); m.put("Tom", "foo"); m.put("Sriram", "foo"); m.put("Doug", "foo"); e.setAttribute("names", m); String expecting = "3"; assertEquals(expecting, e.toString()); } public void testLengthOpWithSet() throws Exception { StringTemplate e = new StringTemplate( "$length(names)$" ); e = e.getInstanceOf(); Set m = new HashSet(); m.add("Tom"); m.add("Sriram"); m.add("Doug"); e.setAttribute("names", m); String expecting = "3"; assertEquals(expecting, e.toString()); } public void testLengthOpNull() throws Exception { StringTemplate e = new StringTemplate( "$length(names)$" ); e = e.getInstanceOf(); e.setAttribute("names", null); String expecting = "0"; assertEquals(expecting, e.toString()); } public void testLengthOpSingleValue() throws Exception { StringTemplate e = new StringTemplate( "$length(names)$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); String expecting = "1"; assertEquals(expecting, e.toString()); } public void testLengthOpPrimitive() throws Exception { StringTemplate e = new StringTemplate( "$length(ints)$" ); e = e.getInstanceOf(); e.setAttribute("ints", new int[] {1,2,3,4} ); String expecting = "4"; assertEquals(expecting, e.toString()); } public void testLengthOpOfListWithNulls() throws Exception { StringTemplate e = new StringTemplate( "$length(data)$" ); e = e.getInstanceOf(); List data = new ArrayList(); data.add("Hi"); data.add(null); data.add("mom"); data.add(null); e.setAttribute("data", data); String expecting = "4"; // nulls are counted assertEquals(expecting, e.toString()); } public void testStripOpOfListWithNulls() throws Exception { StringTemplate e = new StringTemplate( "$strip(data)$" ); e = e.getInstanceOf(); List data = new ArrayList(); data.add("Hi"); data.add(null); data.add("mom"); data.add(null); e.setAttribute("data", data); String expecting = "Himom"; // nulls are skipped assertEquals(expecting, e.toString()); } public void testStripOpOfListOfListsWithNulls() throws Exception { StringTemplate e = new StringTemplate( "$strip(data):{list | $strip(list)$}; separator=\",\"$" ); e = e.getInstanceOf(); List data = new ArrayList(); List dataOne = new ArrayList(); dataOne.add("Hi"); dataOne.add("mom"); data.add(dataOne); data.add(null); List dataTwo = new ArrayList(); dataTwo.add("Hi"); dataTwo.add(null); dataTwo.add("dad"); dataTwo.add(null); data.add(dataTwo); e.setAttribute("data", data); String expecting = "Himom,Hidad"; // nulls are skipped assertEquals(expecting, e.toString()); } public void testStripOpOfSingleAlt() throws Exception { StringTemplate e = new StringTemplate( "$strip(data)$" ); e = e.getInstanceOf(); e.setAttribute("data", "hi"); String expecting = "hi"; // nulls are skipped assertEquals(expecting, e.toString()); } public void testStripOpOfNull() throws Exception { StringTemplate e = new StringTemplate( "$strip(data)$" ); e = e.getInstanceOf(); String expecting = ""; // nulls are skipped assertEquals(expecting, e.toString()); } public void testReUseOfStripResult() throws Exception { String templates = "group test;" +newline+ "a(names) ::= \"\""+newline+ "b(x) ::= \", \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate e = group.getInstanceOf("a"); List names = new ArrayList(); names.add("Ter"); names.add(null); names.add("Tom"); e.setAttribute("names", names); String expecting = "TerTom, TerTom"; assertEquals(expecting, e.toString()); } public void testLengthOpOfStrippedListWithNulls() throws Exception { StringTemplate e = new StringTemplate( "$length(strip(data))$" ); e = e.getInstanceOf(); List data = new ArrayList(); data.add("Hi"); data.add(null); data.add("mom"); data.add(null); e.setAttribute("data", data); String expecting = "2"; // nulls are counted assertEquals(expecting, e.toString()); } public void testLengthOpOfStrippedListWithNullsFrontAndBack() throws Exception { StringTemplate e = new StringTemplate( "$length(strip(data))$" ); e = e.getInstanceOf(); List data = new ArrayList(); data.add(null); data.add(null); data.add(null); data.add("Hi"); data.add(null); data.add(null); data.add(null); data.add("mom"); data.add(null); data.add(null); data.add(null); e.setAttribute("data", data); String expecting = "2"; // nulls are counted assertEquals(expecting, e.toString()); } public void testMapKeys() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", ".", AngleBracketTemplateLexer.class); StringTemplate t = new StringTemplate(group, ":}; separator=\", \">"); HashMap map = new LinkedHashMap(); map.put("int","0"); map.put("float","0.0"); t.setAttribute("aMap", map); assertEquals("int:0, float:0.0",t.toString()); } public void testMapValues() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", ".", AngleBracketTemplateLexer.class); StringTemplate t = new StringTemplate(group, " "); HashMap map = new LinkedHashMap(); map.put("int","0"); map.put("float","0.0"); t.setAttribute("aMap", map); assertEquals("0, 0.0 0", t.toString()); } public void testMapKeysWithIntegerType() throws Exception { // must get back an Integer from keys not a toString()'d version StringTemplateGroup group = new StringTemplateGroup("dummy", ".", AngleBracketTemplateLexer.class); StringTemplate t = new StringTemplate(group, ":}; separator=\", \">"); Map map = new HashMap(); map.put(new Integer(1),new ArrayList(){{add("ick"); add("foo");}}); map.put(new Integer(2),new ArrayList(){{add("x"); add("y");}}); t.setAttribute("aMap", map); String res = t.toString(); boolean passed = false; if (res.equals("2:xy, 1:ickfoo") || res.equals("1:ickfoo, 2:xy")) { passed = true; } assertTrue("Map traversal did not return expected strings", passed); } /** Use when super.attr name is implemented public void testArgumentContext2() throws Exception { // t is referenced within foo and so will be evaluated in that // context. it can therefore see name. StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplate main = group.defineTemplate("main", "$foo(t={Hi, $super.name$}, name=\"parrt\")$"); main.setAttribute("name", "tombu"); StringTemplate foo = group.defineTemplate("foo", "$t$"); String expecting="Hi, parrt"; assertEquals(expecting, main.toString()); } */ /** * Check what happens when a semicolon is appended to a single line template * Should fail with a parse error(?) and not a missing template error. * FIXME: This should generate a warning or error about that semi colon. *

    * Bug ref: JIRA bug ST-2 */ /* public void testGroupTrailingSemiColon() throws Exception { //try { String templates = "group test;" +newline+ "t1()::=\"R1\"; "+newline+ "t2() ::= \"R2\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("t1"); assertEquals("R1", st.toString()); st = group.getInstanceOf("t2"); assertEquals("R2", st.toString()); fail("A parse error should have been generated"); //} catch (ParseError??) { //} } */ public void testSuperReferenceInIfClause() throws Exception { String superGroupString = "group super;" + newline + "a(x) ::= \"super.a\"" + newline + "b(x) ::= \"super.b\"" + newline + "c() ::= \"super.c\"" ; StringTemplateGroup superGroup = new StringTemplateGroup( new StringReader(superGroupString), AngleBracketTemplateLexer.class); String subGroupString = "group sub;\n" + "a(x) ::= \"\"" + newline + "b(x) ::= \"\"" + newline + "c() ::= \"sub.c\"" ; StringTemplateGroup subGroup = new StringTemplateGroup( new StringReader(subGroupString), AngleBracketTemplateLexer.class); subGroup.setSuperGroup(superGroup); StringTemplate a = subGroup.getInstanceOf("a"); a.setAttribute("x", "foo"); assertEquals("super.a", a.toString()); StringTemplate b = subGroup.getInstanceOf("b"); assertEquals("sub.csuper.b", b.toString()); StringTemplate c = subGroup.getInstanceOf("c"); assertEquals("sub.c", c.toString()); } /** Added feature for ST-21 */ public void testListLiteralWithEmptyElements() throws Exception { StringTemplate e = new StringTemplate( "$[\"Ter\",,\"Jesse\"]:{n | $i$:$n$}; separator=\", \", null=\"\"$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("phones", "1"); e.setAttribute("salaries", "big"); String expecting = "1:Ter, 2:, 3:Jesse"; assertEquals(expecting, e.toString()); } public void testTemplateApplicationAsOptionValue() throws Exception { StringTemplate st =new StringTemplate( "Tokens : }> ;", AngleBracketTemplateLexer.class); st.setAttribute("rules", "A"); st.setAttribute("rules", "B"); st.setAttribute("names", "Ter"); st.setAttribute("names", "Tom"); String expecting = "Tokens : ATerTomB ;"; assertEquals(expecting, st.toString()); } public static void writeFile(String dir, String fileName, String content) { try { File f = new File(dir, fileName); FileWriter w = new FileWriter(f); BufferedWriter bw = new BufferedWriter(w); bw.write(content); bw.close(); w.close(); } catch (IOException ioe) { System.err.println("can't write file"); ioe.printStackTrace(System.err); } } } stringtemplate-3.2.1/target/test-classes/org/antlr/stringtemplate/test/method.st0000644000175000017500000000012511274602756030205 0ustar twernertwerner () { } stringtemplate-3.2.1/target/test-classes/org/antlr/stringtemplate/test/body.st0000644000175000017500000000010111274602756027654 0ustar twernertwerner// start of a body // end of a body stringtemplate-3.2.1/target/test-classes/org/antlr/stringtemplate/test/row.st0000644000175000017500000000003311274602756027532 0ustar twernertwerner$it.firstName$ $it.email$ stringtemplate-3.2.1/target/test-classes/org/antlr/stringtemplate/test/page.st0000644000175000017500000000001711274602756027641 0ustar twernertwerner$title$ $body$ stringtemplate-3.2.1/target/test-classes/org/antlr/stringtemplate/test/users_list.st0000644000175000017500000000005411274602756031122 0ustar twernertwerner$users:org/antlr/stringtemplate/test/row()$ stringtemplate-3.2.1/lib/0000755000175000017500000000000011256235341015265 5ustar twernertwernerstringtemplate-3.2.1/test/0000755000175000017500000000000011256235341015476 5ustar twernertwernerstringtemplate-3.2.1/test/org/0000755000175000017500000000000011256235341016265 5ustar twernertwernerstringtemplate-3.2.1/test/org/antlr/0000755000175000017500000000000011256235341017405 5ustar twernertwernerstringtemplate-3.2.1/test/org/antlr/stringtemplate/0000755000175000017500000000000011256235341022447 5ustar twernertwernerstringtemplate-3.2.1/test/org/antlr/stringtemplate/test/0000755000175000017500000000000011256235341023426 5ustar twernertwernerstringtemplate-3.2.1/test/org/antlr/stringtemplate/test/TestStringTemplate.java0000644000175000017500000062071711256235341030110 0ustar twernertwerner/* [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.test; import junit.framework.TestCase; import org.antlr.stringtemplate.*; import org.antlr.stringtemplate.language.AngleBracketTemplateLexer; import org.antlr.stringtemplate.language.DefaultTemplateLexer; import java.io.*; import java.text.SimpleDateFormat; import java.util.*; public class TestStringTemplate extends TestCase { static final String newline = System.getProperty("line.separator"); static class ErrorBuffer implements StringTemplateErrorListener { StringBuffer errorOutput = new StringBuffer(500); int n = 0; public void error(String msg, Throwable e) { n++; if ( n>1 ) { errorOutput.append('\n'); } if ( e!=null ) { StringWriter duh = new StringWriter(); e.printStackTrace(new PrintWriter(duh)); errorOutput.append(msg+": "+duh.toString()); } else { errorOutput.append(msg); } } public void warning(String msg) { n++; errorOutput.append(msg); } public boolean equals(Object o) { String me = toString(); String them = o.toString(); return me.equals(them); } public String toString() { return errorOutput.toString(); } } public void testInterfaceFileFormat() throws Exception { String groupI = "interface test;" +newline+ "t();" +newline+ "bold(item);"+newline+ "optional duh(a,b,c);"+newline; StringTemplateGroupInterface I = new StringTemplateGroupInterface(new StringReader(groupI)); String expecting = "interface test;\n" + "t();\n" + "bold(item);\n" + "optional duh(a, b, c);\n"; assertEquals(expecting,I.toString()); } public void testNoGroupLoader() throws Exception { // this also tests the group loader StringTemplateErrorListener errors = new ErrorBuffer(); String tmpdir = System.getProperty("java.io.tmpdir"); String templates = "group testG implements blort;" +newline+ "t() ::= <>" +newline+ "bold(item) ::= <>"+newline+ "duh(a,b,c) ::= <>"+newline; writeFile(tmpdir, "testG.stg", templates); /*StringTemplateGroup group =*/ new StringTemplateGroup(new FileReader(tmpdir+"/testG.stg"), errors); String expecting = "no group loader registered"; assertEquals(expecting,errors.toString()); } public void testCannotFindInterfaceFile() throws Exception { // this also tests the group loader StringTemplateErrorListener errors = new ErrorBuffer(); String tmpdir = System.getProperty("java.io.tmpdir"); StringTemplateGroup.registerGroupLoader(new PathGroupLoader(tmpdir,errors)); String templates = "group testG implements blort;" +newline+ "t() ::= <>" +newline+ "bold(item) ::= <>"+newline+ "duh(a,b,c) ::= <>"+newline; writeFile(tmpdir, "testG.stg", templates); /*StringTemplateGroup group =*/ new StringTemplateGroup(new FileReader(tmpdir+"/testG.stg"), errors); String expecting = "no such interface file blort.sti"; assertEquals(expecting,errors.toString()); } public void testMultiDirGroupLoading() throws Exception { // this also tests the group loader StringTemplateErrorListener errors = new ErrorBuffer(); String tmpdir = System.getProperty("java.io.tmpdir"); if ( !(new File(tmpdir+"/sub").exists()) ) { if ( !(new File(tmpdir+"/sub").mkdir()) ) { // create a subdir System.err.println("can't make subdir in test"); return; } } StringTemplateGroup.registerGroupLoader( new PathGroupLoader(tmpdir+":"+tmpdir+"/sub",errors) ); String templates = "group testG2;" +newline+ "t() ::= <>" +newline+ "bold(item) ::= <>"+newline+ "duh(a,b,c) ::= <>"+newline; writeFile(tmpdir+"/sub", "testG2.stg", templates); StringTemplateGroup group = StringTemplateGroup.loadGroup("testG2"); String expecting = "group testG2;\n" + "bold(item) ::= <>\n" + "duh(a,b,c) ::= <>\n" + "t() ::= <>\n"; assertEquals(expecting,group.toString()); } public void testGroupSatisfiesSingleInterface() throws Exception { // this also tests the group loader StringTemplateErrorListener errors = new ErrorBuffer(); String tmpdir = System.getProperty("java.io.tmpdir"); StringTemplateGroup.registerGroupLoader(new PathGroupLoader(tmpdir,errors)); String groupI = "interface testI;" +newline+ "t();" +newline+ "bold(item);"+newline+ "optional duh(a,b,c);"+newline; writeFile(tmpdir, "testI.sti", groupI); String templates = "group testG implements testI;" +newline+ "t() ::= <>" +newline+ "bold(item) ::= <>"+newline+ "duh(a,b,c) ::= <>"+newline; writeFile(tmpdir, "testG.stg", templates); /*StringTemplateGroup group =*/ new StringTemplateGroup(new FileReader(tmpdir+"/testG.stg"), errors); String expecting = ""; // should be no errors assertEquals(expecting,errors.toString()); } public void testGroupExtendsSuperGroup() throws Exception { // this also tests the group loader StringTemplateErrorListener errors = new ErrorBuffer(); String tmpdir = System.getProperty("java.io.tmpdir"); StringTemplateGroup.registerGroupLoader( new PathGroupLoader(tmpdir,errors) ); String superGroup = "group superG;" +newline+ "bold(item) ::= <<*$item$*>>;\n"+newline; writeFile(tmpdir, "superG.stg", superGroup); String templates = "group testG : superG;" +newline+ "main(x) ::= <<$bold(x)$>>"+newline; writeFile(tmpdir, "testG.stg", templates); StringTemplateGroup group = new StringTemplateGroup(new FileReader(tmpdir+"/testG.stg"), DefaultTemplateLexer.class, errors); StringTemplate st = group.getInstanceOf("main"); st.setAttribute("x", "foo"); String expecting = "*foo*"; assertEquals(expecting, st.toString()); } public void testGroupExtendsSuperGroupWithAngleBrackets() throws Exception { // this also tests the group loader StringTemplateErrorListener errors = new ErrorBuffer(); String tmpdir = System.getProperty("java.io.tmpdir"); StringTemplateGroup.registerGroupLoader( new PathGroupLoader(tmpdir,errors) ); String superGroup = "group superG;" +newline+ "bold(item) ::= <<**>>;\n"+newline; writeFile(tmpdir, "superG.stg", superGroup); String templates = "group testG : superG;" +newline+ "main(x) ::= \"\""+newline; writeFile(tmpdir, "testG.stg", templates); StringTemplateGroup group = new StringTemplateGroup(new FileReader(tmpdir+"/testG.stg"), errors); StringTemplate st = group.getInstanceOf("main"); st.setAttribute("x", "foo"); String expecting = "*foo*"; assertEquals(expecting, st.toString()); } public void testMissingInterfaceTemplate() throws Exception { // this also tests the group loader StringTemplateErrorListener errors = new ErrorBuffer(); String tmpdir = System.getProperty("java.io.tmpdir"); StringTemplateGroup.registerGroupLoader(new PathGroupLoader(tmpdir,errors)); String groupI = "interface testI;" +newline+ "t();" +newline+ "bold(item);"+newline+ "optional duh(a,b,c);"+newline; writeFile(tmpdir, "testI.sti", groupI); String templates = "group testG implements testI;" +newline+ "t() ::= <>" +newline+ "duh(a,b,c) ::= <>"+newline; writeFile(tmpdir, "testG.stg", templates); /*StringTemplateGroup group =*/ new StringTemplateGroup(new FileReader(tmpdir+"/testG.stg"), errors); String expecting = "group testG does not satisfy interface testI: missing templates [bold]"; assertEquals(expecting, errors.toString()); } public void testMissingOptionalInterfaceTemplate() throws Exception { // this also tests the group loader StringTemplateErrorListener errors = new ErrorBuffer(); String tmpdir = System.getProperty("java.io.tmpdir"); StringTemplateGroup.registerGroupLoader(new PathGroupLoader(tmpdir,errors)); String groupI = "interface testI;" +newline+ "t();" +newline+ "bold(item);"+newline+ "optional duh(a,b,c);"+newline; writeFile(tmpdir, "testI.sti", groupI); String templates = "group testG implements testI;" +newline+ "t() ::= <>" +newline+ "bold(item) ::= <>"; writeFile(tmpdir, "testG.stg", templates); /*StringTemplateGroup group =*/ new StringTemplateGroup(new FileReader(tmpdir+"/testG.stg"), errors); String expecting = ""; // should be NO errors assertEquals(expecting, errors.toString()); } public void testMismatchedInterfaceTemplate() throws Exception { // this also tests the group loader StringTemplateErrorListener errors = new ErrorBuffer(); String tmpdir = System.getProperty("java.io.tmpdir"); StringTemplateGroup.registerGroupLoader(new PathGroupLoader(tmpdir,errors)); String groupI = "interface testI;" +newline+ "t();" +newline+ "bold(item);"+newline+ "optional duh(a,b,c);"+newline; writeFile(tmpdir, "testI.sti", groupI); String templates = "group testG implements testI;" +newline+ "t() ::= <>" +newline+ "bold(item) ::= <>"+newline+ "duh(a,c) ::= <>"+newline; writeFile(tmpdir, "testG.stg", templates); /*StringTemplateGroup group =*/ new StringTemplateGroup(new FileReader(tmpdir+"/testG.stg"), errors); String expecting = "group testG does not satisfy interface testI: mismatched arguments on these templates [optional duh(a, b, c)]"; assertEquals(expecting,errors.toString()); } public void testGroupFileFormat() throws Exception { String templates = "group test;" +newline+ "t() ::= \"literal template\"" +newline+ "bold(item) ::= \"$item$\""+newline+ "duh() ::= <<"+newline+"xx"+newline+">>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class); String expecting = "group test;" +newline+ "bold(item) ::= <<$item$>>" +newline+ "duh() ::= <>" +newline+ "t() ::= <>"+newline; assertEquals(expecting,group.toString()); StringTemplate a = group.getInstanceOf("t"); expecting = "literal template"; assertEquals(expecting,a.toString()); StringTemplate b = group.getInstanceOf("bold"); b.setAttribute("item", "dork"); expecting = "dork"; assertEquals(expecting,b.toString()); } public void testEscapedTemplateDelimiters() throws Exception { String templates = "group test;" +newline+ "t() ::= <<$\"literal\":{a|$a$\\}}$ template\n>>" +newline+ "bold(item) ::= <<$item$>>"+newline+ "duh() ::= <<"+newline+"xx"+newline+">>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class); String expecting = "group test;" +newline+ "bold(item) ::= <<$item$>>" +newline+ "duh() ::= <>" +newline+ "t() ::= <<$\"literal\":{a|$a$\\}}$ template>>"+newline; assertEquals(expecting,group.toString()); StringTemplate b = group.getInstanceOf("bold"); b.setAttribute("item", "dork"); expecting = "dork"; assertEquals(expecting,b.toString()); StringTemplate a = group.getInstanceOf("t"); expecting = "literal} template"; assertEquals(expecting,a.toString()); } /** Check syntax and setAttribute-time errors */ public void testTemplateParameterDecls() throws Exception { String templates = "group test;" +newline+ "t() ::= \"no args but ref $foo$\"" +newline+ "t2(item) ::= \"decl but not used is ok\""+newline + "t3(a,b,c,d) ::= <<$a$ $d$>>"+newline+ "t4(a,b,c,d) ::= <<$a$ $b$ $c$ $d$>>"+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class); // check setting unknown arg in empty formal list StringTemplate a = group.getInstanceOf("t"); String error = null; try { a.setAttribute("foo", "x"); // want NoSuchElementException } catch (NoSuchElementException e) { error = e.getMessage(); } String expecting = "no such attribute: foo in template context [t]"; assertEquals(expecting,error); // check setting known arg a = group.getInstanceOf("t2"); a.setAttribute("item", "x"); // shouldn't get exception // check setting unknown arg in nonempty list of formal args a = group.getInstanceOf("t3"); a.setAttribute("b", "x"); } public void testTemplateRedef() throws Exception { String templates = "group test;" +newline+ "a() ::= \"x\"" +newline+ "b() ::= \"y\"" +newline+ "a() ::= \"z\"" +newline; StringTemplateErrorListener errors = new ErrorBuffer(); /*StringTemplateGroup group =*/ new StringTemplateGroup(new StringReader(templates), errors); String expecting = "redefinition of template: a"; assertEquals(expecting,errors.toString()); } public void testMissingInheritedAttribute() throws Exception { String templates = "group test;" +newline+ "page(title,font) ::= <<"+newline + ""+newline + ""+newline + "$title$
    "+newline + "$body()$"+newline + ""+newline + ""+newline + ">>"+newline + "body() ::= \"my body\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class); StringTemplate t = group.getInstanceOf("page"); t.setAttribute("title","my title"); t.setAttribute("font","Helvetica"); // body() will see it t.toString(); // should be no problem } public void testFormalArgumentAssignment() throws Exception { String templates = "group test;" +newline+ "page() ::= <<$body(font=\"Times\")$>>"+newline + "body(font) ::= \"my body\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class); StringTemplate t = group.getInstanceOf("page"); String expecting = "my body"; assertEquals(expecting, t.toString()); } public void testUndefinedArgumentAssignment() throws Exception { String templates = "group test;" +newline+ "page(x) ::= <<$body(font=x)$>>"+newline + "body() ::= \"my body\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class); StringTemplate t = group.getInstanceOf("page"); t.setAttribute("x","Times"); String error = ""; try { t.toString(); } catch (NoSuchElementException iae) { error = iae.getMessage(); } String expecting = "template body has no such attribute: font in template context [page ]"; assertEquals(expecting, error); } public void testFormalArgumentAssignmentInApply() throws Exception { String templates = "group test;" +newline+ "page(name) ::= <<$name:bold(font=\"Times\")$>>"+newline + "bold(font) ::= \"$it$\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class); StringTemplate t = group.getInstanceOf("page"); t.setAttribute("name", "Ter"); String expecting = "Ter"; assertEquals(expecting, t.toString()); } public void testUndefinedArgumentAssignmentInApply() throws Exception { String templates = "group test;" +newline+ "page(name,x) ::= <<$name:bold(font=x)$>>"+newline + "bold() ::= \"$it$\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class); StringTemplate t = group.getInstanceOf("page"); t.setAttribute("x","Times"); t.setAttribute("name", "Ter"); String error = ""; try { t.toString(); } catch (NoSuchElementException iae) { error = iae.getMessage(); } String expecting = "template bold has no such attribute: font in template context [page ]"; assertEquals(expecting,error); } public void testUndefinedAttributeReference() throws Exception { String templates = "group test;" +newline+ "page() ::= <<$bold()$>>"+newline + "bold() ::= \"$name$\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class); StringTemplate t = group.getInstanceOf("page"); String error = ""; try { t.toString(); } catch (NoSuchElementException iae) { error = iae.getMessage(); } String expecting = "no such attribute: name in template context [page bold]"; assertEquals(expecting,error); } public void testUndefinedDefaultAttributeReference() throws Exception { String templates = "group test;" +newline+ "page() ::= <<$bold()$>>"+newline + "bold() ::= \"$it$\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class); StringTemplate t = group.getInstanceOf("page"); String error = ""; try { t.toString(); } catch (NoSuchElementException nse) { error = nse.getMessage(); } String expecting = "no such attribute: it in template context [page bold]"; assertEquals(expecting,error); } public void testAngleBracketsWithGroupFile() throws Exception { String templates = "group test;" +newline+ "a(s) ::= \" : break;}>\""+newline + "b(t) ::= \"\"" +newline+ "c(t) ::= << >>" +newline; // mainly testing to ensure we don't get parse errors of above StringTemplateGroup group = new StringTemplateGroup( new StringReader(templates)); StringTemplate t = group.getInstanceOf("a"); t.setAttribute("s","Test"); String expecting = "case 1 : Test break;"; assertEquals(expecting, t.toString()); } public void testAngleBracketsNoGroup() throws Exception { StringTemplate st =new StringTemplate( "Tokens : ;", AngleBracketTemplateLexer.class); st.setAttribute("rules", "A"); st.setAttribute("rules", "B"); String expecting = "Tokens : A|B ;"; assertEquals(expecting, st.toString()); } public void testRegionRef() throws Exception { String templates = "group test;" +newline+ "a() ::= \"X$@r()$Y\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class); StringTemplate st = group.getInstanceOf("a"); String result = st.toString(); String expecting = "XY"; assertEquals(expecting, result); } public void testEmbeddedRegionRef() throws Exception { String templates = "group test;" +newline+ "a() ::= \"X$@r$blort$@end$Y\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class); StringTemplate st = group.getInstanceOf("a"); String result = st.toString(); String expecting = "XblortY"; assertEquals(expecting, result); } public void testRegionRefAngleBrackets() throws Exception { String templates = "group test;" +newline+ "a() ::= \"X<@r()>Y\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("a"); String result = st.toString(); String expecting = "XY"; assertEquals(expecting, result); } public void testEmbeddedRegionRefAngleBrackets() throws Exception { String templates = "group test;" +newline+ "a() ::= \"X<@r>blort<@end>Y\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("a"); String result = st.toString(); String expecting = "XblortY"; assertEquals(expecting, result); } // FIXME: This test fails due to inserted white space... public void testEmbeddedRegionRefWithNewlinesAngleBrackets() throws Exception { String templates = "group test;" +newline+ "a() ::= \"X<@r>" +newline+ "blort" +newline+ "<@end>" +newline+ "Y\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("a"); String result = st.toString(); String expecting = "XblortY"; assertEquals(expecting, result); } public void testRegionRefWithDefAngleBrackets() throws Exception { String templates = "group test;" +newline+ "a() ::= \"X<@r()>Y\"" +newline+ "@a.r() ::= \"foo\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("a"); String result = st.toString(); String expecting = "XfooY"; assertEquals(expecting, result); } public void testRegionRefWithDefInConditional() throws Exception { String templates = "group test;" +newline+ "a(v) ::= \"XA<@r()>BY\"" +newline+ "@a.r() ::= \"foo\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("a"); st.setAttribute("v", "true"); String result = st.toString(); String expecting = "XAfooBY"; assertEquals(expecting, result); } public void testRegionRefWithImplicitDefInConditional() throws Exception { String templates = "group test;" +newline+ "a(v) ::= \"XA<@r>yo<@end>BY\"" +newline+ "@a.r() ::= \"foo\"" +newline; StringTemplateErrorListener errors = new ErrorBuffer(); StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), errors); StringTemplate st = group.getInstanceOf("a"); st.setAttribute("v", "true"); String result = st.toString(); String expecting = "XAyoBY"; assertEquals(expecting, result); String err_result = errors.toString(); String err_expecting = "group test line 3: redefinition of template region: @a.r"; assertEquals(err_expecting,err_result); } public void testRegionOverride() throws Exception { String templates1 = "group super;" +newline+ "a() ::= \"X<@r()>Y\"" + "@a.r() ::= \"foo\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates1)); String templates2 = "group sub;" +newline+ "@a.r() ::= \"foo\"" +newline; StringTemplateGroup subGroup = new StringTemplateGroup(new StringReader(templates2), AngleBracketTemplateLexer.class, null, group); StringTemplate st = subGroup.getInstanceOf("a"); String result = st.toString(); String expecting = "XfooY"; assertEquals(expecting, result); } public void testRegionOverrideRefSuperRegion() throws Exception { String templates1 = "group super;" +newline+ "a() ::= \"X<@r()>Y\"" + "@a.r() ::= \"foo\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates1)); String templates2 = "group sub;" +newline+ "@a.r() ::= \"A<@super.r()>B\"" +newline; StringTemplateGroup subGroup = new StringTemplateGroup(new StringReader(templates2), AngleBracketTemplateLexer.class, null, group); StringTemplate st = subGroup.getInstanceOf("a"); String result = st.toString(); String expecting = "XAfooBY"; assertEquals(expecting, result); } public void testRegionOverrideRefSuperRegion3Levels() throws Exception { // Bug: This was causing infinite recursion: // getInstanceOf(super::a) // getInstanceOf(sub::a) // getInstanceOf(subsub::a) // getInstanceOf(subsub::region__a__r) // getInstanceOf(subsub::super.region__a__r) // getInstanceOf(subsub::super.region__a__r) // getInstanceOf(subsub::super.region__a__r) // ... // Somehow, the ref to super in subsub is not moving up the chain // to the @super.r(); oh, i introduced a bug when i put setGroup // into STG.getInstanceOf()! String templates1 = "group super;" +newline+ "a() ::= \"X<@r()>Y\"" + "@a.r() ::= \"foo\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates1)); String templates2 = "group sub;" +newline+ "@a.r() ::= \"<@super.r()>2\"" +newline; StringTemplateGroup subGroup = new StringTemplateGroup(new StringReader(templates2), AngleBracketTemplateLexer.class, null, group); String templates3 = "group subsub;" +newline+ "@a.r() ::= \"<@super.r()>3\"" +newline; StringTemplateGroup subSubGroup = new StringTemplateGroup(new StringReader(templates3), AngleBracketTemplateLexer.class, null, subGroup); StringTemplate st = subSubGroup.getInstanceOf("a"); String result = st.toString(); String expecting = "Xfoo23Y"; assertEquals(expecting, result); } public void testRegionOverrideRefSuperImplicitRegion() throws Exception { String templates1 = "group super;" +newline+ "a() ::= \"X<@r>foo<@end>Y\""+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates1)); String templates2 = "group sub;" +newline+ "@a.r() ::= \"A<@super.r()>\"" +newline; StringTemplateGroup subGroup = new StringTemplateGroup(new StringReader(templates2), AngleBracketTemplateLexer.class, null, group); StringTemplate st = subGroup.getInstanceOf("a"); String result = st.toString(); String expecting = "XAfooY"; assertEquals(expecting, result); } public void testEmbeddedRegionRedefError() throws Exception { // cannot define an embedded template within group String templates = "group test;" +newline+ "a() ::= \"X<@r>dork<@end>Y\"" + "@a.r() ::= \"foo\"" +newline; StringTemplateErrorListener errors = new ErrorBuffer(); StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), errors); StringTemplate st = group.getInstanceOf("a"); st.toString(); String result = errors.toString(); String expecting = "group test line 2: redefinition of template region: @a.r"; assertEquals(expecting, result); } public void testImplicitRegionRedefError() throws Exception { // cannot define an implicitly-defined template more than once String templates = "group test;" +newline+ "a() ::= \"X<@r()>Y\"" +newline+ "@a.r() ::= \"foo\"" +newline+ "@a.r() ::= \"bar\"" +newline; StringTemplateErrorListener errors = new ErrorBuffer(); StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), errors); StringTemplate st = group.getInstanceOf("a"); st.toString(); String result = errors.toString(); String expecting = "group test line 4: redefinition of template region: @a.r"; assertEquals(expecting, result); } public void testImplicitOverriddenRegionRedefError() throws Exception { String templates1 = "group super;" +newline+ "a() ::= \"X<@r()>Y\"" + "@a.r() ::= \"foo\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates1)); String templates2 = "group sub;" +newline+ "@a.r() ::= \"foo\"" +newline+ "@a.r() ::= \"bar\"" +newline; StringTemplateErrorListener errors = new ErrorBuffer(); StringTemplateGroup subGroup = new StringTemplateGroup(new StringReader(templates2), AngleBracketTemplateLexer.class, errors, group); /*StringTemplate st =*/ subGroup.getInstanceOf("a"); String result = errors.toString(); String expecting = "group sub line 3: redefinition of template region: @a.r"; assertEquals(expecting, result); } public void testUnknownRegionDefError() throws Exception { // cannot define an implicitly-defined template more than once String templates = "group test;" +newline+ "a() ::= \"X<@r()>Y\"" +newline+ "@a.q() ::= \"foo\"" +newline; StringTemplateErrorListener errors = new ErrorBuffer(); StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), errors); StringTemplate st = group.getInstanceOf("a"); st.toString(); String result = errors.toString(); String expecting = "group test line 3: template a has no region called q"; assertEquals(expecting, result); } public void testSuperRegionRefError() throws Exception { String templates1 = "group super;" +newline+ "a() ::= \"X<@r()>Y\"" + "@a.r() ::= \"foo\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates1)); String templates2 = "group sub;" +newline+ "@a.r() ::= \"A<@super.q()>B\"" +newline; StringTemplateErrorListener errors = new ErrorBuffer(); StringTemplateGroup subGroup = new StringTemplateGroup(new StringReader(templates2), AngleBracketTemplateLexer.class, errors, group); /*StringTemplate st =*/ subGroup.getInstanceOf("a"); String result = errors.toString(); String expecting = "template a has no region called q"; assertEquals(expecting, result); } public void testMissingEndRegionError() throws Exception { // cannot define an implicitly-defined template more than once String templates = "group test;" +newline+ "a() ::= \"X$@r$foo\"" +newline; StringTemplateErrorListener errors = new ErrorBuffer(); StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class, errors, null); StringTemplate st = group.getInstanceOf("a"); st.toString(); String result = errors.toString(); String expecting = "missing region r $@end$ tag"; assertEquals(expecting, result); } public void testMissingEndRegionErrorAngleBrackets() throws Exception { // cannot define an implicitly-defined template more than once String templates = "group test;" +newline+ "a() ::= \"X<@r>foo\"" +newline; StringTemplateErrorListener errors = new ErrorBuffer(); StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), errors); StringTemplate st = group.getInstanceOf("a"); st.toString(); String result = errors.toString(); String expecting = "missing region r <@end> tag"; assertEquals(expecting, result); } public void testSimpleInheritance() throws Exception { // make a bold template in the super group that you can inherit from sub StringTemplateGroup supergroup = new StringTemplateGroup("super"); StringTemplateGroup subgroup = new StringTemplateGroup("sub"); /*StringTemplate bold =*/ supergroup.defineTemplate("bold", "$it$"); subgroup.setSuperGroup(supergroup); StringTemplateErrorListener errors = new ErrorBuffer(); subgroup.setErrorListener(errors); supergroup.setErrorListener(errors); StringTemplate duh = new StringTemplate(subgroup, "$name:bold()$"); duh.setAttribute("name", "Terence"); String expecting = "Terence"; assertEquals(expecting,duh.toString()); } public void testOverrideInheritance() throws Exception { // make a bold template in the super group and one in sub group StringTemplateGroup supergroup = new StringTemplateGroup("super"); StringTemplateGroup subgroup = new StringTemplateGroup("sub"); supergroup.defineTemplate("bold", "$it$"); subgroup.defineTemplate("bold", "$it$"); subgroup.setSuperGroup(supergroup); StringTemplateErrorListener errors = new ErrorBuffer(); subgroup.setErrorListener(errors); supergroup.setErrorListener(errors); StringTemplate duh = new StringTemplate(subgroup, "$name:bold()$"); duh.setAttribute("name", "Terence"); String expecting = "Terence"; assertEquals(expecting,duh.toString()); } public void testMultiLevelInheritance() throws Exception { // must loop up two levels to find bold() StringTemplateGroup rootgroup = new StringTemplateGroup("root"); StringTemplateGroup level1 = new StringTemplateGroup("level1"); StringTemplateGroup level2 = new StringTemplateGroup("level2"); rootgroup.defineTemplate("bold", "$it$"); level1.setSuperGroup(rootgroup); level2.setSuperGroup(level1); StringTemplateErrorListener errors = new ErrorBuffer(); rootgroup.setErrorListener(errors); level1.setErrorListener(errors); level2.setErrorListener(errors); StringTemplate duh = new StringTemplate(level2, "$name:bold()$"); duh.setAttribute("name", "Terence"); String expecting = "Terence"; assertEquals(expecting,duh.toString()); } public void testComplicatedInheritance() throws Exception { // in super: decls invokes labels // in sub: overridden decls which calls super.decls // overridden labels // Bug: didn't see the overridden labels. In other words, // the overridden decls called super which called labels, but // didn't get the subgroup overridden labels--it calls the // one in the superclass. Ouput was "DL" not "DSL"; didn't // invoke sub's labels(). String basetemplates = "group base;" +newline+ "decls() ::= \"D\""+newline+ "labels() ::= \"L\"" +newline ; StringTemplateGroup base = new StringTemplateGroup(new StringReader(basetemplates)); String subtemplates = "group sub;" +newline+ "decls() ::= \"\""+newline+ "labels() ::= \"SL\"" +newline ; StringTemplateGroup sub = new StringTemplateGroup(new StringReader(subtemplates)); sub.setSuperGroup(base); StringTemplate st = sub.getInstanceOf("decls"); String expecting = "DSL"; String result = st.toString(); assertEquals(expecting, result); } public void test3LevelSuperRef() throws Exception { String templates1 = "group super;" +newline+ "r() ::= \"foo\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates1)); String templates2 = "group sub;" +newline+ "r() ::= \"2\"" +newline; StringTemplateGroup subGroup = new StringTemplateGroup(new StringReader(templates2), AngleBracketTemplateLexer.class, null, group); String templates3 = "group subsub;" +newline+ "r() ::= \"3\"" +newline; StringTemplateGroup subSubGroup = new StringTemplateGroup(new StringReader(templates3), AngleBracketTemplateLexer.class, null, subGroup); StringTemplate st = subSubGroup.getInstanceOf("r"); String result = st.toString(); String expecting = "foo23"; assertEquals(expecting, result); } public void testExprInParens() throws Exception { // specify a template to apply to an attribute // Use a template group so we can specify the start/stop chars StringTemplateGroup group = new StringTemplateGroup("dummy", "."); /*StringTemplate bold =*/ group.defineTemplate("bold", "$it$"); StringTemplate duh = new StringTemplate(group, "$(\"blort: \"+(list)):bold()$"); duh.setAttribute("list", "a"); duh.setAttribute("list", "b"); duh.setAttribute("list", "c"); // System.out.println(duh); String expecting = "blort: abc"; assertEquals(expecting, duh.toString()); } public void testMultipleAdditions() throws Exception { // specify a template to apply to an attribute // Use a template group so we can specify the start/stop chars StringTemplateGroup group = new StringTemplateGroup("dummy", "."); group.defineTemplate("link", "
    $title$"); StringTemplate duh = new StringTemplate(group, "$link(url=\"/member/view?ID=\"+ID+\"&x=y\"+foo, title=\"the title\")$"); duh.setAttribute("ID", "3321"); duh.setAttribute("foo", "fubar"); String expecting = "the title"; assertEquals(expecting, duh.toString()); } public void testCollectionAttributes() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); /*StringTemplate bold =*/ group.defineTemplate("bold", "$it$"); StringTemplate t = new StringTemplate(group, "$data$, $data:bold()$, "+ "$list:bold():bold()$, $array$, $a2$, $a3$, $a4$"); Vector v = new Vector(); v.addElement("1"); v.addElement("2"); v.addElement("3"); List list = new ArrayList(); list.add("a"); list.add("b"); list.add("c"); t.setAttribute("data", v); t.setAttribute("list", list); t.setAttribute("array", new String[] {"x","y"}); t.setAttribute("a2", new int[] {10,20}); t.setAttribute("a3", new float[] {1.2f,1.3f}); t.setAttribute("a4", new double[] {8.7,9.2}); //System.out.println(t); String expecting="123, 123, "+ "abc, xy, 1020, 1.21.3, 8.79.2"; assertEquals(expecting, t.toString()); } public void testParenthesizedExpression() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); /*StringTemplate bold =*/ group.defineTemplate("bold", "$it$"); StringTemplate t = new StringTemplate(group, "$(f+l):bold()$"); t.setAttribute("f", "Joe"); t.setAttribute("l", "Schmoe"); //System.out.println(t); String expecting="JoeSchmoe"; assertEquals(expecting, t.toString()); } public void testApplyTemplateNameExpression() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); /* StringTemplate bold =*/ group.defineTemplate("foobar", "foo$attr$bar"); StringTemplate t = new StringTemplate(group, "$data:(name+\"bar\")()$"); t.setAttribute("data", "Ter"); t.setAttribute("data", "Tom"); t.setAttribute("name", "foo"); //System.out.println(t); String expecting="fooTerbarfooTombar"; assertEquals(expecting, t.toString()); } public void testApplyTemplateNameTemplateEval() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); /*StringTemplate foobar =*/ group.defineTemplate("foobar", "foo$it$bar"); /*StringTemplate a =*/ group.defineTemplate("a", "$it$bar"); StringTemplate t = new StringTemplate(group, "$data:(\"foo\":a())()$"); t.setAttribute("data", "Ter"); t.setAttribute("data", "Tom"); //System.out.println(t); String expecting="fooTerbarfooTombar"; assertEquals(expecting, t.toString()); } public void testTemplateNameExpression() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); /*StringTemplate foo =*/ group.defineTemplate("foo", "hi there!"); StringTemplate t = new StringTemplate(group, "$(name)()$"); t.setAttribute("name", "foo"); //System.out.println(t); String expecting="hi there!"; assertEquals(expecting, t.toString()); } public void testMissingEndDelimiter() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplateErrorListener errors = new ErrorBuffer(); group.setErrorListener(errors); /*StringTemplate t =*/ new StringTemplate(group, "stuff $a then more junk etc..."); String expectingError="problem parsing template 'anonymous': line 1:31: expecting '$', found ''"; //System.out.println("error: '"+errors+"'"); //System.out.println("expecting: '"+expectingError+"'"); assertTrue(errors.toString().startsWith(expectingError)); } public void testSetButNotRefd() throws Exception { StringTemplate.setLintMode(true); StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplate t = new StringTemplate(group, "$a$ then $b$ and $c$ refs."); t.setAttribute("a", "Terence"); t.setAttribute("b", "Terence"); t.setAttribute("cc", "Terence"); // oops...should be 'c' StringTemplateErrorListener errors = new ErrorBuffer(); group.setErrorListener(errors); String expectingError="anonymous: set but not used: cc"; /*String result =*/ t.toString(); // result is irrelevant //System.out.println("result error: '"+errors+"'"); //System.out.println("expecting: '"+expectingError+"'"); StringTemplate.setLintMode(false); assertEquals(expectingError,errors.toString()); } public void testNullTemplateApplication() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplateErrorListener errors = new ErrorBuffer(); group.setErrorListener(errors); StringTemplate t = new StringTemplate(group, "$names:bold(x=it)$"); t.setAttribute("names", "Terence"); String error = null; try { t.toString(); } catch (IllegalArgumentException iae) { error = iae.getMessage(); } String expecting = "Can't find template bold.st; context is [anonymous]; group hierarchy is [test]" ; assertEquals(expecting,error); } public void testNullTemplateToMultiValuedApplication() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplateErrorListener errors = new ErrorBuffer(); group.setErrorListener(errors); StringTemplate t = new StringTemplate(group, "$names:bold(x=it)$"); t.setAttribute("names", "Terence"); t.setAttribute("names", "Tom"); //System.out.println(t); String error = null; try { t.toString(); } catch (IllegalArgumentException iae) { error = iae.getMessage(); } String expecting = "Can't find template bold.st; context is [anonymous]; group hierarchy is [test]"; // bold not found...empty string assertEquals(expecting,error); } public void testChangingAttrValueTemplateApplicationToVector() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); /*StringTemplate bold =*/ group.defineTemplate("bold", "$x$"); StringTemplate t = new StringTemplate(group, "$names:bold(x=it)$"); t.setAttribute("names", "Terence"); t.setAttribute("names", "Tom"); //System.out.println("'"+t.toString()+"'"); String expecting="TerenceTom"; assertEquals(expecting, t.toString()); } public void testChangingAttrValueRepeatedTemplateApplicationToVector() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", "."); /*StringTemplate bold =*/ group.defineTemplate("bold", "$item$"); /*StringTemplate italics =*/ group.defineTemplate("italics", "$it$"); StringTemplate members = new StringTemplate(group, "$members:bold(item=it):italics(it=it)$"); members.setAttribute("members", "Jim"); members.setAttribute("members", "Mike"); members.setAttribute("members", "Ashar"); //System.out.println("members="+members); String expecting = "JimMikeAshar"; assertEquals(expecting,members.toString()); } public void testAlternatingTemplateApplication() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", "."); /*StringTemplate listItem =*/ group.defineTemplate("listItem", "

  • $it$
  • "); /*StringTemplate bold =*/ group.defineTemplate("bold", "$it$"); /*StringTemplate italics =*/ group.defineTemplate("italics", "$it$"); StringTemplate item = new StringTemplate(group, "$item:bold(),italics():listItem()$"); item.setAttribute("item", "Jim"); item.setAttribute("item", "Mike"); item.setAttribute("item", "Ashar"); //System.out.println("ITEM="+item); String expecting = "
  • Jim
  • Mike
  • Ashar
  • "; assertEquals(item.toString(), expecting); } public void testExpressionAsRHSOfAssignment() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); /*StringTemplate hostname =*/ group.defineTemplate("hostname", "$machine$.jguru.com"); /*StringTemplate bold =*/ group.defineTemplate("bold", "$x$"); StringTemplate t = new StringTemplate(group, "$bold(x=hostname(machine=\"www\"))$"); String expecting="www.jguru.com"; assertEquals(expecting, t.toString()); } public void testTemplateApplicationAsRHSOfAssignment() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); /*StringTemplate hostname =*/ group.defineTemplate("hostname", "$machine$.jguru.com"); /*StringTemplate bold =*/ group.defineTemplate("bold", "$x$"); /*StringTemplate italics =*/ group.defineTemplate("italics", "$it$"); StringTemplate t = new StringTemplate(group, "$bold(x=hostname(machine=\"www\"):italics())$"); String expecting="www.jguru.com"; assertEquals(expecting, t.toString()); } public void testParameterAndAttributeScoping() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); /*StringTemplate italics =*/ group.defineTemplate("italics", "$x$"); /*StringTemplate bold =*/ group.defineTemplate("bold", "$x$"); StringTemplate t = new StringTemplate(group, "$bold(x=italics(x=name))$"); t.setAttribute("name", "Terence"); //System.out.println(t); String expecting="Terence"; assertEquals(expecting, t.toString()); } public void testComplicatedSeparatorExpr() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); /*StringTemplate bold =*/ group.defineTemplate("bulletSeparator", "$foo$
  • "); // make separator a complicated expression with args passed to included template StringTemplate t = new StringTemplate(group, "
      $name; separator=bulletSeparator(foo=\" \")+\" \"$
    "); t.setAttribute("name", "Ter"); t.setAttribute("name", "Tom"); t.setAttribute("name", "Mel"); //System.out.println(t); String expecting = "
      Ter
    •  Tom
    •  Mel
    "; assertEquals(expecting, t.toString()); } public void testAttributeRefButtedUpAgainstEndifAndWhitespace() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplate a = new StringTemplate(group, "$if (!firstName)$$email$$endif$"); a.setAttribute("email", "parrt@jguru.com"); String expecting = "parrt@jguru.com"; assertEquals(a.toString(), expecting); } public void testStringCatenationOnSingleValuedAttributeViaTemplateLiteral() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); /*StringTemplate bold =*/ group.defineTemplate("bold", "$it$"); //StringTemplate a = new StringTemplate(group, "$\" Parr\":bold()$"); StringTemplate b = new StringTemplate(group, "$bold(it={$name$ Parr})$"); //a.setAttribute("name", "Terence"); b.setAttribute("name", "Terence"); String expecting = "Terence Parr"; //assertEquals(a.toString(), expecting); assertEquals(b.toString(), expecting); } public void testStringCatenationOpOnArg() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); /*StringTemplate bold =*/ group.defineTemplate("bold", "$it$"); StringTemplate b = new StringTemplate(group, "$bold(it=name+\" Parr\")$"); //a.setAttribute("name", "Terence"); b.setAttribute("name", "Terence"); String expecting = "Terence Parr"; //assertEquals(expecting, a.toString()); assertEquals(expecting, b.toString()); } public void testStringCatenationOpOnArgWithEqualsInString() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); /*StringTemplate bold =*/ group.defineTemplate("bold", "$it$"); StringTemplate b = new StringTemplate(group, "$bold(it=name+\" Parr=\")$"); //a.setAttribute("name", "Terence"); b.setAttribute("name", "Terence"); String expecting = "Terence Parr="; //assertEquals(expecting, a.toString()); assertEquals(expecting, b.toString()); } public void testApplyingTemplateFromDiskWithPrecompiledIF() throws Exception { // Create a temporary working directory File tmpDir = new File(System.getProperty("java.io.tmpdir")); File tmpWorkDir; int counter = (new Random()).nextInt() & 65535;; do { counter++; StringBuffer name = new StringBuffer("st-junit-"); name.append(counter); tmpWorkDir = new File(tmpDir, name.toString()); } while (tmpWorkDir.exists()); tmpWorkDir.mkdirs(); // write the template files first to /tmp File pageFile = new File(tmpWorkDir,"page.st"); FileWriter fw = new FileWriter(pageFile); fw.write(""+newline); //fw.write(" PeerScope: $title$"+newline); fw.write(""+newline); fw.write(""+newline); fw.write("$if(member)$User: $member:terse()$$endif$"+newline); fw.write(""+newline); fw.write(""+newline); fw.close(); File terseFile = new File(tmpWorkDir,"terse.st"); fw = new FileWriter(terseFile); fw.write("$it.firstName$ $it.lastName$ ($it.email$)"+newline); fw.close(); // specify a template to apply to an attribute // Use a template group so we can specify the start/stop chars StringTemplateGroup group = new StringTemplateGroup("dummy", tmpWorkDir.toString()); StringTemplate a = group.getInstanceOf("page"); a.setAttribute("member", new Connector()); String expecting = ""+newline+ ""+newline+ ""+newline+ "User: Terence Parr (parrt@jguru.com)"+newline+ ""+newline+ ""; //System.out.println("'"+a+"'"); assertEquals(expecting, a.toString()); // Cleanup the temp folder. pageFile.delete(); terseFile.delete(); tmpWorkDir.delete(); } public void testMultiValuedAttributeWithAnonymousTemplateUsingIndexVariableI() throws Exception { StringTemplateGroup tgroup = new StringTemplateGroup("dummy", "."); StringTemplate t = new StringTemplate(tgroup, " List:"+newline+" "+newline+"foo"+newline+newline+ "$names:{
    $i$. $it$"+newline+ "}$"); t.setAttribute("names", "Terence"); t.setAttribute("names", "Jim"); t.setAttribute("names", "Sriram"); //System.out.println(t); String expecting = " List:"+newline+ " "+newline+ "foo"+newline+newline+ "
    1. Terence"+newline+ "
    2. Jim"+newline+ "
    3. Sriram"+newline; assertEquals(expecting, t.toString()); } public void testFindTemplateInCLASSPATH() throws Exception { // Look for templates in CLASSPATH as resources StringTemplateGroup mgroup = new StringTemplateGroup("method stuff", AngleBracketTemplateLexer.class); StringTemplate m = mgroup.getInstanceOf("org/antlr/stringtemplate/test/method"); // "method.st" references body() so "body.st" will be loaded too m.setAttribute("visibility", "public"); m.setAttribute("name", "foobar"); m.setAttribute("returnType", "void"); m.setAttribute("statements", "i=1;"); // body inherits these from method m.setAttribute("statements", "x=i;"); String expecting = "public void foobar() {"+newline+ "\t// start of a body"+newline+ "\ti=1;"+newline+ "\tx=i;"+newline+ "\t// end of a body"+newline+ "}"; //System.out.println(m); assertEquals(expecting, m.toString()); } public void testApplyTemplateToSingleValuedAttribute() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); /*StringTemplate bold =*/ group.defineTemplate("bold", "$x$"); StringTemplate name = new StringTemplate(group, "$name:bold(x=name)$"); name.setAttribute("name", "Terence"); assertEquals("Terence",name.toString()); } public void testStringLiteralAsAttribute() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); /*StringTemplate bold =*/ group.defineTemplate("bold", "$it$"); StringTemplate name = new StringTemplate(group, "$\"Terence\":bold()$"); assertEquals("Terence",name.toString()); } public void testApplyTemplateToSingleValuedAttributeWithDefaultAttribute() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); /*StringTemplate bold =*/ group.defineTemplate("bold", "$it$"); StringTemplate name = new StringTemplate(group, "$name:bold()$"); name.setAttribute("name", "Terence"); assertEquals("Terence",name.toString()); } public void testApplyAnonymousTemplateToSingleValuedAttribute() throws Exception { // specify a template to apply to an attribute // Use a template group so we can specify the start/stop chars StringTemplateGroup group = new StringTemplateGroup("dummy", "."); StringTemplate item = new StringTemplate(group, "$item:{
  • $it$
  • }$"); item.setAttribute("item", "Terence"); assertEquals("
  • Terence
  • ",item.toString()); } public void testApplyAnonymousTemplateToMultiValuedAttribute() throws Exception { // specify a template to apply to an attribute // Use a template group so we can specify the start/stop chars StringTemplateGroup group = new StringTemplateGroup("dummy", "."); StringTemplate list = new StringTemplate(group, "
      $items$
    "); // demonstrate setting arg to anonymous subtemplate StringTemplate item = new StringTemplate(group, "$item:{
  • $it$
  • }; separator=\",\"$"); item.setAttribute("item", "Terence"); item.setAttribute("item", "Jim"); item.setAttribute("item", "John"); list.setAttribute("items", item); // nested template String expecting = "
    • Terence
    • ,
    • Jim
    • ,
    • John
    "; assertEquals(expecting,list.toString()); } public void testApplyAnonymousTemplateToAggregateAttribute() throws Exception { StringTemplate st = new StringTemplate("$items:{$it.lastName$, $it.firstName$\n}$"); // also testing wacky spaces in aggregate spec st.setAttribute("items.{ firstName ,lastName}", "Ter", "Parr"); st.setAttribute("items.{firstName, lastName }", "Tom", "Burns"); String expecting = "Parr, Ter"+newline + "Burns, Tom"+newline; assertEquals(expecting, st.toString()); } public void testRepeatedApplicationOfTemplateToSingleValuedAttribute() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", "."); /*StringTemplate search =*/ group.defineTemplate("bold", "$it$"); StringTemplate item = new StringTemplate(group, "$item:bold():bold()$"); item.setAttribute("item", "Jim"); assertEquals("Jim", item.toString()); } public void testRepeatedApplicationOfTemplateToMultiValuedAttributeWithSeparator() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", "."); /*StringTemplate search =*/ group.defineTemplate("bold", "$it$"); StringTemplate item = new StringTemplate(group, "$item:bold():bold(); separator=\",\"$"); item.setAttribute("item", "Jim"); item.setAttribute("item", "Mike"); item.setAttribute("item", "Ashar"); // first application of template must yield another vector! //System.out.println("ITEM="+item); String expecting = "Jim,Mike,Ashar"; assertEquals(item.toString(), expecting); } // ### NEED A TEST OF obj ASSIGNED TO ARG? public void testMultiValuedAttributeWithSeparator() throws Exception { StringTemplate query; // if column can be multi-valued, specify a separator StringTemplateGroup group = new StringTemplateGroup("dummy", ".", AngleBracketTemplateLexer.class); query = new StringTemplate(group, "SELECT FROM ;"); query.setAttribute("column", "name"); query.setAttribute("column", "email"); query.setAttribute("table", "User"); // uncomment next line to make "DISTINCT" appear in output // query.setAttribute("distince", "DISTINCT"); // System.out.println(query); assertEquals("SELECT name, email FROM User;",query.toString()); } public void testSingleValuedAttributes() throws Exception { // all attributes are single-valued: StringTemplate query = new StringTemplate("SELECT $column$ FROM $table$;"); query.setAttribute("column", "name"); query.setAttribute("table", "User"); // System.out.println(query); assertEquals("SELECT name FROM User;",query.toString()); } public void testIFTemplate() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", ".", AngleBracketTemplateLexer.class); StringTemplate t = new StringTemplate(group, "SELECT FROM PERSON "+ "WHERE ID=;"); t.setAttribute("column", "name"); t.setAttribute("cond", "true"); t.setAttribute("id", "231"); assertEquals("SELECT name FROM PERSON WHERE ID=231;",t.toString()); } public void testIFCondWithParensTemplate() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", ".", AngleBracketTemplateLexer.class); StringTemplate t = new StringTemplate(group, " =;"); HashMap map = new HashMap(); map.put("int","0"); t.setAttribute("map", map); t.setAttribute("prop", "x"); t.setAttribute("type", "int"); assertEquals("int x=0;",t.toString()); } public void testIFCondWithParensDollarDelimsTemplate() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", "."); StringTemplate t = new StringTemplate(group, "$if(map.(type))$$type$ $prop$=$map.(type)$;$endif$"); HashMap map = new HashMap(); map.put("int","0"); t.setAttribute("map", map); t.setAttribute("prop", "x"); t.setAttribute("type", "int"); assertEquals("int x=0;",t.toString()); } /** As of 2.0, you can test a boolean value */ public void testIFBoolean() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", "."); StringTemplate t = new StringTemplate(group, "$if(b)$x$endif$ $if(!b)$y$endif$"); t.setAttribute("b", new Boolean(true)); assertEquals(t.toString(), "x "); t = t.getInstanceOf(); t.setAttribute("b", new Boolean(false)); assertEquals(" y", t.toString()); } public void testNestedIFTemplate() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", ".", AngleBracketTemplateLexer.class); StringTemplate t = new StringTemplate(group, "ack"+newline+ "foo"+newline+ "stuff"+newline+ "no"+newline+ "junk"+newline+ "" ); t.setAttribute("a", "blort"); // leave b as null //System.out.println("t="+t); String expecting = "ackfoo"+newline+ "stuff"+newline+ "junk"; assertEquals(expecting, t.toString()); } public void testIFConditionWithTemplateApplication() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", "."); StringTemplate t = new StringTemplate(group, "$if(names:{$it$})$Fail!$endif$ $if(!names:{$it$})$Works!$endif$"); t.setAttribute("b", new Boolean(true)); assertEquals(t.toString(), " Works!"); } public class Connector { public int getID() { return 1; } public String getFirstName() { return "Terence"; } public String getLastName() { return "Parr"; } public String getEmail() { return "parrt@jguru.com"; } public String getBio() { return "Superhero by night..."; } /** As of 2.0, booleans work as you expect. In 1.x, * a missing value simulated a boolean. */ public boolean getCanEdit() { return false; } } public class Connector2 { public int getID() { return 2; } public String getFirstName() { return "Tom"; } public String getLastName() { return "Burns"; } public String getEmail() { return "tombu@jguru.com"; } public String getBio() { return "Superhero by day..."; } public Boolean getCanEdit() { return new Boolean(true); } } public void testObjectPropertyReference() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", "."); StringTemplate t = new StringTemplate( group, "Name: $p.firstName$ $p.lastName$
    "+newline+ "Email: $p.email$
    "+newline+ "$p.bio$" ); t.setAttribute("p", new Connector()); //System.out.println("t is "+t.toString()); String expecting = "Name: Terence Parr
    "+newline+ "Email: parrt@jguru.com
    "+newline+ "Superhero by night..."; assertEquals(expecting, t.toString()); } public void testApplyRepeatedAnonymousTemplateWithForeignTemplateRefToMultiValuedAttribute() throws Exception { // specify a template to apply to an attribute // Use a template group so we can specify the start/stop chars StringTemplateGroup group = new StringTemplateGroup("dummy", "."); group.defineTemplate("link", "$title$"); StringTemplate duh = new StringTemplate(group, "start|$p:{$link(url=\"/member/view?ID=\"+it.ID, title=it.firstName)$ $if(it.canEdit)$canEdit$endif$}:"+ "{$it$
    \n}$|end"); duh.setAttribute("p", new Connector()); duh.setAttribute("p", new Connector2()); //System.out.println(duh); String expecting = "start|Terence
    "+newline+ "Tom canEdit
    "+newline+ "|end"; assertEquals(expecting,duh.toString()); } public static class Tree { protected List children = new LinkedList(); protected String text; public Tree(String t) { text = t; } public String getText() { return text; } public void addChild(Tree c) { children.add(c); } public Tree getFirstChild() { if ( children.size()==0 ) { return null; } return (Tree)children.get(0); } public List getChildren() { return children; } } public void testRecursion() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", ".", AngleBracketTemplateLexer.class); group.defineTemplate("tree", ""+ "( )" + "" + "" + ""); StringTemplate tree = group.getInstanceOf("tree"); // build ( a b (c d) e ) Tree root = new Tree("a"); root.addChild(new Tree("b")); Tree subtree = new Tree("c"); subtree.addChild(new Tree("d")); root.addChild(subtree); root.addChild(new Tree("e")); tree.setAttribute("it", root); String expecting = "( a b ( c d ) e )"; assertEquals(expecting, tree.toString()); } public void testNestedAnonymousTemplates() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", "."); StringTemplate t = new StringTemplate( group, "$A:{" + newline + "$it:{" + newline + "$it$" + newline + "}$" + newline + "}$" ); t.setAttribute("A", "parrt"); String expecting = newline + "" + newline + "parrt" + newline + "" + newline; assertEquals(expecting, t.toString()); } public void testAnonymousTemplateAccessToEnclosingAttributes() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", "."); StringTemplate t = new StringTemplate( group, "$A:{" + newline + "$it:{" + newline + "$it$, $B$" + newline + "}$" + newline + "}$" ); t.setAttribute("A", "parrt"); t.setAttribute("B", "tombu"); String expecting = newline + "" + newline + "parrt, tombu" + newline + "" + newline; assertEquals(expecting, t.toString()); } public void testNestedAnonymousTemplatesAgain() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", "."); StringTemplate t = new StringTemplate( group, "
    "+newline + "$names:{$it:{}$}$"+newline + "
    $it:{$it$}$
    "+newline ); t.setAttribute("names", "parrt"); t.setAttribute("names", "tombu"); String expecting = "" + newline + "" + newline + "
    parrt
    tombu
    " + newline; assertEquals(expecting, t.toString()); } public void testEscapes() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", "."); group.defineTemplate("foo", "$x$ && $it$"); StringTemplate t = new StringTemplate( group, "$A:foo(x=\"dog\\\"\\\"\")$" // $A:foo("dog\"\"")$ ); StringTemplate u = new StringTemplate( group, "$A:foo(x=\"dog\\\"g\")$" // $A:foo(x="dog\"g")$ ); StringTemplate v = new StringTemplate( group, // $A:{$attr:foo(x="\{dog\}\"")$ is cool}$ "$A:{$it:foo(x=\"\\{dog\\}\\\"\")$ is cool}$" ); t.setAttribute("A", "ick"); u.setAttribute("A", "ick"); v.setAttribute("A", "ick"); //System.out.println("t is '"+t.toString()+"'"); //System.out.println("u is '"+u.toString()+"'"); //System.out.println("v is '"+v.toString()+"'"); String expecting = "dog\"\" && ick"; assertEquals(expecting, t.toString()); expecting = "dog\"g && ick"; assertEquals(expecting,u.toString()); expecting = "{dog}\" && ick is cool"; assertEquals(expecting,v.toString()); } public void testEscapesOutsideExpressions() throws Exception { StringTemplate b = new StringTemplate("It\\'s ok...\\$; $a:{\\'hi\\', $it$}$"); b.setAttribute("a", "Ter"); String expecting ="It\\'s ok...$; \\'hi\\', Ter"; String result = b.toString(); assertEquals(expecting, result); } public void testElseClause() throws Exception { StringTemplate e = new StringTemplate( "$if(title)$"+newline + "foo"+newline + "$else$"+newline + "bar"+newline + "$endif$" ); e.setAttribute("title", "sample"); String expecting = "foo"; assertEquals(expecting, e.toString()); e = e.getInstanceOf(); expecting = "bar"; assertEquals(expecting, e.toString()); } public void testElseIfClause() throws Exception { StringTemplate e = new StringTemplate( "$if(x)$"+newline + "foo"+newline + "$elseif(y)$"+newline + "bar"+newline + "$endif$" ); e.setAttribute("y", "yep"); String expecting = "bar"; assertEquals(expecting, e.toString()); } public void testElseIfClauseAngleBrackets() throws Exception { StringTemplate e = new StringTemplate( ""+newline + "foo"+newline + ""+newline + "bar"+newline + "", AngleBracketTemplateLexer.class ); e.setAttribute("y", "yep"); String expecting = "bar"; assertEquals(expecting, e.toString()); } public void testElseIfClause2() throws Exception { StringTemplate e = new StringTemplate( "$if(x)$"+newline + "foo"+newline + "$elseif(y)$"+newline + "bar"+newline + "$elseif(z)$"+newline + "blort"+newline + "$endif$" ); e.setAttribute("z", "yep"); String expecting = "blort"; assertEquals(expecting, e.toString()); } public void testElseIfClauseAndElse() throws Exception { StringTemplate e = new StringTemplate( "$if(x)$"+newline + "foo"+newline + "$elseif(y)$"+newline + "bar"+newline + "$elseif(z)$"+newline + "z"+newline + "$else$"+newline + "blort"+newline + "$endif$" ); String expecting = "blort"; assertEquals(expecting, e.toString()); } public void testNestedIF() throws Exception { StringTemplate e = new StringTemplate( "$if(title)$"+newline + "foo"+newline + "$else$"+newline + "$if(header)$"+newline + "bar"+newline + "$else$"+newline + "blort"+newline + "$endif$"+newline + "$endif$" ); e.setAttribute("title", "sample"); String expecting = "foo"; assertEquals(expecting, e.toString()); e = e.getInstanceOf(); e.setAttribute("header", "more"); expecting = "bar"; assertEquals(expecting, e.toString()); e = e.getInstanceOf(); expecting = "blort"; assertEquals(expecting, e.toString()); } public void testEmbeddedMultiLineIF() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplate main = new StringTemplate(group, "$sub$"); StringTemplate sub = new StringTemplate(group, "begin" + newline + "$if(foo)$" + newline + "$foo$" + newline + "$else$" +newline + "blort" + newline + "$endif$" + newline ); sub.setAttribute("foo", "stuff"); main.setAttribute("sub", sub); String expecting = "begin"+newline+ "stuff"; assertEquals(expecting, main.toString()); main = new StringTemplate(group, "$sub$"); sub = sub.getInstanceOf(); main.setAttribute("sub", sub); expecting = "begin"+newline+ "blort"; assertEquals(expecting, main.toString()); } public void testSimpleIndentOfAttributeList() throws Exception { String templates = "group test;" +newline+ "list(names) ::= <<" + " $names; separator=\"\n\"$"+newline+ ">>"+newline; StringTemplateErrorListener errors = new ErrorBuffer(); StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class, errors); StringTemplate t = group.getInstanceOf("list"); t.setAttribute("names", "Terence"); t.setAttribute("names", "Jim"); t.setAttribute("names", "Sriram"); String expecting = " Terence"+newline+ " Jim"+newline+ " Sriram"; assertEquals(expecting, t.toString()); } public void testIndentOfMultilineAttributes() throws Exception { String templates = "group test;" +newline+ "list(names) ::= <<" + " $names; separator=\"\n\"$"+newline+ ">>"+newline; StringTemplateErrorListener errors = new ErrorBuffer(); StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class, errors); StringTemplate t = group.getInstanceOf("list"); t.setAttribute("names", "Terence\nis\na\nmaniac"); t.setAttribute("names", "Jim"); t.setAttribute("names", "Sriram\nis\ncool"); String expecting = " Terence"+newline+ " is"+newline+ " a"+newline+ " maniac"+newline+ " Jim"+newline+ " Sriram"+newline+ " is"+newline+ " cool"; assertEquals(expecting, t.toString()); } public void testIndentOfMultipleBlankLines() throws Exception { String templates = "group test;" +newline+ "list(names) ::= <<" + " $names$"+newline+ ">>"+newline; StringTemplateErrorListener errors = new ErrorBuffer(); StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class, errors); StringTemplate t = group.getInstanceOf("list"); t.setAttribute("names", "Terence\n\nis a maniac"); String expecting = " Terence"+newline+ ""+newline+ // no indent on blank line " is a maniac"; assertEquals(expecting, t.toString()); } public void testIndentBetweenLeftJustifiedLiterals() throws Exception { String templates = "group test;" +newline+ "list(names) ::= <<" + "Before:"+newline + " $names; separator=\"\\n\"$"+newline+ "after" +newline+ ">>"+newline; StringTemplateErrorListener errors = new ErrorBuffer(); StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class, errors); StringTemplate t = group.getInstanceOf("list"); t.setAttribute("names", "Terence"); t.setAttribute("names", "Jim"); t.setAttribute("names", "Sriram"); String expecting = "Before:" +newline+ " Terence"+newline+ " Jim"+newline+ " Sriram"+newline+ "after"; assertEquals(expecting, t.toString()); } public void testNestedIndent() throws Exception { String templates = "group test;" +newline+ "method(name,stats) ::= <<" + "void $name$() {"+newline + "\t$stats; separator=\"\\n\"$"+newline+ "}" +newline+ ">>"+newline+ "ifstat(expr,stats) ::= <<"+newline + "if ($expr$) {"+newline + " $stats; separator=\"\\n\"$"+newline + "}" + ">>"+newline + "assign(lhs,expr) ::= <<$lhs$=$expr$;>>"+newline ; StringTemplateErrorListener errors = new ErrorBuffer(); StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class, errors); StringTemplate t = group.getInstanceOf("method"); t.setAttribute("name", "foo"); StringTemplate s1 = group.getInstanceOf("assign"); s1.setAttribute("lhs", "x"); s1.setAttribute("expr", "0"); StringTemplate s2 = group.getInstanceOf("ifstat"); s2.setAttribute("expr", "x>0"); StringTemplate s2a = group.getInstanceOf("assign"); s2a.setAttribute("lhs", "y"); s2a.setAttribute("expr", "x+y"); StringTemplate s2b = group.getInstanceOf("assign"); s2b.setAttribute("lhs", "z"); s2b.setAttribute("expr", "4"); s2.setAttribute("stats", s2a); s2.setAttribute("stats", s2b); t.setAttribute("stats", s1); t.setAttribute("stats", s2); String expecting = "void foo() {"+newline+ "\tx=0;"+newline+ "\tif (x>0) {"+newline+ "\t y=x+y;"+newline+ "\t z=4;"+newline+ "\t}"+newline+ "}"; assertEquals(expecting, t.toString()); } public void testAlternativeWriter() throws Exception { final StringBuffer buf = new StringBuffer(); StringTemplateWriter w = new StringTemplateWriter() { public void pushIndentation(String indent) { } public String popIndentation() { return null; } public void pushAnchorPoint() { } public void popAnchorPoint() { } public void setLineWidth(int lineWidth) { } public int write(String str, String wrap) throws IOException { return 0; } public int write(String str) throws IOException { buf.append(str); // just pass thru return str.length(); } public int writeWrapSeparator(String wrap) throws IOException { return 0; } public int writeSeparator(String str) throws IOException { return write(str); } }; StringTemplateGroup group = new StringTemplateGroup("test"); group.defineTemplate("bold", "$x$"); StringTemplate name = new StringTemplate(group, "$name:bold(x=name)$"); name.setAttribute("name", "Terence"); name.write(w); assertEquals("Terence", buf.toString()); } public void testApplyAnonymousTemplateToMapAndSet() throws Exception { StringTemplate st = new StringTemplate("$items:{
  • $it$
  • }$"); Map m = new LinkedHashMap(); m.put("a", "1"); m.put("b", "2"); m.put("c", "3"); st.setAttribute("items", m); String expecting = "
  • 1
  • 2
  • 3
  • "; assertEquals(expecting, st.toString()); st = st.getInstanceOf(); Set s = new HashSet(); s.add("1"); s.add("2"); s.add("3"); st.setAttribute("items", s); expecting = "
  • 3
  • 2
  • 1
  • "; assertEquals(expecting, st.toString()); } public void testDumpMapAndSet() throws Exception { StringTemplate st = new StringTemplate("$items; separator=\",\"$"); Map m = new LinkedHashMap(); m.put("a", "1"); m.put("b", "2"); m.put("c", "3"); st.setAttribute("items", m); String expecting = "1,2,3"; assertEquals(expecting, st.toString()); st = st.getInstanceOf(); Set s = new HashSet(); s.add("1"); s.add("2"); s.add("3"); st.setAttribute("items", s); expecting = "3,2,1"; assertEquals(expecting, st.toString()); } public class Connector3 { public int[] getValues() { return new int[] {1,2,3}; } public Map getStuff() { Map m = new LinkedHashMap(); m.put("a","1"); m.put("b","2"); return m; } } public void testApplyAnonymousTemplateToArrayAndMapProperty() throws Exception { StringTemplate st = new StringTemplate("$x.values:{
  • $it$
  • }$"); st.setAttribute("x", new Connector3()); String expecting = "
  • 1
  • 2
  • 3
  • "; assertEquals(expecting, st.toString()); st = new StringTemplate("$x.stuff:{
  • $it$
  • }$"); st.setAttribute("x", new Connector3()); expecting = "
  • 1
  • 2
  • "; assertEquals(expecting, st.toString()); } public void testSuperTemplateRef() throws Exception { // you can refer to a template defined in a super group via super.t() StringTemplateGroup group = new StringTemplateGroup("super"); StringTemplateGroup subGroup = new StringTemplateGroup("sub"); subGroup.setSuperGroup(group); group.defineTemplate("page", "$font()$:text"); group.defineTemplate("font", "Helvetica"); subGroup.defineTemplate("font", "$super.font()$ and Times"); StringTemplate st = subGroup.getInstanceOf("page"); String expecting = "Helvetica and Times:text"; assertEquals(expecting, st.toString()); } public void testApplySuperTemplateRef() throws Exception { StringTemplateGroup group = new StringTemplateGroup("super"); StringTemplateGroup subGroup = new StringTemplateGroup("sub"); subGroup.setSuperGroup(group); group.defineTemplate("bold", "$it$"); subGroup.defineTemplate("bold", "$it$"); subGroup.defineTemplate("page", "$name:super.bold()$"); StringTemplate st = subGroup.getInstanceOf("page"); st.setAttribute("name", "Ter"); String expecting = "Ter"; assertEquals(expecting, st.toString()); } public void testLazyEvalOfSuperInApplySuperTemplateRef() throws Exception { StringTemplateGroup group = new StringTemplateGroup("base"); StringTemplateGroup subGroup = new StringTemplateGroup("sub"); subGroup.setSuperGroup(group); group.defineTemplate("bold", "$it$"); subGroup.defineTemplate("bold", "$it$"); // this is the same as testApplySuperTemplateRef() test // 'cept notice that here the supergroup defines page // As long as you create the instance via the subgroup, // "super." will evaluate lazily (i.e., not statically // during template compilation) to the templates // getGroup().superGroup value. If I create instance // of page in group not subGroup, however, I will get // an error as superGroup is null for group "group". group.defineTemplate("page", "$name:super.bold()$"); StringTemplate st = subGroup.getInstanceOf("page"); st.setAttribute("name", "Ter"); String error = null; try { st.toString(); } catch (IllegalArgumentException iae) { error = iae.getMessage(); } String expectingError = "base has no super group; invalid template: super.bold"; assertEquals(expectingError, error); } public void testTemplatePolymorphism() throws Exception { StringTemplateGroup group = new StringTemplateGroup("super"); StringTemplateGroup subGroup = new StringTemplateGroup("sub"); subGroup.setSuperGroup(group); // bold is defined in both super and sub // if you create an instance of page via the subgroup, // then bold() should evaluate to the subgroup not the super // even though page is defined in the super. Just like polymorphism. group.defineTemplate("bold", "$it$"); group.defineTemplate("page", "$name:bold()$"); subGroup.defineTemplate("bold", "$it$"); StringTemplate st = subGroup.getInstanceOf("page"); st.setAttribute("name", "Ter"); String expecting = "Ter"; assertEquals(expecting, st.toString()); } public void testListOfEmbeddedTemplateSeesEnclosingAttributes() throws Exception { String templates = "group test;" +newline+ "output(cond,items) ::= <>" +newline+ "mybody() ::= <<$font()$stuff>>" +newline+ "font() ::= <<$if(cond)$this$else$that$endif$>>" ; StringTemplateErrorListener errors = new ErrorBuffer(); StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class, errors); StringTemplate outputST = group.getInstanceOf("output"); StringTemplate bodyST1 = group.getInstanceOf("mybody"); StringTemplate bodyST2 = group.getInstanceOf("mybody"); StringTemplate bodyST3 = group.getInstanceOf("mybody"); outputST.setAttribute("items", bodyST1); outputST.setAttribute("items", bodyST2); outputST.setAttribute("items", bodyST3); String expecting = "page: thatstuffthatstuffthatstuff"; assertEquals(expecting, outputST.toString()); } public void testInheritArgumentFromRecursiveTemplateApplication() throws Exception { // do not inherit attributes through formal args String templates = "group test;" +newline+ "block(stats) ::= \"\"" + "ifstat(stats) ::= \"IF true then \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate b = group.getInstanceOf("block"); b.setAttribute("stats", group.getInstanceOf("ifstat")); b.setAttribute("stats", group.getInstanceOf("ifstat")); String expecting = "IF true then IF true then "; String result = b.toString(); //System.err.println("result='"+result+"'"); assertEquals(expecting, result); } public void testDeliberateRecursiveTemplateApplication() throws Exception { // This test will cause infinite loop. block contains a stat which // contains the same block. Must be in lintMode to detect String templates = "group test;" +newline+ "block(stats) ::= \"\"" + "ifstat(stats) ::= \"IF true then \""+newline ; StringTemplate.setLintMode(true); StringTemplate.resetTemplateCounter(); StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate b = group.getInstanceOf("block"); StringTemplate ifstat = group.getInstanceOf("ifstat"); b.setAttribute("stats", ifstat); // block has if stat ifstat.setAttribute("stats", b); // but make "if" contain block String expectingError = "infinite recursion to referenced in ; stack trace:"+newline + ", attributes=[stats=]>"+newline + ", attributes=[stats=], references=[stats]>"+newline + " (start of recursive cycle)"+newline + "..."; // note that attributes attribute doesn't show up in ifstat() because // recursion detection traps the problem before it writes out the // infinitely-recursive template; I set the attributes attribute right // before I render. String errors = ""; try { /*String result =*/ b.toString(); } catch (IllegalStateException ise) { errors = ise.getMessage(); } //System.err.println("errors="+errors+"'"); //System.err.println("expecting="+expectingError+"'"); StringTemplate.setLintMode(false); assertEquals(expectingError, errors); } public void testImmediateTemplateAsAttributeLoop() throws Exception { // even though block has a stats value that refers to itself, // there is no recursion because each instance of block hides // the stats value from above since it's a formal arg. String templates = "group test;" +newline+ "block(stats) ::= \"{}\"" ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate b = group.getInstanceOf("block"); b.setAttribute("stats", group.getInstanceOf("block")); String expecting ="{{}}"; String result = b.toString(); //System.err.println(result); assertEquals(expecting, result); } public void testTemplateAlias() throws Exception { String templates = "group test;" +newline+ "page(name) ::= \"name is \"" + "other ::= page"+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate b = group.getInstanceOf("other"); // alias for page b.setAttribute("name", "Ter"); String expecting ="name is Ter"; String result = b.toString(); assertEquals(expecting, result); } public void testTemplateGetPropertyGetsAttribute() throws Exception { // This test will cause infinite loop if missing attribute no // properly caught in getAttribute String templates = "group test;"+newline+ "Cfile(funcs) ::= <<"+newline + "#include \\"+newline+ "();}; separator=\"\\n\">"+newline+ ""+newline+ ">>"+newline + "func(name,args,body) ::= <<"+newline+ "public void () {}"+newline + ">>"+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate b = group.getInstanceOf("Cfile"); StringTemplate f1 = group.getInstanceOf("func"); StringTemplate f2 = group.getInstanceOf("func"); f1.setAttribute("name", "f"); f1.setAttribute("args", ""); f1.setAttribute("body", "i=1;"); f2.setAttribute("name", "g"); f2.setAttribute("args", "int arg"); f2.setAttribute("body", "y=1;"); b.setAttribute("funcs",f1); b.setAttribute("funcs",f2); String expecting = "#include " +newline+ "public void f();"+newline+ "public void g(int arg);" +newline+ "public void f() {i=1;}"+newline+ "public void g(int arg) {y=1;}"; assertEquals(expecting,b.toString()); } public static class Decl { String name; String type; public Decl(String name, String type) {this.name=name; this.type=type;} public String getName() {return name;} public String getType() {return type;} } public void testComplicatedIndirectTemplateApplication() throws Exception { String templates = "group Java;"+newline + ""+newline + "file(variables) ::= <<" + "}; separator=\"\\n\">"+newline + ">>"+newline+ "intdecl(decl) ::= \"int = 0;\""+newline + "intarray(decl) ::= \"int[] = null;\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate f = group.getInstanceOf("file"); f.setAttribute("variables.{decl,format}", new Decl("i","int"), "intdecl"); f.setAttribute("variables.{decl,format}", new Decl("a","int-array"), "intarray"); //System.out.println("f='"+f+"'"); String expecting = "int i = 0;" +newline+ "int[] a = null;"; assertEquals(expecting, f.toString()); } public void testIndirectTemplateApplication() throws Exception { String templates = "group dork;"+newline + ""+newline + "test(name) ::= <<" + "<(name)()>"+newline + ">>"+newline+ "first() ::= \"the first\""+newline + "second() ::= \"the second\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate f = group.getInstanceOf("test"); f.setAttribute("name", "first"); String expecting = "the first"; assertEquals(expecting, f.toString()); } public void testIndirectTemplateWithArgsApplication() throws Exception { String templates = "group dork;"+newline + ""+newline + "test(name) ::= <<" + "<(name)(a=\"foo\")>"+newline + ">>"+newline+ "first(a) ::= \"the first: \""+newline + "second(a) ::= \"the second \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate f = group.getInstanceOf("test"); f.setAttribute("name", "first"); String expecting = "the first: foo"; assertEquals(f.toString(), expecting); } public void testNullIndirectTemplateApplication() throws Exception { String templates = "group dork;"+newline + ""+newline + "test(names,t) ::= <<" + ""+newline + // t null be must be defined else error: null attr w/o formal def ">>"+newline+ "ind() ::= \"[]\""+newline; ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate f = group.getInstanceOf("test"); f.setAttribute("names", "me"); f.setAttribute("names", "you"); String expecting = ""; assertEquals(expecting, f.toString()); } public void testNullIndirectTemplate() throws Exception { String templates = "group dork;"+newline + ""+newline + "test(name) ::= <<" + "<(name)()>"+newline + ">>"+newline+ "first() ::= \"the first\""+newline + "second() ::= \"the second\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate f = group.getInstanceOf("test"); //f.setAttribute("name", "first"); String expecting = ""; assertEquals(expecting, f.toString()); } public void testHashMapPropertyFetch() throws Exception { StringTemplate a = new StringTemplate("$stuff.prop$"); HashMap map = new HashMap(); a.setAttribute("stuff", map); map.put("prop", "Terence"); String results = a.toString(); //System.out.println(results); String expecting = "Terence"; assertEquals(expecting, results); } public void testHashMapPropertyFetchEmbeddedStringTemplate() throws Exception { StringTemplate a = new StringTemplate("$stuff.prop$"); HashMap map = new HashMap(); a.setAttribute("stuff", map); a.setAttribute("title", "ST rocks"); map.put("prop", new StringTemplate("embedded refers to $title$")); String results = a.toString(); //System.out.println(results); String expecting = "embedded refers to ST rocks"; assertEquals(expecting, results); } public void testEmbeddedComments() throws Exception { StringTemplate st = new StringTemplate( "Foo $! ignore !$bar" +newline ); String expecting ="Foo bar"+newline; String result = st.toString(); assertEquals(expecting, result); st = new StringTemplate( "Foo $! ignore" +newline+ " and a line break!$" +newline+ "bar" +newline ); expecting ="Foo "+newline+"bar"+newline; result = st.toString(); assertEquals(expecting, result); st = new StringTemplate( "$! start of line $ and $! ick" +newline+ "!$boo"+newline ); expecting ="boo"+newline; result = st.toString(); assertEquals(expecting, result); st = new StringTemplate( "$! start of line !$" +newline+ "$! another to ignore !$" +newline+ "$! ick" +newline+ "!$boo"+newline ); expecting ="boo"+newline; result = st.toString(); assertEquals(expecting, result); st = new StringTemplate( "$! back !$$! to back !$" +newline+ // can't detect; leaves \n "$! ick" +newline+ "!$boo"+newline ); expecting =newline+"boo"+newline; result = st.toString(); assertEquals(expecting, result); } public void testEmbeddedCommentsAngleBracketed() throws Exception { StringTemplate st = new StringTemplate( "Foo bar" +newline, AngleBracketTemplateLexer.class ); String expecting ="Foo bar"+newline; String result = st.toString(); assertEquals(expecting, result); st = new StringTemplate( "Foo " +newline+ "bar" +newline, AngleBracketTemplateLexer.class ); expecting ="Foo "+newline+"bar"+newline; result = st.toString(); assertEquals(expecting, result); st = new StringTemplate( "boo"+newline, AngleBracketTemplateLexer.class ); expecting ="boo"+newline; result = st.toString(); assertEquals(expecting, result); st = new StringTemplate( "" + "" + "boo"+newline, AngleBracketTemplateLexer.class ); expecting ="boo"+newline; result = st.toString(); //System.out.println(result); assertEquals(expecting, result); st = new StringTemplate( "" +newline+ // can't detect; leaves \n "boo"+newline, AngleBracketTemplateLexer.class ); expecting =newline+"boo"+newline; result = st.toString(); assertEquals(expecting, result); } public void testLineBreak() throws Exception { StringTemplate st = new StringTemplate( "Foo <\\\\>"+newline+ " \t bar" +newline, AngleBracketTemplateLexer.class ); StringWriter sw = new StringWriter(); st.write(new AutoIndentWriter(sw,"\n")); // force \n as newline String result = sw.toString(); String expecting ="Foo bar"+newline; // expect \n in output assertEquals(expecting, result); } public void testLineBreak2() throws Exception { StringTemplate st = new StringTemplate( "Foo <\\\\> "+newline+ " \t bar" +newline, AngleBracketTemplateLexer.class ); StringWriter sw = new StringWriter(); st.write(new AutoIndentWriter(sw,"\n")); // force \n as newline String result = sw.toString(); String expecting ="Foo bar"+newline; // expect \n in output assertEquals(expecting, result); } public void testLineBreakNoWhiteSpace() throws Exception { StringTemplate st = new StringTemplate( "Foo <\\\\>"+newline+ "bar" +newline, AngleBracketTemplateLexer.class ); StringWriter sw = new StringWriter(); st.write(new AutoIndentWriter(sw,"\n")); // force \n as newline String result = sw.toString(); String expecting ="Foo bar"+newline; // expect \n in output assertEquals(expecting, result); } public void testLineBreakDollar() throws Exception { StringTemplate st = new StringTemplate( "Foo $\\\\$"+newline+ " \t bar" +newline, DefaultTemplateLexer.class ); StringWriter sw = new StringWriter(); st.write(new AutoIndentWriter(sw,"\n")); // force \n as newline String result = sw.toString(); String expecting ="Foo bar"+newline; // expect \n in output assertEquals(expecting, result); } public void testLineBreakDollar2() throws Exception { StringTemplate st = new StringTemplate( "Foo $\\\\$ "+newline+ " \t bar" +newline, DefaultTemplateLexer.class ); StringWriter sw = new StringWriter(); st.write(new AutoIndentWriter(sw,"\n")); // force \n as newline String result = sw.toString(); String expecting ="Foo bar"+newline; // expect \n in output assertEquals(expecting, result); } public void testLineBreakNoWhiteSpaceDollar() throws Exception { StringTemplate st = new StringTemplate( "Foo $\\\\$"+newline+ "bar" +newline, DefaultTemplateLexer.class ); StringWriter sw = new StringWriter(); st.write(new AutoIndentWriter(sw,"\n")); // force \n as newline String result = sw.toString(); String expecting ="Foo bar"+newline; // expect \n in output assertEquals(expecting, result); } public void testCharLiterals() throws Exception { StringTemplate st = new StringTemplate( "Foo <\\r\\n><\\n><\\t> bar" +newline, AngleBracketTemplateLexer.class ); StringWriter sw = new StringWriter(); st.write(new AutoIndentWriter(sw,"\n")); // force \n as newline String result = sw.toString(); String expecting ="Foo \n\n\t bar"+newline; // expect \n in output assertEquals(expecting, result); st = new StringTemplate( "Foo $\\n$$\\t$ bar" +newline); sw = new StringWriter(); st.write(new AutoIndentWriter(sw,"\n")); // force \n as newline expecting ="Foo \n\t bar"+newline; // expect \n in output result = sw.toString(); assertEquals(expecting, result); st = new StringTemplate( "Foo$\\ $bar$\\n$"); sw = new StringWriter(); st.write(new AutoIndentWriter(sw,"\n")); // force \n as newline result = sw.toString(); expecting ="Foo bar\n"; // force \n assertEquals(expecting, result); } public void testNewlineNormalizationInTemplateString() throws Exception { StringTemplate st = new StringTemplate( "Foo\r\n"+ "Bar\n", AngleBracketTemplateLexer.class ); StringWriter sw = new StringWriter(); st.write(new AutoIndentWriter(sw,"\n")); // force \n as newline String result = sw.toString(); String expecting ="Foo\nBar\n"; // expect \n in output assertEquals(expecting, result); } public void testNewlineNormalizationInTemplateStringPC() throws Exception { StringTemplate st = new StringTemplate( "Foo\r\n"+ "Bar\n", AngleBracketTemplateLexer.class ); StringWriter sw = new StringWriter(); st.write(new AutoIndentWriter(sw,"\r\n")); // force \r\n as newline String result = sw.toString(); String expecting ="Foo\r\nBar\r\n"; // expect \r\n in output assertEquals(expecting, result); } public void testNewlineNormalizationInAttribute() throws Exception { StringTemplate st = new StringTemplate( "Foo\r\n"+ "\n", AngleBracketTemplateLexer.class ); st.setAttribute("name", "a\nb\r\nc"); StringWriter sw = new StringWriter(); st.write(new AutoIndentWriter(sw,"\n")); // force \n as newline String result = sw.toString(); String expecting ="Foo\na\nb\nc\n"; // expect \n in output assertEquals(expecting, result); } public void testUnicodeLiterals() throws Exception { StringTemplate st = new StringTemplate( "Foo <\\uFEA5\\n\\u00C2> bar" +newline, AngleBracketTemplateLexer.class ); String expecting ="Foo \ufea5"+newline+"\u00C2 bar"+newline; String result = st.toString(); assertEquals(expecting, result); st = new StringTemplate( "Foo $\\uFEA5\\n\\u00C2$ bar" +newline); expecting ="Foo \ufea5"+newline+"\u00C2 bar"+newline; result = st.toString(); assertEquals(expecting, result); st = new StringTemplate( "Foo$\\ $bar$\\n$"); expecting ="Foo bar"+newline; result = st.toString(); assertEquals(expecting, result); } public void testEmptyIteratedValueGetsSeparator() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplateErrorListener errors = new ErrorBuffer(); group.setErrorListener(errors); StringTemplate t = new StringTemplate(group, "$names; separator=\",\"$"); t.setAttribute("names", "Terence"); t.setAttribute("names", ""); t.setAttribute("names", ""); t.setAttribute("names", "Tom"); t.setAttribute("names", "Frank"); t.setAttribute("names", ""); // empty values get separator still String expecting="Terence,,,Tom,Frank,"; String result = t.toString(); assertEquals(expecting, result); } public void testMissingIteratedConditionalValueGetsNOSeparator() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplateErrorListener errors = new ErrorBuffer(); group.setErrorListener(errors); StringTemplate t = new StringTemplate(group, "$users:{$if(it.ok)$$it.name$$endif$}; separator=\",\"$"); t.setAttribute("users.{name,ok}", "Terence", new Boolean(true)); t.setAttribute("users.{name,ok}", "Tom", new Boolean(false)); t.setAttribute("users.{name,ok}", "Frank", new Boolean(true)); t.setAttribute("users.{name,ok}", "Johnny", new Boolean(false)); // empty conditional values get no separator String expecting="Terence,Frank"; String result = t.toString(); assertEquals(expecting, result); } public void testMissingIteratedConditionalValueGetsNOSeparator2() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplateErrorListener errors = new ErrorBuffer(); group.setErrorListener(errors); StringTemplate t = new StringTemplate(group, "$users:{$if(it.ok)$$it.name$$endif$}; separator=\",\"$"); t.setAttribute("users.{name,ok}", "Terence", new Boolean(true)); t.setAttribute("users.{name,ok}", "Tom", new Boolean(false)); t.setAttribute("users.{name,ok}", "Frank", new Boolean(false)); t.setAttribute("users.{name,ok}", "Johnny", new Boolean(false)); // empty conditional values get no separator String expecting="Terence"; String result = t.toString(); assertEquals(expecting, result); } public void testMissingIteratedDoubleConditionalValueGetsNOSeparator() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplateErrorListener errors = new ErrorBuffer(); group.setErrorListener(errors); StringTemplate t = new StringTemplate(group, "$users:{$if(it.ok)$$it.name$$endif$$if(it.ok)$$it.name$$endif$}; separator=\",\"$"); t.setAttribute("users.{name,ok}", "Terence", new Boolean(false)); t.setAttribute("users.{name,ok}", "Tom", new Boolean(true)); t.setAttribute("users.{name,ok}", "Frank", new Boolean(true)); t.setAttribute("users.{name,ok}", "Johnny", new Boolean(true)); // empty conditional values get no separator String expecting="TomTom,FrankFrank,JohnnyJohnny"; String result = t.toString(); assertEquals(expecting, result); } public void testIteratedConditionalWithEmptyElseValueGetsSeparator() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplateErrorListener errors = new ErrorBuffer(); group.setErrorListener(errors); StringTemplate t = new StringTemplate(group, "$users:{$if(it.ok)$$it.name$$else$$endif$}; separator=\",\"$"); t.setAttribute("users.{name,ok}", "Terence", new Boolean(true)); t.setAttribute("users.{name,ok}", "Tom", new Boolean(false)); t.setAttribute("users.{name,ok}", "Frank", new Boolean(true)); t.setAttribute("users.{name,ok}", "Johnny", new Boolean(false)); // empty conditional values get no separator String expecting="Terence,,Frank,"; String result = t.toString(); assertEquals(expecting, result); } public void testWhiteSpaceAtEndOfTemplate() throws Exception { StringTemplateGroup group = new StringTemplateGroup("group"); StringTemplate pageST = group.getInstanceOf("org/antlr/stringtemplate/test/page"); StringTemplate listST = group.getInstanceOf("org/antlr/stringtemplate/test/users_list"); // users.list references row.st which has a single blank line at the end. // I.e., there are 2 \n in a row at the end // ST should eat all whitespace at end listST.setAttribute("users", new Connector()); listST.setAttribute("users", new Connector2()); pageST.setAttribute("title", "some title"); pageST.setAttribute("body", listST); String expecting ="some title" +newline+ "Terence parrt@jguru.comTom tombu@jguru.com"; String result = pageST.toString(); //System.out.println("'"+result+"'"); assertEquals(expecting, result); } static class Duh { public List users = new ArrayList(); } public void testSizeZeroButNonNullListGetsNoOutput() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplateErrorListener errors = new ErrorBuffer(); group.setErrorListener(errors); StringTemplate t = new StringTemplate(group, "begin\n" + "$duh.users:{name: $it$}; separator=\", \"$\n" + "end\n"); t.setAttribute("duh", new Duh()); String expecting="begin\nend\n"; String result = t.toString(); assertEquals(expecting, result); } public void testNullListGetsNoOutput() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplateErrorListener errors = new ErrorBuffer(); group.setErrorListener(errors); StringTemplate t = new StringTemplate(group, "begin\n" + "$users:{name: $it$}; separator=\", \"$\n" + "end\n"); //t.setAttribute("users", new Duh()); String expecting="begin\nend\n"; String result = t.toString(); assertEquals(expecting, result); } public void testEmptyListGetsNoOutput() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplateErrorListener errors = new ErrorBuffer(); group.setErrorListener(errors); StringTemplate t = new StringTemplate(group, "begin\n" + "$users:{name: $it$}; separator=\", \"$\n" + "end\n"); t.setAttribute("users", new ArrayList()); String expecting="begin\nend\n"; String result = t.toString(); assertEquals(expecting, result); } public void testEmptyListNoIteratorGetsNoOutput() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplateErrorListener errors = new ErrorBuffer(); group.setErrorListener(errors); StringTemplate t = new StringTemplate(group, "begin\n" + "$users; separator=\", \"$\n" + "end\n"); t.setAttribute("users", new ArrayList()); String expecting="begin\nend\n"; String result = t.toString(); assertEquals(expecting, result); } public void testEmptyExprAsFirstLineGetsNoOutput() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplateErrorListener errors = new ErrorBuffer(); group.setErrorListener(errors); group.defineTemplate("bold", "$it$"); StringTemplate t = new StringTemplate(group, "$users$\n" + "end\n"); String expecting="end\n"; String result = t.toString(); assertEquals(expecting, result); } public void testSizeZeroOnLineByItselfGetsNoOutput() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplateErrorListener errors = new ErrorBuffer(); group.setErrorListener(errors); StringTemplate t = new StringTemplate(group, "begin\n"+ "$name$\n"+ "$users:{name: $it$}$\n"+ "$users:{name: $it$}; separator=\", \"$\n"+ "end\n"); String expecting="begin\nend\n"; String result = t.toString(); assertEquals(expecting, result); } public void testSizeZeroOnLineWithIndentGetsNoOutput() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplateErrorListener errors = new ErrorBuffer(); group.setErrorListener(errors); StringTemplate t = new StringTemplate(group, "begin\n"+ " $name$\n"+ " $users:{name: $it$}$\n"+ " $users:{name: $it$$\\n$}$\n"+ "end\n"); String expecting="begin\nend\n"; String result = t.toString(); assertEquals(expecting, result); } public void testSimpleAutoIndent() throws Exception { StringTemplate a = new StringTemplate( "$title$: {\n" + " $name; separator=\"\n\"$\n" + "}"); a.setAttribute("title", "foo"); a.setAttribute("name", "Terence"); a.setAttribute("name", "Frank"); String results = a.toString(); //System.out.println(results); String expecting = "foo: {\n" + " Terence\n" + " Frank\n" + "}"; assertEquals(results, expecting); } public void testComputedPropertyName() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplateErrorListener errors = new ErrorBuffer(); group.setErrorListener(errors); StringTemplate t = new StringTemplate(group, "variable property $propName$=$v.(propName)$"); t.setAttribute("v", new Decl("i","int")); t.setAttribute("propName", "type"); String expecting="variable property type=int"; String result = t.toString(); assertEquals("", errors.toString()); assertEquals(expecting, result); } public void testNonNullButEmptyIteratorTestsFalse() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplate t = new StringTemplate(group, "$if(users)$\n" + "Users: $users:{$it.name$ }$\n" + "$endif$"); t.setAttribute("users", new LinkedList()); String expecting=""; String result = t.toString(); assertEquals(expecting, result); } public void testDoNotInheritAttributesThroughFormalArgs() throws Exception { String templates = "group test;" +newline+ "method(name) ::= \"\"" +newline+ "stat(name) ::= \"x=y; // \""+newline ; // name is not visible in stat because of the formal arg called name. // somehow, it must be set. StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate b = group.getInstanceOf("method"); b.setAttribute("name", "foo"); String expecting = "x=y; // "; String result = b.toString(); //System.err.println("result='"+result+"'"); assertEquals(expecting, result); } public void testArgEvaluationContext() throws Exception { String templates = "group test;" +newline+ "method(name) ::= \"\"" +newline+ "stat(name) ::= \"x=y; // \""+newline ; // attribute name is not visible in stat because of the formal // arg called name in template stat. However, we can set it's value // with an explicit name=name. This looks weird, but makes total // sense as the rhs is evaluated in the context of method and the lhs // is evaluated in the context of stat's arg list. StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate b = group.getInstanceOf("method"); b.setAttribute("name", "foo"); String expecting = "x=y; // foo"; String result = b.toString(); //System.err.println("result='"+result+"'"); assertEquals(expecting, result); } public void testPassThroughAttributes() throws Exception { String templates = "group test;" +newline+ "method(name) ::= \"\"" +newline+ "stat(name) ::= \"x=y; // \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate b = group.getInstanceOf("method"); b.setAttribute("name", "foo"); String expecting = "x=y; // foo"; String result = b.toString(); //System.err.println("result='"+result+"'"); assertEquals(expecting, result); } public void testPassThroughAttributes2() throws Exception { String templates = "group test;" +newline+ "method(name) ::= <<"+newline+ "" +newline+ ">>"+newline+ "stat(name,value) ::= \"x=; // \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate b = group.getInstanceOf("method"); b.setAttribute("name", "foo"); String expecting = "x=34; // foo"; String result = b.toString(); //System.err.println("result='"+result+"'"); assertEquals(expecting, result); } public void testDefaultArgument() throws Exception { String templates = "group test;" +newline+ "method(name) ::= <<"+newline+ "" +newline+ ">>"+newline+ "stat(name,value=\"99\") ::= \"x=; // \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate b = group.getInstanceOf("method"); b.setAttribute("name", "foo"); String expecting = "x=99; // foo"; String result = b.toString(); //System.err.println("result='"+result+"'"); assertEquals(expecting, result); } public void testDefaultArgument2() throws Exception { String templates = "group test;" +newline+ "stat(name,value=\"99\") ::= \"x=; // \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate b = group.getInstanceOf("stat"); b.setAttribute("name", "foo"); String expecting = "x=99; // foo"; String result = b.toString(); //System.err.println("result='"+result+"'"); assertEquals(expecting, result); } public void testDefaultArgumentManuallySet() throws Exception { class Field { public String name = "parrt"; public int n = 0; public String toString() { return "Field"; } } String templates = "group test;" +newline+ "method(fields) ::= <<"+newline+ "}>" +newline+ ">>"+newline+ "stat(f,value={}) ::= \"x=; // \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate m = group.getInstanceOf("method"); m.setAttribute("fields", new Field()); String expecting = "x=parrt; // parrt"; String result = m.toString(); assertEquals(expecting, result); } /** This fails because checkNullAttributeAgainstFormalArguments looks * for a formal argument at the current level not of the original embedded * template. We have defined it all the way in the embedded, but there is * no value so we try to look upwards ala dynamic scoping. When it reaches * the top, it doesn't find a value but it will miss the * formal argument down in the embedded. * * By definition, though, the formal parameter exists if we have * a default value. look up the value to see if it's null without * checking checkNullAttributeAgainstFormalArguments. */ public void testDefaultArgumentImplicitlySet() throws Exception { class Field { public String name = "parrt"; public int n = 0; public String toString() { return "Field"; } } String templates = "group test;" +newline+ "method(fields) ::= <<"+newline+ "}>" +newline+ ">>"+newline+ "stat(f,value={}) ::= \"x=; // \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate m = group.getInstanceOf("method"); m.setAttribute("fields", new Field()); String expecting = "x=parrt; // parrt"; String result = m.toString(); assertEquals(expecting, result); } /* FIX THIS public void testDefaultArgumentImplicitlySet2() throws Exception { class Field { public String name = "parrt"; public int n = 0; public String toString() { return "Field"; } } String templates = "group test;" +newline+ "method(fields) ::= <<"+newline+ "}>" +newline+ // THIS SHOULD BE ERROR; >1 arg? ">>"+newline+ "stat(f,value={}) ::= \"x=; // \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate m = group.getInstanceOf("method"); m.setAttribute("fields", new Field()); String expecting = "x=parrt; // parrt"; String result = m.toString(); assertEquals(expecting, result); } */ public void testDefaultArgumentAsTemplate() throws Exception { String templates = "group test;" +newline+ "method(name,size) ::= <<"+newline+ "" +newline+ ">>"+newline+ "stat(name,value={}) ::= \"x=; // \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate b = group.getInstanceOf("method"); b.setAttribute("name", "foo"); b.setAttribute("size", "2"); String expecting = "x=foo; // foo"; String result = b.toString(); //System.err.println("result='"+result+"'"); assertEquals(expecting, result); } public void testDefaultArgumentAsTemplate2() throws Exception { String templates = "group test;" +newline+ "method(name,size) ::= <<"+newline+ "" +newline+ ">>"+newline+ "stat(name,value={ [] }) ::= \"x=; // \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate b = group.getInstanceOf("method"); b.setAttribute("name", "foo"); b.setAttribute("size", "2"); String expecting = "x= [foo] ; // foo"; String result = b.toString(); //System.err.println("result='"+result+"'"); assertEquals(expecting, result); } public void testDoNotUseDefaultArgument() throws Exception { String templates = "group test;" +newline+ "method(name) ::= <<"+newline+ "" +newline+ ">>"+newline+ "stat(name,value=\"99\") ::= \"x=; // \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate b = group.getInstanceOf("method"); b.setAttribute("name", "foo"); String expecting = "x=34; // foo"; String result = b.toString(); assertEquals(expecting, result); } public void testDefaultArgumentInParensToEvalEarly() throws Exception { class Counter { int n = 0; public String toString() { return String.valueOf(n++); } } String templates = "group test;" +newline+ "A(x) ::= \"\""+newline+ "B(y={<(x)>}) ::= \" \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate b = group.getInstanceOf("A"); b.setAttribute("x", new Counter()); String expecting = "0 1 2 0"; String result = b.toString(); //System.err.println("result='"+result+"'"); assertEquals(expecting, result); } public void testArgumentsAsTemplates() throws Exception { String templates = "group test;" +newline+ "method(name,size) ::= <<"+newline+ "})>" +newline+ ">>"+newline+ "stat(value) ::= \"x=;\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate b = group.getInstanceOf("method"); b.setAttribute("name", "foo"); b.setAttribute("size", "34"); String expecting = "x=34;"; String result = b.toString(); assertEquals(expecting, result); } public void testTemplateArgumentEvaluatedInSurroundingContext() throws Exception { String templates = "group test;" +newline+ "file(m,size) ::= \"\""+newline+ "method(name) ::= <<"+newline+ ".0})>" +newline+ ">>"+newline+ "stat(value) ::= \"x=;\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate f = group.getInstanceOf("file"); f.setAttribute("size", "34"); StringTemplate m = group.getInstanceOf("method"); m.setAttribute("name", "foo"); f.setAttribute("m", m); String expecting = "x=34.0;"; String result = m.toString(); assertEquals(expecting, result); } public void testArgumentsAsTemplatesDefaultDelimiters() throws Exception { String templates = "group test;" +newline+ "method(name,size) ::= <<"+newline+ "$stat(value={$size$})$" +newline+ ">>"+newline+ "stat(value) ::= \"x=$value$;\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class); StringTemplate b = group.getInstanceOf("method"); b.setAttribute("name", "foo"); b.setAttribute("size", "34"); String expecting = "x=34;"; String result = b.toString(); assertEquals(expecting, result); } public void testDefaultArgsWhenNotInvoked() throws Exception { String templates = "group test;" +newline+ "b(name=\"foo\") ::= \"..\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate b = group.getInstanceOf("b"); String expecting = ".foo."; String result = b.toString(); assertEquals(expecting, result); } public class DateRenderer implements AttributeRenderer { public String toString(Object o) { SimpleDateFormat f = new SimpleDateFormat ("yyyy.MM.dd"); return f.format(((Calendar)o).getTime()); } public String toString(Object o, String formatString) { return toString(o); } } public class DateRenderer2 implements AttributeRenderer { public String toString(Object o) { SimpleDateFormat f = new SimpleDateFormat ("MM/dd/yyyy"); return f.format(((Calendar)o).getTime()); } public String toString(Object o, String formatString) { return toString(o); } } public class DateRenderer3 implements AttributeRenderer { public String toString(Object o) { SimpleDateFormat f = new SimpleDateFormat ("MM/dd/yyyy"); return f.format(((Calendar)o).getTime()); } public String toString(Object o, String formatString) { SimpleDateFormat f = new SimpleDateFormat (formatString); return f.format(((Calendar)o).getTime()); } } public class StringRenderer implements AttributeRenderer { public String toString(Object o) { return (String)o; } public String toString(Object o, String formatString) { if ( formatString.equals("upper") ) { return ((String)o).toUpperCase(); } return toString(o); } } public void testRendererForST() throws Exception { StringTemplate st =new StringTemplate( "date: ", AngleBracketTemplateLexer.class); st.setAttribute("created", new GregorianCalendar(2005, 07-1, 05)); st.registerRenderer(GregorianCalendar.class, new DateRenderer()); String expecting = "date: 2005.07.05"; String result = st.toString(); assertEquals(expecting, result); } public void testRendererWithFormat() throws Exception { StringTemplate st =new StringTemplate( "date: ", AngleBracketTemplateLexer.class); st.setAttribute("created", new GregorianCalendar(2005, 07-1, 05)); st.registerRenderer(GregorianCalendar.class, new DateRenderer3()); String expecting = "date: 2005.07.05"; String result = st.toString(); assertEquals(expecting, result); } public void testRendererWithFormatAndList() throws Exception { StringTemplate st =new StringTemplate( "The names: ", AngleBracketTemplateLexer.class); st.setAttribute("names", "ter"); st.setAttribute("names", "tom"); st.setAttribute("names", "sriram"); st.registerRenderer(String.class, new StringRenderer()); String expecting = "The names: TERTOMSRIRAM"; String result = st.toString(); assertEquals(expecting, result); } public void testRendererWithFormatAndSeparator() throws Exception { StringTemplate st =new StringTemplate( "The names: ", AngleBracketTemplateLexer.class); st.setAttribute("names", "ter"); st.setAttribute("names", "tom"); st.setAttribute("names", "sriram"); st.registerRenderer(String.class, new StringRenderer()); String expecting = "The names: TER and TOM and SRIRAM"; String result = st.toString(); assertEquals(expecting, result); } public void testRendererWithFormatAndSeparatorAndNull() throws Exception { StringTemplate st =new StringTemplate( "The names: ", AngleBracketTemplateLexer.class); List names = new ArrayList(); names.add("ter"); names.add(null); names.add("sriram"); st.setAttribute("names", names); st.registerRenderer(String.class, new StringRenderer()); String expecting = "The names: TER and N/A and SRIRAM"; String result = st.toString(); assertEquals(expecting, result); } public void testEmbeddedRendererSeesEnclosing() throws Exception { // st is embedded in outer; set renderer on outer, st should // still see it. StringTemplate outer =new StringTemplate( "X: ", AngleBracketTemplateLexer.class); StringTemplate st =new StringTemplate( "date: ", AngleBracketTemplateLexer.class); st.setAttribute("created", new GregorianCalendar(2005, 07-1, 05)); outer.setAttribute("x", st); outer.registerRenderer(GregorianCalendar.class, new DateRenderer()); String expecting = "X: date: 2005.07.05"; String result = outer.toString(); assertEquals(expecting, result); } public void testRendererForGroup() throws Exception { String templates = "group test;" +newline+ "dateThing(created) ::= \"date: \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("dateThing"); st.setAttribute("created", new GregorianCalendar(2005, 07-1, 05)); group.registerRenderer(GregorianCalendar.class, new DateRenderer()); String expecting = "date: 2005.07.05"; String result = st.toString(); assertEquals(expecting, result); } public void testOverriddenRenderer() throws Exception { String templates = "group test;" +newline+ "dateThing(created) ::= \"date: \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("dateThing"); st.setAttribute("created", new GregorianCalendar(2005, 07-1, 05)); group.registerRenderer(GregorianCalendar.class, new DateRenderer()); st.registerRenderer(GregorianCalendar.class, new DateRenderer2()); String expecting = "date: 07/05/2005"; String result = st.toString(); assertEquals(expecting, result); } public void testMap() throws Exception { String templates = "group test;" +newline+ "typeInit ::= [\"int\":\"0\", \"float\":\"0.0\"] "+newline+ "var(type,name) ::= \" = ;\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("var"); st.setAttribute("type", "int"); st.setAttribute("name", "x"); String expecting = "int x = 0;"; String result = st.toString(); assertEquals(expecting, result); } public void testMapValuesAreTemplates() throws Exception { String templates = "group test;" +newline+ "typeInit ::= [\"int\":\"0\", \"float\":\"0.0\"] "+newline+ "var(type,w,name) ::= \" = ;\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("var"); st.setAttribute("w", "L"); st.setAttribute("type", "int"); st.setAttribute("name", "x"); String expecting = "int x = 0L;"; String result = st.toString(); assertEquals(expecting, result); } public void testMapKeyLookupViaTemplate() throws Exception { // ST doesn't do a toString on .(key) values, it just uses the value // of key rather than key itself as the key. But, if you compute a // key via a template String templates = "group test;" +newline+ "typeInit ::= [\"int\":\"0\", \"float\":\"0.0\"] "+newline+ "var(type,w,name) ::= \" = ;\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("var"); st.setAttribute("w", "L"); st.setAttribute("type", new StringTemplate("int")); st.setAttribute("name", "x"); String expecting = "int x = 0L;"; String result = st.toString(); assertEquals(expecting, result); } public void testMapMissingDefaultValueIsEmpty() throws Exception { String templates = "group test;" +newline+ "typeInit ::= [\"int\":\"0\", \"float\":\"0.0\"] "+newline+ "var(type,w,name) ::= \" = ;\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("var"); st.setAttribute("w", "L"); st.setAttribute("type", "double"); // double not in typeInit map st.setAttribute("name", "x"); String expecting = "double x = ;"; // weird, but tests default value is key String result = st.toString(); assertEquals(expecting, result); } public void testMapHiddenByFormalArg() throws Exception { String templates = "group test;" +newline+ "typeInit ::= [\"int\":\"0\", \"float\":\"0.0\"] "+newline+ "var(typeInit,type,name) ::= \" = ;\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("var"); st.setAttribute("type", "int"); st.setAttribute("name", "x"); String expecting = "int x = ;"; String result = st.toString(); assertEquals(expecting, result); } public void testMapEmptyValueAndAngleBracketStrings() throws Exception { String templates = "group test;" +newline+ "typeInit ::= [\"int\":\"0\", \"float\":, \"double\":<<0.0L>>] "+newline+ "var(type,name) ::= \" = ;\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("var"); st.setAttribute("type", "float"); st.setAttribute("name", "x"); String expecting = "float x = ;"; String result = st.toString(); assertEquals(expecting, result); } public void testMapDefaultValue() throws Exception { String templates = "group test;" +newline+ "typeInit ::= [\"int\":\"0\", default:\"null\"] "+newline+ "var(type,name) ::= \" = ;\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("var"); st.setAttribute("type", "UserRecord"); st.setAttribute("name", "x"); String expecting = "UserRecord x = null;"; String result = st.toString(); assertEquals(expecting, result); } public void testMapEmptyDefaultValue() throws Exception { String templates = "group test;" +newline+ "typeInit ::= [\"int\":\"0\", default:] "+newline+ "var(type,name) ::= \" = ;\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("var"); st.setAttribute("type", "UserRecord"); st.setAttribute("name", "x"); String expecting = "UserRecord x = ;"; String result = st.toString(); assertEquals(expecting, result); } public void testMapDefaultValueIsKey() throws Exception { String templates = "group test;" +newline+ "typeInit ::= [\"int\":\"0\", default:key] "+newline+ "var(type,name) ::= \" = ;\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("var"); st.setAttribute("type", "UserRecord"); st.setAttribute("name", "x"); String expecting = "UserRecord x = UserRecord;"; String result = st.toString(); assertEquals(expecting, result); } /** * Test that a map can have only the default entry. *

    * Bug ref: JIRA bug ST-15 (Fixed) */ public void testMapDefaultStringAsKey() throws Exception { String templates = "group test;" +newline+ "typeInit ::= [\"default\":\"foo\"] "+newline+ "var(type,name) ::= \" = ;\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("var"); st.setAttribute("type", "default"); st.setAttribute("name", "x"); String expecting = "default x = foo;"; String result = st.toString(); assertEquals(expecting, result); } /** * Test that a map can return a string with the word: default. *

    * Bug ref: JIRA bug ST-15 (Fixed) */ public void testMapDefaultIsDefaultString() throws Exception { String templates = "group test;" +newline+ "map ::= [default: \"default\"] "+newline+ "t1() ::= \"\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("t1"); String expecting = "default"; String result = st.toString(); assertEquals(expecting, result); } public void testMapViaEnclosingTemplates() throws Exception { String templates = "group test;" +newline+ "typeInit ::= [\"int\":\"0\", \"float\":\"0.0\"] "+newline+ "intermediate(type,name) ::= \"\""+newline+ "var(type,name) ::= \" = ;\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("intermediate"); st.setAttribute("type", "int"); st.setAttribute("name", "x"); String expecting = "int x = 0;"; String result = st.toString(); assertEquals(expecting, result); } public void testMapViaEnclosingTemplates2() throws Exception { String templates = "group test;" +newline+ "typeInit ::= [\"int\":\"0\", \"float\":\"0.0\"] "+newline+ "intermediate(stuff) ::= \"\""+newline+ "var(type,name) ::= \" = ;\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate interm = group.getInstanceOf("intermediate"); StringTemplate var = group.getInstanceOf("var"); var.setAttribute("type", "int"); var.setAttribute("name", "x"); interm.setAttribute("stuff", var); String expecting = "int x = 0;"; String result = interm.toString(); assertEquals(expecting, result); } public void testEmptyGroupTemplate() throws Exception { String templates = "group test;" +newline+ "foo() ::= \"\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate a = group.getInstanceOf("foo"); String expecting = ""; String result = a.toString(); assertEquals(expecting, result); } public void testEmptyStringAndEmptyAnonTemplateAsParameterUsingAngleBracketLexer() throws Exception { String templates = "group test;" +newline+ "top() ::= <<>>"+newline+ "x(a,b) ::= \"a=, b=\""+newline; ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate a = group.getInstanceOf("top"); String expecting = "a=, b="; String result = a.toString(); assertEquals(expecting, result); } public void testEmptyStringAndEmptyAnonTemplateAsParameterUsingDollarLexer() throws Exception { String templates = "group test;" +newline+ "top() ::= <<$x(a=\"\", b={})$>>"+newline+ "x(a,b) ::= \"a=$a$, b=$b$\""+newline; ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class); StringTemplate a = group.getInstanceOf("top"); String expecting = "a=, b="; String result = a.toString(); assertEquals(expecting, result); } /** * FIXME: Dannish does not work if typed directly in with default file * encoding on windows. The character needs to be escaped as bellow. * Please correct to escape the correct charcter. */ public void test8BitEuroChars() throws Exception { StringTemplate e = new StringTemplate( "Danish: \u0143 char" ); e = e.getInstanceOf(); String expecting = "Danish: \u0143 char"; assertEquals(expecting, e.toString()); } public void test16BitUnicodeChar() throws Exception { StringTemplate e = new StringTemplate( "DINGBAT CIRCLED SANS-SERIF DIGIT ONE: \u2780" ); e = e.getInstanceOf(); String expecting = "DINGBAT CIRCLED SANS-SERIF DIGIT ONE: \u2780"; assertEquals(expecting, e.toString()); } public void testFirstOp() throws Exception { StringTemplate e = new StringTemplate( "$first(names)$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("names", "Sriram"); String expecting = "Ter"; assertEquals(expecting, e.toString()); } public void testTruncOp() throws Exception { StringTemplate e = new StringTemplate( "$trunc(names); separator=\", \"$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("names", "Sriram"); String expecting = "Ter, Tom"; assertEquals(expecting, e.toString()); } public void testRestOp() throws Exception { StringTemplate e = new StringTemplate( "$rest(names); separator=\", \"$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("names", "Sriram"); String expecting = "Tom, Sriram"; assertEquals(expecting, e.toString()); } public void testRestOpEmptyList() throws Exception { StringTemplate e = new StringTemplate( "$rest(names); separator=\", \"$" ); e = e.getInstanceOf(); e.setAttribute("names", new ArrayList()); String expecting = ""; assertEquals(expecting, e.toString()); } public void testReUseOfRestResult() throws Exception { String templates = "group test;" +newline+ "a(names) ::= \"\""+newline+ "b(x) ::= \", \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate e = group.getInstanceOf("a"); List names = new ArrayList(); names.add("Ter"); names.add("Tom"); e.setAttribute("names", names); String expecting = "Tom, Tom"; assertEquals(expecting, e.toString()); } public void testLastOp() throws Exception { StringTemplate e = new StringTemplate( "$last(names)$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("names", "Sriram"); String expecting = "Sriram"; assertEquals(expecting, e.toString()); } public void testCombinedOp() throws Exception { // replace first of yours with first of mine StringTemplate e = new StringTemplate( "$[first(mine),rest(yours)]; separator=\", \"$" ); e = e.getInstanceOf(); e.setAttribute("mine", "1"); e.setAttribute("mine", "2"); e.setAttribute("mine", "3"); e.setAttribute("yours", "a"); e.setAttribute("yours", "b"); String expecting = "1, b"; assertEquals(expecting, e.toString()); } public void testCatListAndSingleAttribute() throws Exception { // replace first of yours with first of mine StringTemplate e = new StringTemplate( "$[mine,yours]; separator=\", \"$" ); e = e.getInstanceOf(); e.setAttribute("mine", "1"); e.setAttribute("mine", "2"); e.setAttribute("mine", "3"); e.setAttribute("yours", "a"); String expecting = "1, 2, 3, a"; assertEquals(expecting, e.toString()); } public void testReUseOfCat() throws Exception { String templates = "group test;" +newline+ "a(mine,yours) ::= \"\""+newline+ "b(x) ::= \", \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate e = group.getInstanceOf("a"); List mine = new ArrayList(); mine.add("Ter"); mine.add("Tom"); e.setAttribute("mine", mine); List yours = new ArrayList(); yours.add("Foo"); e.setAttribute("yours", yours); String expecting = "TerTomFoo, TerTomFoo"; assertEquals(expecting, e.toString()); } public void testCatListAndEmptyAttributes() throws Exception { // + is overloaded to be cat strings and cat lists so the // two operands (from left to right) determine which way it // goes. In this case, x+mine is a list so everything from their // to the right becomes list cat. StringTemplate e = new StringTemplate( "$[x,mine,y,yours,z]; separator=\", \"$" ); e = e.getInstanceOf(); e.setAttribute("mine", "1"); e.setAttribute("mine", "2"); e.setAttribute("mine", "3"); e.setAttribute("yours", "a"); String expecting = "1, 2, 3, a"; assertEquals(expecting, e.toString()); } public void testNestedOp() throws Exception { StringTemplate e = new StringTemplate( "$first(rest(names))$" // gets 2nd element ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("names", "Sriram"); String expecting = "Tom"; assertEquals(expecting, e.toString()); } public void testFirstWithOneAttributeOp() throws Exception { StringTemplate e = new StringTemplate( "$first(names)$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); String expecting = "Ter"; assertEquals(expecting, e.toString()); } public void testLastWithOneAttributeOp() throws Exception { StringTemplate e = new StringTemplate( "$last(names)$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); String expecting = "Ter"; assertEquals(expecting, e.toString()); } public void testLastWithLengthOneListAttributeOp() throws Exception { StringTemplate e = new StringTemplate( "$last(names)$" ); e = e.getInstanceOf(); e.setAttribute("names", new ArrayList() {{add("Ter");}}); String expecting = "Ter"; assertEquals(expecting, e.toString()); } public void testRestWithOneAttributeOp() throws Exception { StringTemplate e = new StringTemplate( "$rest(names)$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); String expecting = ""; assertEquals(expecting, e.toString()); } public void testRestWithLengthOneListAttributeOp() throws Exception { StringTemplate e = new StringTemplate( "$rest(names)$" ); e = e.getInstanceOf(); e.setAttribute("names", new ArrayList() {{add("Ter");}}); String expecting = ""; assertEquals(expecting, e.toString()); } public void testRepeatedRestOp() throws Exception { StringTemplate e = new StringTemplate( "$rest(names)$, $rest(names)$" // gets 2nd element ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); String expecting = "Tom, Tom"; assertEquals(expecting, e.toString()); } /** If an iterator is sent into ST, it must be cannot be reset after each * use so repeated refs yield empty values. This would * work if we passed in a List not an iterator. Avoid sending in iterators * if you ref it twice. */ public void testRepeatedIteratedAttrFromArg() throws Exception { String templates = "group test;" +newline+ "root(names) ::= \"$other(names)$\""+newline+ "other(x) ::= \"$x$, $x$\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class); StringTemplate e = group.getInstanceOf("root"); List names = new ArrayList(); names.add("Ter"); names.add("Tom"); e.setAttribute("names", names.iterator()); String expecting = "TerTom, "; // This does not give TerTom twice!! assertEquals(expecting, e.toString()); } /** FIXME: BUG! Iterator is not reset from first to second $x$ * Either reset the iterator or pass an attribute that knows to get * the iterator each time. Seems like first, tail do not * have same problem as they yield objects. * * Maybe make a RestIterator like I have CatIterator. */ /* public void testRepeatedRestOpAsArg() throws Exception { String templates = "group test;" +newline+ "root(names) ::= \"$other(rest(names))$\""+newline+ "other(x) ::= \"$x$, $x$\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class); StringTemplate e = group.getInstanceOf("root"); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); String expecting = "Tom, Tom"; assertEquals(expecting, e.toString()); } */ public void testIncomingLists() throws Exception { StringTemplate e = new StringTemplate( "$rest(names)$, $rest(names)$" // gets 2nd element ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); String expecting = "Tom, Tom"; assertEquals(expecting, e.toString()); } public void testIncomingListsAreNotModified() throws Exception { StringTemplate e = new StringTemplate( "$names; separator=\", \"$" // gets 2nd element ); e = e.getInstanceOf(); List names = new ArrayList(); names.add("Ter"); names.add("Tom"); e.setAttribute("names", names); e.setAttribute("names", "Sriram"); String expecting = "Ter, Tom, Sriram"; assertEquals(expecting, e.toString()); assertEquals(names.size(), 2); } public void testIncomingListsAreNotModified2() throws Exception { StringTemplate e = new StringTemplate( "$names; separator=\", \"$" // gets 2nd element ); e = e.getInstanceOf(); List names = new ArrayList(); names.add("Ter"); names.add("Tom"); e.setAttribute("names", "Sriram"); // single element first now e.setAttribute("names", names); String expecting = "Sriram, Ter, Tom"; assertEquals(expecting, e.toString()); assertEquals(names.size(), 2); } public void testIncomingArraysAreOk() throws Exception { StringTemplate e = new StringTemplate( "$names; separator=\", \"$" // gets 2nd element ); e = e.getInstanceOf(); e.setAttribute("names", new String[] {"Ter","Tom"}); e.setAttribute("names", "Sriram"); String expecting = "Ter, Tom, Sriram"; assertEquals(expecting, e.toString()); } public void testMultipleRefsToListAttribute() throws Exception { String templates = "group test;" +newline+ "f(x) ::= \" \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate e = group.getInstanceOf("f"); e.setAttribute("x", "Ter"); e.setAttribute("x", "Tom"); String expecting = "TerTom TerTom"; assertEquals(expecting, e.toString()); } public void testApplyTemplateWithSingleFormalArgs() throws Exception { String templates = "group test;" +newline+ "test(names) ::= << >>"+newline+ "bold(item) ::= <<**>>"+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate e = group.getInstanceOf("test"); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); String expecting = "*Ter*, *Tom* "; String result = e.toString(); assertEquals(expecting, result); } public void testApplyTemplateWithNoFormalArgs() throws Exception { String templates = "group test;" +newline+ "test(names) ::= << >>"+newline+ "bold() ::= <<**>>"+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), AngleBracketTemplateLexer.class); StringTemplate e = group.getInstanceOf("test"); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); String expecting = "*Ter*, *Tom* "; String result = e.toString(); assertEquals(expecting, result); } public void testAnonTemplateArgs() throws Exception { StringTemplate e = new StringTemplate( "$names:{n| $n$}; separator=\", \"$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); String expecting = "Ter, Tom"; assertEquals(expecting, e.toString()); } public void testAnonTemplateWithArgHasNoITArg() throws Exception { StringTemplate e = new StringTemplate( "$names:{n| $n$:$it$}; separator=\", \"$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); String error = null; try { e.toString(); } catch (NoSuchElementException nse) { error = nse.getMessage(); } String expecting = "no such attribute: it in template context [anonymous anonymous]"; assertEquals(error, expecting); } public void testAnonTemplateArgs2() throws Exception { StringTemplate e = new StringTemplate( "$names:{n| .$n$.}:{ n | _$n$_}; separator=\", \"$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); String expecting = "_.Ter._, _.Tom._"; assertEquals(expecting, e.toString()); } public void testFirstWithCatAttribute() throws Exception { StringTemplate e = new StringTemplate( "$first([names,phones])$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("phones", "1"); e.setAttribute("phones", "2"); String expecting = "Ter"; assertEquals(expecting, e.toString()); } public void testFirstWithListOfMaps() throws Exception { StringTemplate e = new StringTemplate( "$first(maps).Ter$" ); e = e.getInstanceOf(); final Map m1 = new HashMap(); final Map m2 = new HashMap(); m1.put("Ter", "x5707"); e.setAttribute("maps", m1); m2.put("Tom", "x5332"); e.setAttribute("maps", m2); String expecting = "x5707"; assertEquals(expecting, e.toString()); e = e.getInstanceOf(); List list = new ArrayList() {{add(m1); add(m2);}}; e.setAttribute("maps", list); expecting = "x5707"; assertEquals(expecting, e.toString()); } // this FAILS! /* public void testFirstWithListOfMaps2() throws Exception { StringTemplate e = new StringTemplate( "$first(maps):{ m | $m.Ter$ }$" ); final Map m1 = new HashMap(); final Map m2 = new HashMap(); m1.put("Ter", "x5707"); e.setAttribute("maps", m1); m2.put("Tom", "x5332"); e.setAttribute("maps", m2); String expecting = "x5707"; assertEquals(expecting, e.toString()); e = e.getInstanceOf(); List list = new ArrayList() {{add(m1); add(m2);}}; e.setAttribute("maps", list); expecting = "x5707"; assertEquals(expecting, e.toString()); } */ public void testJustCat() throws Exception { StringTemplate e = new StringTemplate( "$[names,phones]$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("phones", "1"); e.setAttribute("phones", "2"); String expecting = "TerTom12"; assertEquals(expecting, e.toString()); } public void testCat2Attributes() throws Exception { StringTemplate e = new StringTemplate( "$[names,phones]; separator=\", \"$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("phones", "1"); e.setAttribute("phones", "2"); String expecting = "Ter, Tom, 1, 2"; assertEquals(expecting, e.toString()); } public void testCat2AttributesWithApply() throws Exception { StringTemplate e = new StringTemplate( "$[names,phones]:{a|$a$.}$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("phones", "1"); e.setAttribute("phones", "2"); String expecting = "Ter.Tom.1.2."; assertEquals(expecting, e.toString()); } public void testCat3Attributes() throws Exception { StringTemplate e = new StringTemplate( "$[names,phones,salaries]; separator=\", \"$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("phones", "1"); e.setAttribute("phones", "2"); e.setAttribute("salaries", "big"); e.setAttribute("salaries", "huge"); String expecting = "Ter, Tom, 1, 2, big, huge"; assertEquals(expecting, e.toString()); } public void testCatWithTemplateApplicationAsElement() throws Exception { StringTemplate e = new StringTemplate( "$[names:{$it$!},phones]; separator=\", \"$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("phones" , "1"); e.setAttribute("phones", "2"); String expecting = "Ter!, Tom!, 1, 2"; assertEquals(expecting, e.toString()); } public void testCatWithIFAsElement() throws Exception { StringTemplate e = new StringTemplate( "$[{$if(names)$doh$endif$},phones]; separator=\", \"$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("phones" , "1"); e.setAttribute("phones", "2"); String expecting = "doh, 1, 2"; assertEquals(expecting, e.toString()); } public void testCatWithNullTemplateApplicationAsElement() throws Exception { StringTemplate e = new StringTemplate( "$[names:{$it$!},\"foo\"]:{x}; separator=\", \"$" ); e = e.getInstanceOf(); e.setAttribute("phones", "1"); e.setAttribute("phones", "2"); String expecting = "x"; // only one since template application gives nothing assertEquals(expecting, e.toString()); } public void testCatWithNestedTemplateApplicationAsElement() throws Exception { StringTemplate e = new StringTemplate( "$[names, [\"foo\",\"bar\"]:{$it$!},phones]; separator=\", \"$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("phones", "1"); e.setAttribute("phones", "2"); String expecting = "Ter, Tom, foo!, bar!, 1, 2"; assertEquals(expecting, e.toString()); } public void testListAsTemplateArgument() throws Exception { String templates = "group test;" +newline+ "test(names,phones) ::= \"\""+newline+ "foo(items) ::= \"*}>\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), AngleBracketTemplateLexer.class); StringTemplate e = group.getInstanceOf("test"); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("phones", "1"); e.setAttribute("phones", "2"); String expecting = "*Ter**Tom**1**2*"; String result = e.toString(); assertEquals(expecting, result); } public void testSingleExprTemplateArgument() throws Exception { String templates = "group test;" +newline+ "test(name) ::= \"\""+newline+ "bold(item) ::= \"**\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), AngleBracketTemplateLexer.class); StringTemplate e = group.getInstanceOf("test"); e.setAttribute("name", "Ter"); String expecting = "*Ter*"; String result = e.toString(); assertEquals(expecting, result); } public void testSingleExprTemplateArgumentInApply() throws Exception { // when you specify a single arg on a template application // it overrides the setting of the iterated value "it" to that // same single formal arg. Your arg hides the implicitly set "it". String templates = "group test;" +newline+ "test(names,x) ::= \"\""+newline+ "bold(item) ::= \"**\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), AngleBracketTemplateLexer.class); StringTemplate e = group.getInstanceOf("test"); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("x", "ick"); String expecting = "*ick**ick*"; String result = e.toString(); assertEquals(expecting, result); } public void testSoleFormalTemplateArgumentInMultiApply() throws Exception { String templates = "group test;" +newline+ "test(names) ::= \"\""+newline+ "bold(x) ::= \"**\""+newline+ "italics(y) ::= \"__\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), AngleBracketTemplateLexer.class); StringTemplate e = group.getInstanceOf("test"); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); String expecting = "*Ter*_Tom_"; String result = e.toString(); assertEquals(expecting, result); } public void testSingleExprTemplateArgumentError() throws Exception { String templates = "group test;" +newline+ "test(name) ::= \"\""+newline+ "bold(item,ick) ::= \"**\""+newline ; StringTemplateErrorListener errors = new ErrorBuffer(); StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), AngleBracketTemplateLexer.class, errors); StringTemplate e = group.getInstanceOf("test"); e.setAttribute("name", "Ter"); /*String result =*/ e.toString(); String expecting = "template bold must have exactly one formal arg in template context [test ]"; assertEquals(errors.toString(), expecting); } public void testInvokeIndirectTemplateWithSingleFormalArgs() throws Exception { String templates = "group test;" +newline+ "test(templateName,arg) ::= \"<(templateName)(arg)>\""+newline+ "bold(x) ::= <<**>>"+newline+ "italics(y) ::= <<__>>"+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate e = group.getInstanceOf("test"); e.setAttribute("templateName", "italics"); e.setAttribute("arg", "Ter"); String expecting = "_Ter_"; String result = e.toString(); assertEquals(expecting, result); } public void testParallelAttributeIteration() throws Exception { StringTemplate e = new StringTemplate( "$names,phones,salaries:{n,p,s | $n$@$p$: $s$\n}$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("phones", "1"); e.setAttribute("phones", "2"); e.setAttribute("salaries", "big"); e.setAttribute("salaries", "huge"); String expecting = "Ter@1: big"+newline+"Tom@2: huge"+newline; assertEquals(expecting, e.toString()); } public void testParallelAttributeIterationWithNullValue() throws Exception { StringTemplate e = new StringTemplate( "$names,phones,salaries:{n,p,s | $n$@$p$: $s$\n}$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("names", "Sriram"); e.setAttribute("phones", new ArrayList() {{add("1"); add(null); add("3");}}); e.setAttribute("salaries", "big"); e.setAttribute("salaries", "huge"); e.setAttribute("salaries", "enormous"); String expecting = "Ter@1: big"+newline+ "Tom@: huge"+newline+ "Sriram@3: enormous"+newline; assertEquals(expecting, e.toString()); } public void testParallelAttributeIterationHasI() throws Exception { StringTemplate e = new StringTemplate( "$names,phones,salaries:{n,p,s | $i0$. $n$@$p$: $s$\n}$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("phones", "1"); e.setAttribute("phones", "2"); e.setAttribute("salaries", "big"); e.setAttribute("salaries", "huge"); String expecting = "0. Ter@1: big"+newline+"1. Tom@2: huge"+newline; assertEquals(expecting, e.toString()); } public void testParallelAttributeIterationWithDifferentSizes() throws Exception { StringTemplate e = new StringTemplate( "$names,phones,salaries:{n,p,s | $n$@$p$: $s$}; separator=\", \"$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("names", "Sriram"); e.setAttribute("phones", "1"); e.setAttribute("phones", "2"); e.setAttribute("salaries", "big"); String expecting = "Ter@1: big, Tom@2: , Sriram@: "; assertEquals(expecting, e.toString()); } public void testParallelAttributeIterationWithSingletons() throws Exception { StringTemplate e = new StringTemplate( "$names,phones,salaries:{n,p,s | $n$@$p$: $s$}; separator=\", \"$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("phones", "1"); e.setAttribute("salaries", "big"); String expecting = "Ter@1: big"; assertEquals(expecting, e.toString()); } public void testParallelAttributeIterationWithMismatchArgListSizes() throws Exception { StringTemplateErrorListener errors = new ErrorBuffer(); StringTemplate e = new StringTemplate( "$names,phones,salaries:{n,p | $n$@$p$}; separator=\", \"$" ); e.setErrorListener(errors); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("phones", "1"); e.setAttribute("phones", "2"); e.setAttribute("salaries", "big"); String expecting = "Ter@1, Tom@2"; assertEquals(expecting, e.toString()); String errorExpecting = "number of arguments [n, p] mismatch between attribute list and anonymous template in context [anonymous]"; assertEquals(errorExpecting, errors.toString()); } public void testParallelAttributeIterationWithMissingArgs() throws Exception { StringTemplateErrorListener errors = new ErrorBuffer(); StringTemplate e = new StringTemplate( "$names,phones,salaries:{$n$@$p$}; separator=\", \"$" ); e.setErrorListener(errors); e = e.getInstanceOf(); e.setAttribute("names", "Tom"); e.setAttribute("phones", "2"); e.setAttribute("salaries", "big"); e.toString(); // generate the error String errorExpecting = "missing arguments in anonymous template in context [anonymous]"; assertEquals(errorExpecting, errors.toString()); } public void testParallelAttributeIterationWithDifferentSizesTemplateRefInsideToo() throws Exception { String templates = "group test;" +newline+ "page(names,phones,salaries) ::= "+newline+ " <<$names,phones,salaries:{n,p,s | $value(n)$@$value(p)$: $value(s)$}; separator=\", \"$>>"+newline + "value(x=\"n/a\") ::= \"$x$\"" +newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class); StringTemplate p = group.getInstanceOf("page"); p.setAttribute("names", "Ter"); p.setAttribute("names", "Tom"); p.setAttribute("names", "Sriram"); p.setAttribute("phones", "1"); p.setAttribute("phones", "2"); p.setAttribute("salaries", "big"); String expecting = "Ter@1: big, Tom@2: n/a, Sriram@n/a: n/a"; assertEquals(expecting, p.toString()); } public void testAnonTemplateOnLeftOfApply() throws Exception { StringTemplate e = new StringTemplate( "${foo}:{($it$)}$" ); String expecting = "(foo)"; assertEquals(expecting, e.toString()); } public void testOverrideThroughConditional() throws Exception { String templates = "group base;" +newline+ "body(ick) ::= \"ick\"" + "f() ::= \"foo\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); String templates2 = "group sub;" +newline+ "f() ::= \"bar\""+newline ; StringTemplateGroup subgroup = new StringTemplateGroup(new StringReader(templates2), AngleBracketTemplateLexer.class, null, group); StringTemplate b = subgroup.getInstanceOf("body"); String expecting ="bar"; String result = b.toString(); assertEquals(expecting, result); } public static class NonPublicProperty { } public void testNonPublicPropertyAccess() throws Exception { StringTemplate st = new StringTemplate("$x.foo$:$x.bar$"); Object o = new Object() { public int foo = 9; public int getBar() { return 34; } }; st.setAttribute("x", o); String expecting = "9:34"; assertEquals(expecting, st.toString()); } public void testIndexVar() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", "."); StringTemplate t = new StringTemplate( group, "$A:{$i$. $it$}; separator=\"\\n\"$" ); t.setAttribute("A", "parrt"); t.setAttribute("A", "tombu"); String expecting = "1. parrt" +newline+ "2. tombu"; assertEquals(expecting, t.toString()); } public void testIndex0Var() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", "."); StringTemplate t = new StringTemplate( group, "$A:{$i0$. $it$}; separator=\"\\n\"$" ); t.setAttribute("A", "parrt"); t.setAttribute("A", "tombu"); String expecting = "0. parrt" +newline+ "1. tombu"; assertEquals(expecting, t.toString()); } public void testIndexVarWithMultipleExprs() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", "."); StringTemplate t = new StringTemplate( group, "$A,B:{a,b|$i$. $a$@$b$}; separator=\"\\n\"$" ); t.setAttribute("A", "parrt"); t.setAttribute("A", "tombu"); t.setAttribute("B", "x5707"); t.setAttribute("B", "x5000"); String expecting = "1. parrt@x5707" +newline+ "2. tombu@x5000"; assertEquals(expecting, t.toString()); } public void testIndex0VarWithMultipleExprs() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", "."); StringTemplate t = new StringTemplate( group, "$A,B:{a,b|$i0$. $a$@$b$}; separator=\"\\n\"$" ); t.setAttribute("A", "parrt"); t.setAttribute("A", "tombu"); t.setAttribute("B", "x5707"); t.setAttribute("B", "x5000"); String expecting = "0. parrt@x5707" +newline+ "1. tombu@x5000"; assertEquals(expecting, t.toString()); } public void testArgumentContext() throws Exception { // t is referenced within foo and so will be evaluated in that // context. it can therefore see name. StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplate main = group.defineTemplate("main", "$foo(t={Hi, $name$}, name=\"parrt\")$"); /*StringTemplate foo =*/ group.defineTemplate("foo", "$t$"); String expecting="Hi, parrt"; assertEquals(expecting, main.toString()); } public void testNoDotsInAttributeNames() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", "."); StringTemplate t = new StringTemplate(group, "$user.Name$"); String error=null; try { t.setAttribute("user.Name", "Kunle"); } catch (IllegalArgumentException e) { error = e.getMessage(); } String expecting = "cannot have '.' in attribute names"; assertEquals(expecting,error); } public void testNoDotsInTemplateNames() throws Exception { StringTemplateErrorListener errors = new ErrorBuffer(); String templates = "group test;" +newline+ "a.b() ::= <>"+newline; /*StringTemplateGroup group =*/ new StringTemplateGroup(new StringReader(templates), DefaultTemplateLexer.class, errors); String expecting = "template group parse error: line 2:1: unexpected token:"; assertTrue(errors.toString().startsWith(expecting)); } public void testLineWrap() throws Exception { String templates = "group test;" +newline+ "array(values) ::= < };>>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate a = group.getInstanceOf("array"); a.setAttribute("values", new int[] {3,9,20,2,1,4,6,32,5,6,77,888,2,1,6,32,5,6,77, 4,9,20,2,1,4,63,9,20,2,1,4,6,32,5,6,77,6,32,5,6,77, 3,9,20,2,1,4,6,32,5,6,77,888,1,6,32,5}); String expecting = "int[] a = { 3,9,20,2,1,4,6,32,5,6,77,888,\n" + "2,1,6,32,5,6,77,4,9,20,2,1,4,63,9,20,2,1,\n" + "4,6,32,5,6,77,6,32,5,6,77,3,9,20,2,1,4,6,\n" + "32,5,6,77,888,1,6,32,5 };"; assertEquals(expecting,a.toString(40)); } public void testLineWrapWithNormalizedNewlines() throws Exception { String templates = "group test;" +newline+ "array(values) ::= < };>>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate a = group.getInstanceOf("array"); a.setAttribute("values", new int[] {3,9,20,2,1,4,6,32,5,6,77,888,2,1,6,32,5,6,77, 4,9,20,2,1,4,63,9,20,2,1,4,6,32,5,6,77,6,32,5,6,77, 3,9,20,2,1,4,6,32,5,6,77,888,1,6,32,5}); String expecting = "int[] a = { 3,9,20,2,1,4,6,32,5,6,77,888,\n" + // wrap is \r\n, normalize to \n "2,1,6,32,5,6,77,4,9,20,2,1,4,63,9,20,2,1,\n" + "4,6,32,5,6,77,6,32,5,6,77,3,9,20,2,1,4,6,\n" + "32,5,6,77,888,1,6,32,5 };"; StringWriter sw = new StringWriter(); StringTemplateWriter stw = new AutoIndentWriter(sw,"\n"); // force \n as newline stw.setLineWidth(40); a.write(stw); String result = sw.toString(); assertEquals(expecting, result); } public void testLineWrapAnchored() throws Exception { String templates = "group test;" +newline+ "array(values) ::= < };>>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate a = group.getInstanceOf("array"); a.setAttribute("values", new int[] {3,9,20,2,1,4,6,32,5,6,77,888,2,1,6,32,5,6,77, 4,9,20,2,1,4,63,9,20,2,1,4,6,32,5,6,77,6,32,5,6,77, 3,9,20,2,1,4,6,32,5,6,77,888,1,6,32,5}); String expecting = "int[] a = { 3,9,20,2,1,4,6,32,5,6,77,888,\n" + " 2,1,6,32,5,6,77,4,9,20,2,1,4,\n" + " 63,9,20,2,1,4,6,32,5,6,77,6,\n" + " 32,5,6,77,3,9,20,2,1,4,6,32,\n" + " 5,6,77,888,1,6,32,5 };"; assertEquals(expecting, a.toString(40)); } public void testSubtemplatesAnchorToo() throws Exception { String templates = "group test;" +newline+ "array(values) ::= <<{ }>>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); final StringTemplate x = new StringTemplate(group, "<\\n>{ }<\\n>"); x.setAttribute("stuff", "1"); x.setAttribute("stuff", "2"); x.setAttribute("stuff", "3"); StringTemplate a = group.getInstanceOf("array"); a.setAttribute("values", new ArrayList() {{ add("a"); add(x); add("b"); }}); String expecting = "{ a, \n" + " { 1,\n" + " 2,\n" + " 3 }\n" + " , b }"; assertEquals(expecting, a.toString(40)); } public void testFortranLineWrap() throws Exception { String templates = "group test;" +newline+ "func(args) ::= << FUNCTION line( )>>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate a = group.getInstanceOf("func"); a.setAttribute("args", new String[] {"a","b","c","d","e","f"}); String expecting = " FUNCTION line( a,b,c,d,\n" + " ce,f )"; assertEquals(expecting, a.toString(30)); } public void testLineWrapWithDiffAnchor() throws Exception { String templates = "group test;" +newline+ "array(values) ::= <}; anchor> };>>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate a = group.getInstanceOf("array"); a.setAttribute("values", new int[] {3,9,20,2,1,4,6,32,5,6,77,888,2,1,6,32,5,6,77, 4,9,20,2,1,4,63,9,20,2,1,4,6}); String expecting = "int[] a = { 1,9,2,3,9,20,2,1,4,\n" + " 6,32,5,6,77,888,2,\n" + " 1,6,32,5,6,77,4,9,\n" + " 20,2,1,4,63,9,20,2,\n" + " 1,4,6 };"; assertEquals(expecting, a.toString(30)); } public void testLineWrapEdgeCase() throws Exception { String templates = "group test;" +newline+ "duh(chars) ::= <<>>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate a = group.getInstanceOf("duh"); a.setAttribute("chars", new String[] {"a","b","c","d","e"}); // lineWidth==3 implies that we can have 3 characters at most String expecting = "abc\n"+ "de"; assertEquals(expecting, a.toString(3)); } public void testLineWrapLastCharIsNewline() throws Exception { String templates = "group test;" +newline+ "duh(chars) ::= <<>>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate a = group.getInstanceOf("duh"); a.setAttribute("chars", new String[] {"a","b","\n","d","e"}); // don't do \n if it's last element anyway String expecting = "ab\n"+ "de"; assertEquals(expecting,a.toString(3)); } public void testLineWrapCharAfterWrapIsNewline() throws Exception { String templates = "group test;" +newline+ "duh(chars) ::= <<>>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate a = group.getInstanceOf("duh"); a.setAttribute("chars", new String[] {"a","b","c","\n","d","e"}); // Once we wrap, we must dump chars as we see them. A newline right // after a wrap is just an "unfortunate" event. People will expect // a newline if it's in the data. String expecting = "abc\n" + "\n" + "de"; assertEquals(expecting, a.toString(3)); } public void testLineWrapForAnonTemplate() throws Exception { String templates = "group test;" +newline+ "duh(data) ::= <]}; wrap>!>>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate a = group.getInstanceOf("duh"); a.setAttribute("data", new int[] {1,2,3,4,5,6,7,8,9}); String expecting = "![1][2][3]\n" + // width=9 is the 3 char; don't break til after ] "[4][5][6]\n" + "[7][8][9]!"; assertEquals(expecting,a.toString(9)); } public void testLineWrapForAnonTemplateAnchored() throws Exception { String templates = "group test;" +newline+ "duh(data) ::= <]}; anchor, wrap>!>>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate a = group.getInstanceOf("duh"); a.setAttribute("data", new int[] {1,2,3,4,5,6,7,8,9}); String expecting = "![1][2][3]\n" + " [4][5][6]\n" + " [7][8][9]!"; assertEquals(expecting, a.toString(9)); } public void testLineWrapForAnonTemplateComplicatedWrap() throws Exception { String templates = "group test;" +newline+ "top(s) ::= << .>>"+ "str(data) ::= <]}; wrap=\"!+\\n!\">!>>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate t = group.getInstanceOf("top"); StringTemplate s = group.getInstanceOf("str"); s.setAttribute("data", new int[] {1,2,3,4,5,6,7,8,9}); t.setAttribute("s", s); String expecting = " ![1][2]!+\n" + " ![3][4]!+\n" + " ![5][6]!+\n" + " ![7][8]!+\n" + " ![9]!."; assertEquals(expecting,t.toString(9)); } public void testIndentBeyondLineWidth() throws Exception { String templates = "group test;" +newline+ "duh(chars) ::= << >>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate a = group.getInstanceOf("duh"); a.setAttribute("chars", new String[] {"a","b","c","d","e"}); // String expecting = " a\n" + " b\n" + " c\n" + " d\n" + " e"; assertEquals(expecting, a.toString(2)); } public void testIndentedExpr() throws Exception { String templates = "group test;" +newline+ "duh(chars) ::= << >>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate a = group.getInstanceOf("duh"); a.setAttribute("chars", new String[] {"a","b","c","d","e"}); // String expecting = " ab\n" + " cd\n" + " e"; // width=4 spaces + 2 char. assertEquals(expecting, a.toString(6)); } public void testNestedIndentedExpr() throws Exception { String templates = "group test;" +newline+ "top(d) ::= << !>>"+newline+ "duh(chars) ::= << >>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate top = group.getInstanceOf("top"); StringTemplate duh = group.getInstanceOf("duh"); duh.setAttribute("chars", new String[] {"a","b","c","d","e"}); top.setAttribute("d", duh); String expecting = " ab\n" + " cd\n" + " e!"; // width=4 spaces + 2 char. assertEquals(expecting, top.toString(6)); } public void testNestedWithIndentAndTrackStartOfExpr() throws Exception { String templates = "group test;" +newline+ "top(d) ::= << !>>"+newline+ "duh(chars) ::= <>>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate top = group.getInstanceOf("top"); StringTemplate duh = group.getInstanceOf("duh"); duh.setAttribute("chars", new String[] {"a","b","c","d","e"}); top.setAttribute("d", duh); // String expecting = " x: ab\n" + " cd\n" + " e!"; assertEquals(expecting, top.toString(7)); } public void testLineDoesNotWrapDueToLiteral() throws Exception { String templates = "group test;" +newline+ "m(args,body) ::= <) throws Ick { }>>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate a = group.getInstanceOf("m"); a.setAttribute("args", new String[] {"a", "b", "c"}); a.setAttribute("body", "i=3;"); // make it wrap because of ") throws Ick { " literal int n = "public void foo(a, b, c".length(); String expecting = "public void foo(a, b, c) throws Ick { i=3; }"; assertEquals(expecting, a.toString(n)); } public void testSingleValueWrap() throws Exception { String templates = "group test;" +newline+ "m(args,body) ::= <<{ }>>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate m = group.getInstanceOf("m"); m.setAttribute("body", "i=3;"); // make it wrap because of ") throws Ick { " literal String expecting = "{ \n"+ " i=3; }"; assertEquals(expecting, m.toString(2)); } public void testLineWrapInNestedExpr() throws Exception { String templates = "group test;" +newline+ "top(arrays) ::= <done>>"+newline+ "array(values) ::= < };<\\n\\>>>"+newline; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate top = group.getInstanceOf("top"); StringTemplate a = group.getInstanceOf("array"); a.setAttribute("values", new int[] {3,9,20,2,1,4,6,32,5,6,77,888,2,1,6,32,5,6,77, 4,9,20,2,1,4,63,9,20,2,1,4,6,32,5,6,77,6,32,5,6,77, 3,9,20,2,1,4,6,32,5,6,77,888,1,6,32,5}); top.setAttribute("arrays", a); top.setAttribute("arrays", a); // add twice String expecting = "Arrays: int[] a = { 3,9,20,2,1,4,6,32,5,\n" + " 6,77,888,2,1,6,32,5,\n" + " 6,77,4,9,20,2,1,4,63,\n" + " 9,20,2,1,4,6,32,5,6,\n" + " 77,6,32,5,6,77,3,9,20,\n" + " 2,1,4,6,32,5,6,77,888,\n" + " 1,6,32,5 };\n" + "int[] a = { 3,9,20,2,1,4,6,32,5,6,77,888,\n" + " 2,1,6,32,5,6,77,4,9,20,2,1,4,\n" + " 63,9,20,2,1,4,6,32,5,6,77,6,\n" + " 32,5,6,77,3,9,20,2,1,4,6,32,\n" + " 5,6,77,888,1,6,32,5 };\n" + "done"; assertEquals(expecting, top.toString(40)); } public void testBackslash() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplate t = group.defineTemplate("t", "\\"); String expecting="\\"; assertEquals(expecting, t.toString()); } public void testBackslash2() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplate t = group.defineTemplate("t", "\\ "); String expecting="\\ "; assertEquals(expecting, t.toString()); } public void testEscapeEscape() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplate t = group.defineTemplate("t", "\\\\$v$"); t.setAttribute("v", "Joe"); //System.out.println(t); String expecting="\\Joe"; assertEquals(expecting, t.toString()); } public void testEscapeEscapeNestedAngle() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test", AngleBracketTemplateLexer.class); StringTemplate t = group.defineTemplate("t", "}>"); t.setAttribute("v", "Joe"); //System.out.println(t); String expecting="\\Joe"; assertEquals(expecting, t.toString()); } public void testListOfIntArrays() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test", AngleBracketTemplateLexer.class); StringTemplate t = group.defineTemplate("t", ""); group.defineTemplate("array", "[]"); group.defineTemplate("element", ""); List data = new ArrayList(); data.add(new int[] {1,2,3}); data.add(new int[] {10,20,30}); t.setAttribute("data", data); //System.out.println(t); String expecting="[1,2,3][10,20,30]"; assertEquals(expecting, t.toString()); } // Test null option public void testNullOptionSingleNullValue() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test", AngleBracketTemplateLexer.class); StringTemplate t = group.defineTemplate("t", ""); //System.out.println(t); String expecting="0"; assertEquals(expecting, t.toString()); } public void testNullOptionHasEmptyNullValue() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test", AngleBracketTemplateLexer.class); StringTemplate t = group.defineTemplate("t", ""); List data = new ArrayList(); data.add(null); data.add(new Integer(1)); t.setAttribute("data", data); String expecting=", 1"; assertEquals(expecting, t.toString()); } public void testNullOptionSingleNullValueInList() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test", AngleBracketTemplateLexer.class); StringTemplate t = group.defineTemplate("t", ""); List data = new ArrayList(); data.add(null); t.setAttribute("data", data); //System.out.println(t); String expecting="0"; assertEquals(expecting, t.toString()); } public void testNullValueInList() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test", AngleBracketTemplateLexer.class); StringTemplate t = group.defineTemplate("t", ""); List data = new ArrayList(); data.add(null); data.add(new Integer(1)); data.add(null); data.add(new Integer(3)); data.add(new Integer(4)); data.add(null); t.setAttribute("data", data); //System.out.println(t); String expecting="-1, 1, -1, 3, 4, -1"; assertEquals(expecting, t.toString()); } public void testNullValueInListNoNullOption() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test", AngleBracketTemplateLexer.class); StringTemplate t = group.defineTemplate("t", ""); List data = new ArrayList(); data.add(null); data.add(new Integer(1)); data.add(null); data.add(new Integer(3)); data.add(new Integer(4)); data.add(null); t.setAttribute("data", data); //System.out.println(t); String expecting="1, 3, 4"; assertEquals(expecting, t.toString()); } public void testNullValueInListWithTemplateApply() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test", AngleBracketTemplateLexer.class); StringTemplate t = group.defineTemplate("t", ""); group.defineTemplate("array", ""); List data = new ArrayList(); data.add(new Integer(0)); data.add(null); data.add(new Integer(2)); data.add(null); t.setAttribute("data", data); String expecting="0, -1, 2, -1"; assertEquals(expecting, t.toString()); } public void testNullValueInListWithTemplateApplyNullFirstValue() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test", AngleBracketTemplateLexer.class); StringTemplate t = group.defineTemplate("t", ""); group.defineTemplate("array", ""); List data = new ArrayList(); data.add(null); data.add(new Integer(0)); data.add(null); data.add(new Integer(2)); t.setAttribute("data", data); String expecting="-1, 0, -1, 2"; assertEquals(expecting, t.toString()); } public void testNullSingleValueInListWithTemplateApply() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test", AngleBracketTemplateLexer.class); StringTemplate t = group.defineTemplate("t", ""); group.defineTemplate("array", ""); List data = new ArrayList(); data.add(null); t.setAttribute("data", data); String expecting="-1"; assertEquals(expecting, t.toString()); } public void testNullSingleValueWithTemplateApply() throws Exception { StringTemplateGroup group = new StringTemplateGroup("test", AngleBracketTemplateLexer.class); StringTemplate t = group.defineTemplate("t", ""); group.defineTemplate("array", ""); String expecting="-1"; assertEquals(expecting, t.toString()); } public void testLengthOp() throws Exception { StringTemplate e = new StringTemplate( "$length(names)$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("names", "Tom"); e.setAttribute("names", "Sriram"); String expecting = "3"; assertEquals(expecting, e.toString()); } public void testLengthOpWithMap() throws Exception { StringTemplate e = new StringTemplate( "$length(names)$" ); e = e.getInstanceOf(); Map m = new HashMap(); m.put("Tom", "foo"); m.put("Sriram", "foo"); m.put("Doug", "foo"); e.setAttribute("names", m); String expecting = "3"; assertEquals(expecting, e.toString()); } public void testLengthOpWithSet() throws Exception { StringTemplate e = new StringTemplate( "$length(names)$" ); e = e.getInstanceOf(); Set m = new HashSet(); m.add("Tom"); m.add("Sriram"); m.add("Doug"); e.setAttribute("names", m); String expecting = "3"; assertEquals(expecting, e.toString()); } public void testLengthOpNull() throws Exception { StringTemplate e = new StringTemplate( "$length(names)$" ); e = e.getInstanceOf(); e.setAttribute("names", null); String expecting = "0"; assertEquals(expecting, e.toString()); } public void testLengthOpSingleValue() throws Exception { StringTemplate e = new StringTemplate( "$length(names)$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); String expecting = "1"; assertEquals(expecting, e.toString()); } public void testLengthOpPrimitive() throws Exception { StringTemplate e = new StringTemplate( "$length(ints)$" ); e = e.getInstanceOf(); e.setAttribute("ints", new int[] {1,2,3,4} ); String expecting = "4"; assertEquals(expecting, e.toString()); } public void testLengthOpOfListWithNulls() throws Exception { StringTemplate e = new StringTemplate( "$length(data)$" ); e = e.getInstanceOf(); List data = new ArrayList(); data.add("Hi"); data.add(null); data.add("mom"); data.add(null); e.setAttribute("data", data); String expecting = "4"; // nulls are counted assertEquals(expecting, e.toString()); } public void testStripOpOfListWithNulls() throws Exception { StringTemplate e = new StringTemplate( "$strip(data)$" ); e = e.getInstanceOf(); List data = new ArrayList(); data.add("Hi"); data.add(null); data.add("mom"); data.add(null); e.setAttribute("data", data); String expecting = "Himom"; // nulls are skipped assertEquals(expecting, e.toString()); } public void testStripOpOfListOfListsWithNulls() throws Exception { StringTemplate e = new StringTemplate( "$strip(data):{list | $strip(list)$}; separator=\",\"$" ); e = e.getInstanceOf(); List data = new ArrayList(); List dataOne = new ArrayList(); dataOne.add("Hi"); dataOne.add("mom"); data.add(dataOne); data.add(null); List dataTwo = new ArrayList(); dataTwo.add("Hi"); dataTwo.add(null); dataTwo.add("dad"); dataTwo.add(null); data.add(dataTwo); e.setAttribute("data", data); String expecting = "Himom,Hidad"; // nulls are skipped assertEquals(expecting, e.toString()); } public void testStripOpOfSingleAlt() throws Exception { StringTemplate e = new StringTemplate( "$strip(data)$" ); e = e.getInstanceOf(); e.setAttribute("data", "hi"); String expecting = "hi"; // nulls are skipped assertEquals(expecting, e.toString()); } public void testStripOpOfNull() throws Exception { StringTemplate e = new StringTemplate( "$strip(data)$" ); e = e.getInstanceOf(); String expecting = ""; // nulls are skipped assertEquals(expecting, e.toString()); } public void testReUseOfStripResult() throws Exception { String templates = "group test;" +newline+ "a(names) ::= \"\""+newline+ "b(x) ::= \", \""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate e = group.getInstanceOf("a"); List names = new ArrayList(); names.add("Ter"); names.add(null); names.add("Tom"); e.setAttribute("names", names); String expecting = "TerTom, TerTom"; assertEquals(expecting, e.toString()); } public void testLengthOpOfStrippedListWithNulls() throws Exception { StringTemplate e = new StringTemplate( "$length(strip(data))$" ); e = e.getInstanceOf(); List data = new ArrayList(); data.add("Hi"); data.add(null); data.add("mom"); data.add(null); e.setAttribute("data", data); String expecting = "2"; // nulls are counted assertEquals(expecting, e.toString()); } public void testLengthOpOfStrippedListWithNullsFrontAndBack() throws Exception { StringTemplate e = new StringTemplate( "$length(strip(data))$" ); e = e.getInstanceOf(); List data = new ArrayList(); data.add(null); data.add(null); data.add(null); data.add("Hi"); data.add(null); data.add(null); data.add(null); data.add("mom"); data.add(null); data.add(null); data.add(null); e.setAttribute("data", data); String expecting = "2"; // nulls are counted assertEquals(expecting, e.toString()); } public void testMapKeys() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", ".", AngleBracketTemplateLexer.class); StringTemplate t = new StringTemplate(group, ":}; separator=\", \">"); HashMap map = new LinkedHashMap(); map.put("int","0"); map.put("float","0.0"); t.setAttribute("aMap", map); assertEquals("int:0, float:0.0",t.toString()); } public void testMapValues() throws Exception { StringTemplateGroup group = new StringTemplateGroup("dummy", ".", AngleBracketTemplateLexer.class); StringTemplate t = new StringTemplate(group, " "); HashMap map = new LinkedHashMap(); map.put("int","0"); map.put("float","0.0"); t.setAttribute("aMap", map); assertEquals("0, 0.0 0", t.toString()); } public void testMapKeysWithIntegerType() throws Exception { // must get back an Integer from keys not a toString()'d version StringTemplateGroup group = new StringTemplateGroup("dummy", ".", AngleBracketTemplateLexer.class); StringTemplate t = new StringTemplate(group, ":}; separator=\", \">"); Map map = new HashMap(); map.put(new Integer(1),new ArrayList(){{add("ick"); add("foo");}}); map.put(new Integer(2),new ArrayList(){{add("x"); add("y");}}); t.setAttribute("aMap", map); String res = t.toString(); boolean passed = false; if (res.equals("2:xy, 1:ickfoo") || res.equals("1:ickfoo, 2:xy")) { passed = true; } assertTrue("Map traversal did not return expected strings", passed); } /** Use when super.attr name is implemented public void testArgumentContext2() throws Exception { // t is referenced within foo and so will be evaluated in that // context. it can therefore see name. StringTemplateGroup group = new StringTemplateGroup("test"); StringTemplate main = group.defineTemplate("main", "$foo(t={Hi, $super.name$}, name=\"parrt\")$"); main.setAttribute("name", "tombu"); StringTemplate foo = group.defineTemplate("foo", "$t$"); String expecting="Hi, parrt"; assertEquals(expecting, main.toString()); } */ /** * Check what happens when a semicolon is appended to a single line template * Should fail with a parse error(?) and not a missing template error. * FIXME: This should generate a warning or error about that semi colon. *

    * Bug ref: JIRA bug ST-2 */ /* public void testGroupTrailingSemiColon() throws Exception { //try { String templates = "group test;" +newline+ "t1()::=\"R1\"; "+newline+ "t2() ::= \"R2\""+newline ; StringTemplateGroup group = new StringTemplateGroup(new StringReader(templates)); StringTemplate st = group.getInstanceOf("t1"); assertEquals("R1", st.toString()); st = group.getInstanceOf("t2"); assertEquals("R2", st.toString()); fail("A parse error should have been generated"); //} catch (ParseError??) { //} } */ public void testSuperReferenceInIfClause() throws Exception { String superGroupString = "group super;" + newline + "a(x) ::= \"super.a\"" + newline + "b(x) ::= \"super.b\"" + newline + "c() ::= \"super.c\"" ; StringTemplateGroup superGroup = new StringTemplateGroup( new StringReader(superGroupString), AngleBracketTemplateLexer.class); String subGroupString = "group sub;\n" + "a(x) ::= \"\"" + newline + "b(x) ::= \"\"" + newline + "c() ::= \"sub.c\"" ; StringTemplateGroup subGroup = new StringTemplateGroup( new StringReader(subGroupString), AngleBracketTemplateLexer.class); subGroup.setSuperGroup(superGroup); StringTemplate a = subGroup.getInstanceOf("a"); a.setAttribute("x", "foo"); assertEquals("super.a", a.toString()); StringTemplate b = subGroup.getInstanceOf("b"); assertEquals("sub.csuper.b", b.toString()); StringTemplate c = subGroup.getInstanceOf("c"); assertEquals("sub.c", c.toString()); } /** Added feature for ST-21 */ public void testListLiteralWithEmptyElements() throws Exception { StringTemplate e = new StringTemplate( "$[\"Ter\",,\"Jesse\"]:{n | $i$:$n$}; separator=\", \", null=\"\"$" ); e = e.getInstanceOf(); e.setAttribute("names", "Ter"); e.setAttribute("phones", "1"); e.setAttribute("salaries", "big"); String expecting = "1:Ter, 2:, 3:Jesse"; assertEquals(expecting, e.toString()); } public void testTemplateApplicationAsOptionValue() throws Exception { StringTemplate st =new StringTemplate( "Tokens : }> ;", AngleBracketTemplateLexer.class); st.setAttribute("rules", "A"); st.setAttribute("rules", "B"); st.setAttribute("names", "Ter"); st.setAttribute("names", "Tom"); String expecting = "Tokens : ATerTomB ;"; assertEquals(expecting, st.toString()); } public static void writeFile(String dir, String fileName, String content) { try { File f = new File(dir, fileName); FileWriter w = new FileWriter(f); BufferedWriter bw = new BufferedWriter(w); bw.write(content); bw.close(); w.close(); } catch (IOException ioe) { System.err.println("can't write file"); ioe.printStackTrace(System.err); } } } stringtemplate-3.2.1/test/org/antlr/stringtemplate/test/method.st0000644000175000017500000000012511256235341025254 0ustar twernertwerner () { } stringtemplate-3.2.1/test/org/antlr/stringtemplate/test/body.st0000644000175000017500000000010111256235341024723 0ustar twernertwerner// start of a body // end of a body stringtemplate-3.2.1/test/org/antlr/stringtemplate/test/row.st0000644000175000017500000000003311256235341024601 0ustar twernertwerner$it.firstName$ $it.email$ stringtemplate-3.2.1/test/org/antlr/stringtemplate/test/page.st0000644000175000017500000000001711256235341024710 0ustar twernertwerner$title$ $body$ stringtemplate-3.2.1/test/org/antlr/stringtemplate/test/users_list.st0000644000175000017500000000005411256235341026171 0ustar twernertwerner$users:org/antlr/stringtemplate/test/row()$ stringtemplate-3.2.1/README.txt0000644000175000017500000000205211256235341016214 0ustar twernertwernerStringTemplate 3.2.1 September 22, 2009 Terence Parr, parrt at cs usfca edu ANTLR project lead and supreme dictator for life University of San Francisco ST (StringTemplate) is a java template engine (with ports for C# and Python) for generating source code, web pages, emails, or any other formatted text output. ST is particularly good at multi-targeted code generators, multiple site skins, and internationalization/localization. It evolved over years of effort developing jGuru.com. ST also generates this website and powers the ANTLR v3 code generator. Its distinguishing characteristic is that it strictly enforces model-view separation unlike other engines. The main website is: http://www.stringtemplate.org The documentation is in the wiki: http://www.antlr.org/wiki/display/ST/StringTemplate+Documentation Here are the 3.2.1 release notes: http://www.antlr.org/wiki/display/ST/3.2.1+Release+Notes Per the license in LICENSE.txt, this software is not guaranteed to work and might even destroy all life on this planet. See the CHANGES.txt file. stringtemplate-3.2.1/src/0000755000175000017500000000000011256235341015306 5ustar twernertwernerstringtemplate-3.2.1/src/org/0000755000175000017500000000000011256235341016075 5ustar twernertwernerstringtemplate-3.2.1/src/org/antlr/0000755000175000017500000000000011256235341017215 5ustar twernertwernerstringtemplate-3.2.1/src/org/antlr/stringtemplate/0000755000175000017500000000000011256235341022257 5ustar twernertwernerstringtemplate-3.2.1/src/org/antlr/stringtemplate/StringTemplateGroup.java0000755000175000017500000010234711256235341027113 0ustar twernertwerner/* [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 org.antlr.stringtemplate.language.DefaultTemplateLexer; import org.antlr.stringtemplate.language.GroupLexer; import org.antlr.stringtemplate.language.GroupParser; import org.antlr.stringtemplate.language.AngleBracketTemplateLexer; import java.util.*; import java.io.*; import java.lang.reflect.Constructor; /** Manages a group of named mutually-referential StringTemplate objects. * Currently the templates must all live under a directory so that you * can reference them as foo.st or gutter/header.st. To refresh a * group of templates, just create a new StringTemplateGroup and start * pulling templates from there. Or, set the refresh interval. * * Use getInstanceOf(template-name) to get a string template * to fill in. * * The name of a template is the file name minus ".st" ending if present * unless you name it as you load it. * * You can use the group file format also to define a group of templates * (this works better for code gen than for html page gen). You must give * a Reader to the ctor for it to load the group; this is general and * distinguishes it from the ctors for the old-style "load template files * from the disk". * * 10/2005 I am adding a StringTemplateGroupLoader concept so people can define supergroups * within a group and have it load that group automatically. */ public class StringTemplateGroup { /** What is the group name */ protected String name; /** Maps template name to StringTemplate object */ protected Map templates = new HashMap(); /** Maps map names to HashMap objects. This is the list of maps * defined by the user like typeInitMap ::= ["int":"0"] */ protected Map maps = new HashMap(); /** How to pull apart a template into chunks? */ protected Class templateLexerClass = null; /** You can set the lexer once if you know all of your groups use the * same separator. If the instance has templateLexerClass set * then it is used as an override. */ protected static Class defaultTemplateLexerClass = DefaultTemplateLexer.class; /** Under what directory should I look for templates? If null, * to look into the CLASSPATH for templates as resources. */ protected String rootDir = null; /** Track all groups by name; maps name to StringTemplateGroup */ protected static Map nameToGroupMap = Collections.synchronizedMap(new HashMap()); /** Track all interfaces by name; maps name to StringTemplateGroupInterface */ protected static Map nameToInterfaceMap = Collections.synchronizedMap(new HashMap()); /** Are we derived from another group? Templates not found in this group * will be searched for in the superGroup recursively. */ protected StringTemplateGroup superGroup = null; /** Keep track of all interfaces implemented by this group. */ protected List interfaces = null; /** When templates are files on the disk, the refresh interval is used * to know when to reload. When a Reader is passed to the ctor, * it is a stream full of template definitions. The former is used * for web development, but the latter is most likely used for source * code generation for translators; a refresh is unlikely. Anyway, * I decided to track the source of templates in case such info is useful * in other situations than just turning off refresh interval. I just * found another: don't ever look on the disk for individual templates * if this group is a group file...immediately look into any super group. * If not in the super group, report no such template. */ protected boolean templatesDefinedInGroupFile = false; /** Normally AutoIndentWriter is used to filter output, but user can * specify a new one. */ protected Class userSpecifiedWriter; protected boolean debugTemplateOutput = false; /** The set of templates to ignore when dumping start/stop debug strings */ protected Set noDebugStartStopStrings; /** A Map that allows people to register a renderer for * a particular kind of object to be displayed for any template in this * group. For example, a date should be formatted differently depending * on the locale. You can set Date.class to an object whose * toString(Object) method properly formats a Date attribute * according to locale. Or you can have a different renderer object * for each locale. * * These render objects are used way down in the evaluation chain * right before an attribute's toString() method would normally be * called in ASTExpr.write(). * * Synchronized at creation time. */ protected Map attributeRenderers; /** Maps obj.prop to a value to avoid reflection costs; track one * set of all class.property -> Member mappings for all ST usage in VM. protected static Map classPropertyCache = new HashMap(); public static class ClassPropCacheKey { Class c; String propertyName; public ClassPropCacheKey(Class c, String propertyName) { this.c=c; this.propertyName=propertyName; } public boolean equals(Object other) { ClassPropCacheKey otherKey = (ClassPropCacheKey)other; return c.equals(otherKey.c) && propertyName.equals(otherKey.propertyName); } public int hashCode() { return c.hashCode()+propertyName.hashCode(); } } */ /** If a group file indicates it derives from a supergroup, how do we * find it? Shall we make it so the initial StringTemplateGroup file * can be loaded via this loader? Right now we pass a Reader to ctor * to distinguish from the other variety. */ private static StringTemplateGroupLoader groupLoader = null; /** Where to report errors. All string templates in this group * use this error handler by default. */ protected StringTemplateErrorListener listener = DEFAULT_ERROR_LISTENER; public static StringTemplateErrorListener DEFAULT_ERROR_LISTENER = new StringTemplateErrorListener() { public void error(String s, Throwable e) { System.err.println(s); if ( e!=null ) { e.printStackTrace(System.err); } } public void warning(String s) { System.out.println(s); } }; /** Used to indicate that the template doesn't exist. * We don't have to check disk for it; we know it's not there. */ protected static final StringTemplate NOT_FOUND_ST = new StringTemplate(); /** How long before tossing out all templates in seconds. */ protected int refreshIntervalInSeconds = Integer.MAX_VALUE/1000; // default: no refreshing from disk protected long lastCheckedDisk = 0L; /** How are the files encoded (ascii, UTF8, ...)? You might want to read * UTF8 for example on an ascii machine. */ String fileCharEncoding = System.getProperty("file.encoding"); /** Create a group manager for some templates, all of which are * at or below the indicated directory. */ public StringTemplateGroup(String name, String rootDir) { this(name,rootDir,DefaultTemplateLexer.class); } public StringTemplateGroup(String name, String rootDir, Class lexer) { this.name = name; this.rootDir = rootDir; lastCheckedDisk = System.currentTimeMillis(); nameToGroupMap.put(name, this); this.templateLexerClass = lexer; } /** Create a group manager for some templates, all of which are * loaded as resources via the classloader. */ public StringTemplateGroup(String name) { this(name,null,null); } public StringTemplateGroup(String name, Class lexer) { this(name,null,lexer); } /** Create a group from the template group defined by a input stream. * The name is pulled from the file. The format is * * group name; * * t1(args) ::= "..." * t2() ::= << * >> * ... */ public StringTemplateGroup(Reader r) { this(r,AngleBracketTemplateLexer.class,DEFAULT_ERROR_LISTENER,(StringTemplateGroup)null); } public StringTemplateGroup(Reader r, StringTemplateErrorListener errors) { this(r,AngleBracketTemplateLexer.class,errors,(StringTemplateGroup)null); } public StringTemplateGroup(Reader r, Class lexer) { this(r,lexer,null,(StringTemplateGroup)null); } public StringTemplateGroup(Reader r, Class lexer, StringTemplateErrorListener errors) { this(r,lexer,errors,(StringTemplateGroup)null); } /** Create a group from the input stream, but use a nondefault lexer * to break the templates up into chunks. This is usefor changing * the delimiter from the default $...$ to <...>, for example. */ public StringTemplateGroup(Reader r, Class lexer, StringTemplateErrorListener errors, StringTemplateGroup superGroup) { this.templatesDefinedInGroupFile = true; // if no lexer specified, then assume <...> when loading from group file if ( lexer==null ) { lexer = AngleBracketTemplateLexer.class; } this.templateLexerClass = lexer; if ( errors!=null ) { // always have to have a listener this.listener = errors; } setSuperGroup(superGroup); parseGroup(r); nameToGroupMap.put(name, this); verifyInterfaceImplementations(); } /** What lexer class to use to break up templates. If not lexer set * for this group, use static default. */ public Class getTemplateLexerClass() { if ( templateLexerClass!=null ) { return templateLexerClass; } return defaultTemplateLexerClass; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void setSuperGroup(StringTemplateGroup superGroup) { this.superGroup = superGroup; } /** Called by group parser when ": supergroupname" is found. * This method forces the supergroup's lexer to be same as lexer * for this (sub) group. */ public void setSuperGroup(String superGroupName) { StringTemplateGroup superGroup = (StringTemplateGroup)nameToGroupMap.get(superGroupName); if ( superGroup !=null ) { // we've seen before; just use it setSuperGroup(superGroup); return; } // else load it using this group's template lexer superGroup = loadGroup(superGroupName, this.templateLexerClass, null); if ( superGroup !=null ) { nameToGroupMap.put(superGroupName, superGroup); setSuperGroup(superGroup); } else { if ( groupLoader==null ) { listener.error("no group loader registered", null); } } } /** Just track the new interface; check later. Allows dups, but no biggie. */ public void implementInterface(StringTemplateGroupInterface I) { if ( interfaces==null ) { interfaces = new ArrayList(); } interfaces.add(I); } /** Indicate that this group implements this interface; load if necessary * if not in the nameToInterfaceMap. */ public void implementInterface(String interfaceName) { StringTemplateGroupInterface I = (StringTemplateGroupInterface)nameToInterfaceMap.get(interfaceName); if ( I!=null ) { // we've seen before; just use it implementInterface(I); return; } I = loadInterface(interfaceName); // else load it if ( I!=null ) { nameToInterfaceMap.put(interfaceName, I); implementInterface(I); } else { if ( groupLoader==null ) { listener.error("no group loader registered", null); } } } public StringTemplateGroup getSuperGroup() { return superGroup; } /** Walk up group hierarchy and show top down to this group */ public String getGroupHierarchyStackString() { List groupNames = new LinkedList(); StringTemplateGroup p = this; while ( p!=null ) { groupNames.add(0,p.name); p = p.superGroup; } return groupNames.toString().replaceAll(",",""); } public String getRootDir() { return rootDir; } public void setRootDir(String rootDir) { this.rootDir = rootDir; } /** StringTemplate object factory; each group can have its own. */ public StringTemplate createStringTemplate() { StringTemplate st = new StringTemplate(); return st; } /** A support routine that gets an instance of name knowing which * ST encloses it for error messages. */ protected StringTemplate getInstanceOf(StringTemplate enclosingInstance, String name) throws IllegalArgumentException { //System.out.println("getInstanceOf("+getName()+"::"+name+")"); StringTemplate st = lookupTemplate(enclosingInstance,name); if ( st!=null ) { StringTemplate instanceST = st.getInstanceOf(); return instanceST; } return null; } /** The primary means of getting an instance of a template from this * group. */ public StringTemplate getInstanceOf(String name) { return getInstanceOf(null, name); } /** The primary means of getting an instance of a template from this * group when you have a predefined set of attributes you want to * use. */ public StringTemplate getInstanceOf(String name, Map attributes) { StringTemplate st = getInstanceOf(name); st.attributes = attributes; return st; } public StringTemplate getEmbeddedInstanceOf(StringTemplate enclosingInstance, String name) throws IllegalArgumentException { /* System.out.println("surrounding group is "+ enclosingInstance.getGroup().getName()+ " with native group "+enclosingInstance.getNativeGroup().getName()); */ StringTemplate st = null; // TODO: seems like this should go into lookupTemplate if ( name.startsWith("super.") ) { // for super.foo() refs, ensure that we look at the native // group for the embedded instance not the current evaluation // group (which is always pulled down to the original group // from which somebody did group.getInstanceOf("foo"); st = enclosingInstance.getNativeGroup().getInstanceOf(enclosingInstance, name); } else { st = getInstanceOf(enclosingInstance, name); } // make sure all embedded templates have the same group as enclosing // so that polymorphic refs will start looking at the original group st.setGroup(this); st.setEnclosingInstance(enclosingInstance); return st; } /** Get the template called 'name' from the group. If not found, * attempt to load. If not found on disk, then try the superGroup * if any. If not even there, then record that it's * NOT_FOUND so we don't waste time looking again later. If we've gone * past refresh interval, flush and look again. * * If I find a template in a super group, copy an instance down here */ public synchronized StringTemplate lookupTemplate(StringTemplate enclosingInstance, String name) throws IllegalArgumentException { //System.out.println("look up "+getName()+"::"+name); if ( name.startsWith("super.") ) { if ( superGroup!=null ) { int dot = name.indexOf('.'); name = name.substring(dot+1,name.length()); StringTemplate superScopeST = superGroup.lookupTemplate(enclosingInstance,name); /* System.out.println("superScopeST is "+ superScopeST.getGroup().getName()+"::"+name+ " with native group "+superScopeST.getNativeGroup().getName()); */ return superScopeST; } throw new IllegalArgumentException(getName()+ " has no super group; invalid template: "+name); } checkRefreshInterval(); StringTemplate st = (StringTemplate)templates.get(name); if ( st==null ) { // not there? Attempt to load if ( !templatesDefinedInGroupFile ) { // only check the disk for individual template st = loadTemplateFromBeneathRootDirOrCLASSPATH(getFileNameFromTemplateName(name)); } if ( st==null && superGroup!=null ) { // try to resolve in super group st = superGroup.getInstanceOf(name); // make sure that when we inherit a template, that it's // group is reset; it's nativeGroup will remain where it was if ( st!=null ) { st.setGroup(this); } } if ( st!=null ) { // found in superGroup // insert into this group; refresh will allow super // to change it's def later or this group to add // an override. templates.put(name, st); } else { // not found; remember that this sucker doesn't exist templates.put(name, NOT_FOUND_ST); String context = ""; if ( enclosingInstance!=null ) { context = "; context is "+ enclosingInstance.getEnclosingInstanceStackString(); } String hier = getGroupHierarchyStackString(); context += "; group hierarchy is "+hier; throw new IllegalArgumentException("Can't find template "+ getFileNameFromTemplateName(name)+ context); } } else if ( st==NOT_FOUND_ST ) { return null; } //System.out.println("lookup found "+st.getGroup().getName()+"::"+st.getName()); return st; } public StringTemplate lookupTemplate(String name) { return lookupTemplate(null, name); } protected void checkRefreshInterval() { if ( templatesDefinedInGroupFile ) { return; } boolean timeToFlush=refreshIntervalInSeconds==0 || (System.currentTimeMillis()-lastCheckedDisk)>=refreshIntervalInSeconds*1000; if ( timeToFlush ) { // throw away all pre-compiled references templates.clear(); lastCheckedDisk = System.currentTimeMillis(); } } protected StringTemplate loadTemplate(String name, BufferedReader r) throws IOException { String line; String nl = System.getProperty("line.separator"); StringBuffer buf = new StringBuffer(300); while ((line = r.readLine()) != null) { buf.append(line); buf.append(nl); } // strip newlines etc.. from front/back since filesystem // may add newlines etc... String pattern = buf.toString().trim(); if ( pattern.length()==0 ) { error("no text in template '"+name+"'"); return null; } return defineTemplate(name, pattern); } /** Load a template whose name is derived from the template filename. * If there is no root directory, try to load the template from * the classpath. If there is a rootDir, try to load the file * from there. */ protected StringTemplate loadTemplateFromBeneathRootDirOrCLASSPATH(String fileName) { StringTemplate template = null; String name = getTemplateNameFromFileName(fileName); // if no rootDir, try to load as a resource in CLASSPATH if ( rootDir==null ) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); InputStream is = cl.getResourceAsStream(fileName); if ( is==null ) { cl = this.getClass().getClassLoader(); is = cl.getResourceAsStream(fileName); } if ( is==null ) { return null; } BufferedReader br = null; try { br = new BufferedReader(getInputStreamReader(is)); template = loadTemplate(name, br); } catch (IOException ioe) { error("Problem reading template file: "+fileName,ioe); } finally { if ( br!=null ) { try { br.close(); } catch (IOException ioe2) { error("Cannot close template file: "+fileName, ioe2); } } } return template; } // load via rootDir template = loadTemplate(name, rootDir+"/"+fileName); return template; } /** (public so that people can override behavior; not a general * purpose method) */ public String getFileNameFromTemplateName(String templateName) { return templateName+".st"; } /** Convert a filename relativePath/name.st to relativePath/name. * (public so that people can override behavior; not a general * purpose method) */ public String getTemplateNameFromFileName(String fileName) { String name = fileName; int suffix = name.lastIndexOf(".st"); if ( suffix>=0 ) { name = name.substring(0, suffix); } return name; } protected StringTemplate loadTemplate(String name, String fileName) { BufferedReader br = null; StringTemplate template = null; try { InputStream fin = new FileInputStream(fileName); InputStreamReader isr = getInputStreamReader(fin); br = new BufferedReader(isr); template = loadTemplate(name, br); br.close(); br = null; } catch (IOException ioe) { if ( br!=null ) { try { br.close(); } catch (IOException ioe2) { error("Cannot close template file: "+fileName); } } } return template; } protected InputStreamReader getInputStreamReader(InputStream in) { InputStreamReader isr = null; try { isr = new InputStreamReader(in, fileCharEncoding); } catch (UnsupportedEncodingException uee) { error("Invalid file character encoding: "+fileCharEncoding); } return isr; } public String getFileCharEncoding() { return fileCharEncoding; } public void setFileCharEncoding(String fileCharEncoding) { this.fileCharEncoding = fileCharEncoding; } /** Define an examplar template; precompiled and stored * with no attributes. Remove any previous definition. */ public synchronized StringTemplate defineTemplate(String name, String template) { //System.out.println("defineTemplate "+getName()+"::"+name); if ( name!=null && name.indexOf('.')>=0 ) { throw new IllegalArgumentException("cannot have '.' in template names"); } StringTemplate st = createStringTemplate(); st.setName(name); st.setGroup(this); st.setNativeGroup(this); st.setTemplate(template); st.setErrorListener(listener); templates.put(name, st); return st; } /** Track all references to regions <@foo>...<@end> or <@foo()>. */ public StringTemplate defineRegionTemplate(String enclosingTemplateName, String regionName, String template, int type) { String mangledName = getMangledRegionName(enclosingTemplateName,regionName); StringTemplate regionST = defineTemplate(mangledName, template); regionST.setIsRegion(true); regionST.setRegionDefType(type); return regionST; } /** Track all references to regions <@foo>...<@end> or <@foo()>. */ public StringTemplate defineRegionTemplate(StringTemplate enclosingTemplate, String regionName, String template, int type) { StringTemplate regionST = defineRegionTemplate(enclosingTemplate.getOutermostName(), regionName, template, type); enclosingTemplate.getOutermostEnclosingInstance().addRegionName(regionName); return regionST; } /** Track all references to regions <@foo()>. We automatically * define as * * @enclosingtemplate.foo() ::= "" * * You cannot set these manually in the same group; you have to subgroup * to override. */ public StringTemplate defineImplicitRegionTemplate(StringTemplate enclosingTemplate, String name) { return defineRegionTemplate(enclosingTemplate, name, "", StringTemplate.REGION_IMPLICIT); } /** The "foo" of t() ::= "<@foo()>" is mangled to "region#t#foo" */ public String getMangledRegionName(String enclosingTemplateName, String name) { return "region__"+enclosingTemplateName+"__"+name; } /** Return "t" from "region__t__foo" */ public String getUnMangledTemplateName(String mangledName) { return mangledName.substring("region__".length(), mangledName.lastIndexOf("__")); } /** Make name and alias for target. Replace any previous def of name */ public synchronized StringTemplate defineTemplateAlias(String name, String target) { StringTemplate targetST=getTemplateDefinition(target); if ( targetST==null ){ error("cannot alias "+name+" to undefined template: "+target); return null; } templates.put(name, targetST); return targetST; } public synchronized boolean isDefinedInThisGroup(String name) { StringTemplate st = (StringTemplate)templates.get(name); if ( st!=null ) { if ( st.isRegion() ) { // don't allow redef of @t.r() ::= "..." or <@r>...<@end> if ( st.getRegionDefType()==StringTemplate.REGION_IMPLICIT ) { return false; } } return true; } return false; } /** Get the ST for 'name' in this group only */ public synchronized StringTemplate getTemplateDefinition(String name) { return (StringTemplate)templates.get(name); } /** Is there *any* definition for template 'name' in this template * or above it in the group hierarchy? */ public boolean isDefined(String name) { try { return lookupTemplate(name)!=null; } catch (IllegalArgumentException iae) { return false; } } protected void parseGroup(Reader r) { try { GroupLexer lexer = new GroupLexer(r); GroupParser parser = new GroupParser(lexer); parser.group(this); //System.out.println("read group\n"+this.toString()); } catch (Exception e) { String name = ""; if ( getName()!=null ) { name = getName(); } error("problem parsing group "+name+": "+e, e); } } /** verify that this group satisfies its interfaces */ protected void verifyInterfaceImplementations() { for (int i = 0; interfaces!=null && i < interfaces.size(); i++) { StringTemplateGroupInterface I = (StringTemplateGroupInterface)interfaces.get(i); List missing = I.getMissingTemplates(this); List mismatched = I.getMismatchedTemplates(this); if ( missing!=null ) { error("group "+getName()+" does not satisfy interface "+ I.getName()+": missing templates "+missing); } if ( mismatched!=null ) { error("group "+getName()+" does not satisfy interface "+ I.getName()+": mismatched arguments on these templates "+mismatched); } } } public int getRefreshInterval() { return refreshIntervalInSeconds; } /** How often to refresh all templates from disk. This is a crude * mechanism at the moment--just tosses everything out at this * frequency. Set interval to 0 to refresh constantly (no caching). * Set interval to a huge number like MAX_INT to have no refreshing * at all (DEFAULT); it will cache stuff. */ public void setRefreshInterval(int refreshInterval) { this.refreshIntervalInSeconds = refreshInterval; } public void setErrorListener(StringTemplateErrorListener listener) { this.listener = listener; } public StringTemplateErrorListener getErrorListener() { return listener; } /** Specify a StringTemplateWriter implementing class to use for * filtering output */ public void setStringTemplateWriter(Class c) { userSpecifiedWriter = c; } /** return an instance of a StringTemplateWriter that spits output to w. * If a writer is specified, use it instead of the default. */ public StringTemplateWriter getStringTemplateWriter(Writer w) { StringTemplateWriter stw = null; if ( userSpecifiedWriter!=null ) { try { Constructor ctor = userSpecifiedWriter.getConstructor(new Class[] {Writer.class}); stw = (StringTemplateWriter) ctor.newInstance(new Object[] {w}); } catch (Exception e) { error("problems getting StringTemplateWriter",e); } } if ( stw==null ) { stw = new AutoIndentWriter(w); } return stw; } /** Specify a complete map of what object classes should map to which * renderer objects for every template in this group (that doesn't * override it per template). */ public void setAttributeRenderers(Map renderers) { this.attributeRenderers = renderers; } /** Register a renderer for all objects of a particular type for all * templates in this group. */ public void registerRenderer(Class attributeClassType, Object renderer) { if ( attributeRenderers==null ) { attributeRenderers = Collections.synchronizedMap(new HashMap()); } attributeRenderers.put(attributeClassType, renderer); } /** What renderer is registered for this attributeClassType for * this group? If not found, as superGroup if it has one. */ public AttributeRenderer getAttributeRenderer(Class attributeClassType) { if ( attributeRenderers==null ) { if ( superGroup==null ) { return null; // no renderers and no parent? Stop. } // no renderers; consult super group return superGroup.getAttributeRenderer(attributeClassType); } AttributeRenderer renderer = (AttributeRenderer)attributeRenderers.get(attributeClassType); if ( renderer==null ) { if ( superGroup!=null ) { // no renderer registered for this class, check super group renderer = superGroup.getAttributeRenderer(attributeClassType); } } return renderer; } /* public void cacheClassProperty(Class c, String propertyName, Member member) { Object key = new ClassPropCacheKey(c,propertyName); classPropertyCache.put(key,member); } public Member getCachedClassProperty(Class c, String propertyName) { Object key = new ClassPropCacheKey(c,propertyName); return (Member)classPropertyCache.get(key); } */ public Map getMap(String name) { if ( maps==null ) { if ( superGroup==null ) { return null; } return superGroup.getMap(name); } Map m = (Map)maps.get(name); if ( m==null && superGroup!=null ) { m = superGroup.getMap(name); } return m; } /** Define a map for this group; not thread safe...do not keep adding * these while you reference them. */ public void defineMap(String name, Map mapping) { maps.put(name, mapping); } public static void registerDefaultLexer(Class lexerClass) { defaultTemplateLexerClass = lexerClass; } public static void registerGroupLoader(StringTemplateGroupLoader loader) { groupLoader = loader; } public static StringTemplateGroup loadGroup(String name) { return loadGroup(name, null, null); } public static StringTemplateGroup loadGroup(String name, StringTemplateGroup superGroup) { return loadGroup(name, null, superGroup); } public static StringTemplateGroup loadGroup(String name, Class lexer, StringTemplateGroup superGroup) { if ( groupLoader!=null ) { return groupLoader.loadGroup(name, lexer, superGroup); } return null; } public static StringTemplateGroupInterface loadInterface(String name) { if ( groupLoader!=null ) { return groupLoader.loadInterface(name); } return null; } public void error(String msg) { error(msg, null); } public void error(String msg, Exception e) { if ( listener!=null ) { listener.error(msg,e); } else { System.err.println("StringTemplate: "+msg); if ( e!=null ) { e.printStackTrace(); } } } public synchronized Set getTemplateNames() { return templates.keySet(); } /** Indicate whether ST should emit ... * strings for debugging around output for templates from this group. */ public void emitDebugStartStopStrings(boolean emit) { this.debugTemplateOutput = emit; } public void doNotEmitDebugStringsForTemplate(String templateName) { if ( noDebugStartStopStrings==null ) { noDebugStartStopStrings = new HashSet(); } noDebugStartStopStrings.add(templateName); } public void emitTemplateStartDebugString(StringTemplate st, StringTemplateWriter out) throws IOException { if ( noDebugStartStopStrings==null || !noDebugStartStopStrings.contains(st.getName()) ) { String groupPrefix = ""; if ( !st.getName().startsWith("if") && !st.getName().startsWith("else") ) { if ( st.getNativeGroup()!=null ) { groupPrefix = st.getNativeGroup().getName()+"."; } else { groupPrefix = st.getGroup().getName()+"."; } } out.write("<"+groupPrefix +st.getName()+">"); } } public void emitTemplateStopDebugString(StringTemplate st, StringTemplateWriter out) throws IOException { if ( noDebugStartStopStrings==null || !noDebugStartStopStrings.contains(st.getName()) ) { String groupPrefix = ""; if ( !st.getName().startsWith("if") && !st.getName().startsWith("else") ) { if ( st.getNativeGroup()!=null ) { groupPrefix = st.getNativeGroup().getName()+"."; } else { groupPrefix = st.getGroup().getName()+"."; } } out.write(""); } } public String toString() { return toString(true); } public String toString(boolean showTemplatePatterns) { StringBuffer buf = new StringBuffer(); Set templateNameSet = templates.keySet(); List sortedNames = new ArrayList(templateNameSet); Collections.sort(sortedNames); Iterator iter = sortedNames.iterator(); buf.append("group "+getName()+";\n"); StringTemplate formalArgs = new StringTemplate("$args;separator=\",\"$"); while (iter.hasNext()) { String tname = (String) iter.next(); StringTemplate st = (StringTemplate)templates.get(tname); if ( st!=NOT_FOUND_ST ) { formalArgs = formalArgs.getInstanceOf(); formalArgs.setAttribute("args", st.getFormalArguments()); buf.append(tname+"("+formalArgs+")"); if ( showTemplatePatterns ) { buf.append(" ::= <<"); buf.append(st.getTemplate()); buf.append(">>\n"); } else { buf.append('\n'); } } } return buf.toString(); } } stringtemplate-3.2.1/src/org/antlr/stringtemplate/AttributeRenderer.java0000644000175000017500000000453311256235341026561 0ustar twernertwerner/* [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; /** This interface describes an object that knows how to format or otherwise * render an object appropriately. Usually this is used for locale changes * for objects such as Date and floating point numbers... You can either * have an object that is sensitive to the locale or have a different object * per locale. * * Each template may have a renderer for each object type or can default * to the group's renderer or the super group's renderer if the group doesn't * have one. * * The toString(Object,String) method is used when the user uses the * format option: $o; format="f"$. It checks the formatName and applies the * appropriate formatting. If the format string passed to the renderer is * not recognized then simply call toString(). @since 3.1 */ public interface AttributeRenderer { public String toString(Object o); public String toString(Object o, String formatName); } stringtemplate-3.2.1/src/org/antlr/stringtemplate/misc/0000755000175000017500000000000011256235341023212 5ustar twernertwernerstringtemplate-3.2.1/src/org/antlr/stringtemplate/misc/JTreeStringTemplateModel.java0000644000175000017500000002657311256235341030747 0ustar twernertwerner/* [Adapted from 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.misc; import antlr.collections.AST; import javax.swing.event.*; import javax.swing.tree.*; import org.antlr.stringtemplate.StringTemplate; import org.antlr.stringtemplate.StringTemplateGroup; import org.antlr.stringtemplate.language.*; import java.util.*; import java.lang.reflect.Constructor; /** A model that pulls data from a string template hierarchy. This code * is extremely ugly! */ public class JTreeStringTemplateModel implements TreeModel { static Map classNameToWrapperMap = new HashMap(); static { classNameToWrapperMap.put("org.antlr.stringtemplate.StringTemplate", StringTemplateWrapper.class); classNameToWrapperMap.put("org.antlr.stringtemplate.language.ASTExpr", ExprWrapper.class); classNameToWrapperMap.put("java.util.Hashtable", HashMapWrapper.class); classNameToWrapperMap.put("java.util.ArrayList", ListWrapper.class); classNameToWrapperMap.put("java.util.Vector", ListWrapper.class); } static abstract class Wrapper { public abstract int getChildCount(Object parent); public abstract int getIndexOfChild(Object parent, Object child); public abstract Object getChild(Object parent, int index); public abstract Object getWrappedObject(); public boolean isLeaf(Object node) { return true; } } static class StringTemplateWrapper extends Wrapper { StringTemplate st = null; public StringTemplateWrapper(Object o) { this.st = (StringTemplate)o; } public Object getWrappedObject() { return getStringTemplate(); } public StringTemplate getStringTemplate() { return st; } public Object getChild(Object parent, int index) { StringTemplate st = ((StringTemplateWrapper)parent).getStringTemplate(); if ( index==0 ) { // System.out.println("chunk type index "+index+" is attributes"); // return attributes return new HashMapWrapper(st.getAttributes()); } Expr chunk = (Expr) st.getChunks().get(index-1); // System.out.println("chunk type index "+index+" is "+chunk.getClass().getName()); if ( chunk instanceof StringRef ) { return chunk; } return new ExprWrapper(chunk); } public int getChildCount(Object parent) { return st.getChunks().size()+1; // extra one is attribute list } public int getIndexOfChild(Object parent, Object child) { if ( child instanceof Wrapper ) { child = ((Wrapper)child).getWrappedObject(); } int index = st.getChunks().indexOf(child)+1; // System.out.println("index of "+child+" is "+index); return index; } public boolean isLeaf(Object node) { return false; } public String toString() { if ( st==null ) { return ""; } return st.getName(); } } static class ExprWrapper extends Wrapper { Expr expr = null; public ExprWrapper(Object o) { this.expr = (Expr)o; } public Expr getExpr() { return expr; } public Object getWrappedObject() { return expr; } public Object getChild(Object parent, int index) { Expr expr = ((ExprWrapper)parent).getExpr(); if ( expr instanceof ConditionalExpr ) { // System.out.println("return wrapped subtemplate"); return new StringTemplateWrapper( ((ConditionalExpr)expr).getSubtemplate() ); } if ( expr instanceof ASTExpr ) { ASTExpr astExpr = (ASTExpr)expr; AST root = astExpr.getAST(); if ( root.getType()== ActionEvaluatorTokenTypes.INCLUDE ) { switch (index) { case 0 : return root.getFirstChild().getNextSibling().toStringList(); case 1 : String templateName = root.getFirstChild().getText(); StringTemplate enclosingST = expr.getEnclosingTemplate(); StringTemplateGroup group = enclosingST.getGroup(); StringTemplate embedded = group.getEmbeddedInstanceOf(enclosingST, templateName); return new StringTemplateWrapper(embedded); } } } return ""; } public int getChildCount(Object parent) { if ( expr instanceof ConditionalExpr ) { return 1; } AST tree = ((ASTExpr)expr).getAST(); if ( tree.getType()==ActionEvaluatorTokenTypes.INCLUDE ) { return 2; // one for args and one for template } return 0; } public int getIndexOfChild(Object parent, Object child) { //System.out.println("Get index of child of "+parent.getClass().getName()); if ( expr instanceof ConditionalExpr ) { return 0; } return -1; } public boolean isLeaf(Object node) { if ( expr instanceof ConditionalExpr ) { return false; } if ( expr instanceof ASTExpr ) { AST tree = ((ASTExpr)expr).getAST(); if ( tree.getType()==ActionEvaluatorTokenTypes.INCLUDE ) { return false; } } return true; } /** Display different things depending on the ASTExpr type */ public String toString() { if ( expr instanceof ASTExpr ) { AST tree = ((ASTExpr)expr).getAST(); if ( tree.getType()==ActionEvaluatorTokenTypes.INCLUDE ) { return "$include$"; } return "$"+((ASTExpr)expr).getAST().toStringList()+"$"; } if ( expr instanceof StringRef ) { return expr.toString(); } return ""; } } static class ListWrapper extends Wrapper { List v = null; public ListWrapper(Object o) { v = (List)o; } public int getChildCount(Object parent) { return v.size(); } public int getIndexOfChild(Object parent, Object child) { if ( child instanceof Wrapper ) { child = ((Wrapper)child).getWrappedObject(); } return v.indexOf(child); } public Object getChild(Object parent, int index) { return v.get(index); } public Object getWrappedObject() { return v; } public boolean isLeaf(Object node) { return false; } } /** Wrap an entry in a map so that name appears as the root and the value * appears as the child or children. */ static class MapEntryWrapper extends Wrapper { Object key, value; public MapEntryWrapper(Object key, Object value) { this.key = key; this.value = value; } public Object getWrappedObject() { return wrap(value); } public int getChildCount(Object parent) { if ( value instanceof Wrapper ) { return ((Wrapper)value).getChildCount(value); } return 1; } public int getIndexOfChild(Object parent, Object child) { if ( value instanceof Wrapper ) { return ((Wrapper)value).getIndexOfChild(value, child); } return 0; } public Object getChild(Object parent, int index) { if ( value instanceof Wrapper ) { return ((Wrapper)value).getChild(value, index); } return value; } public boolean isLeaf(Object node) { return false; } public String toString() { return key.toString(); } } static class HashMapWrapper extends Wrapper { HashMap table; public HashMapWrapper(Object o) { this.table = (HashMap)o; } public Object getWrappedObject() { return table; } public Object getChild(Object parent, int index) { List attributes = getTableAsListOfKeys(); String key = (String)attributes.get(index); Object attr = table.get(key); Object wrappedAttr = wrap(attr); return new MapEntryWrapper(key, wrappedAttr); } public int getChildCount(Object parent) { List attributes = getTableAsListOfKeys(); return attributes.size(); } public int getIndexOfChild(Object parent, Object child) { List attributes = getTableAsListOfKeys(); return attributes.indexOf(child); } public boolean isLeaf(Object node) { return false; } public String toString() { return "attributes"; } private List getTableAsListOfKeys() { if ( table==null ) { return new LinkedList(); } Set keys = table.keySet(); List v = new LinkedList(); for (Iterator itr = keys.iterator(); itr.hasNext();) { String attributeName = (String) itr.next(); v.add(attributeName); } return v; } } Wrapper root = null; /** Get a wrapper object by adding "Wrapper" to class name. * If not present, return the object. */ public static Object wrap(Object o) { Object wrappedObject = o; Class wrapperClass = null; try { wrapperClass = (Class)classNameToWrapperMap.get(o.getClass().getName()); Constructor ctor = wrapperClass.getConstructor(new Class[]{Object.class}); wrappedObject = ctor.newInstance(new Object[] {o}); } catch (Exception e) { // some problem...oh well, just use the object ; } return wrappedObject; } public JTreeStringTemplateModel(StringTemplate st) { if (st == null) { throw new IllegalArgumentException("root is null"); } root = new StringTemplateWrapper(st); } public void addTreeModelListener(TreeModelListener l) { } /** Get a child object. If Conditional then return subtemplate. * If ASTExpr and INCLUDE then return ith chunk of sub StringTemplate */ public Object getChild(Object parent, int index) { //System.out.println("Get index "+index+" of "+parent.toString()+":"+parent.getClass().getName()); if (parent == null) { return null; } return ((Wrapper)parent).getChild(parent, index); } public int getChildCount(Object parent) { if (parent == null) { throw new IllegalArgumentException("root is null"); } return ((Wrapper)parent).getChildCount(parent); } public int getIndexOfChild(Object parent, Object child) { if (parent == null || child == null) { throw new IllegalArgumentException("root or child is null"); } return ((Wrapper)parent).getIndexOfChild(parent,child); } public Object getRoot() { return root; } public boolean isLeaf(Object node) { if (node == null) { throw new IllegalArgumentException("node is null"); } if ( node instanceof Wrapper ) { return ((Wrapper)node).isLeaf(node); } return true; } public void removeTreeModelListener(TreeModelListener l) { } public void valueForPathChanged(TreePath path, Object newValue) { System.out.println("heh, who is calling this mystery method?"); } } stringtemplate-3.2.1/src/org/antlr/stringtemplate/misc/JTreeStringTemplatePanel.java0000644000175000017500000000436411256235341030740 0ustar twernertwerner/* [Adapted from 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.misc; import java.awt.*; import javax.swing.*; import javax.swing.tree.*; import javax.swing.event.*; public class JTreeStringTemplatePanel extends JPanel { JTree tree; public JTreeStringTemplatePanel(TreeModel tm, TreeSelectionListener listener) { // use a layout that will stretch tree to panel size setLayout(new BorderLayout()); // Create tree tree = new JTree(tm); // Change line style tree.putClientProperty("JTree.lineStyle", "Angled"); // Add TreeSelectionListener if (listener != null) tree.addTreeSelectionListener(listener); // Put tree in a scrollable pane's viewport JScrollPane sp = new JScrollPane(); sp.getViewport().add(tree); add(sp, BorderLayout.CENTER); } } stringtemplate-3.2.1/src/org/antlr/stringtemplate/misc/StringTemplateTreeView.java0000644000175000017500000000714711256235341030503 0ustar twernertwerner/* [Adapted from 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.misc; import org.antlr.stringtemplate.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.tree.*; /** This class visually illustrates a StringTemplate instance including * the chunks (text + expressions) and the attributes table. It correctly * handles nested templates and so on. A prototype really, but may prove * useful for debugging StringTemplate applications. Use it like this: * *

     *  StringTemplate st = ...;
     *  StringTemplateTreeView viz =
     *  		new StringTemplateTreeView("sample",st);
     *  viz.setVisible(true);
     * 
    */ public class StringTemplateTreeView extends JFrame { // The initial width and height of the frame static final int WIDTH = 200; static final int HEIGHT = 300; public StringTemplateTreeView(String label, StringTemplate st) { super(label); JTreeStringTemplatePanel tp = new JTreeStringTemplatePanel(new JTreeStringTemplateModel(st), null); Container content = getContentPane(); content.add(tp, BorderLayout.CENTER); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { Frame f = (Frame)e.getSource(); f.setVisible(false); f.dispose(); // System.exit(0); } }); setSize(WIDTH, HEIGHT); } public static void main(String args[]) { StringTemplateGroup group = new StringTemplateGroup("dummy"); StringTemplate bold = group.defineTemplate("bold", "$attr$"); StringTemplate banner = group.defineTemplate("banner", "the banner"); StringTemplate st = new StringTemplate( group, "\n" + // doesn't like the first < and doesn't show :( "$banner(a=b)$"+ "

    $name$:$email$"+ "$if(member)$$fontTag$member$endif$" ); st.setAttribute("name", "Terence"); st.setAttribute("name", "Tom"); st.setAttribute("email", "parrt@cs.usfca.edu"); st.setAttribute("templateAttr", bold); StringTemplateTreeView frame = new StringTemplateTreeView("StringTemplate JTree Example", st); frame.setVisible(true); } } stringtemplate-3.2.1/src/org/antlr/stringtemplate/NoIndentWriter.java0000644000175000017500000000340211256235341026034 0ustar twernertwerner/* [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.Writer; import java.io.IOException; /** Just pass through the text */ public class NoIndentWriter extends AutoIndentWriter { public NoIndentWriter(Writer out) { super(out); } public int write(String str) throws IOException { out.write(str); return str.length(); } } stringtemplate-3.2.1/src/org/antlr/stringtemplate/language/0000755000175000017500000000000011274602736024050 5ustar twernertwernerstringtemplate-3.2.1/src/org/antlr/stringtemplate/language/StringRef.java0000644000175000017500000000453311256235341026615 0ustar twernertwerner/* [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.language; import org.antlr.stringtemplate.StringTemplate; import org.antlr.stringtemplate.StringTemplateWriter; import java.io.IOException; /** Represents a chunk of just simple text to spit out; nothing to "evaluate" */ public class StringRef extends Expr { String str; public StringRef(StringTemplate enclosingTemplate, String str) { super(enclosingTemplate); this.str = str; } /** Just print out the string; no reference to self because this * is a literal--not sensitive to attribute values. These strings * never wrap because they are not part of an <...> expression. * <"foo"; wrap="\n"> should wrap though if necessary. */ public int write(StringTemplate self, StringTemplateWriter out) throws IOException { if ( str!=null ) { int n = out.write(str); return n; } return 0; } public String toString() { if ( str!=null ) { return str; } return ""; } } stringtemplate-3.2.1/src/org/antlr/stringtemplate/language/interface.g0000644000175000017500000000705711256235341026163 0ustar twernertwernerheader { /* [The "BSD licence"] Copyright (c) 2003-2004 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.language; import org.antlr.stringtemplate.*; import java.util.*; } /** Match an ST group interface. Just a list of template names with args. * Here is a sample interface file: * * interface nfa; * nfa(states,edges); * optional state(name); */ class InterfaceParser extends Parser; options { k=3; } { protected StringTemplateGroupInterface groupI; public void reportError(RecognitionException e) { if ( groupI!=null ) { groupI.error("template group interface parse error", e); } else { System.err.println("template group interface parse error: "+e); e.printStackTrace(System.err); } } } groupInterface[StringTemplateGroupInterface groupI] {this.groupI = groupI;} : "interface" name:ID {groupI.setName(name.getText());} SEMI ( template[groupI] )+ ; template[StringTemplateGroupInterface groupI] { LinkedHashMap formalArgs = new LinkedHashMap(); // leave blank if no args String templateName=null; } : (opt:"optional")? name:ID LPAREN (formalArgs=args)? RPAREN SEMI { templateName = name.getText(); groupI.defineTemplate(templateName, formalArgs, opt!=null); } ; args returns [LinkedHashMap args=new LinkedHashMap()] : a:ID {args.put(a.getText(), new FormalArgument(a.getText()));} ( COMMA b:ID {args.put(b.getText(), new FormalArgument(b.getText()));} )* ; class InterfaceLexer extends Lexer; options { k=2; charVocabulary = '\u0000'..'\uFFFE'; } ID : ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'-'|'_')* ; LPAREN: '(' ; RPAREN: ')' ; COMMA: ',' ; SEMI: ';' ; COLON: ':' ; // Single-line comments SL_COMMENT : "//" (~('\n'|'\r'))* (('\r')? '\n')? {$setType(Token.SKIP); newline();} ; // multiple-line comments ML_COMMENT : "/*" ( options { greedy=false; } : ('\r')? '\n' {newline();} | . )* "*/" {$setType(Token.SKIP);} ; // Whitespace -- ignored WS : ( ' ' | '\t' | '\f' | ('\r')? '\n' { newline(); } )+ { $setType(Token.SKIP); } ; stringtemplate-3.2.1/src/org/antlr/stringtemplate/language/ArrayIterator.java0000644000175000017500000000147211256235341027501 0ustar twernertwernerpackage org.antlr.stringtemplate.language; import java.util.Iterator; import java.util.NoSuchElementException; import java.lang.reflect.Array; /** Iterator for an array so I don't have to copy the array to a List * just to make it iteratable. */ public class ArrayIterator implements Iterator { /** Index into the data array */ protected int i = -1; protected Object array = null; /** Arrays are fixed size; precompute. */ protected int n; public ArrayIterator(Object array) { this.array = array; n = Array.getLength(array); } public boolean hasNext() { return (i+1)0; } public Object next() { i++; // move to next element if ( i >= n ) { throw new NoSuchElementException(); } return Array.get(array, i); } public void remove() { throw new UnsupportedOperationException(); } } stringtemplate-3.2.1/src/org/antlr/stringtemplate/language/Cat.java0000644000175000017500000000216411256235341025417 0ustar twernertwernerpackage org.antlr.stringtemplate.language; import java.util.Iterator; import java.util.List; import java.util.AbstractList; import java.util.ArrayList; /** Given a list of attributes, return the combined elements in a list. */ public class Cat extends AbstractList { protected List elements; public Iterator iterator() { return super.iterator(); } public Object get(int index) { return elements.get(index); } public int size() { return elements.size(); } public Cat(List attributes) { elements = new ArrayList(); for (int i = 0; i < attributes.size(); i++) { Object attribute = (Object) attributes.get(i); attribute = ASTExpr.convertAnythingIteratableToIterator(attribute); if ( attribute instanceof Iterator ) { Iterator it = (Iterator)attribute; while (it.hasNext()) { Object o = (Object) it.next(); elements.add(o); } } else { elements.add(attribute); } } } public String toString() { StringBuffer buf = new StringBuffer(); for (int i = 0; i < elements.size(); i++) { Object o = (Object) elements.get(i); buf.append(o); } return buf.toString(); } } stringtemplate-3.2.1/src/org/antlr/stringtemplate/language/StringTemplateToken.java0000644000175000017500000000434111256235341030652 0ustar twernertwerner/* [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.language; import antlr.CommonToken; import java.util.List; public class StringTemplateToken extends CommonToken { /** Track any args for anonymous templates like * then }> * The lexer in action.g returns a single token ANONYMOUS_TEMPLATE * and so I need to have it parse args in the lexer and make them * available for when I build the anonymous template. */ public List args; public StringTemplateToken() { super(); } public StringTemplateToken(int type, String text) { super(type, text); } public StringTemplateToken(String text) { super(text); } public StringTemplateToken(int type, String text, List args) { super(type,text); this.args = args; } public String toString() { return super.toString()+"; args="+args; } } stringtemplate-3.2.1/src/org/antlr/stringtemplate/language/ChunkToken.java0000644000175000017500000000433711256235341026765 0ustar twernertwerner/* [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.language; import antlr.CommonToken; /** Tracks the various string and attribute chunks discovered * by the lexer. Subclassed CommonToken so that I could pass * the indentation to the parser, which will add it to the * ASTExpr created for the $...$ attribute reference. */ public class ChunkToken extends CommonToken { protected String indentation; public ChunkToken() { super(); } public ChunkToken(int type, String text, String indentation) { super(type,text); setIndentation(indentation); } public String getIndentation() { return indentation; } public void setIndentation(String indentation) { this.indentation = indentation; } public String toString() { return super.toString()+""; } } stringtemplate-3.2.1/src/org/antlr/stringtemplate/language/StringTemplateAST.java0000644000175000017500000000367611256235341030233 0ustar twernertwerner/* [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.language; import antlr.CommonAST; import org.antlr.stringtemplate.StringTemplate; public class StringTemplateAST extends CommonAST { protected StringTemplate st = null; // track template for ANONYMOUS blocks public StringTemplateAST() {;} public StringTemplateAST(int type, String text) { this.setType(type); this.setText(text); } public StringTemplate getStringTemplate() { return st; } public void setStringTemplate(StringTemplate st) { this.st = st; } } stringtemplate-3.2.1/src/org/antlr/stringtemplate/language/eval.g0000755000175000017500000002331411256235341025147 0ustar twernertwernerheader { /* [The "BSD licence"] Copyright (c) 2003-2004 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.language; import org.antlr.stringtemplate.*; import java.util.*; import java.io.*; import java.lang.reflect.*; } class ActionEvaluator extends TreeParser; options { importVocab=ActionParser; ASTLabelType = "org.antlr.stringtemplate.language.StringTemplateAST"; } { public static class NameValuePair { public String name; public Object value; }; protected StringTemplate self = null; protected StringTemplateWriter out = null; protected ASTExpr chunk = null; /** Create an evaluator using attributes from self */ public ActionEvaluator(StringTemplate self, ASTExpr chunk, StringTemplateWriter out) { this.self = self; this.chunk = chunk; this.out = out; } public void reportError(RecognitionException e) { self.error("eval tree parse error", e); } } action returns [int numCharsWritten=0] { Object e=null; } : e=expr {numCharsWritten = chunk.writeAttribute(self,e,out);} ; expr returns [Object value=null] { Object a=null, b=null, e=null; Map argumentContext=null; } : #(PLUS a=expr b=expr {value = chunk.add(a,b);}) | value=templateApplication | value=attribute | value=templateInclude | value=function | value=list | #(VALUE e=expr) // convert to string (force early eval) { StringWriter buf = new StringWriter(); StringTemplateWriter sw = self.getGroup().getStringTemplateWriter(buf); int n = chunk.writeAttribute(self,e,sw); if ( n > 0 ) { value = buf.toString(); } } ; /** create a new list of expressions as a new multi-value attribute */ list returns [Object value=null] { Object e = null; List elements = new ArrayList(); } : #( LIST ( e=expr { if ( e!=null ) { elements.add(e); } } | NOTHING { List nullSingleton = new ArrayList() {{add(null);}}; elements.add(nullSingleton.iterator()); // add a blank } )+ ) {value = new Cat(elements);} ; templateInclude returns [Object value=null] { StringTemplateAST args = null; String name = null; Object n = null; } : #( INCLUDE // {value = chunk.getTemplateInclude(self, name.getText(), #args);} ( id:ID a1:. {name=id.getText(); args=#a1;} | #( VALUE n=expr a2:. ) {if (n!=null) {name=n.toString();} args=#a2;} ) ) { if ( name!=null ) { value = chunk.getTemplateInclude(self, name, args); } } ; /** Apply template(s) to an attribute; can be applied to another apply * result. */ templateApplication returns [Object value=null] { Object a=null; Vector templatesToApply=new Vector(); List attributes = new ArrayList(); } : #( APPLY a=expr (template[templatesToApply])+ {value = chunk.applyListOfAlternatingTemplates(self,a,templatesToApply);} ) | #( MULTI_APPLY (a=expr {attributes.add(a);} )+ COLON anon:ANONYMOUS_TEMPLATE { StringTemplate anonymous = anon.getStringTemplate(); templatesToApply.addElement(anonymous); value = chunk.applyTemplateToListOfAttributes(self, attributes, anon.getStringTemplate()); } ) ; function returns [Object value=null] { Object a; } : #( FUNCTION ( "first" a=singleFunctionArg {value=chunk.first(a);} | "rest" a=singleFunctionArg {value=chunk.rest(a);} | "last" a=singleFunctionArg {value=chunk.last(a);} | "length" a=singleFunctionArg {value=chunk.length(a);} | "strip" a=singleFunctionArg {value=chunk.strip(a);} | "trunc" a=singleFunctionArg {value=chunk.trunc(a);} ) ) ; singleFunctionArg returns [Object value=null] : #( SINGLEVALUEARG value=expr ) ; template[Vector templatesToApply] { Map argumentContext = null; Object n = null; } : #( TEMPLATE ( t:ID args:. // don't eval argList now; must re-eval each iteration { String templateName = t.getText(); StringTemplateGroup group = self.getGroup(); StringTemplate embedded = group.getEmbeddedInstanceOf(self, templateName); if ( embedded!=null ) { embedded.setArgumentsAST(#args); templatesToApply.addElement(embedded); } } | anon:ANONYMOUS_TEMPLATE { StringTemplate anonymous = anon.getStringTemplate(); // to properly see overridden templates, always set // anonymous' group to be self's group anonymous.setGroup(self.getGroup()); templatesToApply.addElement(anonymous); } | #( VALUE n=expr args2:. { StringTemplate embedded = null; if ( n!=null ) { String templateName = n.toString(); StringTemplateGroup group = self.getGroup(); embedded = group.getEmbeddedInstanceOf(self, templateName); if ( embedded!=null ) { embedded.setArgumentsAST(#args2); templatesToApply.addElement(embedded); } } } ) ) ) ; ifCondition returns [boolean value=false] { Object a=null, b=null; } : a=ifAtom {value = chunk.testAttributeTrue(a);} | #(NOT a=ifAtom) {value = !chunk.testAttributeTrue(a);} ; ifAtom returns [Object value=null] : value=expr ; attribute returns [Object value=null] { Object obj = null; Object propName = null; Object e = null; } : #( DOT obj=expr ( prop:ID {propName = prop.getText();} // don't force early eval here in case it's a map // we need the right type on the key. // E.g., :}> // If aMap has Integer keys, can't convert k to string then lookup. | #(VALUE e=expr) {if (e!=null) {propName=e;}} ) ) {value = chunk.getObjectProperty(self,obj,propName);} | i3:ID { value=self.getAttribute(i3.getText()); } | i:INT {value=new Integer(i.getText());} | s:STRING { value=s.getText(); } | at:ANONYMOUS_TEMPLATE { value=at.getText(); if ( at.getText()!=null ) { StringTemplate valueST =new StringTemplate(self.getGroup(), at.getText()); valueST.setEnclosingInstance(self); valueST.setName(""); value = valueST; } } ; /** self is assumed to be the enclosing context as foo(x=y) must find y in * the template that encloses the ref to foo(x=y). We must pass in * the embedded template (the one invoked) so we can check formal args * in rawSetArgumentAttribute. */ argList[StringTemplate embedded, Map initialContext] returns [Map argumentContext=null] { argumentContext = initialContext; if ( argumentContext==null ) { argumentContext=new HashMap(); } } : #( ARGS (argumentAssignment[embedded,argumentContext])* ) | singleTemplateArg[embedded,argumentContext] ; singleTemplateArg[StringTemplate embedded, Map argumentContext] { Object e = null; } : #( SINGLEVALUEARG e=expr ) { if ( e!=null ) { String soleArgName = null; // find the sole defined formal argument for embedded boolean error = false; Map formalArgs = embedded.getFormalArguments(); if ( formalArgs!=null ) { Set argNames = formalArgs.keySet(); if ( argNames.size()==1 ) { soleArgName = (String)argNames.toArray()[0]; //System.out.println("sole formal arg of "+embedded.getName()+" is "+soleArgName); } else { error=true; } } else { error=true; } if ( error ) { self.error("template "+embedded.getName()+ " must have exactly one formal arg in template context "+ self.getEnclosingInstanceStackString()); } else { self.rawSetArgumentAttribute(embedded,argumentContext,soleArgName,e); } } } ; argumentAssignment[StringTemplate embedded, Map argumentContext] { Object e = null; } : #( ASSIGN arg:ID e=expr ) { if ( e!=null ) { self.rawSetArgumentAttribute(embedded,argumentContext,arg.getText(),e); } } | DOTDOTDOT {embedded.setPassThroughAttributes(true);} ; stringtemplate-3.2.1/src/org/antlr/stringtemplate/language/NewlineRef.java0000644000175000017500000000366111256235341026751 0ustar twernertwerner/* [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.language; import org.antlr.stringtemplate.*; import org.antlr.stringtemplate.language.Expr; import org.antlr.stringtemplate.StringTemplate; import java.io.Writer; import java.io.IOException; /** Represents a newline. Separated so I can do smart things like not * spitting out newlines when the only thing on a line is an attr expr. */ public class NewlineRef extends StringRef { public NewlineRef(StringTemplate enclosingTemplate, String str) { super(enclosingTemplate, str); } } stringtemplate-3.2.1/src/org/antlr/stringtemplate/language/action.g0000755000175000017500000002015211256235341025472 0ustar twernertwernerheader { /* [The "BSD licence"] Copyright (c) 2003-2004 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.language; import org.antlr.stringtemplate.*; import java.util.*; } /** Parse the individual attribute expressions */ class ActionParser extends Parser; options { k = 2; buildAST = true; ASTLabelType = "org.antlr.stringtemplate.language.StringTemplateAST"; } tokens { APPLY; // template application MULTI_APPLY; // parallel array template application ARGS; // subtree is a list of (possibly empty) arguments INCLUDE;// isolated template include (no attribute) CONDITIONAL="if"; VALUE; // used for (foo): #(VALUE foo) TEMPLATE; FUNCTION; SINGLEVALUEARG; LIST; // [a,b,c] NOTHING; // empty list element [a, ,c] } { protected StringTemplate self = null; public ActionParser(TokenStream lexer, StringTemplate self) { this(lexer, 2); this.self = self; } public void reportError(RecognitionException e) { StringTemplateGroup group = self.getGroup(); if ( group==StringTemplate.defaultGroup ) { self.error("action parse error; template context is "+self.getEnclosingInstanceStackString(), e); } else { self.error("action parse error in group "+self.getGroup().getName()+" line "+self.getGroupFileLine()+"; template context is "+self.getEnclosingInstanceStackString(), e); } } } action returns [Map opts=null] : templatesExpr (SEMI! opts=optionList)? | "if"^ LPAREN! ifCondition RPAREN! | "elseif"! LPAREN! ifCondition RPAREN! // return just conditional ; optionList! returns [Map opts=new HashMap()] : option[opts] (COMMA option[opts])* ; option[Map opts] { Object v=null; } : i:ID ( ASSIGN e:nonAlternatingTemplateExpr {v=#e;} | {v=ASTExpr.EMPTY_OPTION;} ) {opts.put(#i.getText(),v);} ; templatesExpr : (parallelArrayTemplateApplication)=> parallelArrayTemplateApplication | expr ( c:COLON^ {#c.setType(APPLY);} template (COMMA! template)* )* ; parallelArrayTemplateApplication : expr (COMMA! expr)+ c:COLON anonymousTemplate {#parallelArrayTemplateApplication = #(#[MULTI_APPLY,"MULTI_APPLY"],parallelArrayTemplateApplication);} ; ifCondition : ifAtom | NOT^ ifAtom ; ifAtom : templatesExpr ; expr: primaryExpr (PLUS^ primaryExpr)* ; primaryExpr : (templateInclude)=>templateInclude // (see past parens to arglist) | atom ( DOT^ // ignore warning on DOT ID ( ID | valueExpr ) )* | function ( DOT^ ( ID | valueExpr ) )* | valueExpr | list ; valueExpr : eval:LPAREN^ templatesExpr RPAREN! {#eval.setType(VALUE); #eval.setText("value");} ; nonAlternatingTemplateExpr : expr ( c:COLON^ {#c.setType(APPLY);} template )* ; function : ( "first" | "rest" | "last" | "length" | "strip" | "trunc" ) singleArg {#function = #(#[FUNCTION],function);} ; template : ( namedTemplate // foo() | anonymousTemplate // {foo} ) {#template = #(#[TEMPLATE],template);} ; namedTemplate : ID argList | "super"! DOT! qid:ID {#qid.setText("super."+#qid.getText());} argList | indirectTemplate ; anonymousTemplate : t:ANONYMOUS_TEMPLATE { StringTemplate anonymous = new StringTemplate(); anonymous.setGroup(self.getGroup()); anonymous.setEnclosingInstance(self); anonymous.setTemplate(t.getText()); anonymous.defineFormalArguments(((StringTemplateToken)t).args); #t.setStringTemplate(anonymous); } ; atom: ID | STRING | INT | ANONYMOUS_TEMPLATE ; list: lb:LBRACK^ {#lb.setType(LIST); #lb.setText("value");} listElement (COMMA! listElement)* RBRACK! ; listElement : nonAlternatingTemplateExpr | {#listElement = #[NOTHING, "NOTHING"];} ; templateInclude : ( id:ID argList | "super"! DOT! qid:ID {#qid.setText("super."+#qid.getText());} argList | indirectTemplate ) {#templateInclude = #(#[INCLUDE,"include"], templateInclude);} ; /** Match (foo)() and (foo+".terse")() */ indirectTemplate! : LPAREN e:templatesExpr RPAREN args:argList {#indirectTemplate = #(#[VALUE,"value"],e,args);} ; argList :! LPAREN! RPAREN! {#argList = #[ARGS,"ARGS"];} // view() | (singleArg)=>singleArg // bold(name) | LPAREN! argumentAssignment (COMMA! argumentAssignment)* RPAREN! {#argList = #(#[ARGS,"ARGS"],#argList);} ; singleArg : LPAREN! nonAlternatingTemplateExpr RPAREN! {#singleArg = #(#[SINGLEVALUEARG,"SINGLEVALUEARG"],#singleArg);} ; argumentAssignment : ID ASSIGN^ nonAlternatingTemplateExpr | DOTDOTDOT ; class ActionLexer extends Lexer; options { k=2; charVocabulary = '\003'..'\uFFFE'; testLiterals=false; } ID options { testLiterals=true; } : ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_'|'/')* ; INT : ('0'..'9')+ ; STRING : '"'! (ESC_CHAR[true] | ~'"')* '"'! ; ANONYMOUS_TEMPLATE { List args=null; StringTemplateToken t = null; } : '{'! ( (TEMPLATE_ARGS)=> args=TEMPLATE_ARGS (options{greedy=true;}:WS_CHAR!)? { // create a special token to track args t = new StringTemplateToken(ANONYMOUS_TEMPLATE,$getText,args); $setToken(t); } | ) ('\\'! '{' | '\\'! '}' | ESC_CHAR[false] | NESTED_ANONYMOUS_TEMPLATE | ~'}')* { if ( t!=null ) { t.setText($getText); } } '}'! ; protected TEMPLATE_ARGS returns [List args=new ArrayList()] :! (WS_CHAR)? a:ID {args.add(a.getText());} (options{greedy=true;}:(WS_CHAR)? ',' (WS_CHAR)? a2:ID {args.add(a2.getText());})* (WS_CHAR)? '|' ; protected NESTED_ANONYMOUS_TEMPLATE : '{' ('\\'! '{' | '\\'! '}' | ESC_CHAR[false] | NESTED_ANONYMOUS_TEMPLATE | ~'}')* '}' ; /** Match escape sequences, optionally translating them for strings, but not * for templates. Do \} only when in {...} templates. */ protected ESC_CHAR[boolean doEscape] : '\\' ( options {generateAmbigWarnings=false;} // . ambig with others : 'n' {if (doEscape) { $setText("\n"); }} | 'r' {if (doEscape) { $setText("\r"); }} | 't' {if (doEscape) { $setText("\t"); }} | 'b' {if (doEscape) { $setText("\b"); }} | 'f' {if (doEscape) { $setText("\f"); }} | c:. {if (doEscape) {$setText(String.valueOf(c));}} ) ; LBRACK: '[' ; RBRACK: ']' ; LPAREN : '(' ; RPAREN : ')' ; COMMA : ',' ; DOT : '.' ; ASSIGN : '=' ; COLON : ':' ; PLUS : '+' ; SEMI : ';' ; NOT : '!' ; DOTDOTDOT : "..." ; WS : (' '|'\t'|'\r'|'\n'{newline();})+ {$setType(Token.SKIP);} ; protected WS_CHAR : ' '|'\t'|'\r'|'\n'{newline();} ; stringtemplate-3.2.1/src/org/antlr/stringtemplate/language/ConditionalExpr.java0000644000175000017500000001262311256235341030013 0ustar twernertwerner/* [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.language; import antlr.RecognitionException; import antlr.collections.AST; import org.antlr.stringtemplate.StringTemplate; import org.antlr.stringtemplate.StringTemplateWriter; import java.io.IOException; import java.util.List; import java.util.ArrayList; /** A conditional reference to an embedded subtemplate. */ public class ConditionalExpr extends ASTExpr { StringTemplate subtemplate = null; List elseIfSubtemplates = null; StringTemplate elseSubtemplate = null; protected static class ElseIfClauseData { ASTExpr expr; StringTemplate st; } public ConditionalExpr(StringTemplate enclosingTemplate, AST tree) { super(enclosingTemplate,tree,null); } public void setSubtemplate(StringTemplate subtemplate) { this.subtemplate = subtemplate; } public void addElseIfSubtemplate(final ASTExpr conditionalTree, final StringTemplate subtemplate) { if ( elseIfSubtemplates==null ) { elseIfSubtemplates = new ArrayList(); } ElseIfClauseData d = new ElseIfClauseData() {{ expr = conditionalTree; st = subtemplate; }}; elseIfSubtemplates.add(d); } public StringTemplate getSubtemplate() { return subtemplate; } public StringTemplate getElseSubtemplate() { return elseSubtemplate; } public void setElseSubtemplate(StringTemplate elseSubtemplate) { this.elseSubtemplate = elseSubtemplate; } /** To write out the value of a condition expr, invoke the evaluator in eval.g * to walk the condition tree computing the boolean value. If result * is true, then write subtemplate. */ public int write(StringTemplate self, StringTemplateWriter out) throws IOException { if ( exprTree==null || self==null || out==null ) { return 0; } // System.out.println("evaluating conditional tree: "+exprTree.toStringList()); ActionEvaluator eval = new ActionEvaluator(self,this,out); int n = 0; try { boolean testedTrue = false; // get conditional from tree and compute result AST cond = exprTree.getFirstChild(); boolean includeSubtemplate = eval.ifCondition(cond); // eval and write out tree // System.out.println("subtemplate "+subtemplate); // IF if ( includeSubtemplate ) { n = writeSubTemplate(self, out, subtemplate); testedTrue = true; } // ELSEIF else if ( elseIfSubtemplates!=null && elseIfSubtemplates.size()>0 ) { for (int i=0; i MISSING output not empty if ( !testedTrue && elseSubtemplate==null ) n = MISSING; } catch (RecognitionException re) { self.error("can't evaluate tree: "+exprTree.toStringList(), re); } return n; } protected int writeSubTemplate(StringTemplate self, StringTemplateWriter out, StringTemplate subtemplate) throws IOException { /* To evaluate the IF chunk, make a new instance whose enclosingInstance * points at 'self' so get attribute works. Otherwise, enclosingInstance * points at the template used to make the precompiled code. We need a * new template instance every time we exec this chunk to get the new * "enclosing instance" pointer. */ StringTemplate s = subtemplate.getInstanceOf(); s.setEnclosingInstance(self); // make sure we evaluate in context of enclosing template's // group so polymorphism works. :) s.setGroup(self.getGroup()); s.setNativeGroup(self.getNativeGroup()); return s.write(out); } } stringtemplate-3.2.1/src/org/antlr/stringtemplate/language/Expr.java0000644000175000017500000000616611256235341025634 0ustar twernertwerner/* [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.language; import org.antlr.stringtemplate.StringTemplate; import org.antlr.stringtemplate.StringTemplateGroup; import org.antlr.stringtemplate.StringTemplateWriter; import java.io.Writer; import java.io.IOException; import java.util.Hashtable; import java.util.Enumeration; /** A string template expression embedded within the template. * A template is parsed into a tokenized vector of Expr objects * and then executed after the user sticks in attribute values. * * This list of Expr objects represents a "program" for the StringTemplate * evaluator. */ abstract public class Expr { /** The StringTemplate object surrounding this expr */ protected StringTemplate enclosingTemplate; /** Any thing spit out as a chunk (even plain text) must be indented * according to whitespace before the action that generated it. So, * plain text in the outermost template is never indented, but the * text and attribute references in a nested template will all be * indented by the amount seen directly in front of the attribute * reference that initiates construction of the nested template. */ protected String indentation = null; public Expr(StringTemplate enclosingTemplate) { this.enclosingTemplate = enclosingTemplate; } /** How to write this node to output; return how many char written */ abstract public int write(StringTemplate self, StringTemplateWriter out) throws IOException; public StringTemplate getEnclosingTemplate() { return enclosingTemplate; } public String getIndentation() { return indentation; } public void setIndentation(String indentation) { this.indentation = indentation; } } stringtemplate-3.2.1/src/org/antlr/stringtemplate/language/FormalArgument.java0000644000175000017500000000552511256235341027637 0ustar twernertwernerpackage org.antlr.stringtemplate.language; import org.antlr.stringtemplate.StringTemplate; import java.util.HashMap; import java.util.Map; import java.util.List; import java.util.LinkedHashMap; /** Represents the name of a formal argument * defined in a template: * * group test; * test(a,b) : "$a$ $b$" * t() : "blort" * * Each template has a set of these formal arguments or uses * a placeholder object: UNKNOWN (indicating that no arguments * were specified such as when a template is loaded from a file.st). * * Note: originally, I tracked cardinality as well as the name of an * attribute. I'm leaving the code here as I suspect something may come * of it later. Currently, though, cardinality is not used. */ public class FormalArgument { // the following represent bit positions emulating a cardinality bitset. public static final int OPTIONAL = 1; // a? public static final int REQUIRED = 2; // a public static final int ZERO_OR_MORE = 4; // a* public static final int ONE_OR_MORE = 8; // a+ public static final String[] suffixes = { null, "?", "", null, "*", null, null, null, "+" }; /** When template arguments are not available such as when the user * uses "new StringTemplate(...)", then the list of formal arguments * must be distinguished from the case where a template can specify * args and there just aren't any such as the t() template above. */ public static final LinkedHashMap UNKNOWN = new LinkedHashMap(); public String name; //protected int cardinality = REQUIRED; /** If they specified name="value", store the template here */ public StringTemplate defaultValueST; public FormalArgument(String name) { this.name = name; } public FormalArgument(String name, StringTemplate defaultValueST) { this.name = name; this.defaultValueST = defaultValueST; } public static String getCardinalityName(int cardinality) { switch (cardinality) { case OPTIONAL : return "optional"; case REQUIRED : return "exactly one"; case ZERO_OR_MORE : return "zero-or-more"; case ONE_OR_MORE : return "one-or-more"; default : return "unknown"; } } public boolean equals(Object o) { if ( o==null || !(o instanceof FormalArgument) ) { return false; } FormalArgument other = (FormalArgument)o; if ( !this.name.equals(other.name) ) { return false; } // only check if there is a default value; that's all if ( (this.defaultValueST!=null && other.defaultValueST==null) || (this.defaultValueST==null && other.defaultValueST!=null) ) { return false; } return true; } public String toString() { if ( defaultValueST!=null ) { return name+"="+defaultValueST; } return name; } } stringtemplate-3.2.1/src/org/antlr/stringtemplate/language/angle.bracket.template.g0000644000175000017500000001660611256235341030535 0ustar twernertwernerheader { /* [The "BSD licence"] Copyright (c) 2003-2004 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.language; import org.antlr.stringtemplate.*; import java.io.*; } /** Break up an input text stream into chunks of either plain text * or template actions in "<...>". Treat IF and ENDIF tokens * specially. */ class AngleBracketTemplateLexer extends Lexer; options { importVocab=TemplateParser; k=7; // see "" charVocabulary = '\u0001'..'\uFFFE'; } { protected String currentIndent = null; protected StringTemplate self; public AngleBracketTemplateLexer(StringTemplate self, Reader r) { this(r); this.self = self; } public void reportError(RecognitionException e) { self.error("<...> chunk lexer error", e); } protected boolean upcomingELSE(int i) throws CharStreamException { return LA(i)=='<'&&LA(i+1)=='e'&&LA(i+2)=='l'&&LA(i+3)=='s'&&LA(i+4)=='e'&& LA(i+5)=='>'; } protected boolean upcomingENDIF(int i) throws CharStreamException { return LA(i)=='<'&&LA(i+1)=='e'&&LA(i+2)=='n'&&LA(i+3)=='d'&&LA(i+4)=='i'&& LA(i+5)=='f'&&LA(i+6)=='>'; } protected boolean upcomingAtEND(int i) throws CharStreamException { return LA(i)=='<'&&LA(i+1)=='@'&&LA(i+2)=='e'&&LA(i+3)=='n'&&LA(i+4)=='d'&&LA(i+5)=='>'; } protected boolean upcomingNewline(int i) throws CharStreamException { return (LA(i)=='\r'&&LA(i+1)=='\n')||LA(i)=='\n'; } } LITERAL : {LA(1)!='\r'&&LA(1)!='\n'}? ( options { generateAmbigWarnings=false; } { int loopStartIndex=text.length(); int col=getColumn(); } : '\\'! '<' // allow escaped delimiter | '\\'! '>' | '\\'! '\\' // always replace \\ with \ | '\\' ~('<'|'>') // otherwise ignore escape char | ind:INDENT { if ( col==1 && LA(1)=='<' ) { // store indent in ASTExpr not in a literal currentIndent=ind.getText(); text.setLength(loopStartIndex); // reset length to wack text } else currentIndent=null; } | ~('<'|'\r'|'\n') )+ {if (($getText).length()==0) {$setType(Token.SKIP);}} // pure indent? ; protected INDENT : ( options {greedy=true;}: ' ' | '\t')+ ; NEWLINE : ('\r')? '\n' {newline(); currentIndent=null;} ; ACTION options { generateAmbigWarnings=false; // is ambig with } { int startCol = getColumn(); } : LINE_BREAK {$setType(Token.SKIP);} | // Match escapes not in a string like <\n\ufea5> {StringBuffer buf = new StringBuffer(); char uc = '\u0000';} '<'! (uc=ESC_CHAR {buf.append(uc);} )+'>'! {$setText(buf.toString()); $setType(LITERAL);} | COMMENT {$setType(Token.SKIP);} | ( options { generateAmbigWarnings=false; // $EXPR$ is ambig with $endif$ etc... } : '<'! "if" (' '!)* "(" IF_EXPR ")" '>'! {$setType(TemplateParser.IF);} ( ('\r'!)? '\n'! {newline();})? // ignore any newline right after an IF | '<'! "elseif" (' '!)* "(" IF_EXPR ")" '>'! {$setType(TemplateParser.ELSEIF);} ( ('\r'!)? '\n'! {newline();})? // ignore any newline right after an IF | '<'! "else" '>'! {$setType(TemplateParser.ELSE);} ( ('\r'!)? '\n'! {newline();})? // ignore any newline right after an ELSE | '<'! "endif" '>'! {$setType(TemplateParser.ENDIF);} ( {startCol==1}? ('\r'!)? '\n'! {newline();})? // ignore after ENDIF if on line by itself | // match <@foo()> => foo // match <@foo>...<@end> => foo::=... '<'! '@'! (~('>'|'('))+ ( "()"! '>'! {$setType(TemplateParser.REGION_REF);} | '>'! { $setType(TemplateParser.REGION_DEF); String t=$getText; $setText(t+"::="); } ( options {greedy=true;} : ('\r'!)? '\n'! {newline();})? {boolean atLeft = false;} ( options {greedy=true;} // handle greedy=false with predicate : {!(upcomingAtEND(1)||(upcomingNewline(1)&&upcomingAtEND(2)))}? ( ('\r')? '\n' {newline(); atLeft = true;} | . {atLeft = false;} ) )+ ( ('\r'!)? '\n'! {newline(); atLeft = true;} )? ( "<@end>"! | . {self.error("missing region "+t+" <@end> tag");} ) ( {atLeft}? ('\r'!)? '\n'! {newline();})? ) | '<'! EXPR '>'! ) { ChunkToken t = new ChunkToken(_ttype, $getText, currentIndent); $setToken(t); } ; protected EXPR: ( ESC | ('\r')? '\n' {newline();} | SUBTEMPLATE | ('='|'+') TEMPLATE | ('='|'+') SUBTEMPLATE | ('='|'+') ~('"'|'<'|'{') | ~'>' )+ ; protected TEMPLATE : '"' ( ESC | ~'"' )* '"' | "<<" (options {greedy=true;}:('\r'!)?'\n'! {newline();})? // consume 1st \n ( options {greedy=false;} // stop when you see the >> : {LA(3)=='>'&&LA(4)=='>'}? '\r'! '\n'! {newline();} // kill last \r\n | {LA(2)=='>'&&LA(3)=='>'}? '\n'! {newline();} // kill last \n | ('\r')? '\n' {newline();} // else keep | . )* ">>" ; protected IF_EXPR:( ESC | ('\r')? '\n' {newline();} | SUBTEMPLATE | NESTED_PARENS | ~')' )+ ; protected ESC_CHAR returns [char uc='\u0000'] : "\\n"! {uc = '\n';} | "\\r"! {uc = '\r';} | "\\t"! {uc = '\t';} | "\\ "! {uc = ' ';} | "\\u"! a:HEX! b:HEX! c:HEX! d:HEX! {uc = (char)Integer.parseInt(a.getText()+b.getText()+c.getText()+d.getText(), 16);} ; // just used to skip stuff (not part of unicode escape stuff) protected ESC : '\\' . // ('<'|'>'|'n'|'t'|'"'|'\''|':'|'{'|'}'|'\\') ; protected HEX : '0'..'9'|'A'..'F'|'a'..'f' ; protected SUBTEMPLATE : '{' (SUBTEMPLATE|ESC|~'}')* '}' ; protected NESTED_PARENS : '(' (options {greedy=false;}:NESTED_PARENS|ESC|~')')+ ')' ; protected COMMENT { int startCol = getColumn(); } : "" ( {startCol==1}? ('\r')? '\n' {newline();} )? ; protected LINE_BREAK : "<\\\\>" (INDENT)? ('\r')? '\n' {newline();} (INDENT)? ; stringtemplate-3.2.1/src/org/antlr/stringtemplate/language/group.g0000644000175000017500000002064311256235341025353 0ustar twernertwernerheader { /* [The "BSD licence"] Copyright (c) 2003-2004 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.language; import org.antlr.stringtemplate.*; import java.util.*; } /** Match a group of template definitions beginning * with a group name declaration. Templates are enclosed * in double-quotes or <<...>> quotes for multi-line templates. * Template names have arg lists that indicate the cardinality * of the attribute: present, optional, zero-or-more, one-or-more. * Here is a sample group file: group nfa; // an NFA has edges and states nfa(states,edges) ::= << digraph NFA { rankdir=LR; } >> state(name) ::= "node [shape = circle]; ;" */ class GroupParser extends Parser; options { k=3; } { protected StringTemplateGroup group; public void reportError(RecognitionException e) { if ( group!=null ) { group.error("template group parse error", e); } else { System.err.println("template group parse error: "+e); e.printStackTrace(System.err); } } } group[StringTemplateGroup g] { this.group = g; } : "group" name:ID {g.setName(name.getText());} ( COLON s:ID {g.setSuperGroup(s.getText());} )? ( "implements" i:ID {g.implementInterface(i.getText());} (COMMA i2:ID {g.implementInterface(i2.getText());} )* )? SEMI ( template[g] | mapdef[g] )+ ; template[StringTemplateGroup g] { Map formalArgs = null; StringTemplate st = null; boolean ignore = false; String templateName=null; int line = LT(1).getLine(); } : ( AT scope:ID DOT region:ID { templateName=g.getMangledRegionName(scope.getText(),region.getText()); if ( g.isDefinedInThisGroup(templateName) ) { g.error("group "+g.getName()+" line "+line+": redefinition of template region: @"+ scope.getText()+"."+region.getText()); st = new StringTemplate(); // create bogus template to fill in } else { boolean err = false; // @template.region() ::= "..." StringTemplate scopeST = g.lookupTemplate(scope.getText()); if ( scopeST==null ) { g.error("group "+g.getName()+" line "+line+": reference to region within undefined template: "+ scope.getText()); err=true; } if ( !scopeST.containsRegionName(region.getText()) ) { g.error("group "+g.getName()+" line "+line+": template "+scope.getText()+" has no region called "+ region.getText()); err=true; } if ( err ) { st = new StringTemplate(); } else { st = g.defineRegionTemplate(scope.getText(), region.getText(), null, StringTemplate.REGION_EXPLICIT); } } } | name:ID {templateName = name.getText();} { if ( g.isDefinedInThisGroup(templateName) ) { g.error("redefinition of template: "+templateName); st = new StringTemplate(); // create bogus template to fill in } else { st = g.defineTemplate(templateName, null); } } ) {if ( st!=null ) {st.setGroupFileLine(line);}} LPAREN (args[st]|{st.defineEmptyFormalArgumentList();}) RPAREN DEFINED_TO_BE ( t:STRING {st.setTemplate(t.getText());} | bt:BIGSTRING {st.setTemplate(bt.getText());} ) | alias:ID DEFINED_TO_BE target:ID {g.defineTemplateAlias(alias.getText(), target.getText());} ; args[StringTemplate st] : arg[st] ( COMMA arg[st] )* ; arg[StringTemplate st] { StringTemplate defaultValue = null; } : name:ID ( ASSIGN s:STRING { defaultValue=new StringTemplate("$_val_$"); defaultValue.setAttribute("_val_", s.getText()); defaultValue.defineFormalArgument("_val_"); defaultValue.setName("<"+st.getName()+"'s arg "+name.getText()+" default value subtemplate>"); } | ASSIGN bs:ANONYMOUS_TEMPLATE { defaultValue=new StringTemplate(st.getGroup(), bs.getText()); defaultValue.setName("<"+st.getName()+"'s arg "+name.getText()+" default value subtemplate>"); } )? {st.defineFormalArgument(name.getText(), defaultValue);} ; /* suffix returns [int cardinality=FormalArgument.REQUIRED] : OPTIONAL {cardinality=FormalArgument.OPTIONAL;} | STAR {cardinality=FormalArgument.ZERO_OR_MORE;} | PLUS {cardinality=FormalArgument.ONE_OR_MORE;} | ; */ mapdef[StringTemplateGroup g] { Map m=null; } : name:ID DEFINED_TO_BE m=map { if ( g.getMap(name.getText())!=null ) { g.error("redefinition of map: "+name.getText()); } else if ( g.isDefinedInThisGroup(name.getText()) ) { g.error("redefinition of template as map: "+name.getText()); } else { g.defineMap(name.getText(), m); } } ; map returns [Map mapping=new HashMap()] : LBRACK mapPairs[mapping] RBRACK ; mapPairs [Map mapping] : keyValuePair[mapping] (COMMA keyValuePair[mapping])* (COMMA defaultValuePair[mapping])? | defaultValuePair[mapping] ; defaultValuePair[Map mapping] { StringTemplate v = null; } : "default" COLON v=keyValue {mapping.put(ASTExpr.DEFAULT_MAP_VALUE_NAME, v);} ; keyValuePair[Map mapping] { StringTemplate v = null; } : key:STRING COLON v=keyValue {mapping.put(key.getText(), v);} ; keyValue returns [StringTemplate value=null] : s1:BIGSTRING {value = new StringTemplate(group,s1.getText());} | s2:STRING {value = new StringTemplate(group,s2.getText());} | k:ID {k.getText().equals("key")}? {value = ASTExpr.MAP_KEY_VALUE;} | {value = null;} ; class GroupLexer extends Lexer; options { k=2; charVocabulary = '\u0000'..'\uFFFE'; testLiterals=false; } ID options { testLiterals=true; } : ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'-'|'_')* ; STRING : '"'! ( '\\'! '"' | '\\' ~'"' | ~'"' )* '"'! ; BIGSTRING : "<<"! (options {greedy=true;}:('\r'!)?'\n'! {newline();})? // consume 1st \n ( options {greedy=false;} // stop when you see the >> : {LA(3)=='>'&&LA(4)=='>'}? '\r'! '\n'! {newline();} // kill last \r\n | {LA(2)=='>'&&LA(3)=='>'}? '\n'! {newline();} // kill last \n | ('\r')? '\n' {newline();} // else keep | '\\'! '>' // \> escape | . )* ">>"! ; ANONYMOUS_TEMPLATE { List args=null; StringTemplateToken t = null; } : '{'! ( options {greedy=false;} // stop when you see the >> : ('\r')? '\n' {newline();} // else keep | '\\'! '}' // \} escape | . )* '}'! ; AT : '@' ; LPAREN: '(' ; RPAREN: ')' ; LBRACK: '[' ; RBRACK: ']' ; COMMA: ',' ; DOT: '.' ; DEFINED_TO_BE: "::=" ; SEMI: ';' ; COLON: ':' ; STAR: '*' ; PLUS: '+' ; ASSIGN: '=' ; OPTIONAL : '?' ; // Single-line comments SL_COMMENT : "//" (~('\n'|'\r'))* (('\r')? '\n')? {$setType(Token.SKIP); newline();} ; // multiple-line comments ML_COMMENT : "/*" ( options { greedy=false; } : ('\r')? '\n' {newline();} | . )* "*/" {$setType(Token.SKIP);} ; // Whitespace -- ignored WS : ( ' ' | '\t' | '\f' | ('\r')? '\n' { newline(); } )+ { $setType(Token.SKIP); } ; stringtemplate-3.2.1/src/org/antlr/stringtemplate/language/ASTExpr.java0000644000175000017500000012060311256235341026175 0ustar twernertwerner/* [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.language; import antlr.RecognitionException; import antlr.collections.AST; import org.antlr.stringtemplate.AttributeRenderer; import org.antlr.stringtemplate.StringTemplate; import org.antlr.stringtemplate.StringTemplateGroup; import org.antlr.stringtemplate.StringTemplateWriter; import java.io.IOException; import java.io.StringWriter; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; /** A single string template expression enclosed in $...; separator=...$ * parsed into an AST chunk to be evaluated. */ public class ASTExpr extends Expr { public static final int MISSING = -1; // writing -1 char means missing not empty public static final String DEFAULT_ATTRIBUTE_NAME = "it"; public static final String DEFAULT_ATTRIBUTE_NAME_DEPRECATED = "attr"; public static final String DEFAULT_INDEX_VARIABLE_NAME = "i"; public static final String DEFAULT_INDEX0_VARIABLE_NAME = "i0"; public static final String DEFAULT_MAP_VALUE_NAME = "_default_"; public static final String DEFAULT_MAP_KEY_NAME = "key"; /** Used to indicate "default:key" in maps within groups */ public static final StringTemplate MAP_KEY_VALUE = new StringTemplate(); /** Using an expr option w/o value, makes options table hold EMPTY_OPTION * value for that key. */ public static final String EMPTY_OPTION = "empty expr option"; public static final Map defaultOptionValues = new HashMap() { { put("anchor", new StringTemplateAST(ActionEvaluator.STRING,"true")); put("wrap", new StringTemplateAST(ActionEvaluator.STRING,"\n")); } }; /** John Snyders gave me an example implementation for this checking */ public static final Set supportedOptions = new HashSet() { { add("anchor"); add("format"); add("null"); add("separator"); add("wrap"); } }; AST exprTree = null; /** store separator etc... */ Map options = null; /** A cached value of wrap=expr from the <...> expression. * Computed in write(StringTemplate, StringTemplateWriter) and used * in writeAttribute. */ String wrapString = null; /** For null values in iterated attributes and single attributes that * are null, use this value instead of skipping. For single valued * attributes like it's a shorthand for * n/a * For iterated values , you get 0 for * for null list values. Works for template application like: * }; null="0"> also. */ String nullValue = null; /** A cached value of separator=expr from the <...> expression. * Computed in write(StringTemplate, StringTemplateWriter) and used * in writeAttribute. */ String separatorString = null; /** A cached value of option format=expr */ String formatString = null; public ASTExpr(StringTemplate enclosingTemplate, AST exprTree, Map options) { super(enclosingTemplate); this.exprTree = exprTree; this.options = options; } /** Return the tree interpreted when this template is written out. */ public AST getAST() { return exprTree; } /** To write out the value of an ASTExpr, invoke the evaluator in eval.g * to walk the tree writing out the values. For efficiency, don't * compute a bunch of strings and then pack them together. Write out directly. * * Compute separator and wrap expressions, save as strings so we don't * recompute for each value in a multi-valued attribute or expression. * * If they set anchor option, then inform the writer to push current * char position. */ public int write(StringTemplate self, StringTemplateWriter out) throws IOException { if ( exprTree==null || self==null || out==null ) { return 0; } // handle options, anchor, wrap, separator... StringTemplateAST anchorAST = (StringTemplateAST)getOption("anchor"); if ( anchorAST!=null ) { // any non-empty expr means true; check presence out.pushAnchorPoint(); } out.pushIndentation(getIndentation()); handleExprOptions(self); //System.out.println("evaluating tree: "+exprTree.toStringList()); ActionEvaluator eval = new ActionEvaluator(self,this,out); int n = 0; try { n = eval.action(exprTree); // eval and write out tree } catch (RecognitionException re) { self.error("can't evaluate tree: "+exprTree.toStringList(), re); } out.popIndentation(); if ( anchorAST!=null ) { out.popAnchorPoint(); } return n; } /** Grab and cache options; verify options are valid */ protected void handleExprOptions(StringTemplate self) { // make sure options don't use format / renderer. They are usually // strings which might invoke a string renderer etc... formatString = null; StringTemplateAST wrapAST = (StringTemplateAST)getOption("wrap"); if ( wrapAST!=null ) { wrapString = evaluateExpression(self,wrapAST); } StringTemplateAST nullValueAST = (StringTemplateAST)getOption("null"); if ( nullValueAST!=null ) { nullValue = evaluateExpression(self,nullValueAST); } StringTemplateAST separatorAST = (StringTemplateAST)getOption("separator"); if ( separatorAST!=null ) { separatorString = evaluateExpression(self, separatorAST); } // following addition inspired by John Snyders StringTemplateAST formatAST = (StringTemplateAST)getOption("format"); if ( formatAST!=null ) { formatString = evaluateExpression(self, formatAST); } // Check that option is valid if ( options != null ) { Iterator it = options.keySet().iterator(); while ( it.hasNext() ) { String option = (String)it.next(); if (!supportedOptions.contains(option)) { self.warning("ignoring unsupported option: "+option); } } } } // HELP ROUTINES CALLED BY EVALUATOR TREE WALKER /** For treat the names, phones as lists * to be walked in lock step as n=names[i], p=phones[i]. */ public Object applyTemplateToListOfAttributes(StringTemplate self, List attributes, StringTemplate templateToApply) { if ( attributes==null || templateToApply==null || attributes.size()==0 ) { return null; // do not apply if missing templates or empty values } Map argumentContext = null; // indicate it's an ST-created list List results = new StringTemplate.STAttributeList(); // convert all attributes to iterators even if just one value for (int a = 0; a < attributes.size(); a++) { Object o = (Object) attributes.get(a); if ( o!=null ) { o = convertAnythingToIterator(o); attributes.set(a, o); // alter the list in place } } int numAttributes = attributes.size(); // ensure arguments line up Map formalArguments = templateToApply.getFormalArguments(); if ( formalArguments==null || formalArguments.size()==0 ) { self.error("missing arguments in anonymous"+ " template in context "+self.getEnclosingInstanceStackString()); return null; } Object[] formalArgumentNames = formalArguments.keySet().toArray(); if ( formalArgumentNames.length!=numAttributes ) { self.error("number of arguments "+formalArguments.keySet()+ " mismatch between attribute list and anonymous"+ " template in context "+self.getEnclosingInstanceStackString()); // truncate arg list to match smaller size int shorterSize = Math.min(formalArgumentNames.length, numAttributes); numAttributes = shorterSize; Object[] newFormalArgumentNames = new Object[shorterSize]; System.arraycopy(formalArgumentNames, 0, newFormalArgumentNames, 0, shorterSize); formalArgumentNames = newFormalArgumentNames; } // keep walking while at least one attribute has values int i = 0; // iteration number from 0 while ( true ) { argumentContext = new HashMap(); // get a value for each attribute in list; put into arg context // to simulate template invocation of anonymous template int numEmpty = 0; for (int a = 0; a < numAttributes; a++) { Iterator it = (Iterator) attributes.get(a); if ( it!=null && it.hasNext() ) { String argName = (String)formalArgumentNames[a]; Object iteratedValue = it.next(); argumentContext.put(argName, iteratedValue); } else { numEmpty++; } } if ( numEmpty==numAttributes ) { break; } argumentContext.put(DEFAULT_INDEX_VARIABLE_NAME, new Integer(i+1)); argumentContext.put(DEFAULT_INDEX0_VARIABLE_NAME, new Integer(i)); StringTemplate embedded = templateToApply.getInstanceOf(); embedded.setEnclosingInstance(self); embedded.setArgumentContext(argumentContext); results.add(embedded); i++; } return results; } public Object applyListOfAlternatingTemplates(StringTemplate self, Object attributeValue, List templatesToApply) { if ( attributeValue==null || templatesToApply==null || templatesToApply.size()==0 ) { return null; // do not apply if missing templates or empty value } StringTemplate embedded = null; Map argumentContext = null; // normalize collections and such to use iterators // anything iteratable can be used for "APPLY" attributeValue = convertArrayToList(attributeValue); attributeValue = convertAnythingIteratableToIterator(attributeValue); if ( attributeValue instanceof Iterator ) { // results can be treated list an attribute, indicate ST created list List resultVector = new StringTemplate.STAttributeList(); Iterator iter = (Iterator)attributeValue; int i = 0; while ( iter.hasNext() ) { Object ithValue = iter.next(); if ( ithValue==null ) { if ( nullValue==null ) { continue; } ithValue = nullValue; } int templateIndex = i % templatesToApply.size(); // rotate through embedded = (StringTemplate)templatesToApply.get(templateIndex); // template to apply is an actual StringTemplate (created in // eval.g), but that is used as the examplar. We must create // a new instance of the embedded template to apply each time // to get new attribute sets etc... StringTemplateAST args = embedded.getArgumentsAST(); embedded = embedded.getInstanceOf(); // make new instance embedded.setEnclosingInstance(self); embedded.setArgumentsAST(args); argumentContext = new HashMap(); Map formalArgs = embedded.getFormalArguments(); boolean isAnonymous = embedded.getName() == StringTemplate.ANONYMOUS_ST_NAME; setSoleFormalArgumentToIthValue(embedded, argumentContext, ithValue); // if it's an anonymous template with a formal arg, don't set it/attr if ( !(isAnonymous && formalArgs!=null && formalArgs.size()>0) ) { argumentContext.put(DEFAULT_ATTRIBUTE_NAME, ithValue); argumentContext.put(DEFAULT_ATTRIBUTE_NAME_DEPRECATED, ithValue); } argumentContext.put(DEFAULT_INDEX_VARIABLE_NAME, new Integer(i+1)); argumentContext.put(DEFAULT_INDEX0_VARIABLE_NAME, new Integer(i)); embedded.setArgumentContext(argumentContext); evaluateArguments(embedded); /* System.err.println("i="+i+": applyTemplate("+embedded.getName()+ ", args="+argumentContext+ " to attribute value "+ithValue); */ resultVector.add(embedded); i++; } if ( resultVector.size()==0 ) { resultVector = null; } return resultVector; } else { /* System.out.println("setting attribute "+DEFAULT_ATTRIBUTE_NAME+" in arg context of "+ embedded.getName()+ " to "+attributeValue); */ embedded = (StringTemplate)templatesToApply.get(0); argumentContext = new HashMap(); Map formalArgs = embedded.getFormalArguments(); StringTemplateAST args = embedded.getArgumentsAST(); setSoleFormalArgumentToIthValue(embedded, argumentContext, attributeValue); boolean isAnonymous = embedded.getName() == StringTemplate.ANONYMOUS_ST_NAME; // if it's an anonymous template with a formal arg, don't set it/attr if ( !(isAnonymous && formalArgs!=null && formalArgs.size()>0) ) { argumentContext.put(DEFAULT_ATTRIBUTE_NAME, attributeValue); argumentContext.put(DEFAULT_ATTRIBUTE_NAME_DEPRECATED, attributeValue); } argumentContext.put(DEFAULT_INDEX_VARIABLE_NAME, new Integer(1)); argumentContext.put(DEFAULT_INDEX0_VARIABLE_NAME, new Integer(0)); embedded.setArgumentContext(argumentContext); evaluateArguments(embedded); return embedded; } } protected void setSoleFormalArgumentToIthValue(StringTemplate embedded, Map argumentContext, Object ithValue) { Map formalArgs = embedded.getFormalArguments(); if ( formalArgs!=null ) { String soleArgName = null; boolean isAnonymous = embedded.getName() == StringTemplate.ANONYMOUS_ST_NAME; if ( formalArgs.size()==1 || (isAnonymous&&formalArgs.size()>0) ) { if ( isAnonymous && formalArgs.size()>1 ) { embedded.error("too many arguments on {...} template: "+formalArgs); } // if exactly 1 arg or anonymous, give that the value of // "it" as a convenience like they said // $list:template(arg=it)$ Set argNames = formalArgs.keySet(); soleArgName = (String)argNames.toArray()[0]; argumentContext.put(soleArgName, ithValue); } } } /** Return o.getPropertyName() given o and propertyName. If o is * a stringtemplate then access it's attributes looking for propertyName * instead (don't check any of the enclosing scopes; look directly into * that object). Also try isXXX() for booleans. Allow Map * as special case (grab value for key). * * Cache repeated requests for obj.prop within same group. */ public Object getObjectProperty(StringTemplate self, final Object o, final Object propertyName) { if ( o==null || propertyName==null ) { return null; } /* // see if property is cached in group's cache Object cachedValue = self.getGroup().getCachedObjectProperty(o,propertyName); if ( cachedValue!=null ) { return cachedValue; } Object value = rawGetObjectProperty(self, o, propertyName); // take care of array properties...convert to a List so we can // apply templates to the elements etc... value = convertArrayToList(value); self.getGroup().cacheObjectProperty(o,propertyName,value); */ Object value = rawGetObjectProperty(self, o, propertyName); // take care of array properties...convert to a List so we can // apply templates to the elements etc... value = convertArrayToList(value); return value; } protected Object rawGetObjectProperty(StringTemplate self, Object o, Object property) { Class c = o.getClass(); Object value = null; // Special case: our automatically created Aggregates via // attribute name: "{obj.{prop1,prop2}}" if ( c==StringTemplate.Aggregate.class ) { String propertyName = (String)property; value = ((StringTemplate.Aggregate)o).get((String)propertyName); return value; } // Special case: if it's a template, pull property from // it's attribute table. // TODO: TJP just asked himself why we can't do inherited attr here? else if ( c==StringTemplate.class ) { Map attributes = ((StringTemplate)o).getAttributes(); if ( attributes!=null ) { String propertyName = (String)property; value = attributes.get(propertyName); return value; } } // Special case: if it's a Map then pull using // key not the property method. if ( o instanceof Map ) { Map map = (Map)o; if ( property.equals("keys") ) { value = map.keySet(); } else if ( property.equals("values") ) { value = map.values(); } else if ( map.containsKey(property) ) { value = map.get(property); } else if ( map.containsKey(property.toString()) ) { // if we can't find the key, toString it value = map.get(property.toString()); } else { if ( map.containsKey(DEFAULT_MAP_VALUE_NAME) ) { value = map.get(DEFAULT_MAP_VALUE_NAME); } } if ( value == MAP_KEY_VALUE ) { value = property; } return value; } // try getXXX and isXXX properties // check cache Method m = null; /* Member cachedMember = self.getGroup().getCachedClassProperty(c,propertyName); if ( cachedMember!=null ) { try { if ( cachedMember instanceof Method ) { m = (Method)cachedMember; value = invokeMethod(m, o, value); } else { // must be a field Field f = (Field)cachedMember; value = accessField(f, o, value); } } catch (Exception e) { self.error("Can't get property "+propertyName+ " from "+c.getName()+" instance", e); } return value; } */ // must look up using reflection String propertyName = (String)property; String methodSuffix = Character.toUpperCase(propertyName.charAt(0))+ propertyName.substring(1,propertyName.length()); m = getMethod(c,"get"+methodSuffix); if ( m==null ) { m = getMethod(c, "is"+methodSuffix); } if ( m != null ) { // save to avoid lookup later //self.getGroup().cacheClassProperty(c,propertyName,m); try { value = invokeMethod(m, o, value); } catch (Exception e) { self.error("Can't get property "+propertyName+" using method get/is"+methodSuffix+ " from "+c.getName()+" instance", e); } } else { // try for a visible field try { Field f = c.getField(propertyName); //self.getGroup().cacheClassProperty(c,propertyName,f); try { value = accessField(f, o, value); } catch (IllegalAccessException iae) { self.error("Can't access property "+propertyName+" using method get/is"+methodSuffix+ " or direct field access from "+c.getName()+" instance", iae); } } catch (NoSuchFieldException nsfe) { self.error("Class "+c.getName()+" has no such attribute: "+propertyName+ " in template context "+self.getEnclosingInstanceStackString(), nsfe); } } return value; } protected Object accessField(Field f, Object o, Object value) throws IllegalAccessException { try { // make sure it's accessible (stupid java) f.setAccessible(true); } catch (SecurityException se) { ; // oh well; security won't let us } value = f.get(o); return value; } protected Object invokeMethod(Method m, Object o, Object value) throws IllegalAccessException, InvocationTargetException { try { // make sure it's accessible (stupid java) m.setAccessible(true); } catch (SecurityException se) { ; // oh well; security won't let us } value = m.invoke(o,(Object[])null); return value; } protected Method getMethod(Class c, String methodName) { Method m; try { m = c.getMethod(methodName, (Class[])null); } catch (NoSuchMethodException nsme) { m = null; } return m; } /** Normally StringTemplate tests presence or absence of attributes * for adherence to my principles of separation, but some people * disagree and want to change. * * For 2.0, if the object is a boolean, do something special. $if(boolean)$ * will actually test the value. Now, this breaks my rules of entanglement * listed in my paper, but it truly surprises programmers to have booleans * always true. Further, the key to isolating logic in the model is avoiding * operators (for which you need attribute values). But, no operator is * needed to use boolean values. Well, actually I guess "!" (not) is * an operator. Regardless, for practical reasons, I'm going to technically * violate my rules as I currently have them defined. Perhaps for a future * version of the paper I will refine the rules. * * Post 2.1, I added a check for non-null Iterators, Collections, ... * with size==0 to return false. TJP 5/1/2005 */ public boolean testAttributeTrue(Object a) { if ( a==null ) { return false; } if ( a instanceof Boolean ) { return ((Boolean)a).booleanValue(); } if ( a instanceof Collection ) { return ((Collection)a).size()>0; } if ( a instanceof Map ) { return ((Map)a).size()>0; } if ( a instanceof Iterator ) { return ((Iterator)a).hasNext(); } return true; // any other non-null object, return true--it's present } /** For now, we can only add two objects as strings; convert objects to * Strings then cat. */ public Object add(Object a, Object b) { if ( a==null ) { // a null value means don't do cat, just return other value return b; } else if ( b==null ) { return a; } return a.toString() + b.toString(); } /** Call a string template with args and return result. Do not convert * to a string yet. It may need attributes that will be available after * this is inserted into another template. */ public StringTemplate getTemplateInclude(StringTemplate enclosing, String templateName, StringTemplateAST argumentsAST) { //System.out.println("getTemplateInclude: look up "+enclosing.getGroup().getName()+"::"+templateName); StringTemplateGroup group = enclosing.getGroup(); StringTemplate embedded = group.getEmbeddedInstanceOf(enclosing, templateName); if ( embedded==null ) { enclosing.error("cannot make embedded instance of "+templateName+ " in template "+enclosing.getName()); return null; } embedded.setArgumentsAST(argumentsAST); evaluateArguments(embedded); return embedded; } /** How to spit out an object. If it's not a StringTemplate nor a * List, just do o.toString(). If it's a StringTemplate, * do o.write(out). If it's a Vector, do a write(out, * o.elementAt(i)) for all elements. Note that if you do * something weird like set the values of a multivalued tag * to be vectors, it will effectively flatten it. * * If self is an embedded template, you might have specified * a separator arg; used when is a vector. */ public int writeAttribute(StringTemplate self, Object o, StringTemplateWriter out) { return write(self,o,out); } /* Write o relative to self to out. * * John Snyders fixes here for formatString. Basically, any time * you are about to write a value, check formatting. */ protected int write(StringTemplate self, Object o, StringTemplateWriter out) { if ( o==null ) { if ( nullValue==null ) { return MISSING; } o = nullValue; // continue with null option if specified } int n = 0; try { if ( o instanceof StringTemplate ) return writeTemplate(self, o, out); o = convertAnythingIteratableToIterator(o); // normalize if ( o instanceof Iterator ) return writeIterableValue(self, o, out); return writePOJO(self, o, out); } catch (IOException io) { self.error("problem writing object: "+o, io); } return n; } protected int writePOJO(StringTemplate self, Object o, StringTemplateWriter out) throws IOException { int n = 0; AttributeRenderer renderer = self.getAttributeRenderer(o.getClass()); String v = null; if ( renderer!=null ) { if ( formatString != null ) v = renderer.toString(o, formatString); else v = renderer.toString(o); } else v = o.toString(); if ( wrapString!=null ) n = out.write(v, wrapString); else n = out.write( v ); return n; } protected int writeTemplate(StringTemplate self, Object o, StringTemplateWriter out) throws IOException { int n = 0; StringTemplate stToWrite = (StringTemplate)o; // failsafe: perhaps enclosing instance not set // Or, it could be set to another context! This occurs // when you store a template instance as an attribute of more // than one template (like both a header file and C file when // generating C code). It must execute within the context of // the enclosing template. stToWrite.setEnclosingInstance(self); // if self is found up the enclosing instance chain, then // infinite recursion if ( StringTemplate.inLintMode() && StringTemplate.isRecursiveEnclosingInstance(stToWrite) ) { // throw exception since sometimes eval keeps going // even after I ignore this write of o. throw new IllegalStateException("infinite recursion to "+ stToWrite.getTemplateDeclaratorString()+" referenced in "+ stToWrite.getEnclosingInstance().getTemplateDeclaratorString()+ "; stack trace:\n"+stToWrite.getEnclosingInstanceStackTrace()); } else { // if we have a wrap string, then inform writer it // might need to wrap if ( wrapString!=null ) { n = out.writeWrapSeparator(wrapString); } // check if formatting needs to be applied to the stToWrite if ( formatString != null ) { AttributeRenderer renderer = self.getAttributeRenderer(String.class); if ( renderer != null ) { // you pay a penalty for applying format option to a template // because the template must be written to a temp StringWriter so it can // be formatted before being written to the real output. StringWriter buf = new StringWriter(); StringTemplateWriter sw = self.getGroup().getStringTemplateWriter(buf); stToWrite.write(sw); n = out.write(renderer.toString(buf.toString(), formatString)); return n; } } n = stToWrite.write(out); } return n; } protected int writeIterableValue(StringTemplate self, Object o, StringTemplateWriter out) throws IOException { int n = 0; Iterator iter = (Iterator)o; boolean seenAValue = false; while ( iter.hasNext() ) { Object iterValue = iter.next(); if ( iterValue==null ) iterValue = nullValue; if ( iterValue!=null ) { // if no separator or separator but iterValue isn't // a single IF condition template if ( separatorString==null ) { // if no separator, don't waste time writing to // temp buffer int nw = write(self, iterValue, out); if ( nw!=MISSING ) n += nw; continue; } // if value to emit is a template, only buffer its // value if it's nullable (can eval to missing). // Only a sequence of IF can eval to missing. if ( iterValue instanceof StringTemplate ) { StringTemplate st = (StringTemplate)iterValue; int nchunks = st.getChunks()!=null ? st.getChunks().size() : 0; boolean nullable = true; for (int i=0; i"); argContextST.setEnclosingInstance(enclosing); argContextST.setArgumentContext(self.getArgumentContext()); ActionEvaluator eval = new ActionEvaluator(argContextST,this,null); /* System.out.println("eval args: "+argumentsAST.toStringList()); System.out.println("ctx is "+self.getArgumentContext()); */ try { // using any initial argument context (such as when obj is set), // evaluate the arg list like bold(item=obj). Since we pass // in any existing arg context, that context gets filled with // new values. With bold(item=obj), context becomes: // {[obj=...],[item=...]}. Map ac = eval.argList(argumentsAST, self, self.getArgumentContext()); self.setArgumentContext(ac); } catch (RecognitionException re) { self.error("can't evaluate tree: "+argumentsAST.toStringList(), re); } } /* public static final Set arraysConvertibleToList = new HashSet() { { add(int[].class); add(long[].class); add(float[].class); add(double[].class); } }; */ /** Do a standard conversion of array attributes to a List. Wrap the * array instead of copying like old version. Make an * ArrayWrappedInList that knows to create an ArrayIterator. */ public static Object convertArrayToList(Object value) { if ( value==null ) { return null; } if ( value.getClass().isArray() ) { if ( value.getClass().getComponentType().isPrimitive() ) { return new ArrayWrappedInList(value); } return Arrays.asList((Object[])value); } return value; } protected static Object convertAnythingIteratableToIterator(Object o) { Iterator iter = null; if ( o instanceof Collection ) { iter = ((Collection)o).iterator(); } else if ( o instanceof Map ) { iter = ((Map)o).values().iterator(); } else if ( o instanceof Iterator ) { iter = (Iterator)o; } if ( iter==null ) { return o; } return iter; } protected static Iterator convertAnythingToIterator(Object o) { Iterator iter = null; if ( o instanceof Collection ) { iter = ((Collection)o).iterator(); } else if ( o instanceof Map ) { iter = ((Map)o).values().iterator(); } else if ( o instanceof Iterator ) { iter = (Iterator)o; } if ( iter==null ) { List singleton = new StringTemplate.STAttributeList(1); singleton.add(o); return singleton.iterator(); } return iter; } /** Return the first attribute if multiple valued or the attribute * itself if single-valued. Used in */ public Object first(Object attribute) { if ( attribute==null ) { return null; } Object f = attribute; attribute = convertAnythingIteratableToIterator(attribute); if ( attribute instanceof Iterator ) { Iterator it = (Iterator)attribute; if ( it.hasNext() ) { f = it.next(); } } return f; } /** Return the everything but the first attribute if multiple valued * or null if single-valued. Used in . */ public Object rest(Object attribute) { if ( attribute==null ) { return null; } Object theRest = attribute; attribute = convertAnythingIteratableToIterator(attribute); if ( attribute instanceof Iterator ) { List a = new ArrayList(); Iterator it = (Iterator)attribute; if ( !it.hasNext() ) { return null; // if not even one value return null } it.next(); // ignore first value while (it.hasNext()) { Object o = (Object) it.next(); if ( o!=null ) a.add(o); } return a; } else { theRest = null; // rest of single-valued attribute is null } return theRest; } /** Return the last attribute if multiple valued or the attribute * itself if single-valued. Used in . This is pretty * slow as it iterates until the last element. Ultimately, I could * make a special case for a List or Vector. */ public Object last(Object attribute) { if ( attribute==null ) { return null; } Object last = attribute; attribute = convertAnythingIteratableToIterator(attribute); if ( attribute instanceof Iterator ) { Iterator it = (Iterator)attribute; while ( it.hasNext() ) { last = it.next(); } } return last; } /** Return a new list w/o null values. */ public Object strip(Object attribute) { if ( attribute==null ) { return null; } attribute = convertAnythingIteratableToIterator(attribute); if ( attribute instanceof Iterator ) { List a = new ArrayList(); Iterator it = (Iterator)attribute; while (it.hasNext()) { Object o = (Object) it.next(); if ( o!=null ) a.add(o); } return a; } return attribute; // strip(x)==x when x single-valued attribute } /** Return all but the last element. trunc(x)=null if x is single-valued. */ public Object trunc(Object attribute) { if ( attribute==null ) { return null; } attribute = convertAnythingIteratableToIterator(attribute); if ( attribute instanceof Iterator ) { List a = new ArrayList(); Iterator it = (Iterator)attribute; while (it.hasNext()) { Object o = (Object) it.next(); if ( it.hasNext() ) a.add(o); // only add if not last one } return a; } return null; // trunc(x)==null when x single-valued attribute } /** Return the length of a multiple valued attribute or 1 if it is a * single attribute. If attribute is null return 0. * Special case several common collections and primitive arrays for * speed. This method by Kay Roepke. */ public Object length(Object attribute) { if ( attribute == null) { return new Integer(0); } int i = 1; // we have at least one of something. Iterator and arrays might be empty. if (attribute instanceof Map) { i = ((Map)attribute).size(); } else if (attribute instanceof Collection) { i = ((Collection)attribute).size(); } else if ( attribute instanceof Object[] ) { Object[] list = (Object[])attribute; i = list.length; } else if ( attribute instanceof int[] ) { int[] list = (int[])attribute; i = list.length; } else if ( attribute instanceof long[] ) { long[] list = (long[])attribute; i = list.length; } else if ( attribute instanceof float[] ) { float[] list = (float[])attribute; i = list.length; } else if ( attribute instanceof double[] ) { double[] list = (double[])attribute; i = list.length; } else if ( attribute instanceof Iterator) { Iterator it = (Iterator)attribute; i = 0; while ( it.hasNext() ) { it.next(); i++; } } return new Integer(i); } public Object getOption(String name) { Object value = null; if ( options!=null ) { value = options.get(name); if ( value==EMPTY_OPTION ) { return defaultOptionValues.get(name); } } return value; } public String toString() { return exprTree.toStringList(); } } stringtemplate-3.2.1/src/org/antlr/stringtemplate/language/ArrayWrappedInList.java0000644000175000017500000000150311256235341030430 0ustar twernertwernerpackage org.antlr.stringtemplate.language; import java.util.ArrayList; import java.util.Iterator; import java.lang.reflect.Array; /** Turn an array into a List; subclass ArrayList for easy development, but * it really doesn't use super stuff for anything. Ensure we create * ArrayIterator for this List. */ public class ArrayWrappedInList extends ArrayList { protected Object array = null; /** Arrays are fixed size; precompute. */ protected int n; public ArrayWrappedInList(Object array) { this.array = array; n = Array.getLength(array); } public Object get(int i) { return Array.get(array, i); } public int size() { return n; } public boolean isEmpty() { return n==0; } public Object[] toArray() { return (Object[])array; } public Iterator iterator() { return new ArrayIterator(array); } } stringtemplate-3.2.1/src/org/antlr/stringtemplate/language/template.g0000644000175000017500000003051011256235341026024 0ustar twernertwernerheader { /* [The "BSD licence"] Copyright (c) 2003-2004 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.language; import org.antlr.stringtemplate.*; import java.io.*; } /** A parser used to break up a single template into chunks, text literals * and attribute expressions. */ class TemplateParser extends Parser; { protected StringTemplate self; public void reportError(RecognitionException e) { StringTemplateGroup group = self.getGroup(); if ( group==StringTemplate.defaultGroup ) { self.error("template parse error; template context is "+self.getEnclosingInstanceStackString(), e); } else { self.error("template parse error in group "+self.getGroup().getName()+" line "+self.getGroupFileLine()+"; template context is "+self.getEnclosingInstanceStackString(), e); } } } template[StringTemplate self] { this.self = self; } : ( s:LITERAL {self.addChunk(new StringRef(self,s.getText()));} | nl:NEWLINE { if ( LA(1)!=ELSE && LA(1)!=ENDIF ) { self.addChunk(new NewlineRef(self,nl.getText())); } } | action[self] )* ; action[StringTemplate self] : a:ACTION { String indent = ((ChunkToken)a).getIndentation(); ASTExpr c = self.parseAction(a.getText()); c.setIndentation(indent); self.addChunk(c); } | i:IF { ConditionalExpr c = (ConditionalExpr)self.parseAction(i.getText()); // create and precompile the subtemplate StringTemplate subtemplate = new StringTemplate(self.getGroup(), null); subtemplate.setEnclosingInstance(self); subtemplate.setName(i.getText()+"_subtemplate"); self.addChunk(c); } template[subtemplate] {if ( c!=null ) c.setSubtemplate(subtemplate);} ( ei:ELSEIF { ASTExpr ec = self.parseAction(ei.getText()); // create and precompile the subtemplate StringTemplate elseIfSubtemplate = new StringTemplate(self.getGroup(), null); elseIfSubtemplate.setEnclosingInstance(self); elseIfSubtemplate.setName(ei.getText()+"_subtemplate"); } template[elseIfSubtemplate] {if ( c!=null ) c.addElseIfSubtemplate(ec, elseIfSubtemplate);} )* ( ELSE { // create and precompile the subtemplate StringTemplate elseSubtemplate = new StringTemplate(self.getGroup(), null); elseSubtemplate.setEnclosingInstance(self); elseSubtemplate.setName("else_subtemplate"); } template[elseSubtemplate] {if ( c!=null ) c.setElseSubtemplate(elseSubtemplate);} )? ENDIF | rr:REGION_REF { // define implicit template and // convert <@r()> to String regionName = rr.getText(); String mangledRef = null; boolean err = false; // watch out for <@super.r()>; that does NOT def implicit region // convert to if ( regionName.startsWith("super.") ) { //System.out.println("super region ref "+regionName); String regionRef = regionName.substring("super.".length(),regionName.length()); String templateScope = self.getGroup().getUnMangledTemplateName(self.getName()); StringTemplate scopeST = self.getGroup().lookupTemplate(templateScope); if ( scopeST==null ) { self.getGroup().error("reference to region within undefined template: "+ templateScope); err=true; } if ( !scopeST.containsRegionName(regionRef) ) { self.getGroup().error("template "+templateScope+" has no region called "+ regionRef); err=true; } else { mangledRef = self.getGroup().getMangledRegionName(templateScope,regionRef); mangledRef = "super."+mangledRef; } } else { //System.out.println("region ref "+regionName); StringTemplate regionST = self.getGroup().defineImplicitRegionTemplate(self,regionName); mangledRef = regionST.getName(); } if ( !err ) { // treat as regular action: mangled template include String indent = ((ChunkToken)rr).getIndentation(); ASTExpr c = self.parseAction(mangledRef+"()"); c.setIndentation(indent); self.addChunk(c); } } | rd:REGION_DEF { String combinedNameTemplateStr = rd.getText(); int indexOfDefSymbol = combinedNameTemplateStr.indexOf("::="); if ( indexOfDefSymbol>=1 ) { String regionName = combinedNameTemplateStr.substring(0,indexOfDefSymbol); String template = combinedNameTemplateStr.substring(indexOfDefSymbol+3, combinedNameTemplateStr.length()); StringTemplate regionST = self.getGroup().defineRegionTemplate(self, regionName, template, StringTemplate.REGION_EMBEDDED); // treat as regular action: mangled template include String indent = ((ChunkToken)rd).getIndentation(); ASTExpr c = self.parseAction(regionST.getName()+"()"); c.setIndentation(indent); self.addChunk(c); } else { self.error("embedded region definition screwed up"); } } ; /** Break up an input text stream into chunks of either plain text * or template actions in "$...$". Treat IF and ENDIF tokens * specially. */ class DefaultTemplateLexer extends Lexer; options { k=7; // see "$endif$" charVocabulary = '\u0001'..'\uFFFE'; } { protected String currentIndent = null; protected StringTemplate self; public DefaultTemplateLexer(StringTemplate self, Reader r) { this(r); this.self = self; } public void reportError(RecognitionException e) { self.error("$...$ chunk lexer error", e); } protected boolean upcomingELSE(int i) throws CharStreamException { return LA(i)=='$'&&LA(i+1)=='e'&&LA(i+2)=='l'&&LA(i+3)=='s'&&LA(i+4)=='e'&& LA(i+5)=='$'; } protected boolean upcomingENDIF(int i) throws CharStreamException { return LA(i)=='$'&&LA(i+1)=='e'&&LA(i+2)=='n'&&LA(i+3)=='d'&&LA(i+4)=='i'&& LA(i+5)=='f'&&LA(i+6)=='$'; } protected boolean upcomingAtEND(int i) throws CharStreamException { return LA(i)=='$'&&LA(i+1)=='@'&&LA(i+2)=='e'&&LA(i+3)=='n'&&LA(i+4)=='d'&&LA(i+5)=='$'; } protected boolean upcomingNewline(int i) throws CharStreamException { return (LA(i)=='\r'&&LA(i+1)=='\n')||LA(i)=='\n'; } } LITERAL : {LA(1)!='\r'&&LA(1)!='\n'}? ( options { generateAmbigWarnings=false;} { int loopStartIndex=text.length(); int col=getColumn(); } : '\\'! '$' // allow escaped delimiter | '\\'! '\\' // always replace \\ with \ | '\\' ~'$' // otherwise ignore escape char | ind:INDENT { if ( col==1 && LA(1)=='$' ) { // store indent in ASTExpr not in a literal currentIndent=ind.getText(); text.setLength(loopStartIndex); // reset length to wack text } else currentIndent=null; } | ~('$'|'\r'|'\n') )+ {if (($getText).length()==0) {$setType(Token.SKIP);}} // pure indent? ; NEWLINE : ('\r')? '\n' {newline(); currentIndent=null;} ; ACTION options { generateAmbigWarnings=false; // $EXPR$ is ambig with $!..!$ } { int startCol = getColumn(); } : LINE_BREAK {$setType(Token.SKIP);} | // Match escapes not in a string like <\n\ufea5> {StringBuffer buf = new StringBuffer(); char uc = '\u0000';} '$'! (uc=ESC_CHAR {buf.append(uc);} )+'$'! {$setText(buf.toString()); $setType(LITERAL);} | COMMENT {$setType(Token.SKIP);} | ( options { generateAmbigWarnings=false; // $EXPR$ is ambig with $endif$ etc... } : '$'! "if" (' '!)* "(" IF_EXPR ")" '$'! {$setType(TemplateParser.IF);} ( ('\r'!)? '\n'! {newline();})? // ignore any newline right after an IF | '$'! "elseif" (' '!)* "(" IF_EXPR ")" '$'! {$setType(TemplateParser.ELSEIF);} ( ('\r'!)? '\n'! {newline();})? // ignore any newline right after an IF | '$'! "else" '$'! {$setType(TemplateParser.ELSE);} ( ('\r'!)? '\n'! {newline();})? // ignore any newline right after an ELSE | '$'! "endif" '$'! {$setType(TemplateParser.ENDIF);} ( {startCol==1}? ('\r'!)? '\n'! {newline();})? // ignore after ENDIF if on line by itself | // match $@foo()$ => foo // match $@foo$...$@end$ => foo::=... '$'! '@'! (~('$'|'('))+ ( "()"! '$'! {$setType(TemplateParser.REGION_REF);} | '$'! {$setType(TemplateParser.REGION_DEF); String t=$getText; $setText(t+"::="); } ( options {greedy=true;} : ('\r'!)? '\n'! {newline();})? {boolean atLeft = false;} ( options {greedy=true;} // handle greedy=false with predicate : {!(upcomingAtEND(1)||(upcomingNewline(1)&&upcomingAtEND(2)))}? ( ('\r')? '\n' {newline(); atLeft = true;} | . {atLeft = false;} ) )+ ( ('\r'!)? '\n'! {newline(); atLeft = true;} )? ( "$@end$"! | . {self.error("missing region "+t+" $@end$ tag");} ) ( {atLeft}? ('\r'!)? '\n'! {newline();})? ) | '$'! EXPR '$'! // (Can't start with '!', which would mean comment) ) { ChunkToken t = new ChunkToken(_ttype, $getText, currentIndent); $setToken(t); } ; protected EXPR: ( ESC | ('\r')? '\n' {newline();} | SUBTEMPLATE | ('='|'+') TEMPLATE | ('='|'+') SUBTEMPLATE | ('='|'+') ~('"'|'<'|'{') | ~'$' )+ ; protected TEMPLATE : '"' ( ESC | ~'"' )* '"' | "<<" (options {greedy=true;}:('\r'!)?'\n'! {newline();})? // consume 1st \n ( options {greedy=false;} // stop when you see the >> : {LA(3)=='>'&&LA(4)=='>'}? '\r'! '\n'! {newline();} // kill last \r\n | {LA(2)=='>'&&LA(3)=='>'}? '\n'! {newline();} // kill last \n | ('\r')? '\n' {newline();} // else keep | . )* ">>" ; protected IF_EXPR:( ESC | ('\r')? '\n' {newline();} | SUBTEMPLATE | NESTED_PARENS | ~')' )+ ; protected ESC_CHAR returns [char uc='\u0000'] : "\\n"! {uc = '\n';} | "\\r"! {uc = '\r';} | "\\t"! {uc = '\t';} | "\\ "! {uc = ' ';} | "\\u"! a:HEX! b:HEX! c:HEX! d:HEX! {uc = (char)Integer.parseInt(a.getText()+b.getText()+c.getText()+d.getText(), 16);} ; protected ESC : '\\' . // ('$'|'n'|'t'|'"'|'\''|':'|'{'|'}') ; protected HEX : '0'..'9'|'A'..'F'|'a'..'f' ; protected SUBTEMPLATE : '{' (SUBTEMPLATE|ESC|~'}')* '}' ; protected NESTED_PARENS : '(' (options {greedy=false;}:NESTED_PARENS|ESC|~')')+ ')' ; protected INDENT : ( options {greedy=true;}: ' ' | '\t')+ ; protected COMMENT { int startCol = getColumn(); } : "$!" ( options {greedy=false;} : ('\r')? '\n' {newline();} | . )* "!$" ( {startCol==1}? ('\r')? '\n' {newline();} )? ; protected LINE_BREAK : "$\\\\$" (INDENT)? ('\r')? '\n' {newline();} (INDENT)? ; stringtemplate-3.2.1/src/org/antlr/stringtemplate/StringTemplate.java0000644000175000017500000015344011256235341026073 0ustar twernertwerner/* [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 java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import org.antlr.stringtemplate.language.*; import antlr.*; import antlr.collections.AST; import antlr.collections.ASTEnumeration; /** 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 propName, Object propValue) { properties.put(propName, propValue); } public Object get(String propName) { return properties.get(propName); } public String toString() { return properties.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 = ANONYMOUS_ST_NAME; private static int templateCounter=0; private static synchronized int getNextTemplateCounter() { templateCounter++; return templateCounter; } /** 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() { templateCounter = 0; } 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, * 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 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 * 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. */ protected LinkedHashMap formalArguments = FormalArgument.UNKNOWN; /** 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: to say "pass in * all data". Works great. Can also say */ 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" */ protected StringTemplateGroup nativeGroup; /** 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 */ StringTemplateErrorListener listener = null; /** 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 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() { group = defaultGroup; // 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(null, template); } public StringTemplate(String template, Class lexer) { this(); setGroup(new StringTemplateGroup("defaultGroup", lexer)); setTemplate(template); } /** Create an anonymous template with no name, but with a group */ public StringTemplate(StringTemplateGroup group, String template) { this(); if ( group!=null ) { setGroup(group); } setTemplate(template); } public StringTemplate(StringTemplateGroup group, String template, HashMap attributes) { this(group,template); this.attributes = 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 from, StringTemplate 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. */ public StringTemplate getInstanceOf() { StringTemplate t = null; if ( nativeGroup!=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. t = nativeGroup.createStringTemplate(); } else { t = group.createStringTemplate(); } dup(this, t); return t; } public StringTemplate getEnclosingInstance() { return enclosingInstance; } public StringTemplate getOutermostEnclosingInstance() { if ( enclosingInstance!=null ) { return enclosingInstance.getOutermostEnclosingInstance(); } 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 = enclosingInstance; } public Map getArgumentContext() { return argumentContext; } public void setArgumentContext(Map ac) { argumentContext = ac; } public StringTemplateAST getArgumentsAST() { return argumentsAST; } public void setArgumentsAST(StringTemplateAST argumentsAST) { this.argumentsAST = argumentsAST; } public String getName() { return name; } public String getOutermostName() { if ( enclosingInstance!=null ) { return enclosingInstance.getOutermostName(); } return getName(); } public void setName(String name) { this.name = name; } public StringTemplateGroup getGroup() { return group; } public void setGroup(StringTemplateGroup group) { this.group = group; } public StringTemplateGroup getNativeGroup() { return nativeGroup; } public void setNativeGroup(StringTemplateGroup nativeGroup) { this.nativeGroup = nativeGroup; } /** Return the outermost template's group file line number */ public int getGroupFileLine() { if ( enclosingInstance!=null ) { return enclosingInstance.getGroupFileLine(); } return groupFileLine; } public void setGroupFileLine(int groupFileLine) { this.groupFileLine = groupFileLine; } public void setTemplate(String template) { this.pattern = template; breakTemplateIntoChunks(); } public String getTemplate() { return pattern; } public void setErrorListener(StringTemplateErrorListener listener) { this.listener = listener; } public StringTemplateErrorListener getErrorListener() { if ( listener==null ) { return group.getErrorListener(); } return listener; } public void reset() { attributes = 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 ( attributes!=null ) attributes.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 name, Object value) { if ( value==null || name==null ) { return; } if ( name.indexOf('.')>=0 ) { throw new IllegalArgumentException("cannot have '.' in attribute names"); } if ( attributes==null ) { attributes = new HashMap(); } if ( value instanceof StringTemplate ) { ((StringTemplate)value).setEnclosingInstance(this); } else { // convert value if array value = ASTExpr.convertArrayToList(value); } // convert plain collections // get exactly in this scope (no enclosing) Object o = this.attributes.get(name); if ( o==null ) { // new attribute rawSetAttribute(this.attributes, name, value); 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.attributes, name, v); // 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.attributes, name, v); // 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 name, int value) { setAttribute(name, new Integer(value)); } /** Set an aggregate attribute with two values. The attribute name * must have the format: "name.{propName1,propName2}". */ public void setAttribute(String aggrSpec, Object v1, Object v2) { setAttribute(aggrSpec, new Object[] {v1,v2}); } public void setAttribute(String aggrSpec, Object v1, Object v2, Object v3) { setAttribute(aggrSpec, new Object[] {v1,v2,v3}); } public void setAttribute(String aggrSpec, Object v1, Object v2, Object v3, Object v4) { setAttribute(aggrSpec, new Object[] {v1,v2,v3,v4}); } public void setAttribute(String aggrSpec, Object v1, Object v2, Object v3, Object v4, Object v5) { setAttribute(aggrSpec, new 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 aggrSpec, Object[] values) { List properties = new ArrayList(); String aggrName = parseAggregateAttributeSpec(aggrSpec, properties); 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.length; i++) { Object value = values[i]; if ( value instanceof StringTemplate ) { ((StringTemplate)value).setEnclosingInstance(this); } else { value = ASTExpr.convertArrayToList(value); } aggr.put((String)properties.get(i), value); } setAttribute(aggrName, aggr); } /** Split "aggrName.{propName1,propName2}" into list [propName1,propName2] * and the aggrName. Space is allowed around ','. */ protected String parseAggregateAttributeSpec(String aggrSpec, List 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) { if ( formalArguments!=FormalArgument.UNKNOWN && getFormalArgument(name)==null ) { // a normal call to setAttribute with unknown attribute throw new NoSuchElementException("no such attribute: "+name+ " in template context "+ getEnclosingInstanceStackString()); } if ( value == null ) { return; } attributes.put(name, value); } /** 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!=FormalArgument.UNKNOWN && embedded.getFormalArgument(name)==null ) { throw new NoSuchElementException("template "+embedded.getName()+ " has no such attribute: "+name+ " in template context "+ getEnclosingInstanceStackString()); } if ( value == null ) { return; } attributes.put(name, value); } public Object getAttribute(String name) { Object v = get(this,name); if ( v==null ) { checkNullAttributeAgainstFormalArguments(this, name); } 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 out) throws IOException { if ( group.debugTemplateOutput ) { group.emitTemplateStartDebugString(this,out); } int n = 0; boolean missing = true; setPredefinedAttributes(); setDefaultArgumentValues(); for (int i=0; chunks!=null && i NEWLINE if ( chunkN<=0 && i==0 && (i+1) 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 && chunks.get(i-1) instanceof NewlineRef && (i+1)0 ) return ASTExpr.MISSING; 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 self, String 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 ( lintMode ) { 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.enclosingInstance, attribute); /* 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 ( pattern==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 = group.getTemplateLexerClass(); Constructor ctor = lexerClass.getConstructor( new Class[] {StringTemplate.class,Reader.class} ); CharScanner chunkStream = (CharScanner) ctor.newInstance( new Object[] {this,new StringReader(pattern)} ); 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 = ""; 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(lexer, this); 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()==ActionParser.CONDITIONAL ) { 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 templateID; } public Map getAttributes() { return attributes; } /** Get a list of the strings and subtemplates and attribute * refs in a template. */ public List getChunks() { return chunks; } public void addChunk(Expr e) { if ( chunks==null ) { chunks = new ArrayList(); } chunks.add(e); } public void setAttributes(Map attributes) { this.attributes = attributes; } // F o r m a l A r g S t u f f public Map getFormalArguments() { return formalArguments; } public void setFormalArguments(LinkedHashMap args) { formalArguments = 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); if ( numberOfDefaultArgumentValues==0 ) { return; } if ( argumentContext==null ) { argumentContext = new HashMap(); } if ( formalArguments!=FormalArgument.UNKNOWN ) { //System.out.println("formal args="+formalArguments.keySet()); Set argNames = formalArguments.keySet(); for (Iterator it = argNames.iterator(); it.hasNext();) { String argName = (String) it.next(); // use the default value then FormalArgument arg = (FormalArgument)formalArguments.get(argName); 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()==ActionEvaluator.VALUE ) { defaultValue = e.evaluateExpression(this, e.getAST()); } } } argumentContext.put(argName, defaultValue); } } } } } /** From this template upward in the enclosing template tree, * recursively look for the formal parameter. */ public FormalArgument lookupFormalArgument(String name) { FormalArgument arg = getFormalArgument(name); if ( arg==null && enclosingInstance!=null ) { arg = enclosingInstance.lookupFormalArgument(name); } return arg; } public FormalArgument getFormalArgument(String name) { return (FormalArgument)formalArguments.get(name); } public void defineEmptyFormalArgumentList() { setFormalArguments(new LinkedHashMap()); } public void defineFormalArgument(String name) { defineFormalArgument(name,null); } public void defineFormalArguments(List names) { if ( names==null ) { return; } for (int i = 0; i < names.size(); i++) { String name = (String) names.get(i); defineFormalArgument(name); } } public void defineFormalArgument(String name, StringTemplate defaultValue) { /* System.out.println("define formal arg "+this.name+"."+name+ ", def value="+(defaultValue!=null?defaultValue.chunks:"null")); */ if ( defaultValue!=null ) { numberOfDefaultArgumentValues++; } FormalArgument a = new FormalArgument(name,defaultValue); if ( formalArguments==FormalArgument.UNKNOWN ) { formalArguments = new LinkedHashMap(); } formalArguments.put(name, a); } /** 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 = passThroughAttributes; } /** Specify a complete map of what object classes should map to which * renderer objects. */ public void setAttributeRenderers(Map renderers) { this.attributeRenderers = 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 attributeClassType, AttributeRenderer renderer) { if ( attributeRenderers==null ) { attributeRenderers = new HashMap(); } attributeRenderers.put(attributeClassType, renderer); } /** 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 ( attributeRenderers!=null ) { renderer = (AttributeRenderer)attributeRenderers.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 ( enclosingInstance!=null ) { return enclosingInstance.getAttributeRenderer(attributeClassType); } // else check group return group.getAttributeRenderer(attributeClassType); } // U T I L I T Y R O U T I N E S public void error(String msg) { error(msg, null); } public void warning(String msg) { if ( getErrorListener()!=null ) { getErrorListener().warning(msg); } else { System.err.println("StringTemplate: warning: "+msg); } } public void error(String msg, Throwable e) { if ( getErrorListener()!=null ) { getErrorListener().error(msg,e); } else { if ( e!=null ) { System.err.println("StringTemplate: error: "+msg+": "+e.toString()); if ( e instanceof InvocationTargetException ) { e = ((InvocationTargetException)e).getTargetException(); } e.printStackTrace(System.err); } else { System.err.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) { StringTemplate.lintMode = lint; } public static boolean inLintMode() { return lintMode; } /** Indicates that 'name' has been referenced in this template. */ protected void trackAttributeReference(String name) { if ( referencedAttributes==null ) { referencedAttributes = new ArrayList(); } referencedAttributes.add(name); } /** 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; } public String getEnclosingInstanceStackTrace() { StringBuffer buf = new StringBuffer(); Set seen = new HashSet(); StringTemplate p = this; while ( p!=null ) { if ( seen.contains(p) ) { buf.append(p.getTemplateDeclaratorString()); buf.append(" (start of recursive cycle)"); buf.append("\n"); buf.append("..."); break; } seen.add(p); buf.append(p.getTemplateDeclaratorString()); if ( p.attributes!=null ) { buf.append(", attributes=["); int i = 0; for (Iterator iter = p.attributes.keySet().iterator(); iter.hasNext();) { String attrName = (String) iter.next(); if ( i>0 ) { buf.append(", "); } i++; buf.append(attrName); Object o = p.attributes.get(attrName); if ( o instanceof StringTemplate ) { StringTemplate st = (StringTemplate)o; 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(); } public String getTemplateDeclaratorString() { StringBuffer buf = new StringBuffer(); buf.append("<"); buf.append(getName()); buf.append("("); buf.append(formalArguments.keySet()); buf.append(")@"); buf.append(String.valueOf(getTemplateID())); buf.append(">"); return buf.toString(); } protected String getTemplateHeaderString(boolean showAttributes) { if ( showAttributes ) { StringBuffer buf = new StringBuffer(); buf.append(getName()); if ( attributes!=null ) { buf.append(attributes.keySet()); } 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. */ protected void checkNullAttributeAgainstFormalArguments( StringTemplate self, String attribute) { if ( self.getFormalArguments()==FormalArgument.UNKNOWN ) { // bypass unknown arg lists if ( self.enclosingInstance!=null ) { checkNullAttributeAgainstFormalArguments( 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 ( attributes==null ) { return; } Set names = attributes.keySet(); Iterator iter = names.iterator(); // if in names and not in referenced attributes, trouble while ( iter.hasNext() ) { String name = (String)iter.next(); if ( referencedAttributes!=null && !referencedAttributes.contains(name) ) { 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]". */ public String getEnclosingInstanceStackString() { 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 isRegion; } public void setIsRegion(boolean isRegion) { this.isRegion = isRegion; } public void addRegionName(String name) { if ( regions==null ) { regions = new HashSet(); } regions.add(name); } /** Does this template ref or embed region name? */ public boolean containsRegionName(String name) { if ( regions==null ) { return false; } return regions.contains(name); } public int getRegionDefType() { return regionDefType; } public void setRegionDefType(int regionDefType) { this.regionDefType = regionDefType; } public String toDebugString() { StringBuffer buf = new StringBuffer(); buf.append("template-"+getTemplateDeclaratorString()+":"); buf.append("chunks="); if ( chunks!=null ) { buf.append(chunks.toString()); } buf.append("attributes=["); if ( attributes!=null ) { Set attrNames = attributes.keySet(); int n=0; for (Iterator iter = attrNames.iterator(); iter.hasNext();) { if ( n>0 ) { buf.append(','); } String name = (String) iter.next(); buf.append(name+"="); Object value = attributes.get(name); if ( value instanceof StringTemplate ) { buf.append(((StringTemplate)value).toDebugString()); } else { buf.append(value); } n++; } buf.append("]"); } return buf.toString(); } /** Don't print values, just report the nested structure with attribute names. * Follow (nest) attributes that are templates only. */ public String toStructureString() { return toStructureString(0); } public String toStructureString(int indent) { StringBuffer buf = new StringBuffer(); for (int i=1; i<=indent; i++) { // indent buf.append(" "); } buf.append(getName()); buf.append(attributes.keySet()); buf.append(":\n"); if ( attributes!=null ) { Set attrNames = attributes.keySet(); for (Iterator iter = attrNames.iterator(); iter.hasNext();) { String name = (String) iter.next(); Object value = attributes.get(name); if ( value instanceof StringTemplate ) { // descend buf.append(((StringTemplate)value).toStructureString(indent+1)); } else { if ( value instanceof List ) { List alist = (List)value; for (int i = 0; i < alist.size(); i++) { Object o = (Object) alist.get(i); if ( o instanceof StringTemplate ) { // descend buf.append(((StringTemplate)o).toStructureString(indent+1)); } } } else if ( value instanceof Map ) { Map m = (Map)value; Collection mvalues = m.values(); for (Iterator iterator = mvalues.iterator(); iterator.hasNext();) { Object o = (Object) iterator.next(); if ( o instanceof StringTemplate ) { // descend buf.append(((StringTemplate)o).toStructureString(indent+1)); } } } } } } return buf.toString(); } /* public String getDOTForDependencyGraph(boolean showAttributes) { StringBuffer buf = new StringBuffer(); buf.append("digraph prof {\n"); HashMap edges = new HashMap(); this.getDependencyGraph(edges, showAttributes); Set sourceNodes = edges.keySet(); // for each source template for (Iterator it = sourceNodes.iterator(); it.hasNext();) { String src = (String) it.next(); Set targetNodes = (Set)edges.get(src); // for each target template for (Iterator it2 = targetNodes.iterator(); it2.hasNext();) { String trg = (String) it2.next(); buf.append('"'); buf.append(src); buf.append('"'); buf.append("->"); buf.append('"'); buf.append(trg); buf.append("\"\n"); } } buf.append("}"); return buf.toString(); } */ /** Generate a DOT file for displaying the template enclosure graph; e.g., digraph prof { "t1" -> "t2" "t1" -> "t3" "t4" -> "t5" } */ public StringTemplate getDOTForDependencyGraph(boolean showAttributes) { String structure = "digraph StringTemplateDependencyGraph {\n" + "node [shape=$shape$, $if(width)$width=$width$,$endif$" + " $if(height)$height=$height$,$endif$ fontsize=$fontsize$];\n" + "$edges:{e|\"$e.src$\" -> \"$e.trg$\"\n}$" + "}\n"; StringTemplate graphST = new StringTemplate(structure); HashMap edges = new HashMap(); this.getDependencyGraph(edges, showAttributes); Set sourceNodes = edges.keySet(); // for each source template for (Iterator it = sourceNodes.iterator(); it.hasNext();) { String src = (String) it.next(); Set targetNodes = (Set)edges.get(src); // for each target template for (Iterator it2 = targetNodes.iterator(); it2.hasNext();) { String trg = (String) it2.next(); graphST.setAttribute("edges.{src,trg}", src, trg); } } graphST.setAttribute("shape", "none"); graphST.setAttribute("fontsize", "11"); graphST.setAttribute("height", "0"); // make height return graphST; } /** Get a list of n->m edges where template n contains template m. * The map you pass in is filled with edges: key->value. Useful * for having DOT print out an enclosing template graph. It * finds all direct template invocations too like but not * indirect ones like <(name)()>. * * Ack, I just realized that this is done statically and hence * cannot see runtime arg values on statically included templates. * Hmm...someday figure out to do this dynamically as if we were * evaluating the templates. There will be extra nodes in the tree * because we are static like method and method[...] with args. */ public void getDependencyGraph(Map edges, boolean showAttributes) { String srcNode = this.getTemplateHeaderString(showAttributes); if ( attributes!=null ) { Set attrNames = attributes.keySet(); for (Iterator iter = attrNames.iterator(); iter.hasNext();) { String name = (String) iter.next(); Object value = attributes.get(name); if ( value instanceof StringTemplate ) { String targetNode = ((StringTemplate)value).getTemplateHeaderString(showAttributes); putToMultiValuedMap(edges,srcNode,targetNode); ((StringTemplate)value).getDependencyGraph(edges,showAttributes); // descend } else { if ( value instanceof List ) { List alist = (List)value; for (int i = 0; i < alist.size(); i++) { Object o = (Object) alist.get(i); if ( o instanceof StringTemplate ) { String targetNode = ((StringTemplate)o).getTemplateHeaderString(showAttributes); putToMultiValuedMap(edges,srcNode,targetNode); ((StringTemplate)o).getDependencyGraph(edges,showAttributes); // descend } } } else if ( value instanceof Map ) { Map m = (Map)value; Collection mvalues = m.values(); for (Iterator iterator = mvalues.iterator(); iterator.hasNext();) { Object o = (Object) iterator.next(); if ( o instanceof StringTemplate ) { String targetNode = ((StringTemplate)o).getTemplateHeaderString(showAttributes); putToMultiValuedMap(edges,srcNode,targetNode); ((StringTemplate)o).getDependencyGraph(edges,showAttributes); // descend } } } } } } // look in chunks too for template refs for (int i = 0; chunks!=null && i < chunks.size(); i++) { Expr expr = (Expr) chunks.get(i); if ( expr instanceof ASTExpr ) { ASTExpr e = (ASTExpr)expr; AST tree = e.getAST(); AST includeAST = new CommonAST(new CommonToken(ActionEvaluator.INCLUDE,"include")); ASTEnumeration it = tree.findAllPartial(includeAST); while (it.hasMoreNodes()) { AST t = (AST) it.nextNode(); String templateInclude = t.getFirstChild().getText(); System.out.println("found include "+templateInclude); putToMultiValuedMap(edges,srcNode,templateInclude); StringTemplateGroup group = getGroup(); if ( group!=null ) { StringTemplate st = group.getInstanceOf(templateInclude); // descend into the reference template st.getDependencyGraph(edges, showAttributes); } } } } } /** Manage a hash table like it has multiple unique values. Map. */ protected void putToMultiValuedMap(Map map, Object key, Object value) { HashSet bag = (HashSet)map.get(key); if ( bag==null ) { bag = new HashSet(); map.put(key, bag); } bag.add(value); } public void printDebugString() { System.out.println("template-"+getName()+":"); System.out.print("chunks="); System.out.println(chunks.toString()); if ( attributes==null ) { return; } System.out.print("attributes=["); Set attrNames = attributes.keySet(); int n=0; for (Iterator iter = attrNames.iterator(); iter.hasNext();) { if ( n>0 ) { System.out.print(','); } String name = (String) iter.next(); Object value = attributes.get(name); if ( value instanceof StringTemplate ) { System.out.print(name+"="); ((StringTemplate)value).printDebugString(); } else { if ( value instanceof List ) { ArrayList alist = (ArrayList)value; for (int i = 0; i < alist.size(); i++) { Object o = (Object) alist.get(i); System.out.print(name+"["+i+"] is "+o.getClass().getName()+"="); if ( o instanceof StringTemplate ) { ((StringTemplate)o).printDebugString(); } else { System.out.println(o); } } } else { System.out.print(name+"="); System.out.println(value); } } n++; } System.out.print("]\n"); } public String toString() { return toString(StringTemplateWriter.NO_WRAP); } public String toString(int lineWidth) { StringWriter out = new StringWriter(); // Write the output to a StringWriter StringTemplateWriter wr = group.getStringTemplateWriter(out); wr.setLineWidth(lineWidth); try { write(wr); } catch (IOException io) { error("Got IOException writing to writer "+wr.getClass().getName()); } // reset so next toString() does not wrap; normally this is a new writer // each time, but just in case they override the group to reuse the // writer. wr.setLineWidth(StringTemplateWriter.NO_WRAP); return out.toString(); } } stringtemplate-3.2.1/src/org/antlr/stringtemplate/StringTemplateErrorListener.java0000644000175000017500000000325611256235341030612 0ustar twernertwerner/* [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; /** Lets you specify where errors, warnings go. Warning: debug is useful at * the moment. */ public interface StringTemplateErrorListener { public void error(String msg, Throwable e); public void warning(String msg); } stringtemplate-3.2.1/src/org/antlr/stringtemplate/PathGroupLoader.java0000644000175000017500000001031611256235341026163 0ustar twernertwernerpackage org.antlr.stringtemplate; import org.antlr.stringtemplate.language.AngleBracketTemplateLexer; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; /** A brain dead loader that looks only in the directory(ies) you * specify in the ctor. * You may specify the char encoding. * NOTE: this does not work when you jar things up! Use * CommonGroupLoader instead in that case */ public class PathGroupLoader implements StringTemplateGroupLoader { /** List of ':' separated dirs to pull groups from */ protected List dirs = null; protected StringTemplateErrorListener errors = null; /** How are the files encoded (ascii, UTF8, ...)? You might want to read * UTF8 for example on an ascii machine. */ String fileCharEncoding = System.getProperty("file.encoding"); public PathGroupLoader(StringTemplateErrorListener errors) { this.errors = errors; } /** Pass a single dir or multiple dirs separated by colons from which * to load groups/interfaces. */ public PathGroupLoader(String dirStr, StringTemplateErrorListener errors) { this.errors = errors; StringTokenizer tokenizer = new StringTokenizer(dirStr, ":", false); while (tokenizer.hasMoreElements()) { String dir = (String) tokenizer.nextElement(); if ( dirs==null ) { dirs = new ArrayList(); } dirs.add(dir); } } /** Load a group with a specified superGroup. Groups with * region definitions must know their supergroup to find templates * during parsing. */ public StringTemplateGroup loadGroup(String groupName, Class templateLexer, StringTemplateGroup superGroup) { StringTemplateGroup group = null; BufferedReader br = null; // group file format defaults to <...> Class lexer = AngleBracketTemplateLexer.class; if ( templateLexer!=null ) { lexer = templateLexer; } try { br = locate(groupName+".stg"); if ( br==null ) { error("no such group file "+groupName+".stg"); return null; } group = new StringTemplateGroup(br, lexer, errors, superGroup); br.close(); br = null; } catch (IOException ioe) { error("can't load group "+groupName, ioe); } finally { if ( br!=null ) { try { br.close(); } catch (IOException ioe2) { error("Cannot close template group file: "+groupName+".stg", ioe2); } } } return group; } public StringTemplateGroup loadGroup(String groupName, StringTemplateGroup superGroup) { return loadGroup(groupName, null, superGroup); } public StringTemplateGroup loadGroup(String groupName) { return loadGroup(groupName, null); } public StringTemplateGroupInterface loadInterface(String interfaceName) { StringTemplateGroupInterface I = null; try { BufferedReader br = locate(interfaceName+".sti"); if ( br==null ) { error("no such interface file "+interfaceName+".sti"); return null; } I = new StringTemplateGroupInterface(br, errors); } catch (IOException ioe) { error("can't load interface "+interfaceName, ioe); } return I; } /** Look in each directory for the file called 'name'. */ protected BufferedReader locate(String name) throws IOException { for (int i = 0; i < dirs.size(); i++) { String dir = (String) dirs.get(i); String fileName = dir+"/"+name; if ( new File(fileName).exists() ) { FileInputStream fis = new FileInputStream(fileName); InputStreamReader isr = getInputStreamReader(fis); return new BufferedReader(isr); } } return null; } protected InputStreamReader getInputStreamReader(InputStream in) { InputStreamReader isr = null; try { isr = new InputStreamReader(in, fileCharEncoding); } catch (UnsupportedEncodingException uee) { error("Invalid file character encoding: "+fileCharEncoding); } return isr; } public String getFileCharEncoding() { return fileCharEncoding; } public void setFileCharEncoding(String fileCharEncoding) { this.fileCharEncoding = fileCharEncoding; } public void error(String msg) { error(msg, null); } public void error(String msg, Exception e) { if ( errors!=null ) { errors.error(msg,e); } else { System.err.println("StringTemplate: "+msg); if ( e!=null ) { e.printStackTrace(); } } } } stringtemplate-3.2.1/src/org/antlr/stringtemplate/CommonGroupLoader.java0000644000175000017500000000304511256235341026520 0ustar twernertwernerpackage org.antlr.stringtemplate; import java.io.*; /** A simple loader that looks only in the directory(ies) you * specify in the ctor, but it uses the classpath rather than * absolute dirs so it can be used when the ST application is jar'd up. * You may specify the char encoding. */ public class CommonGroupLoader extends PathGroupLoader { public CommonGroupLoader(StringTemplateErrorListener errors) { super(errors); } /** Pass a single dir or multiple dirs separated by colons from which * to load groups/interfaces. These are interpreted as relative * paths to be used with CLASSPATH to locate groups. E.g., * If you pass in "org/antlr/codegen/templates" and ask to load * group "foo" it will try to load via classpath as * "org/antlr/codegen/templates/foo". */ public CommonGroupLoader(String dirStr, StringTemplateErrorListener errors) { super(dirStr,errors); } /** Look in each relative directory for the file called 'name'. * Load via classpath. */ protected BufferedReader locate(String name) throws IOException { for (int i = 0; i < dirs.size(); i++) { String dir = (String) dirs.get(i); String fileName = dir+"/"+name; //System.out.println("trying "+fileName); ClassLoader cl = Thread.currentThread().getContextClassLoader(); InputStream is = cl.getResourceAsStream(fileName); if ( is==null ) { cl = this.getClass().getClassLoader(); is = cl.getResourceAsStream(fileName); } if ( is!=null ) { return new BufferedReader(getInputStreamReader(is)); } } return null; } }stringtemplate-3.2.1/src/org/antlr/stringtemplate/StringTemplateWriter.java0000644000175000017500000000555411256235341027272 0ustar twernertwerner/* [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.IOException; /** Generic StringTemplate output writer filter. * * Literals and the elements of expressions are emitted via write(). * Separators are emitted via writeSeparator() because they must be * handled specially when wrapping lines (we don't want to wrap * in between an element and it's separator). */ public interface StringTemplateWriter { public static final int NO_WRAP = -1; void pushIndentation(String indent); String popIndentation(); void pushAnchorPoint(); void popAnchorPoint(); void setLineWidth(int lineWidth); /** Write the string and return how many actual chars were written. * With autoindentation and wrapping, more chars than length(str) * can be emitted. No wrapping is done. */ int write(String str) throws IOException; /** Same as write, but wrap lines using the indicated string as the * wrap character (such as "\n"). */ int write(String str, String wrap) throws IOException; /** Because we might need to wrap at a non-atomic string boundary * (such as when we wrap in between template applications * ]}; wrap>) we need to expose the wrap string * writing just like for the separator. */ public int writeWrapSeparator(String wrap) throws IOException; /** Write a separator. Same as write() except that a \n cannot * be inserted before emitting a separator. */ int writeSeparator(String str) throws IOException; } stringtemplate-3.2.1/src/org/antlr/stringtemplate/AutoIndentWriter.java0000644000175000017500000001763611256235341026406 0ustar twernertwerner/* [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.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.List; /** Essentially a char filter that knows how to auto-indent output * by maintaining a stack of indent levels. I set a flag upon newline * and then next nonwhitespace char resets flag and spits out indention. * The indent stack is a stack of strings so we can repeat original indent * not just the same number of columns (don't have to worry about tabs vs * spaces then). * * Anchors are char positions (tabs won't work) that indicate where all * future wraps should justify to. The wrap position is actually the * larger of either the last anchor or the indentation level. * * This is a filter on a Writer. * * \n is the proper way to say newline for options and templates. * Templates can mix them but use \n for sure and options like * wrap="\n". ST will generate the right thing. Override the default (locale) * newline by passing in a string to the constructor. */ public class AutoIndentWriter implements StringTemplateWriter { /** stack of indents; use List as it's much faster than Stack. Grows * from 0..n-1. List */ protected List indents = new ArrayList(); /** Stack of integer anchors (char positions in line); avoid Integer * creation overhead. */ protected int[] anchors = new int[10]; protected int anchors_sp = -1; /** \n or \r\n? */ protected String newline; protected Writer out = null; protected boolean atStartOfLine = true; /** Track char position in the line (later we can think about tabs). * Indexed from 0. We want to keep charPosition <= lineWidth. * This is the position we are *about* to write not the position * last written to. */ protected int charPosition = 0; protected int lineWidth = NO_WRAP; protected int charPositionOfStartOfExpr = 0; public AutoIndentWriter(Writer out, String newline) { this.out = out; indents.add(null); // s oftart with no indent this.newline = newline; } public AutoIndentWriter(Writer out) { this(out, System.getProperty("line.separator")); } public void setLineWidth(int lineWidth) { this.lineWidth = lineWidth; } /** Push even blank (null) indents as they are like scopes; must * be able to pop them back off stack. * * To deal with combined anchors and indentation, force indents to * include any current anchor point. If current anchor is beyond * current indent width, add the difference to the indent to be added. * * This prevents a check later to deal with anchors when starting new line. */ public void pushIndentation(String indent) { int lastAnchor = 0; int indentWidth = getIndentationWidth(); // If current anchor is beyond current indent width, add in difference if ( anchors_sp>=0 && anchors[anchors_sp]>indentWidth ) { lastAnchor = anchors[anchors_sp]; StringBuffer buf = getIndentString(lastAnchor-indentWidth); if ( indent!=null ) buf.append(indent); // don't add if null indents.add(buf.toString()); return; } indents.add(indent); } public String popIndentation() { return (String)indents.remove(indents.size()-1); } public void pushAnchorPoint() { if ( (anchors_sp +1)>=anchors.length ) { int[] a = new int[anchors.length*2]; System.arraycopy(anchors, 0, a, 0, anchors.length-1); anchors = a; } anchors_sp++; anchors[anchors_sp] = charPosition; } public void popAnchorPoint() { anchors_sp--; } public int getIndentationWidth() { int n = 0; for (int i=0; i= lineWidth ) { // ok to wrap // Walk wrap string and look for A\nB. Spit out A\n // then spit indent or anchor, whichever is larger // then spit out B. for (int i=0; i. */ public StringTemplateGroup loadGroup(String groupName, Class templateLexer, StringTemplateGroup superGroup); /** Load the interface called interfaceName from somewhere. Return null * if no interface is found. */ public StringTemplateGroupInterface loadInterface(String interfaceName); } stringtemplate-3.2.1/src/org/antlr/stringtemplate/StringTemplateGroupInterface.java0000644000175000017500000001432311256235341030725 0ustar twernertwernerpackage org.antlr.stringtemplate; import org.antlr.stringtemplate.language.*; import java.util.*; import java.io.Reader; /** A group interface is like a group without the template implementations; * there are just template names/argument-lists like this: * * interface foo; * class(name,fields); * method(name,args,body); * */ public class StringTemplateGroupInterface { /** What is the group name */ protected String name; /** Maps template name to TemplateDefinition object */ protected Map templates = new LinkedHashMap(); /** Are we derived from another group? Templates not found in this group * will be searched for in the superGroup recursively. */ protected StringTemplateGroupInterface superInterface = null; /** Where to report errors. All string templates in this group * use this error handler by default. */ protected StringTemplateErrorListener listener = DEFAULT_ERROR_LISTENER; public static StringTemplateErrorListener DEFAULT_ERROR_LISTENER = new StringTemplateErrorListener() { public void error(String s, Throwable e) { System.err.println(s); if ( e!=null ) { e.printStackTrace(System.err); } } public void warning(String s) { System.out.println(s); } }; /** All the info we need to track for a template defined in an interface */ static class TemplateDefinition { public String name; public LinkedHashMap formalArgs; // LinkedHashMap public boolean optional = false; public TemplateDefinition(String name, LinkedHashMap formalArgs, boolean optional) { this.name = name; this.formalArgs = formalArgs; this.optional = optional; } } public StringTemplateGroupInterface(Reader r) { this(r,DEFAULT_ERROR_LISTENER,(StringTemplateGroupInterface)null); } public StringTemplateGroupInterface(Reader r, StringTemplateErrorListener errors) { this(r,errors,(StringTemplateGroupInterface)null); } /** Create an interface from the input stream */ public StringTemplateGroupInterface(Reader r, StringTemplateErrorListener errors, StringTemplateGroupInterface superInterface) { this.listener = errors; setSuperInterface(superInterface); parseInterface(r); } public StringTemplateGroupInterface getSuperInterface() { return superInterface; } public void setSuperInterface(StringTemplateGroupInterface superInterface) { this.superInterface = superInterface; } protected void parseInterface(Reader r) { try { InterfaceLexer lexer = new InterfaceLexer(r); InterfaceParser parser = new InterfaceParser(lexer); parser.groupInterface(this); //System.out.println("read interface\n"+this.toString()); } catch (Exception e) { String name = ""; if ( getName()!=null ) { name = getName(); } error("problem parsing group "+name+": "+e, e); } } public void defineTemplate(String name, LinkedHashMap formalArgs, boolean optional) { TemplateDefinition d = new TemplateDefinition(name,formalArgs,optional); templates.put(d.name,d); } /** Return a list of all template names missing from group that are defined * in this interface. Return null if all is well. */ public List getMissingTemplates(StringTemplateGroup group) { List missing = new ArrayList(); for (Iterator it = templates.keySet().iterator(); it.hasNext();) { String name = (String)it.next(); TemplateDefinition d = (TemplateDefinition)templates.get(name); if ( !d.optional && !group.isDefined(d.name) ) { missing.add(d.name); } } if ( missing.size()==0 ) { missing = null; } return missing; } /** Return a list of all template sigs that are present in the group, but * that have wrong formal argument lists. Return null if all is well. */ public List getMismatchedTemplates(StringTemplateGroup group) { List mismatched = new ArrayList(); for (Iterator it = templates.keySet().iterator(); it.hasNext();) { String name = (String)it.next(); TemplateDefinition d = (TemplateDefinition)templates.get(name); if ( group.isDefined(d.name) ) { StringTemplate defST = group.getTemplateDefinition(d.name); Map formalArgs = defST.getFormalArguments(); boolean ack = false; if ( (d.formalArgs!=null && formalArgs==null) || (d.formalArgs==null && formalArgs!=null) || d.formalArgs.size() != formalArgs.size() ) { ack=true; } if ( !ack ) { for (Iterator it2 = formalArgs.keySet().iterator(); it2.hasNext();) { String argName = (String)it2.next(); if ( d.formalArgs.get(argName)==null ) { ack=true; break; } } } if ( ack ) { //System.out.println(d.formalArgs+"!="+formalArgs); mismatched.add(getTemplateSignature(d)); } } } if ( mismatched.size()==0 ) { mismatched = null; } return mismatched; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void error(String msg) { error(msg, null); } public void error(String msg, Exception e) { if ( listener!=null ) { listener.error(msg,e); } else { System.err.println("StringTemplate: "+msg); if ( e!=null ) { e.printStackTrace(); } } } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("interface "); buf.append(getName()); buf.append(";\n"); for (Iterator it = templates.keySet().iterator(); it.hasNext();) { String name = (String)it.next(); TemplateDefinition d = (TemplateDefinition)templates.get(name); buf.append( getTemplateSignature(d) ); buf.append(";\n"); } return buf.toString(); } protected String getTemplateSignature(TemplateDefinition d) { StringBuffer buf = new StringBuffer(); if ( d.optional ) { buf.append("optional "); } buf.append(d.name); if ( d.formalArgs!=null ) { StringBuffer args = new StringBuffer(); args.append('('); int i=1; for (Iterator it = d.formalArgs.keySet().iterator(); it.hasNext();) { String name = (String) it.next(); if ( i>1 ) { args.append(", "); } args.append(name); i++; } args.append(')'); buf.append(args); } else { buf.append("()"); } return buf.toString(); } } stringtemplate-3.2.1/build.xml0000755000175000017500000002457011256235341016353 0ustar twernertwerner stringtemplate-3.2.1/CHANGES.txt0000644000175000017500000007673411256235341016351 0ustar twernertwernerChanges to ST (StringTemplate). #### Releases 3.2.1: September 22, 2009 3.2: June 11, 2008 3.1: January 23, 2008 3.0: September 6, 2006 2.2: August 5, 2005 2.1: January 22, 2005 2.0: July 16, 2004 1.0.3: Feb 5, 2004 1.0.2: Oct 14, 2003 #### Fixed bugs and changes 09-22-2009 -- 3.2.1 release 07-11-2009 o If default arg is a template with single expression wrapped in parens, x={<(...)>}, then eval to string rather than setting x to the template for later eval. Useful in rare cases where the expression can change value when you read it, such as accessing time value or random number generator object. o Added line break operator <\\>. It consumes remaining whitespace on that line, the first and then any whitespace. Added a number of unit tests. example: "foo <\\> bar" emits "foo bar". All of the whitespace after the <\\> gets thrown away like a comment. 07-02-2009 o IF with false condition results in missing not empty value. So, }; separator=","> doesn't emit a separator for non-cool names. See http://www.antlr.org/pipermail/stringtemplate-interest/2009-July/002020.html WARNING: You now pay a penalty now for a separator if the iterated value is nullable. Nullable if iterable or a template with nothing buf IF statements. If nullable, ST writes each element to a temp buffer before emitting. Expensive. 08-13-2008 o IF conditionals and list elements couldn't use template application. Can do $if(names:{$it$})$Fail!$endif$ and $[names:{$it$!},phones]$ and $[names, ["foo","bar"]:{$it$!},phones]$ Can't use IF inside of a [...] because those are expressions not statements. 08-11-2008 o Made template output sensitive to the anchor of any enclosing template instances. ST used to ignore anchor unless you had a wrap and now it looks at anchor like an indent; uses widest. ST used to give this: { a, { 1, 2, 3 } , b } for these templates where the first was stuck into second <\n>{ }<\n> { } but now gives: { a, { 1, 2, 3 } , b }; see testSubtemplatesAnchorToo() o To deal with combined anchors and indentation, force indents to include any current anchor point. Prevents a check later in write to deal with anchors when starting new line. See pushIndentation() 06-11-2008 -- 3.2 release o Fixed ST-36; allow o Fixed ST-37; chk for null 06-04-2008 o Added \r\n normalization in AutoIndentWriter. Converts \r\n or \n to whatever the writer's newline instance var is. wrap="\n" will give the proper newline by locale as will \n and \r\n in the templates or even incoming data attributes (toString()'d of course). Added unit tests. It even works with special literals <\r\n> and <\n>. 06-03-2008 o Fixed ST-39; an obscure memory leak issue with embeddedInstances 06-02-2008 o rest and strip returned iterators. Made them return show list copies so recursion works. iterators have side-effects. Added 2 unit tests. o implemented trunc. returns all but last element. o Fix ST-33; [a,b] cat function used iterators; side-effect problem. 05-07-2008 o Had a problem with "int" : "0" in a map but ST as incoming lookup key. Decided that I'd lookup as raw object first so Integer lookup works but I try toString version if not found. Document this! 05-06-2008 o no longer calls toString() on k. :} was not working when aMap had Integer keys. Added unit test. 04-07-2008 o Made unit tests not depend on map order. commented out tests that fail. 02-11-2008 o debug tags now emit group name with tags. improves debugging ability. 01-23-2008 -- 3.1 release o reader was not closed in PathGroupLoader. o removed some counters used to test the efficiency of reflection cache. o updated unit tests to work with new improved error messages. o $first(list).prop$ is not allowed. Fixed and added a unit test. 12-29-2007 o Improved error message for "template not found". Shows template hierarchy now not just context (if any). E.g., Can't find template noRewrite.st; group hierarchy is [Java] 12-12-2007 o allows unicode escapes as expression literals but only if it's the whole expression: <\uFEA5\n\u00C2> Previously could only do one char and just the special ones like <\n>. 12-11-2007 o resolve ST-34. Super group loading was not using template lexer (<...> or $...$) according to subclass. Updated group loader interface. 11-09-2007 o added elseif. $if(x)$...$elseif(y)$...$else$...$endif$ o updated some unit tests (names, guts) to make more sense. o updated group.g and eval.g so that list literals can have empty atoms like $["a",,"b"]:{n | ...}; null="nullstring"$. 11-08-2007 o "default" was not a valid value in map. had testLiterals looking even at strings in lexer for group.g. ST-15 o ST-18 fixed. put close in a finally block. 08-30-2007 o i0 was not set when you applied a template to a single value. 08-17-2007 o Thomas Brandon pointed out that we have a bug in our if/else computation. You could not reference super.attr inside the if/else sub templates. August 6, 2007: 3.1b1 (starting towards a 3.1) 05-19-2007 o changed to 3.1b1 in anticipation of diong a 3.1 release using ANTLR v3. 05-03-2007 o Updated group.g to allow default clause by itself in map (from Caleb Lyness) o Caleb also revamped entire TestStringTemplate to run under windows. o Added 16 bit char unit test also. 01-30-2007 o Made convertArrayToList create an ArrayWrappedInList so it doesn't copy arrays any more. 01-27-2007 o John Snyders found bug in format stuff. Renderer was being called for string expr options. o Another bug fix by John. Length problem. ?? o added format option 10-30-2006 o \_ was not allowed in group/interface.g but in group.g. Now \_ is allowed as first char. 09-25-2006 o ST.dup() was not copying renderers field. September 6 -- 3.0 release 08-14-2006 o added toString to Aggregate so that setAttribute("foo.{x,y}", ...) and then referencing foo in isolation prints something useful. 08-09-2006 o had to fix that: << InputStream is = cl.getResourceAsStream(fileName); if ( is==null ) { cl = ErrorManager.class.getClassLoader(); is = cl.getResourceAsStream(fileName); } >> 08-07-2006 o allow different source of classloader: ClassLoader cl = Thread.currentThread().getContextClassLoader(); if ( cl==null ) { cl = this.getClass().getClassLoader(); } 07-26-2006 o fixed bug where separator did not appear in lists of stuff with lots of null entries. o map still iterates over values if you say but it is now shorthand for . Similarly walks over the keys. You can do stuff like: maps to }>. 07-24-2006 o added length(attribute) thanks to Kay Roepke. For now it does not work on strings; it works on attributes so length("foo") is 1 meaning 1 attribute. Nulls are counted in lists so a list of 300 nulls is length 300. If you don't want to count nulls, use length(strip(list)). o added strip(attribute) that returns an iterator that skips any null values. strip(x)=x when x is a single-valued attribute. Added StripIterator to handle this. 07-20-2006 o BACKWARD INCOMPATIBLE: I had to make a more clear distinction between empty and null. Null means there is nothing there whereas empty means the value is there but renders to an empty string. IF conditionals now evaluate to empty if condition is false. o BACKWARD INCOMPATIBLE: Changed how separators are generated. Now I generate a separator for any non-null value in the list even if that value is a conditional that evaluates to false. Iterated empty values always get a separator. Note that empty is not the same thing as missing. "" is not missing and hence will get a separator. This made the ASTExpr.write separator computation much simpler and allowed me to properly handle the new "null" option. o Added null=expr option on expressions. For null values in iterated attributes and single attributes that are null, use this value instead of skipping. For single valued attributes like It's a shorthand for n/a For iterated values you get 0 for or null list values. Works for template application like this also: }; null="0"> This does not replace empty strings like "" as they are not null. 07-11-2006 o made static maps in STG synchronized, also synchronized the look up/def methods for templates in STG. o removed reflection property lookup; too complex for value. profiling indicates it's a small cost. No thread synch issues either now. 06-24-2006 o template evaluation for anonymous templates did not properly look up overridden templates. The group for anonymous templates was not reset to be the current enclosing template's group (remember we can dynamically set the superGroup). 06-20-2006 o Signature changed to use AttributeRenderer: public void registerRenderer(Class attributeClassType, AttributeRenderer renderer) 06-19-2006 o If expr in <(expr):template()> evaluated to nothing, the template was still invoked. 06-12-2006 o added ability to show start/stop of template with .... clean up! emitTemplateStartDebugString/emitTemplateStopDebugString and doNotEmitDebugStringsForTemplate(tempaltename) and gate:emitDebugStartStopStrings(boolean) 06-03-2006 o Improved error when property ref causes the error internally. Now shows that exception rather than invocation target exception. o Couldn't handle List. Nested int[] was not iteratable. 06-02-2006 o Couldn't gen \ in a template. \ in a template escaped the <. \\ printed both slashes. Fixed. o added line wrap facility. st.toString(72). Wraps in between expressions or elements of a multiple value attribute if you use new expression option "wrap". It will not break line between element and separator. toString(72) followed by toString() does not wrap on the second invocation. Wrap is a soft width; does not break elements to enforce a hard right edge. WARNING: separators and wrap values are templates and are evaluated once *before* multi-valued expressions are evaluated. You cannot change the wrap based on, for example, . Default values for wrap="\n", anchor="true" (any non-null value means anchor). o Updated StringTemplateWriter: << void pushAnchorPoint(); void popAnchorPoint(); void setLineWidth(int lineWidth); /** Same as write, but wrap lines using the indicated string as the * wrap character (such as "\n"). */ int write(String str, String wrap) throws IOException; /** Write a separator. Same as write() except that a \n cannot * be inserted before emitting a separator. */ int writeSeparator(String str) throws IOException; >> o Examples of wrapping: << data(a) ::= < };\>> int[] a = { 1,9,2,3,9,20,2,1,4, 6,32,5,6,77,888,2,1,6,32,5,6,77, 4,9,20,2,1,4,63,9,20,2,1,4,6 }; data(a) ::= < };\>> int[] a = { 1,9,2,3,9,20,2,1,4, 6,32,5,6,77, 888,2,1,6,32, 5,6,77,4,9,20, 2,1,4,63,9,20, 2,1,4,6 }; data(a) ::= <}; anchor> };\>> int[] a = { 1,9,2,3,9,20,2,1,4, 6,32,5,6,77,888,2, 1,6,32,5,6,77,4,9, 20,2,1,4,63,9,20,2, 1,4,6 }; >> 05-27-2006 o Couldn't use \\\{ inside of a {...} anonymous template. 05-18-2006 o Fixed: you could not have template expressions, just simple expressions in indirect template expressions like $data:("foo":a())()$. I decided not to allow IF expressions inside. o now throws exception when dots are in template names or attribute names o don't set "it" nor "attr" default attributes if there is a parameter to an anonymous block like o Bug fix. If you passed in a list and then another element, it added it to the list you passed in! Now, I make a (shallow) copy of the list. o Bug fix. If you passed an element then a list to an attr and I think it didn't flatten out properly! o added build.xml ANT file (ick) o {} and "" work as arguments now to templates 05-17-2006 o Couldn't escape in template group. \>> failed as did {...\}} for anonymous templates. o When creating an aggregate list, couldn't have spaces in {...} such as "folders.{a, b}". o Embedded templates such as {...} anonymous templates couldn't see the renderers for enclosing templates. Easy to set one renderer in root template for, say, Date and forget about it. If none found for that class in containment hierarchy, then group hierarchy is checked. 05-12-2006 o using nativegroup to create instances now in ST.getInstanceOf. Needed so that super.foo works properly. THe new instance's group will point at creating group so polymorphism works properly. 04-07-2006 o BACKWARD INCOMPATIBLE: <...> is now default delimiter for group files. 04-01-2006 o note in doc that map strings are now templates and that <<...>> works too. default or others can have empty values (implying no value) or use "key" but not in template; it's a keyword. Also, default must be at end now (and only 1). Default value is empty as before. To return null, use "default :" at end. Can use empty values too: {"float":}, {"int":"0"}, ... 03-4-2006 o added cache for all obj.prop lookups o added PathGroupLoader/CommonGroupLoader (which uses CLASSPATH) 03-1-2006 o added i0 which is like i except indexed from 0 not 1. o auto defined attribute i was not defined for case. ooops. 02-11-2006 o You couldn't have '=' in a string if preceded by '+' like foo+"ick=". 01-27-2006 o Added default lexer mechanism for groups so you can set once public static void registerDefaultLexer(Class lexerClass) 01-02-2005 o Added STG.getInstanceOf(name,attributes) 12-28-2005 o Fixed bug where an expr on the first line that yields no output left a blank line. 12-27-2005 o Added group inheritance notation; added unit tests. setSuperGroup(name) now does something useful. Notation: group subG : superG; 12-24-2005 o Added interfaces. See unit tests. group Java implements ANTLRCoreTarget; rule(...) ::= "..." ... You can say "optional template(args);" also. Uses group loader to find interfaces. o Added CommonGroupLoader so you can reference groups/interfaces now in group files etc... String tmpdir = System.getProperty("java.io.tmpdir"); StringTemplateGroup.registerGroupLoader(new CommonGroupLoader(tmpdir,errors)); The tmpdir can be "dir1:dir2:dir3" etc... o There was a bug in StringTemplateGroup.isDefined that it always returned true. o Added StringTemplate.getDependencyGraph() to get a list of n->m edges where template n contains template m. Also made convenient getDOTForDependencyGraph(). You get a template back that lets you reset node shape, fontsize, width, height attributes. Use removeAttribute before setting so you are sure you only get one value. o Added StringTemplate.toStructureString() to help discover nested structure. 11-25-2005 If you iterated multiple empty attributes, it iterated once with null values. Bizarre. Fixed. 11-12-2005 Bug in polymorphism when an overridden template called its super which called another template which was also overridden; didn't call the overridden method. Fixed getInstanceOf() so that it always sets the proper group so polymorphic template lookup also starts at the right group. Test testLazyEvalOfSuperInApplySuperTemplateRef was wrong...The "super." prefix is (like in Java, ...) a scope override and is always evaluated relative to the template in which it was defined not the template in which it is evaluate! Ugh. I *think* I have this polymorphism nailed down now. 11-11-2005 Improving error messages to be more specific when you get a parser error. I'm including more context info and hopefully the file within a group file the error occurs. The defaultGroup is now public so you can know StringTemplate's default group when you see it: << public static StringTemplateGroup defaultGroup = new StringTemplateGroup("defaultGroup", "."); >> 10-27-2005 Template polymorphism bug: wouldn't work for references in IF clauses! 10-26-2005 Added regions. 10-23-2005 Any Map instance is now allowed as a "map" attribute not just Hashtable, HashMap. 10-14-2005 NullPtrExc if you registered a renderer and sent an object as an attribute of another type! 10-09-2005 The tree viewer didn't work; class cast problem with Hashtable vs HashMap. 07-31-2005 Thanks to Joe Soroka, he showed me how to fix some weird thing in Java where public members of an anonymous class weren't visible to StringTemplate. You have to setAccessible on the field or method object. Bizarre. 07-23-2005 o removed debug code as it's useless/broken 07-14-2005 o decided that {+} should not be the list creation operator. {[a,b,c]} should be the thing as it mirrors the maps in group files. I want {+} to mean add still. o also decided that default arg values are templates only if "\{...}" is used and strings in arg lists are just strings. I added \{...} instead: $bold(it=\{$name$ Parr})$ instead. Default values can be string and {...} as can args. You can have {...} on left side of apply now: $\{foo}:\{($it$)}$ 07-12-2005 o Decided that {+} should always return a multi-valued attribute; _this is backward incompatible for anyone using + to mean string cat_. Instead of << $link(url="/home/"+user)$ >> now do this: << $link(url="/home/$user$")$ >> 07-09-2005 o added multiple attributes to left of the apply operator; works for anonymous templates only! $names,phones:{n,p | $n$: $p$}$. An error is generated if you have too many args for the number of parallel lists. Iteration proceeds while at least one of the attributes ({names} or {phones}, in this case) has values. o added '+' cat operator for multi-valued attributes, yielding single, longer multi-valued attribute. $mine+yours$ is a new list with both elements; all of "mine" first then all of yours. o allows any template invocation to assume sole argument name if just one formal argument. If you do {$bold(name)$} and {bold} has one formal argument, then it gets the value of name. This works also for template application: << test(names) ::= << >> bold(x) ::= "**" italics(y) ::= "__" >> Note: The binding of a value to the name of a sole formal argument is done dynamically so that indirect template invocation and lazy evaluation stuff works properly. For example {(templateName)(value)} should work for different templates with differently-name (but sole) args. See unit test testInvokeIndirectTemplateWithSingleFormalArgs(). o I changed the first, rest, tail operators from yesterday. It was weird doing {users:first()}...seems like {first(users)} is better. This introduces a function-like syntax, which necessitated the "assign to sole formal arg" functionality above that supports things like {bold(name)}. Makes it possible to say {first(rest(names))} to get second element now. Previous syntax made it impossible. 07-08-2005 o Added attribute functions: first (get first element), last (get last element) and tail (get everything but first element). [backward incompatible if you used first,last,tail as an attribute or template name] o if you are applying a template to a list and that template only has one formal argument, that arg gets the same value as the iterated value, "it". I.e., previously this didn't work: $list:bold()$ where bold was << bold(item) ::= "$item$" >> A template define as << bold() ::= "$it" >> would still work though. o You can define arguments for anonymous templates now, which is much nicer that using all the time: << $names:{n| $n$}; separator=","$ >> o To define an empty template, you had to write <<>>; "" didn't work. 07-06-2005 o Added maps to the group: << typeInitMap ::= ["int"="0", "float"="0.0", default="null"] >> then within a template you can refer to them {}, which returns "0". Those strings are actually templates, but I can't really think of a use for that just yet. ;) If your type name is an attribute not a constant like int, then use {}. The maps are defined in the group's scope and are visible if no attribute hides them. For example, if you define a formal argument called {typeInitMap} in template {foo} then {foo} cannot see the map defined in the group (though you could pass it in, which would be the point). If a name is not an attribute and it's not in the group's maps table, then the super group is consulted etc... You may not redefine a map and it may not have the same name as a template in that group. The {default} value is used if you use a key as a property that doesn't exist. For example {} returns "{null}". 07-05-2005 o Added renderers per template and group. Templates are inherited from super group. Thanks to Anton Keks for his suggestion and sample implementation. 06-26-2005 o literal arguments are now templates not just strings. :) You can even use <<...>> literals as argument now. In bug list: Template inclusion expressions won't accept a nested template as an argument. I'd like to be able to write , which would mean the same thing as . o added default argument templates like bold(x="empty") ::= ... Note: because of lazy evaluation semantics, default value templates may refer to argument values. Everything is evaluated after arg values are set. This works for invoked templates and templates you create with code. o all strings are now templates; does that mean "\n" is not newline anymore? Did I break compatibility? o when calling another template, y, from within a template, x, none of the x parameters are visible to y because the formal parameters force you to define values. This prevents surprises and makes it easy to ensure a a value is empty unless you specifically set it for that template. The problem is that I need to factor templates sometimes and I want to refine behavior with a subclass or just invoke another shared template but erases all of x's parameters. Perhaps or as a syntax to indicate y should inherit all values. would mean that I set one, but the others are inherited whereas only has name set; others are empty. Ok, I made it work today. Was a 10 minute tweak. Easy. You can set manually with StringTemplate.setPassThroughAttributes(). This is awesome. 06-25-2005 o When you invoke foo(x=y), x must be an attribute of foo (well if you have formal args defined that is) and y is evaluated within the context of the surrounding template; more precisely, it's evaluated in the context of the actual template invocation (which can have predefined attributes like attr, it, and i). It's weird, but foo(x=x) also makes sense. See new unit test testArgEvaluationContext(). This was not working before, though I thought it was! o error messages are better for setting an undefined argument. 05-02-2005 o When a property is not found, you get a better error. I show the template context (nested tree of templates). 05-01-2005 o Collections, Maps, and Iterators that are non-null but have no elements return false in conditionals; e.g., $if(users)$ is false if users is an empty list. 03-30-2005 o added template context upon no such element. It says stuff like: << no such attribute: decisionNumber in template context [outputFile lexer cyclicDFA cyclicDFAState cyclicDFAEdge lookaheadTest] >> 03-28-2005 o added ability to use indirect property names. $user.(propName)$ evaluates (propName) to find the name of the property and then looks it up in user object. 01-22-2005 o Empty output for a single attribute expression one a line by itself gets no newline (i.e., you don't get a blank line). 01-02-2005 o You can access public fields now instead of via just accessors o empty (i.e., no char output) values in an iteration do not get a separator if specified. This will be 99% of the time what you want. Only if pure IF (no else). 12-25-2004 o Made convertArrayToList() handle long[] also and made "a.{f1,f2}" type aggregate attributes properly convert incoming arrays to lists for normalization. 12-24-2004 o Made a template lookup that is not defined throw an IllegalArgumentException rather than generate an error directly. 12-19-2004 o Made null indirect template generate nothing; used to generate null-ptr exception. 11-20-2004 o trap all antlr generated errors now and send to listener. 11-07-2004 o Added << /** Specify a StringTemplateWriter implementing class to use for * filtering output */ public void setStringTemplateWriter(Class c) { userSpecifiedWriter = c; } >> and made StringTemplate.toString() sensitive to it. 11-04-2004 o added support for nonlocal file encodings; added property fileCharEncoding. The template loading routines are now sensitive to this property. Defaults to the file.encoding system property. 11-03-2004 o STG.templateIsDefinedInThisGroup -> isDefinedInThisGroup o added isDefined(name) that checks whole hierarchy 10-31-2004 o addressed whitespace at begin/end of template .st file issue. Decided to let it continue to strip all front/back whitespace and then make you add it directly. This is a simple rule and can be made to do what you want. It is consistent with the strip newline before \>\> rule too. o added <\ > for space char o updated testing harness to be same as ANTLR 3.0's which is more sophisticated. o the newline immediately preceding >> in a template group file is tossed out just like the newline right after the \<< 10-30-2004 o newlines ignored before and . Rule is: kill a single newline after , <<, , and (but for only if it's on a line by itself) . Kill newlines before and and >>. o added <\n>, <\r>, <\t> o fixed \n refs in TestStringTemplate unit tests to be portable newline reference. 10-29-2004 o added $!...!$ and comments (version 2.1b3) 10-10-2004 o allow HashMap, Hashtable precisely but not Map in attribute.property lookup o $attributes$ is a text string when lint mode on that recursively dumps out types, properties, etc... (no values) 09-25-2004 o Templates track their embedded instances; can ask for embedded o added isXXX accessor properties so x.special invokes x.getSpecial then x.isSpecial if not successful. o bug in st.attribute...if no attributes table, got null ptr exception 07-07-2004 o given the big changes to ST, I'm going to deprecate attr and use "it" as the default iterator attribute. Says "iterator" and is sort of like "this". I looked at "this", "that", "iter", and even "the". "ith" even [i]. 07-01-2004 o a.b yields a's b attribute if a is stringtemplate, which lets you treat a list of templates or nested set of templates as a data structure. For example, given a list of templates representing output rules from antlr, i can generate both the C function definitions for those rules and the list of C function declarations: ( (\}}> o applying a template to a list of attributes reused the same template, but you need a new one to get a new attribute set etc... o apply a template to a list of attributes did a toString() rather than build up a list of templates to apply later. o to prevent recursion, formally defined parameters hide any (dynamically) enclosing scope. The attributes can be null or have values still, but you cannot inherit an attribute from an enclosing scope, bypassing an empty local attribute formally defined in that template. See test case that used to cause infinite recursion. Hmm...can i limit to the case where same template is up the call stack somewhere? Any other inheritance should be ok, right? This is not always what you want. If you set the font for a table, then nested tables cannot inherit the font. However it prevents you from forgetting to set the rows attr in the nested, which would cause an infinite recursive loop. Actually figured out precisely what it should be. Can't avoid infinite recursion without expensive tests so make part of lintMode: StringTemplate: error: possible recursive self-reference to stats in template ifstat If you get a value in getAttribute that refers to the current template or an enclosing template, must be in an infinite loop. Can't stop it, but error to errorListener. Ok, now I really have it. In ASTExpr.write, if the object to write out is a ST, then it walks up enclosing chain and makes sure it is unique. Otherwise, it's infinite recursion. Same template, different instance is fine. Only in lintMode! throws IllegalStateException. Back to formal arg always hides enclosing value, though if you stick in a looped attribute set then I catch it in lint mode. 06-26-2004 o added helper method setAttribute(String,int) o removed ability to pass hashtable in as initial args...security hole. 06-24-2004 o included templates like computed the text right away rather than lazily evaluating when the outer template evaluated. Missed some parameters that way. o when embedding a template inside another via setAttribute, it must set the enclosingInstance so that it can inherit attributes. This was not working when you setAttribute("foo"...) multiple times for attribute foo. It was just adding stuff to the internal array without checking to see if it was a ST. 05-08-2004 o Improved test harness so we can time tests; added some eval speed tests. 05-07-2004 o nested IF works o $else$ clause added o antlr lexer used to chunk now two predefined $..$ and <..> o added group file format o changed boolean so that you are testing its value not presence/absence o added formal parameter checking. Can only set attributes that exist at a template or enclosing template. Can only ref attributes that exist at that template or above. Throws NoSuchElement exceptions. o added general notion of StringTemplateWriter so you can do output filters. o predefined auto indentation filter (default used). o properties that return arrays are converted to iterators. Factored out this normalization code into static ASTExpr methods. Did not handle properties that return collections as multi-valued values. 05-03-2004 o Added Collection and Iterator stuff in ASTExpr writeAttribute. Can dump or apply template to either Map, Collection, or Iterator now. o anything iteratable can be used for "APPLY" template 01-23-2004 o Fixed some errors in the escape char when in anonymous templates {...} o Fixed so nested anonymous templates works now. o Changed some protections and so on so that can override behavior more easily. 5-16-2003 o Make StringTemplate to List interface or collection. [Fixed 5-17-2003] o Need $(foo)()$. What about $names:(boldtemplate)():italics()$? What about $(foo)()+(bar)()$? $(foo+".template")()$ [Fixed 5-17-2003] 4-11-2003 o if a template name is not found, it will still try to apply it to an attribute [Fixed 5-15-2003] o fix missing end $. now it consumes the rest of the file. [Fixed 5-15-2003. Well, it still consumes, but now the listener gets the error actually.] o add more messages that go to the error listener [Fixed 5-15-2003]: added warning(msg) to listener added setLintMode(true), makes setting of unknown attr a warning 4-01-2003 [Fixed 5-15-2003] o attr is not re-evaluated in template application to a vector--args are evaluated a priori! $members:link(url=attr.homepage, title=attr.name)$ does not work! stringtemplate-3.2.1/pom.xml0000644000175000017500000001645211256235341016044 0ustar twernertwerner 4.0.0 org.antlr stringtemplate jar 3.3-SNAPSHOT ANTLR StringTemplate StringTemplate is a java template engine for generating source code, web pages, emails, or any other formatted text output. StringTemplate is particularly good at multi-targeted code generators, multiple site skins, and internationalization/localization. It evolved over years of effort developing jGuru.com. StringTemplate also generates the stringtemplate website: http://www.stringtemplate.org and powers the ANTLR v3 code generator. Its distinguishing characteristic is that unlike other engines, it strictly enforces model-view separation. Strict separation makes websites and code generators more flexible and maintainable; it also provides an excellent defense against malicious template authors. There are currently about 600 StringTemplate source downloads a month. http://www.stringtemplate.org Terence Parr USFCA http://www.cs.usfca.edu parrt@antlr.org Project Leader Developer - Java Target PST Jim Idle Temporal Wave LLC http://www.temporal-wave.com jimi@temporal-wave.com Developer - Maven stuff PST BSD licence http://antlr.org/license.html repo http://fisheye2.cenqua.com/browse/stringtemplate http://fisheye2.cenqua.com/browse/stringtemplate antlr-repo ANTLR Testing repository scpexe://antlr.org/home/mavensync/antlr-repo antlr-snapshot ANTLR Testing Snapshot Repository scpexe://antlr.org/home/mavensync/antlr-snapshot junit junit 4.5 test antlr antlr 2.7.7 compile install org.apache.maven.wagon wagon-ssh-external 1.0-beta-2 src test test org.codehaus.mojo antlr-maven-plugin src/org/antlr/stringtemplate/language template.g, angle.bracket.template.g, action.g, eval.g, group.g, interface.g generate maven-compiler-plugin 1.4 1.4 src maven-surefire-plugin ${basedir}/src org.codehaus.mojo findbugs-maven-plugin true true true