Java Code Examples for jdk.nashorn.internal.runtime.ScriptFunction

The following examples show how to use jdk.nashorn.internal.runtime.ScriptFunction. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: jdk8u60   Source File: NativeFunction.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * ECMA 15.3.4.4 Function.prototype.call (thisArg [ , arg1 [ , arg2, ... ] ] )
 *
 * @param self self reference
 * @param args arguments for call
 * @return result of call
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1)
public static Object call(final Object self, final Object... args) {
    checkCallable(self);

    final Object thiz = (args.length == 0) ? UNDEFINED : args[0];
    Object[] arguments;

    if (args.length > 1) {
        arguments = new Object[args.length - 1];
        System.arraycopy(args, 1, arguments, 0, arguments.length);
    } else {
        arguments = ScriptRuntime.EMPTY_ARRAY;
    }

    if (self instanceof ScriptFunction) {
        return ScriptRuntime.apply((ScriptFunction)self, thiz, arguments);
    } else if (self instanceof JSObject) {
        return ((JSObject)self).call(thiz, arguments);
    }

    throw new AssertionError("should not reach here");
}
 
Example 2
@Override
public Iterator<String> propertyIterator() {
    // Try __getIds__ first, if not found then try __getKeys__
    // In jdk6, we had added "__getIds__" so this is just for compatibility.
    Object func = adaptee.get(__getIds__);
    if (!(func instanceof ScriptFunction)) {
        func = adaptee.get(__getKeys__);
    }

    Object obj;
    if (func instanceof ScriptFunction) {
        obj = ScriptRuntime.apply((ScriptFunction)func, adaptee);
    } else {
        obj = new NativeArray(0);
    }

    final List<String> array = new ArrayList<>();
    for (final Iterator<Object> iter = ArrayLikeIterator.arrayLikeIterator(obj); iter.hasNext(); ) {
        array.add((String)iter.next());
    }

    return array.iterator();
}
 
Example 3
Source Project: hottub   Source File: ContextTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void compileErrorTest() {
    final Options options = new Options("");
    final ErrorManager errors = new ErrorManager();
    final Context cx = new Context(options, errors, Thread.currentThread().getContextClassLoader());
    final Global oldGlobal = Context.getGlobal();
    Context.setGlobal(cx.createGlobal());
    try {
        final ScriptFunction script = cx.compileScript(sourceFor("<evalCompileErrorTest>", "*/"), Context.getGlobal());
        if (script != null) {
            fail("Invalid script compiled without errors");
        }
        if (errors.getNumberOfErrors() != 1) {
            fail("Wrong number of errors: " + errors.getNumberOfErrors());
        }
    } finally {
        Context.setGlobal(oldGlobal);
    }
}
 
Example 4
@Override
public Object newObject(final Object... args) {
    final ScriptObject oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != global);

    try {
        if (globalChanged) {
            Context.setGlobal(global);
        }

        if (sobj instanceof ScriptFunction) {
            final Object[] modArgs = globalChanged? wrapArray(args, oldGlobal) : args;
            return wrap(ScriptRuntime.construct((ScriptFunction)sobj, unwrapArray(modArgs, global)), global);
        }

        throw new RuntimeException("not a constructor: " + toString());
    } catch (final RuntimeException | Error e) {
        throw e;
    } catch (final Throwable t) {
        throw new RuntimeException(t);
    } finally {
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }
}
 
Example 5
/**
 * Given a JS script object, retrieves a function from it by name, binds it to the script object as its "this", and
 * adapts its parameter types, return types, and arity to the specified type and arity. This method is public mainly
 * for implementation reasons, so the adapter classes can invoke it from their constructors that take a Object
 * in its first argument to obtain the method handles for their method implementations.
 * @param obj the script obj
 * @param name the name of the property that contains the function
 * @param type the method type it has to conform to
 * @return the appropriately adapted method handle for invoking the script function, or null if the value of the
 * property is either null or undefined, or "toString" was requested as the name, but the object doesn't directly
 * define it but just inherits it through prototype.
 */
public static MethodHandle getHandle(final Object obj, final String name, final MethodType type) {
    if (! (obj instanceof ScriptObject)) {
        throw typeError("not.an.object", ScriptRuntime.safeToString(obj));
    }

    final ScriptObject sobj = (ScriptObject)obj;
    // Since every JS Object has a toString, we only override "String toString()" it if it's explicitly specified
    if ("toString".equals(name) && !sobj.hasOwnProperty("toString")) {
        return null;
    }

    final Object fnObj = sobj.get(name);
    if (fnObj instanceof ScriptFunction) {
        return bindAndAdaptHandle((ScriptFunction)fnObj, sobj, type);
    } else if(fnObj == null || fnObj instanceof Undefined) {
        return null;
    } else {
        throw typeError("not.a.function", name);
    }
}
 
Example 6
Source Project: TencentKona-8   Source File: Global.java    License: GNU General Public License v2.0 6 votes vote down vote up
private List<jdk.nashorn.internal.runtime.Property> extractBuiltinProperties(final String name, final ScriptObject func) {
    final List<jdk.nashorn.internal.runtime.Property> list = new ArrayList<>();

    list.addAll(Arrays.asList(func.getMap().getProperties()));

    if (func instanceof ScriptFunction) {
        final ScriptObject proto = ScriptFunction.getPrototype((ScriptFunction)func);
        if (proto != null) {
            list.addAll(Arrays.asList(proto.getMap().getProperties()));
        }
    }

    final jdk.nashorn.internal.runtime.Property prop = getProperty(name);
    if (prop != null) {
        list.add(prop);
    }

    return list;
}
 
Example 7
private static boolean isInterfaceImplemented(final Class<?> iface, final ScriptObject sobj) {
    for (final Method method : iface.getMethods()) {
        // ignore methods of java.lang.Object class
        if (method.getDeclaringClass() == Object.class) {
            continue;
        }

        // skip check for default methods - non-abstract, interface methods
        if (! Modifier.isAbstract(method.getModifiers())) {
            continue;
        }

        final Object obj = sobj.get(method.getName());
        if (! (obj instanceof ScriptFunction)) {
            return false;
        }
    }
    return true;
}
 
Example 8
Source Project: nashorn   Source File: ScriptObjectMirror.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public Object call(final Object thiz, final Object... args) {
    final ScriptObject oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != global);

    try {
        if (globalChanged) {
            Context.setGlobal(global);
        }

        if (sobj instanceof ScriptFunction) {
            final Object[] modArgs = globalChanged? wrapArray(args, oldGlobal) : args;
            final Object self = globalChanged? wrap(thiz, oldGlobal) : thiz;
            return wrap(ScriptRuntime.apply((ScriptFunction)sobj, unwrap(self, global), unwrapArray(modArgs, global)), global);
        }

        throw new RuntimeException("not a function: " + toString());
    } catch (final RuntimeException | Error e) {
        throw e;
    } catch (final Throwable t) {
        throw new RuntimeException(t);
    } finally {
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }
}
 
Example 9
Source Project: jdk8u_nashorn   Source File: Global.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static boolean isBuiltinFunctionProperty(final String name) {
    final Global instance = Global.instance();
    final ScriptFunction builtinFunction = instance.getBuiltinFunction();
    if (builtinFunction == null) {
        return false; //conservative for compile-only mode
    }
    final boolean isBuiltinFunction = instance.function == builtinFunction;
    return isBuiltinFunction && ScriptFunction.getPrototype(builtinFunction).getProperty(name).isBuiltin();
}
 
Example 10
private String callReplaceValue(final ScriptFunction function, final RegExpMatcher matcher, final String string) {
    final Object[] groups = groups(matcher);
    final Object[] args   = Arrays.copyOf(groups, groups.length + 2);

    args[groups.length]     = matcher.start();
    args[groups.length + 1] = string;

    final Object self = function.isStrict() ? UNDEFINED : Global.instance();

    return JSType.toString(ScriptRuntime.apply(function, self, args));
}
 
Example 11
Source Project: hottub   Source File: Bootstrap.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns if the given object is a "callable"
 * @param obj object to be checked for callability
 * @return true if the obj is callable
 */
public static boolean isCallable(final Object obj) {
    if (obj == ScriptRuntime.UNDEFINED || obj == null) {
        return false;
    }

    return obj instanceof ScriptFunction ||
        isJSObjectFunction(obj) ||
        BeansLinker.isDynamicMethod(obj) ||
        obj instanceof BoundCallable ||
        isFunctionalInterfaceObject(obj) ||
        obj instanceof StaticClass;
}
 
Example 12
Source Project: openjdk-jdk9   Source File: Global.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Adds jjs shell interactive mode builtin functions to global scope.
 */
public void addShellBuiltins() {
    Object value = ScriptFunction.createBuiltin("input", ShellFunctions.INPUT);
    addOwnProperty("input", Attribute.NOT_ENUMERABLE, value);

    value = ScriptFunction.createBuiltin("evalinput", ShellFunctions.EVALINPUT);
    addOwnProperty("evalinput", Attribute.NOT_ENUMERABLE, value);
}
 
Example 13
Source Project: TencentKona-8   Source File: Global.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void initErrorObjects() {
    // Error objects
    this.builtinError = initConstructor("Error", ScriptFunction.class);
    final ScriptObject errorProto = getErrorPrototype();

    // Nashorn specific accessors on Error.prototype - stack, lineNumber, columnNumber and fileName
    final ScriptFunction getStack = ScriptFunction.createBuiltin("getStack", NativeError.GET_STACK);
    final ScriptFunction setStack = ScriptFunction.createBuiltin("setStack", NativeError.SET_STACK);
    errorProto.addOwnProperty("stack", Attribute.NOT_ENUMERABLE, getStack, setStack);
    final ScriptFunction getLineNumber = ScriptFunction.createBuiltin("getLineNumber", NativeError.GET_LINENUMBER);
    final ScriptFunction setLineNumber = ScriptFunction.createBuiltin("setLineNumber", NativeError.SET_LINENUMBER);
    errorProto.addOwnProperty("lineNumber", Attribute.NOT_ENUMERABLE, getLineNumber, setLineNumber);
    final ScriptFunction getColumnNumber = ScriptFunction.createBuiltin("getColumnNumber", NativeError.GET_COLUMNNUMBER);
    final ScriptFunction setColumnNumber = ScriptFunction.createBuiltin("setColumnNumber", NativeError.SET_COLUMNNUMBER);
    errorProto.addOwnProperty("columnNumber", Attribute.NOT_ENUMERABLE, getColumnNumber, setColumnNumber);
    final ScriptFunction getFileName = ScriptFunction.createBuiltin("getFileName", NativeError.GET_FILENAME);
    final ScriptFunction setFileName = ScriptFunction.createBuiltin("setFileName", NativeError.SET_FILENAME);
    errorProto.addOwnProperty("fileName", Attribute.NOT_ENUMERABLE, getFileName, setFileName);

    // ECMA 15.11.4.2 Error.prototype.name
    // Error.prototype.name = "Error";
    errorProto.set(NativeError.NAME, "Error", 0);
    // ECMA 15.11.4.3 Error.prototype.message
    // Error.prototype.message = "";
    errorProto.set(NativeError.MESSAGE, "", 0);

    tagBuiltinProperties("Error", builtinError);

    this.builtinReferenceError = initErrorSubtype("ReferenceError", errorProto);
    this.builtinSyntaxError = initErrorSubtype("SyntaxError", errorProto);
    this.builtinTypeError = initErrorSubtype("TypeError", errorProto);
}
 
Example 14
Source Project: openjdk-8   Source File: Global.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void initErrorObjects() {
    // Error objects
    this.builtinError = (ScriptFunction)initConstructor("Error");
    final ScriptObject errorProto = getErrorPrototype();

    // Nashorn specific accessors on Error.prototype - stack, lineNumber, columnNumber and fileName
    final ScriptFunction getStack = ScriptFunctionImpl.makeFunction("getStack", NativeError.GET_STACK);
    final ScriptFunction setStack = ScriptFunctionImpl.makeFunction("setStack", NativeError.SET_STACK);
    errorProto.addOwnProperty("stack", Attribute.NOT_ENUMERABLE, getStack, setStack);
    final ScriptFunction getLineNumber = ScriptFunctionImpl.makeFunction("getLineNumber", NativeError.GET_LINENUMBER);
    final ScriptFunction setLineNumber = ScriptFunctionImpl.makeFunction("setLineNumber", NativeError.SET_LINENUMBER);
    errorProto.addOwnProperty("lineNumber", Attribute.NOT_ENUMERABLE, getLineNumber, setLineNumber);
    final ScriptFunction getColumnNumber = ScriptFunctionImpl.makeFunction("getColumnNumber", NativeError.GET_COLUMNNUMBER);
    final ScriptFunction setColumnNumber = ScriptFunctionImpl.makeFunction("setColumnNumber", NativeError.SET_COLUMNNUMBER);
    errorProto.addOwnProperty("columnNumber", Attribute.NOT_ENUMERABLE, getColumnNumber, setColumnNumber);
    final ScriptFunction getFileName = ScriptFunctionImpl.makeFunction("getFileName", NativeError.GET_FILENAME);
    final ScriptFunction setFileName = ScriptFunctionImpl.makeFunction("setFileName", NativeError.SET_FILENAME);
    errorProto.addOwnProperty("fileName", Attribute.NOT_ENUMERABLE, getFileName, setFileName);

    // ECMA 15.11.4.2 Error.prototype.name
    // Error.prototype.name = "Error";
    errorProto.set(NativeError.NAME, "Error", false);
    // ECMA 15.11.4.3 Error.prototype.message
    // Error.prototype.message = "";
    errorProto.set(NativeError.MESSAGE, "", false);

    this.builtinEvalError = initErrorSubtype("EvalError", errorProto);
    this.builtinRangeError = initErrorSubtype("RangeError", errorProto);
    this.builtinReferenceError = initErrorSubtype("ReferenceError", errorProto);
    this.builtinSyntaxError = initErrorSubtype("SyntaxError", errorProto);
    this.builtinTypeError = initErrorSubtype("TypeError", errorProto);
    this.builtinURIError = initErrorSubtype("URIError", errorProto);
}
 
Example 15
Source Project: jdk8u60   Source File: Global.java    License: GNU General Public License v2.0 5 votes vote down vote up
private ScriptFunction initErrorSubtype(final String name, final ScriptObject errorProto) {
    final ScriptFunction cons = initConstructor(name, ScriptFunction.class);
    final ScriptObject prototype = ScriptFunction.getPrototype(cons);
    prototype.set(NativeError.NAME, name, 0);
    prototype.set(NativeError.MESSAGE, "", 0);
    prototype.setInitialProto(errorProto);
    tagBuiltinProperties(name, cons);
    return cons;
}
 
Example 16
Source Project: openjdk-jdk8u   Source File: Bootstrap.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns if the given object is a "callable"
 * @param obj object to be checked for callability
 * @return true if the obj is callable
 */
public static boolean isCallable(final Object obj) {
    if (obj == ScriptRuntime.UNDEFINED || obj == null) {
        return false;
    }

    return obj instanceof ScriptFunction ||
        isJSObjectFunction(obj) ||
        BeansLinker.isDynamicMethod(obj) ||
        obj instanceof BoundCallable ||
        isFunctionalInterfaceObject(obj) ||
        obj instanceof StaticClass;
}
 
