jdk.nashorn.internal.objects.Global Java Examples

The following examples show how to use jdk.nashorn.internal.objects.Global. 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 File: NashornScriptEngine.java    From jdk8u_nashorn with GNU General Public License v2.0 6 votes vote down vote up
private Object evalImpl(final Context.MultiGlobalCompiledScript mgcs, final ScriptContext ctxt, final Global ctxtGlobal) throws ScriptException {
    final Global oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != ctxtGlobal);
    try {
        if (globalChanged) {
            Context.setGlobal(ctxtGlobal);
        }

        final ScriptFunction script = mgcs.getFunction(ctxtGlobal);
        final ScriptContext oldCtxt = ctxtGlobal.getScriptContext();
        ctxtGlobal.setScriptContext(ctxt);
        try {
            return ScriptObjectMirror.translateUndefined(ScriptObjectMirror.wrap(ScriptRuntime.apply(script, ctxtGlobal), ctxtGlobal));
        } finally {
            ctxtGlobal.setScriptContext(oldCtxt);
        }
    } catch (final Exception e) {
        throwAsScriptException(e, ctxtGlobal);
        throw new AssertionError("should not reach here");
    } finally {
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }
}
 
Example #2
Source File: Shell.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Run method logic.
 *
 * @param in input stream for Shell
 * @param out output stream for Shell
 * @param err error stream for Shell
 * @param args arguments to Shell
 *
 * @return exit code
 *
 * @throws IOException if there's a problem setting up the streams
 */
protected final int run(final InputStream in, final OutputStream out, final OutputStream err, final String[] args) throws IOException {
    final Context context = makeContext(in, out, err, args);
    if (context == null) {
        return COMMANDLINE_ERROR;
    }

    final Global global = context.createGlobal();
    final ScriptEnvironment env = context.getEnv();
    final List<String> files = env.getFiles();
    if (files.isEmpty()) {
        return readEvalPrint(context, global);
    }

    if (env._compile_only) {
        return compileScripts(context, global, files);
    }

    if (env._fx) {
        return runFXScripts(context, global, files);
    }

    return runScripts(context, global, files);
}
 
Example #3
Source File: NashornScriptEngine.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private ScriptFunction compileImpl(final Source source, final Global newGlobal) throws ScriptException {
    final Global oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != newGlobal);
    try {
        if (globalChanged) {
            Context.setGlobal(newGlobal);
        }

        return nashornContext.compileScript(source, newGlobal);
    } catch (final Exception e) {
        throwAsScriptException(e, newGlobal);
        throw new AssertionError("should not reach here");
    } finally {
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }
}
 
Example #4
Source File: NashornScriptEngine.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private ScriptFunction compileImpl(final Source source, final Global newGlobal) throws ScriptException {
    final Global oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != newGlobal);
    try {
        if (globalChanged) {
            Context.setGlobal(newGlobal);
        }

        return nashornContext.compileScript(source, newGlobal);
    } catch (final Exception e) {
        throwAsScriptException(e, newGlobal);
        throw new AssertionError("should not reach here");
    } finally {
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }
}
 
Example #5
Source File: ContextTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void evalTest() {
    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 {
        String code = "22 + 10";
        assertTrue(32.0 == ((Number)(eval(cx, "<evalTest>", code))).doubleValue());

        code = "obj = { js: 'nashorn' }; obj.js";
        assertEquals(eval(cx, "<evalTest2>", code), "nashorn");
    } finally {
        Context.setGlobal(oldGlobal);
    }
}
 
Example #6
Source File: JSONFunctions.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Parses the given JSON text string and returns object representation.
 *
 * @param text JSON text to be parsed
 * @param reviver  optional value: function that takes two parameters (key, value)
 * @return Object representation of JSON text given
 */
public static Object parse(final Object text, final Object reviver) {
    final String     str    = JSType.toString(text);
    final Global     global = Context.getGlobal();
    final boolean    dualFields = ((ScriptObject) global).useDualFields();
    final JSONParser parser = new JSONParser(str, global, dualFields);
    final Object     value;

    try {
        value = parser.parse();
    } catch (final ParserException e) {
        throw ECMAErrors.syntaxError(e, "invalid.json", e.getMessage());
    }

    return applyReviver(global, value, reviver);
}
 
