
org.snapscript.tree.template.TextTemplate Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of snap-all Show documentation
Show all versions of snap-all Show documentation
Dynamic scripting for the JVM
package org.snapscript.tree.template;
import static org.snapscript.core.constraint.Constraint.STRING;
import static org.snapscript.core.scope.index.CaptureType.TEMPLATE;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import org.snapscript.core.Compilation;
import org.snapscript.core.Context;
import org.snapscript.core.Evaluation;
import org.snapscript.core.ExpressionEvaluator;
import org.snapscript.core.constraint.Constraint;
import org.snapscript.core.convert.proxy.ProxyWrapper;
import org.snapscript.core.module.Module;
import org.snapscript.core.module.Path;
import org.snapscript.core.scope.Scope;
import org.snapscript.core.scope.index.CaptureScopeExtractor;
import org.snapscript.core.scope.index.CaptureType;
import org.snapscript.core.variable.Value;
import org.snapscript.parse.StringToken;
public class TextTemplate implements Compilation {
private final StringToken template;
public TextTemplate(StringToken template) {
this.template = template;
}
@Override
public Evaluation compile(Module module, Path path, int line) throws Exception {
Context context = module.getContext();
ProxyWrapper wrapper = context.getWrapper();
ExpressionEvaluator evaluator = context.getEvaluator();
String text = template.getValue();
char[] source = text.toCharArray();
return new CompileResult(evaluator, wrapper, source);
}
private static class CompileResult extends Evaluation {
private CaptureScopeExtractor extractor;
private SegmentIterator iterator;
private List segments;
public CompileResult(ExpressionEvaluator evaluator, ProxyWrapper wrapper, char[] source) {
this.iterator = new SegmentIterator(evaluator, wrapper, source);
this.extractor = new CaptureScopeExtractor(TEMPLATE);
this.segments = new ArrayList();
}
@Override
public Constraint compile(Scope scope, Constraint left) throws Exception {
List list = new ArrayList();
while(iterator.hasNext()) {
Segment token = iterator.next();
if(token != null) {
list.add(token);
}
}
segments = list;
return STRING;
}
@Override
public Value evaluate(Scope scope, Value left) throws Exception {
StringWriter writer = new StringWriter();
if(!segments.isEmpty()) {
Scope capture = extractor.extract(scope);
for(Segment segment : segments) {
segment.process(capture, writer);
}
}
String result = writer.toString();
return Value.getTransient(result);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy