1 package jfun.yan.xml; 2 3 import java.util.ArrayList ; 4 5 import jfun.util.dict.Dict; 6 7 8 class StringInterpolator { 9 17 static Object interpolate(final String src, jfun.util.dict.Map ctxt, final Location loc){ 18 if(src==null) return null; 19 final ArrayList tokens = new ArrayList (); 20 final StringBuffer buf = new StringBuffer (); 21 final int sz = src.length(); 22 for(int i=0; i<sz; i++){ 23 final char c = src.charAt(i); 24 if(c == '$'){ 25 final char c1 = src.charAt(++i); 27 if(c1=='{'){ 28 final int start = ++i; 30 for(;;i++){ 31 if(i>=sz){ 32 throw new ConfigurationException( 33 "invalid string interpolation syntax, '}' expected", loc); 34 } 35 final char c2 = src.charAt(i); 36 if(c2=='}'){ 37 final int end = i; 38 final String var = src.substring(start, end); 39 final Object val = ctxt.get(var); 40 if(val==null){ 41 throw new ConfigurationException("unrecognized variable: "+var, loc); 42 } 43 if(val instanceof Stmt){ 44 tokens.add(buf.toString()); 45 buf.setLength(0); 46 tokens.add(val); 47 } 48 else{ 49 buf.append(val); 50 } 51 break; 52 } 53 } 54 } 55 56 else{ 57 buf.append(c); 58 if(c1!='$'){ 59 buf.append(c1); 60 } 61 } 62 } 63 else{ 64 buf.append(c); 65 } 66 } 67 if(buf.length()>0){ 68 tokens.add(buf.toString()); 69 buf.setLength(0); 70 } 71 return returnStmt(src, tokens, loc); 72 } 73 74 private static Object returnStmt(final String src, final ArrayList tokens, final Location loc) { 75 final int token_count = tokens.size(); 76 if(token_count==0) 77 return ""; 78 else if(token_count==1){ 79 final Object tok = tokens.get(0); 80 return tok; 81 } 82 else{ 83 final Object [] toks = tokens.toArray(); 84 return new Stmt(){ 85 public Class getType() { 86 return String .class; 87 } 88 public Object run(Dict frame, Runtime runtime) { 89 final StringBuffer buf = new StringBuffer (); 90 for(int i=0; i<toks.length; i++){ 91 final Object tok = toks[i]; 92 if(tok instanceof Stmt){ 93 buf.append(((Stmt)tok).run(frame, runtime)); 94 } 95 else{ 96 buf.append(tok); 97 } 98 } 99 return buf.toString(); 100 } 101 public Location getLocation() { 102 return loc; 103 } 104 public String toString(){ 105 return src; 106 } 107 }; 108 } 109 } 110 } 111 | Popular Tags |