Example #7
Source File: NashornScriptEngine.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
private static void throwAsScriptException(final Exception e, final Global global) throws ScriptException {
    if (e instanceof ScriptException) {
        throw (ScriptException)e;
    } else if (e instanceof NashornException) {
        final NashornException ne = (NashornException)e;
        final ScriptException se = new ScriptException(
            ne.getMessage(), ne.getFileName(),
            ne.getLineNumber(), ne.getColumnNumber());
        ne.initEcmaError(global);
        se.initCause(e);
        throw se;
    } else if (e instanceof RuntimeException) {
        throw (RuntimeException)e;
    } else {
        // wrap any other exception as ScriptException
        throw new ScriptException(e);
    }
}
 
Example #8
Source File: ContextTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void evalTest() {
    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 {
        String code = "22 + 10";
        assertTrue(32.0 == ((Number)(eval(cx, "<evalTest>", code))).doubleValue());

        code = "obj = { js: 'nashorn' }; obj.js";
        assertEquals(eval(cx, "<evalTest2>", code), "nashorn");
    } finally {
        Context.setGlobal(oldGlobal);
    }
}
 
Example #9
Source File: NashornScriptEngine.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private static void throwAsScriptException(final Exception e, final Global global) throws ScriptException {
    if (e instanceof ScriptException) {
        throw (ScriptException)e;
    } else if (e instanceof NashornException) {
        final NashornException ne = (NashornException)e;
        final ScriptException se = new ScriptException(
            ne.getMessage(), ne.getFileName(),
            ne.getLineNumber(), ne.getColumnNumber());
        ne.initEcmaError(global);
        se.initCause(e);
        throw se;
    } else if (e instanceof RuntimeException) {
        throw (RuntimeException)e;
    } else {
        // wrap any other exception as ScriptException
        throw new ScriptException(e);
    }
}
 
Example #10
Source File: ScriptObjectMirror.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Make a script object mirror on given object if needed. Also converts ConsString instances to Strings.
 *
 * @param obj object to be wrapped/converted
 * @param homeGlobal global to which this object belongs. Not used for ConsStrings.
 * @param jsonCompatible if true, the created wrapper will implement the Java {@code List} interface if
 * {@code obj} is a JavaScript {@code Array} object. Arrays retrieved through its properties (transitively)
 * will also implement the list interface.
 * @return wrapped/converted object
 */
private static Object wrap(final Object obj, final Object homeGlobal, final boolean jsonCompatible) {
    if(obj instanceof ScriptObject) {
        if (!(homeGlobal instanceof Global)) {
            return obj;
        }
        final ScriptObject sobj = (ScriptObject)obj;
        final Global global = (Global)homeGlobal;
        final ScriptObjectMirror mirror = new ScriptObjectMirror(sobj, global, jsonCompatible);
        if (jsonCompatible && sobj.isArray()) {
            return new JSONListAdapter(mirror, global);
        }
        return mirror;
    } else if(obj instanceof ConsString) {
        return obj.toString();
    } else if (jsonCompatible && obj instanceof ScriptObjectMirror) {
        // Since choosing JSON compatible representation is an explicit decision on user's part, if we're asked to
        // wrap a mirror that was not JSON compatible, explicitly create its compatible counterpart following the
        // principle of least surprise.
        return ((ScriptObjectMirror)obj).asJSONCompatible();
    }
    return obj;
}
 
Example #11
Source File: NashornScriptEngine.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private Object evalImpl(final Context.MultiGlobalCompiledScript mgcs, final ScriptContext ctxt, final Global ctxtGlobal) throws ScriptException {
    final Global oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != ctxtGlobal);
    try {
        if (globalChanged) {
            Context.setGlobal(ctxtGlobal);
        }

        final ScriptFunction script = mgcs.getFunction(ctxtGlobal);
        final ScriptContext oldCtxt = ctxtGlobal.getScriptContext();
        ctxtGlobal.setScriptContext(ctxt);
        try {
            return ScriptObjectMirror.translateUndefined(ScriptObjectMirror.wrap(ScriptRuntime.apply(script, ctxtGlobal), ctxtGlobal));
        } finally {
            ctxtGlobal.setScriptContext(oldCtxt);
        }
    } catch (final Exception e) {
        throwAsScriptException(e, ctxtGlobal);
        throw new AssertionError("should not reach here");
    } finally {
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }
}
 
Example #12
Source File: NashornScriptEngine.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private ScriptFunction compileImpl(final Source source, final Global newGlobal) throws ScriptException {
    final Global oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != newGlobal);
    try {
        if (globalChanged) {
            Context.setGlobal(newGlobal);
        }

        return nashornContext.compileScript(source, newGlobal);
    } catch (final Exception e) {
        throwAsScriptException(e, newGlobal);
        throw new AssertionError("should not reach here");
    } finally {
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }
}
 
