use of org.whole.lang.scripts.model.Source in project whole by wholeplatform.
the class ScriptsInterpreterVisitor method visit.
@Override
public void visit(Script entity) {
Writer outputWriter = op().getWriter();
IBindingManager bm = getBindings();
BindingsAdapter bindingsAdapter = new BindingsAdapter(bm, true);
LanguageName languageName = entity.getLanguageName();
/*
* TODO
* if contains an upper level fragment fail
*/
Source source = entity.getSource();
IEntity sourceRoot = EntityUtils.isFragment(source) ? source.wGetRoot() : source;
IEntity result0 = bm.getResult();
IVisitor ov = op().setVisitor(sourceRoot, 0, op().getVisitor(sourceRoot, 1));
op().stagedVisit(source);
IEntity sourceModel = bm.getResult();
// workaround restore previous value (also for self and queryIterator?)
bm.setResult(result0);
op().setVisitor(sourceRoot, 0, ov);
String sourceString = toPrettyPrintString(sourceModel);
ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
ScriptEngine scriptEngine = scriptEngineManager.getEngineByName(languageName.getValue());
if (scriptEngine == null)
throw new VisitException("Cannot find an interpreter for the language: " + languageName);
scriptEngine.setBindings(bindingsAdapter, ScriptContext.ENGINE_SCOPE);
PrintWriter printWriter = new PrintWriter(outputWriter);
scriptEngine.getContext().setWriter(printWriter);
scriptEngine.getContext().setErrorWriter(printWriter);
Object result = null;
bm.wEnterScope();
do {
try {
result = scriptEngine.eval(sourceString);
break;
} catch (ScriptException e) {
bm.wExitScope();
if (!bindingsAdapter.isAutoboxing())
throw new VisitException("Script Interpreter failure.", e);
bindingsAdapter.setAutoboxing(false);
bm.wEnterScope();
}
} while (true);
bm.wExitScope(true);
if (result instanceof IEntity)
bm.setResult((IEntity) result);
else if (result != null)
bm.setResult(BindingManagerFactory.instance.createSpecificValue(result));
}
Aggregations