use of org.mozilla.javascript.ast.ScriptNode in project HL4A by HL4A.
the class IRFactory method transformScript.
private Node transformScript(ScriptNode node) {
decompiler.addToken(Token.SCRIPT);
if (currentScope != null)
Kit.codeBug();
currentScope = node;
Node body = new Node(Token.BLOCK);
for (Node kid : node) {
body.addChildToBack(transform((AstNode) kid));
}
node.removeChildren();
Node children = body.getFirstChild();
if (children != null) {
node.addChildrenToBack(children);
}
return node;
}
use of org.mozilla.javascript.ast.ScriptNode in project HL4A by HL4A.
the class Node method toStringTreeHelper.
private static void toStringTreeHelper(ScriptNode treeTop, Node n, ObjToIntMap printIds, int level, StringBuilder sb) {
if (Token.printTrees) {
if (printIds == null) {
printIds = new ObjToIntMap();
generatePrintIds(treeTop, printIds);
}
for (int i = 0; i != level; ++i) {
sb.append(" ");
}
n.toString(printIds, sb);
sb.append('\n');
for (Node cursor = n.getFirstChild(); cursor != null; cursor = cursor.getNext()) {
if (cursor.getType() == Token.FUNCTION) {
int fnIndex = cursor.getExistingIntProp(Node.FUNCTION_PROP);
FunctionNode fn = treeTop.getFunctionNode(fnIndex);
toStringTreeHelper(fn, fn, null, level + 1, sb);
} else {
toStringTreeHelper(treeTop, cursor, printIds, level + 1, sb);
}
}
}
}
use of org.mozilla.javascript.ast.ScriptNode in project pentaho-kettle by pentaho.
the class ScriptDialog method test.
private boolean test(boolean getvars, boolean popup) {
boolean retval = true;
StyledTextComp wScript = getStyledTextComp();
String scr = wScript.getText();
KettleException testException = null;
Context jscx;
Scriptable jsscope;
// Script jsscript;
// Making Refresh to get Active Script State
refreshScripts();
jscx = ContextFactory.getGlobal().enterContext();
jscx.setOptimizationLevel(-1);
jsscope = jscx.initStandardObjects(null, false);
// Adding the existing Scripts to the Context
for (int i = 0; i < folder.getItemCount(); i++) {
StyledTextComp sItem = getStyledTextComp(folder.getItem(i));
Scriptable jsR = Context.toObject(sItem.getText(), jsscope);
jsscope.put(folder.getItem(i).getText(), jsscope, jsR);
}
// Adding the Name of the Transformation to the Context
jsscope.put("_TransformationName_", jsscope, this.stepname);
try {
RowMetaInterface rowMeta = transMeta.getPrevStepFields(stepname);
if (rowMeta != null) {
ScriptDummy dummyStep = new ScriptDummy(rowMeta, transMeta.getStepFields(stepname));
Scriptable jsvalue = Context.toObject(dummyStep, jsscope);
jsscope.put("_step_", jsscope, jsvalue);
// Modification for Additional Script parsing
try {
if (input.getAddClasses() != null) {
for (int i = 0; i < input.getAddClasses().length; i++) {
Object jsOut = Context.javaToJS(input.getAddClasses()[i].getAddObject(), jsscope);
ScriptableObject.putProperty(jsscope, input.getAddClasses()[i].getJSName(), jsOut);
}
}
} catch (Exception e) {
testException = new KettleException(BaseMessages.getString(PKG, "ScriptDialog.CouldNotAddToContext", e.toString()));
retval = false;
}
// Adding some default JavaScriptFunctions to the System
try {
Context.javaToJS(ScriptAddedFunctions.class, jsscope);
((ScriptableObject) jsscope).defineFunctionProperties(jsFunctionList, ScriptAddedFunctions.class, ScriptableObject.DONTENUM);
} catch (Exception ex) {
testException = new KettleException(BaseMessages.getString(PKG, "ScriptDialog.CouldNotAddDefaultFunctions", ex.toString()));
retval = false;
}
// Adding some Constants to the JavaScript
try {
jsscope.put("SKIP_TRANSFORMATION", jsscope, Integer.valueOf(SKIP_TRANSFORMATION));
jsscope.put("ABORT_TRANSFORMATION", jsscope, Integer.valueOf(ABORT_TRANSFORMATION));
jsscope.put("ERROR_TRANSFORMATION", jsscope, Integer.valueOf(ERROR_TRANSFORMATION));
jsscope.put("CONTINUE_TRANSFORMATION", jsscope, Integer.valueOf(CONTINUE_TRANSFORMATION));
} catch (Exception ex) {
testException = new KettleException(BaseMessages.getString(PKG, "ScriptDialog.CouldNotAddTransformationConstants", ex.toString()));
retval = false;
}
try {
Object[] row = new Object[rowMeta.size()];
Scriptable jsRowMeta = Context.toObject(rowMeta, jsscope);
jsscope.put("rowMeta", jsscope, jsRowMeta);
for (int i = 0; i < rowMeta.size(); i++) {
ValueMetaInterface valueMeta = rowMeta.getValueMeta(i);
Object valueData = null;
//
if (valueMeta.isDate()) {
valueData = new Date();
}
if (valueMeta.isString()) {
valueData = "test value test value test value test value test " + "value test value test value test value test value test value";
}
if (valueMeta.isInteger()) {
valueData = Long.valueOf(0L);
}
if (valueMeta.isNumber()) {
valueData = new Double(0.0);
}
if (valueMeta.isBigNumber()) {
valueData = BigDecimal.ZERO;
}
if (valueMeta.isBoolean()) {
valueData = Boolean.TRUE;
}
if (valueMeta.isBinary()) {
valueData = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
}
if (valueMeta.isStorageBinaryString()) {
valueMeta.setStorageType(ValueMetaInterface.STORAGE_TYPE_NORMAL);
}
row[i] = valueData;
Scriptable jsarg = Context.toObject(valueData, jsscope);
jsscope.put(valueMeta.getName(), jsscope, jsarg);
}
// OK, for these input values, we're going to allow the user to edit the default values...
// We are displaying a
// 2)
// Add support for Value class (new Value())
Scriptable jsval = Context.toObject(Value.class, jsscope);
jsscope.put("Value", jsscope, jsval);
// Add the old style row object for compatibility reasons...
//
Scriptable jsRow = Context.toObject(row, jsscope);
jsscope.put("row", jsscope, jsRow);
} catch (Exception ev) {
testException = new KettleException(BaseMessages.getString(PKG, "ScriptDialog.CouldNotAddInputFields", ev.toString()));
retval = false;
}
try {
// Checking for StartScript
if (strActiveStartScript != null && !folder.getSelection().getText().equals(strActiveStartScript) && strActiveStartScript.length() > 0) {
String strStartScript = getStyledTextComp(folder.getItem(getCTabPosition(strActiveStartScript))).getText();
/* Object startScript = */
jscx.evaluateString(jsscope, strStartScript, "trans_Start", 1, null);
}
} catch (Exception e) {
testException = new KettleException(BaseMessages.getString(PKG, "ScriptDialog.CouldProcessStartScript", e.toString()));
retval = false;
}
try {
Script evalScript = jscx.compileString(scr, "script", 1, null);
evalScript.exec(jscx, jsscope);
if (getvars) {
ScriptNode tree = parseVariables(jscx, jsscope, scr, "script", 1, null);
for (int i = 0; i < tree.getParamAndVarCount(); i++) {
String varname = tree.getParamOrVarName(i);
if (!varname.equalsIgnoreCase("row") && !varname.equalsIgnoreCase("trans_Status")) {
int type = ValueMetaInterface.TYPE_STRING;
int length = -1, precision = -1;
Object result = jsscope.get(varname, jsscope);
if (result != null) {
String classname = result.getClass().getName();
if (classname.equalsIgnoreCase("java.lang.Byte")) {
// MAX = 127
type = ValueMetaInterface.TYPE_INTEGER;
length = 3;
precision = 0;
} else if (classname.equalsIgnoreCase("java.lang.Integer")) {
// MAX = 2147483647
type = ValueMetaInterface.TYPE_INTEGER;
length = 9;
precision = 0;
} else if (classname.equalsIgnoreCase("java.lang.Long")) {
// MAX = 9223372036854775807
type = ValueMetaInterface.TYPE_INTEGER;
length = 18;
precision = 0;
} else if (classname.equalsIgnoreCase("java.lang.Double")) {
type = ValueMetaInterface.TYPE_NUMBER;
length = 16;
precision = 2;
} else if (classname.equalsIgnoreCase("org.mozilla.javascript.NativeDate") || classname.equalsIgnoreCase("java.util.Date")) {
type = ValueMetaInterface.TYPE_DATE;
} else if (classname.equalsIgnoreCase("java.lang.Boolean")) {
type = ValueMetaInterface.TYPE_BOOLEAN;
}
}
TableItem ti = new TableItem(wFields.table, SWT.NONE);
ti.setText(1, varname);
ti.setText(2, "");
ti.setText(3, ValueMetaFactory.getValueMetaName(type));
ti.setText(4, length >= 0 ? ("" + length) : "");
ti.setText(5, precision >= 0 ? ("" + precision) : "");
// If the variable name exists in the input, suggest to replace the value
//
ti.setText(6, (rowMeta.indexOfValue(varname) >= 0) ? YES_NO_COMBO[1] : YES_NO_COMBO[0]);
}
}
wFields.removeEmptyRows();
wFields.setRowNums();
wFields.optWidth(true);
}
// End Script!
} catch (EvaluatorException e) {
String position = "(" + e.lineNumber() + ":" + e.columnNumber() + ")";
String message = BaseMessages.getString(PKG, "ScriptDialog.Exception.CouldNotExecuteScript", position);
testException = new KettleException(message, e);
retval = false;
} catch (JavaScriptException e) {
String position = "(" + e.lineNumber() + ":" + e.columnNumber() + ")";
String message = BaseMessages.getString(PKG, "ScriptDialog.Exception.CouldNotExecuteScript", position);
testException = new KettleException(message, e);
retval = false;
} catch (Exception e) {
testException = new KettleException(BaseMessages.getString(PKG, "ScriptDialog.Exception.CouldNotExecuteScript2"), e);
retval = false;
}
} else {
testException = new KettleException(BaseMessages.getString(PKG, "ScriptDialog.Exception.CouldNotGetFields"));
retval = false;
}
if (popup) {
if (retval) {
if (!getvars) {
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION);
mb.setMessage(BaseMessages.getString(PKG, "ScriptDialog.ScriptCompilationOK") + Const.CR);
mb.setText("OK");
mb.open();
}
} else {
new ErrorDialog(shell, BaseMessages.getString(PKG, "ScriptDialog.TestFailed.DialogTitle"), BaseMessages.getString(PKG, "ScriptDialog.TestFailed.DialogMessage"), testException);
}
}
} catch (KettleException ke) {
retval = false;
new ErrorDialog(shell, BaseMessages.getString(PKG, "ScriptDialog.TestFailed.DialogTitle"), BaseMessages.getString(PKG, "ScriptDialog.TestFailed.DialogMessage"), ke);
} finally {
if (jscx != null) {
Context.exit();
}
}
return retval;
}
use of org.mozilla.javascript.ast.ScriptNode in project hackpad by dropbox.
the class BodyCodegen method generateNativeFunctionOverrides.
private void generateNativeFunctionOverrides(ClassFileWriter cfw, String encodedSource) {
// Override NativeFunction.getLanguageVersion() with
// public int getLanguageVersion() { return <version-constant>; }
cfw.startMethod("getLanguageVersion", "()I", ClassFileWriter.ACC_PUBLIC);
cfw.addPush(compilerEnv.getLanguageVersion());
cfw.add(ByteCode.IRETURN);
// 1: this and no argument or locals
cfw.stopMethod((short) 1);
// The rest of NativeFunction overrides require specific code for each
// script/function id
final int Do_getFunctionName = 0;
final int Do_getParamCount = 1;
final int Do_getParamAndVarCount = 2;
final int Do_getParamOrVarName = 3;
final int Do_getEncodedSource = 4;
final int Do_getParamOrVarConst = 5;
final int SWITCH_COUNT = 6;
for (int methodIndex = 0; methodIndex != SWITCH_COUNT; ++methodIndex) {
if (methodIndex == Do_getEncodedSource && encodedSource == null) {
continue;
}
// Generate:
// prologue;
// switch over function id to implement function-specific action
// epilogue
short methodLocals;
switch(methodIndex) {
case Do_getFunctionName:
// Only this
methodLocals = 1;
cfw.startMethod("getFunctionName", "()Ljava/lang/String;", ClassFileWriter.ACC_PUBLIC);
break;
case Do_getParamCount:
// Only this
methodLocals = 1;
cfw.startMethod("getParamCount", "()I", ClassFileWriter.ACC_PUBLIC);
break;
case Do_getParamAndVarCount:
// Only this
methodLocals = 1;
cfw.startMethod("getParamAndVarCount", "()I", ClassFileWriter.ACC_PUBLIC);
break;
case Do_getParamOrVarName:
// this + paramOrVarIndex
methodLocals = 1 + 1;
cfw.startMethod("getParamOrVarName", "(I)Ljava/lang/String;", ClassFileWriter.ACC_PUBLIC);
break;
case Do_getParamOrVarConst:
// this + paramOrVarName
methodLocals = 1 + 1 + 1;
cfw.startMethod("getParamOrVarConst", "(I)Z", ClassFileWriter.ACC_PUBLIC);
break;
case Do_getEncodedSource:
// Only this
methodLocals = 1;
cfw.startMethod("getEncodedSource", "()Ljava/lang/String;", ClassFileWriter.ACC_PUBLIC);
cfw.addPush(encodedSource);
break;
default:
throw Kit.codeBug();
}
int count = scriptOrFnNodes.length;
int switchStart = 0;
int switchStackTop = 0;
if (count > 1) {
// Generate switch but only if there is more then one
// script/function
cfw.addLoadThis();
cfw.add(ByteCode.GETFIELD, cfw.getClassName(), ID_FIELD_NAME, "I");
// do switch from 1 .. count - 1 mapping 0 to the default case
switchStart = cfw.addTableSwitch(1, count - 1);
}
for (int i = 0; i != count; ++i) {
ScriptNode n = scriptOrFnNodes[i];
if (i == 0) {
if (count > 1) {
cfw.markTableSwitchDefault(switchStart);
switchStackTop = cfw.getStackTop();
}
} else {
cfw.markTableSwitchCase(switchStart, i - 1, switchStackTop);
}
// Impelemnet method-specific switch code
switch(methodIndex) {
case Do_getFunctionName:
// Push function name
if (n.getType() == Token.SCRIPT) {
cfw.addPush("");
} else {
String name = ((FunctionNode) n).getName();
cfw.addPush(name);
}
cfw.add(ByteCode.ARETURN);
break;
case Do_getParamCount:
// Push number of defined parameters
cfw.addPush(n.getParamCount());
cfw.add(ByteCode.IRETURN);
break;
case Do_getParamAndVarCount:
// Push number of defined parameters and declared variables
cfw.addPush(n.getParamAndVarCount());
cfw.add(ByteCode.IRETURN);
break;
case Do_getParamOrVarName:
// Push name of parameter using another switch
// over paramAndVarCount
int paramAndVarCount = n.getParamAndVarCount();
if (paramAndVarCount == 0) {
// The runtime should never call the method in this
// case but to make bytecode verifier happy return null
// as throwing execption takes more code
cfw.add(ByteCode.ACONST_NULL);
cfw.add(ByteCode.ARETURN);
} else if (paramAndVarCount == 1) {
// As above do not check for valid index but always
// return the name of the first param
cfw.addPush(n.getParamOrVarName(0));
cfw.add(ByteCode.ARETURN);
} else {
// Do switch over getParamOrVarName
// param or var index
cfw.addILoad(1);
// do switch from 1 .. paramAndVarCount - 1 mapping 0
// to the default case
int paramSwitchStart = cfw.addTableSwitch(1, paramAndVarCount - 1);
for (int j = 0; j != paramAndVarCount; ++j) {
if (cfw.getStackTop() != 0)
Kit.codeBug();
String s = n.getParamOrVarName(j);
if (j == 0) {
cfw.markTableSwitchDefault(paramSwitchStart);
} else {
cfw.markTableSwitchCase(paramSwitchStart, j - 1, 0);
}
cfw.addPush(s);
cfw.add(ByteCode.ARETURN);
}
}
break;
case Do_getParamOrVarConst:
// Push name of parameter using another switch
// over paramAndVarCount
paramAndVarCount = n.getParamAndVarCount();
boolean[] constness = n.getParamAndVarConst();
if (paramAndVarCount == 0) {
// The runtime should never call the method in this
// case but to make bytecode verifier happy return null
// as throwing execption takes more code
cfw.add(ByteCode.ICONST_0);
cfw.add(ByteCode.IRETURN);
} else if (paramAndVarCount == 1) {
// As above do not check for valid index but always
// return the name of the first param
cfw.addPush(constness[0]);
cfw.add(ByteCode.IRETURN);
} else {
// Do switch over getParamOrVarName
// param or var index
cfw.addILoad(1);
// do switch from 1 .. paramAndVarCount - 1 mapping 0
// to the default case
int paramSwitchStart = cfw.addTableSwitch(1, paramAndVarCount - 1);
for (int j = 0; j != paramAndVarCount; ++j) {
if (cfw.getStackTop() != 0)
Kit.codeBug();
if (j == 0) {
cfw.markTableSwitchDefault(paramSwitchStart);
} else {
cfw.markTableSwitchCase(paramSwitchStart, j - 1, 0);
}
cfw.addPush(constness[j]);
cfw.add(ByteCode.IRETURN);
}
}
break;
case Do_getEncodedSource:
// Push number encoded source start and end
// to prepare for encodedSource.substring(start, end)
cfw.addPush(n.getEncodedSourceStart());
cfw.addPush(n.getEncodedSourceEnd());
cfw.addInvoke(ByteCode.INVOKEVIRTUAL, "java/lang/String", "substring", "(II)Ljava/lang/String;");
cfw.add(ByteCode.ARETURN);
break;
default:
throw Kit.codeBug();
}
}
cfw.stopMethod(methodLocals);
}
}
use of org.mozilla.javascript.ast.ScriptNode in project hackpad by dropbox.
the class BodyCodegen method generateCallMethod.
private void generateCallMethod(ClassFileWriter cfw) {
cfw.startMethod("call", "(Lorg/mozilla/javascript/Context;" + "Lorg/mozilla/javascript/Scriptable;" + "Lorg/mozilla/javascript/Scriptable;" + "[Ljava/lang/Object;)Ljava/lang/Object;", (short) (ClassFileWriter.ACC_PUBLIC | ClassFileWriter.ACC_FINAL));
// Generate code for:
// if (!ScriptRuntime.hasTopCall(cx)) {
// return ScriptRuntime.doTopCall(this, cx, scope, thisObj, args);
// }
int nonTopCallLabel = cfw.acquireLabel();
//cx
cfw.addALoad(1);
cfw.addInvoke(ByteCode.INVOKESTATIC, "org/mozilla/javascript/ScriptRuntime", "hasTopCall", "(Lorg/mozilla/javascript/Context;" + ")Z");
cfw.add(ByteCode.IFNE, nonTopCallLabel);
cfw.addALoad(0);
cfw.addALoad(1);
cfw.addALoad(2);
cfw.addALoad(3);
cfw.addALoad(4);
cfw.addInvoke(ByteCode.INVOKESTATIC, "org/mozilla/javascript/ScriptRuntime", "doTopCall", "(Lorg/mozilla/javascript/Callable;" + "Lorg/mozilla/javascript/Context;" + "Lorg/mozilla/javascript/Scriptable;" + "Lorg/mozilla/javascript/Scriptable;" + "[Ljava/lang/Object;" + ")Ljava/lang/Object;");
cfw.add(ByteCode.ARETURN);
cfw.markLabel(nonTopCallLabel);
// Now generate switch to call the real methods
cfw.addALoad(0);
cfw.addALoad(1);
cfw.addALoad(2);
cfw.addALoad(3);
cfw.addALoad(4);
int end = scriptOrFnNodes.length;
boolean generateSwitch = (2 <= end);
int switchStart = 0;
int switchStackTop = 0;
if (generateSwitch) {
cfw.addLoadThis();
cfw.add(ByteCode.GETFIELD, cfw.getClassName(), ID_FIELD_NAME, "I");
// do switch from (1, end - 1) mapping 0 to
// the default case
switchStart = cfw.addTableSwitch(1, end - 1);
}
for (int i = 0; i != end; ++i) {
ScriptNode n = scriptOrFnNodes[i];
if (generateSwitch) {
if (i == 0) {
cfw.markTableSwitchDefault(switchStart);
switchStackTop = cfw.getStackTop();
} else {
cfw.markTableSwitchCase(switchStart, i - 1, switchStackTop);
}
}
if (n.getType() == Token.FUNCTION) {
OptFunctionNode ofn = OptFunctionNode.get(n);
if (ofn.isTargetOfDirectCall()) {
int pcount = ofn.fnode.getParamCount();
if (pcount != 0) {
// stack top == arguments array from addALoad4()
for (int p = 0; p != pcount; ++p) {
cfw.add(ByteCode.ARRAYLENGTH);
cfw.addPush(p);
int undefArg = cfw.acquireLabel();
int beyond = cfw.acquireLabel();
cfw.add(ByteCode.IF_ICMPLE, undefArg);
// get array[p]
cfw.addALoad(4);
cfw.addPush(p);
cfw.add(ByteCode.AALOAD);
cfw.add(ByteCode.GOTO, beyond);
cfw.markLabel(undefArg);
pushUndefined(cfw);
cfw.markLabel(beyond);
// Only one push
cfw.adjustStackTop(-1);
cfw.addPush(0.0);
// restore invariant
cfw.addALoad(4);
}
}
}
}
cfw.addInvoke(ByteCode.INVOKESTATIC, mainClassName, getBodyMethodName(n), getBodyMethodSignature(n));
cfw.add(ByteCode.ARETURN);
}
cfw.stopMethod((short) 5);
// 5: this, cx, scope, js this, args[]
}
Aggregations