Example #13
Source File: Context.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Initialize given global scope object.
 *
 * @param global the global
 * @param engine the associated ScriptEngine instance, can be null
 * @return the initialized global scope object.
 */
public Global initGlobal(final Global global, final ScriptEngine engine) {
    // Need only minimal global object, if we are just compiling.
    if (!env._compile_only) {
        final Global oldGlobal = Context.getGlobal();
        try {
            Context.setGlobal(global);
            // initialize global scope with builtin global objects
            global.initBuiltinObjects(engine);
        } finally {
            Context.setGlobal(oldGlobal);
        }
    }

    return global;
}
 
Example #14
Source File: NashornScriptEngine.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private Global globalFromMirror(final ScriptObjectMirror mirror) {
    final ScriptObject sobj = mirror.getScriptObject();
    if (sobj instanceof Global && isOfContext((Global)sobj, nashornContext)) {
        return (Global)sobj;
    }

    return null;
}
 
Example #15
Source File: NashornScriptEngine.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private Object evalImpl(final ScriptFunction script, final ScriptContext ctxt, final Global ctxtGlobal) throws ScriptException {
    if (script == null) {
        return null;
    }
    final Global oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != ctxtGlobal);
    try {
        if (globalChanged) {
            Context.setGlobal(ctxtGlobal);
        }

        final ScriptContext oldCtxt = ctxtGlobal.getScriptContext();
        ctxtGlobal.setScriptContext(ctxt);
        try {
            return ScriptObjectMirror.translateUndefined(ScriptObjectMirror.wrap(ScriptRuntime.apply(script, ctxtGlobal), ctxtGlobal));
        } finally {
            ctxtGlobal.setScriptContext(oldCtxt);
        }
    } catch (final Exception e) {
        throwAsScriptException(e, ctxtGlobal);
        throw new AssertionError("should not reach here");
    } finally {
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }
}
 
Example #16
Source File: ScriptObject.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * ECMA 8.12.1 [[GetOwnProperty]] (P)
 *
 * @param key property key
 *
 * @return Returns the Property Descriptor of the named own property of this
 * object, or undefined if absent.
 */
public Object getOwnPropertyDescriptor(final String key) {
    final Property property = getMap().findProperty(key);

    final Global global = Context.getGlobal();

    if (property != null) {
        final ScriptFunction get   = property.getGetterFunction(this);
        final ScriptFunction set   = property.getSetterFunction(this);

        final boolean configurable = property.isConfigurable();
        final boolean enumerable   = property.isEnumerable();
        final boolean writable     = property.isWritable();

        if (property instanceof UserAccessorProperty) {
            return global.newAccessorDescriptor(
                get != null ?
                    get :
                    UNDEFINED,
                set != null ?
                    set :
                    UNDEFINED,
                configurable,
                enumerable);
        }

        return global.newDataDescriptor(getWithProperty(property), configurable, enumerable, writable);
    }

    final int index = getArrayIndex(key);
    final ArrayData array = getArray();

    if (array.has(index)) {
        return array.getDescriptor(global, index);
    }

    return UNDEFINED;
}
 
Example #17
Source File: ScriptRuntime.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns an iterator over property identifiers used in the {@code for...in} statement. Note that the ECMAScript
 * 5.1 specification, chapter 12.6.4. uses the terminology "property names", which seems to imply that the property
 * identifiers are expected to be strings, but this is not actually spelled out anywhere, and Nashorn will in some
 * cases deviate from this. Namely, we guarantee to always return an iterator over {@link String} values for any
 * built-in JavaScript object. We will however return an iterator over {@link Integer} objects for native Java
 * arrays and {@link List} objects, as well as arbitrary objects representing keys of a {@link Map}. Therefore, the
 * expression {@code typeof i} within a {@code for(i in obj)} statement can return something other than
 * {@code string} when iterating over native Java arrays, {@code List}, and {@code Map} objects.
 * @param obj object to iterate on.
 * @return iterator over the object's property names.
 */
public static Iterator<?> toPropertyIterator(final Object obj) {
    if (obj instanceof ScriptObject) {
        return ((ScriptObject)obj).propertyIterator();
    }

    if (obj != null && obj.getClass().isArray()) {
        return new RangeIterator(Array.getLength(obj));
    }

    if (obj instanceof JSObject) {
        return ((JSObject)obj).keySet().iterator();
    }

    if (obj instanceof List) {
        return new RangeIterator(((List<?>)obj).size());
    }

    if (obj instanceof Map) {
        return ((Map<?,?>)obj).keySet().iterator();
    }

    final Object wrapped = Global.instance().wrapAsObject(obj);
    if (wrapped instanceof ScriptObject) {
        return ((ScriptObject)wrapped).propertyIterator();
    }

    return Collections.emptyIterator();
}
 