Example 17
Source Project: jdk8u_nashorn   Source File: Global.java    License: GNU General Public License v2.0 5 votes vote down vote up
private <T extends ScriptObject> T initConstructor(final String name, final Class<T> clazz) {
    try {
        // Assuming class name pattern for built-in JS constructors.
        final StringBuilder sb = new StringBuilder("jdk.nashorn.internal.objects.");

        sb.append("Native");
        sb.append(name);
        sb.append("$Constructor");

        final Class<?> funcClass = Class.forName(sb.toString());
        final T res = clazz.cast(funcClass.newInstance());

        if (res instanceof ScriptFunction) {
            // All global constructor prototypes are not-writable,
            // not-enumerable and not-configurable.
            final ScriptFunction func = (ScriptFunction)res;
            func.modifyOwnProperty(func.getProperty("prototype"), Attribute.NON_ENUMERABLE_CONSTANT);
        }

        if (res.getProto() == null) {
            res.setInitialProto(getObjectPrototype());
        }

        res.setIsBuiltin();

        return res;
    } catch (final ClassNotFoundException | InstantiationException | IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}
 
Example 18
Source Project: jdk8u60   Source File: Global.java    License: GNU General Public License v2.0 5 votes vote down vote up
private synchronized ScriptFunction getBuiltinRegExp() {
    if (this.builtinRegExp == null) {
        this.builtinRegExp = initConstructorAndSwitchPoint("RegExp", ScriptFunction.class);
        final ScriptObject regExpProto = ScriptFunction.getPrototype(builtinRegExp);
        // initialize default regexp object
        this.DEFAULT_REGEXP = new NativeRegExp("(?:)", "", this, regExpProto);
        // RegExp.prototype should behave like a RegExp object. So copy the
        // properties.
        regExpProto.addBoundProperties(DEFAULT_REGEXP);
    }
    return builtinRegExp;
}
 
Example 19
/**
 * Factory to create correct Arguments object based on strict mode.
 *
 * @param arguments the actual arguments array passed
 * @param callee the callee function that uses arguments object
 * @param numParams the number of declared (named) function parameters
 * @return Arguments Object
 */
public static ScriptObject allocate(final Object[] arguments, final ScriptFunction callee, final int numParams) {
    // Strict functions won't always have a callee for arguments, and will pass null instead.
    final boolean isStrict = callee == null || callee.isStrict();
    final Global global = Global.instance();
    final ScriptObject proto = global.getObjectPrototype();
    if (isStrict) {
        return new NativeStrictArguments(arguments, numParams, proto, NativeStrictArguments.getInitialMap());
    }
    return new NativeArguments(arguments, callee, numParams, proto, NativeArguments.getInitialMap());
}
 
Example 20
Source Project: hottub   Source File: Global.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static boolean isBuiltinFunctionProperty(final String name) {
    final Global instance = Global.instance();
    final ScriptFunction builtinFunction = instance.getBuiltinFunction();
    if (builtinFunction == null) {
        return false; //conservative for compile-only mode
    }
    final boolean isBuiltinFunction = instance.function == builtinFunction;
    return isBuiltinFunction && ScriptFunction.getPrototype(builtinFunction).getProperty(name).isBuiltin();
}
 
Example 21
Source Project: jdk8u_nashorn   Source File: Global.java    License: GNU General Public License v2.0 5 votes vote down vote up
private synchronized ScriptFunction getBuiltinJavaImporter() {
    if (getContext().getEnv()._no_java) {
        throw new IllegalStateException();
    }
    if (this.builtinJavaImporter == null) {
        this.builtinJavaImporter = initConstructor("JavaImporter", ScriptFunction.class);
    }
    return this.builtinJavaImporter;
}
 
Example 22
@Override
public Object newObject(final Object... args) {
    final Global oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != global);

    try {
        if (globalChanged) {
            Context.setGlobal(global);
        }

        if (sobj instanceof ScriptFunction) {
            final Object[] modArgs = globalChanged? wrapArrayLikeMe(args, oldGlobal) : args;
            return wrapLikeMe(ScriptRuntime.construct((ScriptFunction)sobj, unwrapArray(modArgs, global)));
        }

        throw new RuntimeException("not a constructor: " + toString());
    } catch (final NashornException ne) {
        throw ne.initEcmaError(global);
    } catch (final RuntimeException | Error e) {
        throw e;
    } catch (final Throwable t) {
        throw new RuntimeException(t);
    } finally {
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }
}
 