Example #18
Source File: Context.java    From jdk8u_nashorn with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Implementation of {@code loadWithNewGlobal} Nashorn extension. Load a script file from a source
 * expression, after creating a new global scope.
 *
 * @param from source expression for script
 * @param args (optional) arguments to be passed to the loaded script
 *
 * @return return value for load call (undefined)
 *
 * @throws IOException if source cannot be found or loaded
 */
public Object loadWithNewGlobal(final Object from, final Object...args) throws IOException {
    final Global oldGlobal = getGlobal();
    final Global newGlobal = AccessController.doPrivileged(new PrivilegedAction<Global>() {
       @Override
       public Global run() {
           try {
               return newGlobal();
           } catch (final RuntimeException e) {
               if (Context.DEBUG) {
                   e.printStackTrace();
               }
               throw e;
           }
       }
    }, CREATE_GLOBAL_ACC_CTXT);
    // initialize newly created Global instance
    initGlobal(newGlobal);
    setGlobal(newGlobal);

    final Object[] wrapped = args == null? ScriptRuntime.EMPTY_ARRAY :  ScriptObjectMirror.wrapArray(args, oldGlobal);
    newGlobal.put("arguments", newGlobal.wrapAsObject(wrapped), env._strict);

    try {
        // wrap objects from newGlobal's world as mirrors - but if result
        // is from oldGlobal's world, unwrap it!
        return ScriptObjectMirror.unwrap(ScriptObjectMirror.wrap(load(newGlobal, from), newGlobal), oldGlobal);
    } finally {
        setGlobal(oldGlobal);
    }
}
 
Example #19
Source File: Context.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Set the current global scope
 * @param global the global scope
 */
public static void setGlobal(final ScriptObject global) {
    if (global != null && !(global instanceof Global)) {
        throw new IllegalArgumentException("global is not an instance of Global!");
    }

    setGlobalTrusted(global);
}
 
Example #20
Source File: ListAdapter.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private static JSObject getJSObject(final Object obj, final Global global) {
    if (obj instanceof ScriptObject) {
        return (JSObject)ScriptObjectMirror.wrap(obj, global);
    } else if (obj instanceof JSObject) {
        return (JSObject)obj;
    }
    throw new IllegalArgumentException("ScriptObject or JSObject expected");
}
 
Example #21
Source File: NashornScriptEngine.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private Object evalImpl(final ScriptFunction script, final ScriptContext ctxt, final Global ctxtGlobal) throws ScriptException {
    if (script == null) {
        return null;
    }
    final Global oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != ctxtGlobal);
    try {
        if (globalChanged) {
            Context.setGlobal(ctxtGlobal);
        }

        final ScriptContext oldCtxt = ctxtGlobal.getScriptContext();
        ctxtGlobal.setScriptContext(ctxt);
        try {
            return ScriptObjectMirror.translateUndefined(ScriptObjectMirror.wrap(ScriptRuntime.apply(script, ctxtGlobal), ctxtGlobal));
        } finally {
            ctxtGlobal.setScriptContext(oldCtxt);
        }
    } catch (final Exception e) {
        throwAsScriptException(e, ctxtGlobal);
        throw new AssertionError("should not reach here");
    } finally {
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }
}
 
Example #22
Source File: ScriptObjectMirror.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Object call(final Object thiz, 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;
            final Object self = globalChanged? wrapLikeMe(thiz, oldGlobal) : thiz;
            return wrapLikeMe(ScriptRuntime.apply((ScriptFunction)sobj, unwrap(self, global), unwrapArray(modArgs, global)));
        }

        throw new RuntimeException("not a function: " + 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
Source File: JavaAdapterServices.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Set the current global scope to that of the adapter global
 * @param adapterGlobal the adapter's global scope
 * @return a Runnable that when invoked restores the previous global
 */
public static Runnable setGlobal(final ScriptObject adapterGlobal) {
    final Global currentGlobal = Context.getGlobal();
    if (adapterGlobal != currentGlobal) {
        Context.setGlobal(adapterGlobal);
        return ()->Context.setGlobal(currentGlobal);
    }
    return ()->{};
}
 
Example #24
Source File: ScriptObject.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unused")
private static Object globalFilter(final Object object) {
    ScriptObject sobj = (ScriptObject) object;
    while (sobj != null && !(sobj instanceof Global)) {
        sobj = sobj.getProto();
    }
    return sobj;
}
 
Example #25
Source File: JSObjectLinker.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unused")
private static Object jsObjectScopeCall(final JSObject jsObj, final Object thiz, final Object[] args) {
    final Object modifiedThiz;
    if (thiz == ScriptRuntime.UNDEFINED && !jsObj.isStrictFunction()) {
        final Global global = Context.getGlobal();
        modifiedThiz = ScriptObjectMirror.wrap(global, global);
    } else {
        modifiedThiz = thiz;
    }
    return jsObj.call(modifiedThiz, args);
}
 
Example #26
Source File: NashornScriptEngine.java    From jdk8u_nashorn with GNU General Public License v2.0 5 votes vote down vote up
private CompiledScript asCompiledScript(final Source source) throws ScriptException {
    final Context.MultiGlobalCompiledScript mgcs;
    final ScriptFunction func;
    final Global oldGlobal = Context.getGlobal();
    final Global newGlobal = getNashornGlobalFrom(context);
    final boolean globalChanged = (oldGlobal != newGlobal);
    try {
        if (globalChanged) {
            Context.setGlobal(newGlobal);
        }

        mgcs = nashornContext.compileScript(source);
        func = mgcs.getFunction(newGlobal);
    } catch (final Exception e) {
        throwAsScriptException(e, newGlobal);
        throw new AssertionError("should not reach here");
    } finally {
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }

    return new CompiledScript() {
        @Override
        public Object eval(final ScriptContext ctxt) throws ScriptException {
            final Global globalObject = getNashornGlobalFrom(ctxt);
            // Are we running the script in the same global in which it was compiled?
            if (func.getScope() == globalObject) {
                return evalImpl(func, ctxt, globalObject);
            }

            // different global
            return evalImpl(mgcs, ctxt, globalObject);
        }
        @Override
        public ScriptEngine getEngine() {
            return NashornScriptEngine.this;
        }
    };
}
 
Example #27
Source File: ReflectionCheckLinker.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
static void checkReflectionAccess(final Class<?> clazz, final boolean isStatic) {
    final Global global = Context.getGlobal();
    final ClassFilter cf = global.getClassFilter();
    if (cf != null && isReflectiveCheckNeeded(clazz, isStatic)) {
        throw typeError("no.reflection.with.classfilter");
    }

    final SecurityManager sm = System.getSecurityManager();
    if (sm != null && isReflectiveCheckNeeded(clazz, isStatic)) {
        checkReflectionPermission(sm);
    }
}
 
Example #28
Source File: FindProperty.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private MethodHandle insertAccessorsGetter(final UserAccessorProperty uap, final LinkRequest request, final MethodHandle mh) {
    MethodHandle superGetter = uap.getAccessorsGetter();
    if (isInherited()) {
        superGetter = ScriptObject.addProtoFilter(superGetter, getProtoChainLength());
    }
    if (request != null && !(request.getReceiver() instanceof ScriptObject)) {
        final MethodHandle wrapFilter = Global.getPrimitiveWrapFilter(request.getReceiver());
        superGetter = MH.filterArguments(superGetter, 0, wrapFilter.asType(wrapFilter.type().changeReturnType(superGetter.type().parameterType(0))));
    }
    superGetter = MH.asType(superGetter, superGetter.type().changeParameterType(0, Object.class));

    return MH.foldArguments(mh, superGetter);
}
 
Example #29
Source File: ScriptObjectMirror.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Call member function
 * @param functionName function name
 * @param args         arguments
 * @return return value of function
 */
public Object callMember(final String functionName, final Object... args) {
    Objects.requireNonNull(functionName);
    final Global oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != global);

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

        final Object val = sobj.get(functionName);
        if (val instanceof ScriptFunction) {
            final Object[] modArgs = globalChanged? wrapArrayLikeMe(args, oldGlobal) : args;
            return wrapLikeMe(ScriptRuntime.apply((ScriptFunction)val, sobj, unwrapArray(modArgs, global)));
        } else if (val instanceof JSObject && ((JSObject)val).isFunction()) {
            return ((JSObject)val).call(sobj, args);
        }

        throw new NoSuchMethodException("No such function " + functionName);
    } 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 #30
Source File: ScriptObjectMirror.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Object call(final Object thiz, 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;
            final Object self = globalChanged? wrapLikeMe(thiz, oldGlobal) : thiz;
            return wrapLikeMe(ScriptRuntime.apply((ScriptFunction)sobj, unwrap(self, global), unwrapArray(modArgs, global)));
        }

        throw new RuntimeException("not a function: " + 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);
        }
    }
}