Example 23
/**
 * Returns if the given object is a "callable"
 * @param obj object to be checked for callability
 * @return true if the obj is callable
 */
public static boolean isCallable(final Object obj) {
    if (obj == ScriptRuntime.UNDEFINED || obj == null) {
        return false;
    }

    return obj instanceof ScriptFunction ||
        isJSObjectFunction(obj) ||
        BeansLinker.isDynamicMethod(obj) ||
        obj instanceof BoundCallable ||
        isFunctionalInterfaceObject(obj) ||
        obj instanceof StaticClass;
}
 
Example 24
Source Project: openjdk-jdk9   Source File: NativeFunction.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * ECMA 15.3.4.3 Function.prototype.apply (thisArg, argArray)
 *
 * @param self   self reference
 * @param thiz   {@code this} arg for apply
 * @param array  array of argument for apply
 * @return result of apply
 */
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static Object apply(final Object self, final Object thiz, final Object array) {
    checkCallable(self);
    final Object[] args = toApplyArgs(array);

    if (self instanceof ScriptFunction) {
        return ScriptRuntime.apply((ScriptFunction)self, thiz, args);
    } else if (self instanceof JSObject) {
        return ((JSObject)self).call(thiz, args);
    }
    throw new AssertionError("Should not reach here");
}
 
Example 25
Source Project: openjdk-jdk9   Source File: NativeJava.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns synchronized wrapper version of the given ECMAScript function.
 * @param self not used
 * @param func the ECMAScript function whose synchronized version is returned.
 * @param obj the object (i.e, lock) on which the function synchronizes.
 * @return synchronized wrapper version of the given ECMAScript function.
 */
@Function(name="synchronized", attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static Object synchronizedFunc(final Object self, final Object func, final Object obj) {
    if (func instanceof ScriptFunction) {
        return ((ScriptFunction)func).createSynchronized(obj);
    }

    throw typeError("not.a.function", ScriptRuntime.safeToString(func));
}
 
Example 26
Source Project: openjdk-8   Source File: Global.java    License: GNU General Public License v2.0 4 votes vote down vote up
ScriptObject getURIErrorPrototype() {
    return ScriptFunction.getPrototype(builtinURIError);
}
 
Example 27
Source Project: openjdk-8-source   Source File: Global.java    License: GNU General Public License v2.0 4 votes vote down vote up
ScriptObject getRegExpPrototype() {
    return ScriptFunction.getPrototype(builtinRegExp);
}
 
Example 28
Source Project: openjdk-jdk8u   Source File: Global.java    License: GNU General Public License v2.0 4 votes vote down vote up
ScriptObject getSyntaxErrorPrototype() {
    return ScriptFunction.getPrototype(builtinSyntaxError);
}
 
Example 29
Source Project: openjdk-jdk9   Source File: Global.java    License: GNU General Public License v2.0 4 votes vote down vote up
ScriptObject getInt16ArrayPrototype() {
    return ScriptFunction.getPrototype(getBuiltinInt16Array());
}
 
Example 30
Source Project: jdk8u60   Source File: ContextTest.java    License: GNU General Public License v2.0 4 votes vote down vote up
private static Object eval(final Context cx, final String name, final String code) {
    final Source source = sourceFor(name, code);
    final ScriptObject global = Context.getGlobal();
    final ScriptFunction func = cx.compileScript(source, global);
    return func != null ? ScriptRuntime.apply(func, global) : null;
}