Java Code Examples for jdk.nashorn.api.scripting.JSObject

The following are top voted examples for showing how to use jdk.nashorn.api.scripting.JSObject. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: OpenJSharp   File: NativeFunction.java   Source Code and License 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
Project: OpenJSharp   File: JSObjectLinker.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unused")
private static Object get(final MethodHandle fallback, final Object jsobj, final Object key)
    throws Throwable {
    if (key instanceof Integer) {
        return ((JSObject)jsobj).getSlot((Integer)key);
    } else if (key instanceof Number) {
        final int index = getIndex((Number)key);
        if (index > -1) {
            return ((JSObject)jsobj).getSlot(index);
        }
    } else if (key instanceof String) {
        final String name = (String)key;
        // get with method name and signature. delegate it to beans linker!
        if (name.indexOf('(') != -1) {
            return fallback.invokeExact(jsobj, key);
        }
        return ((JSObject)jsobj).getMember(name);
    }
    return null;
}
 
Example 3
Project: OpenJSharp   File: ScriptRuntime.java   Source Code and License 6 votes vote down vote up
/**
 * ECMA 11.8.6 - The in operator - generic implementation
 *
 * @param property property to check for
 * @param obj object in which to check for property
 *
 * @return true if objects are equal
 */
public static boolean IN(final Object property, final Object obj) {
    final JSType rvalType = JSType.ofNoFunction(obj);

    if (rvalType == JSType.OBJECT) {
        if (obj instanceof ScriptObject) {
            return ((ScriptObject)obj).has(property);
        }

        if (obj instanceof JSObject) {
            return ((JSObject)obj).hasMember(Objects.toString(property));
        }

        return false;
    }

    throw typeError("in.with.non.object", rvalType.toString().toLowerCase(Locale.ENGLISH));
}
 
Example 4
Project: OpenJSharp   File: ScriptRuntime.java   Source Code and License 6 votes vote down vote up
/**
 * ECMA 11.8.6 - The strict instanceof operator - generic implementation
 *
 * @param obj first object to compare
 * @param clazz type to check against
 *
 * @return true if {@code obj} is an instanceof {@code clazz}
 */
public static boolean INSTANCEOF(final Object obj, final Object clazz) {
    if (clazz instanceof ScriptFunction) {
        if (obj instanceof ScriptObject) {
            return ((ScriptObject)clazz).isInstance((ScriptObject)obj);
        }
        return false;
    }

    if (clazz instanceof StaticClass) {
        return ((StaticClass)clazz).getRepresentedClass().isInstance(obj);
    }

    if (clazz instanceof JSObject) {
        return ((JSObject)clazz).isInstance(obj);
    }

    // provide for reverse hook
    if (obj instanceof JSObject) {
        return ((JSObject)obj).isInstanceOf(clazz);
    }

    throw typeError("instanceof.on.non.object");
}
 
Example 5
Project: openjdk-jdk10   File: NativeFunction.java   Source Code and License 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 6
Project: openjdk-jdk10   File: NativeArray.java   Source Code and License 6 votes vote down vote up
private static void concatToList(final ArrayList<Object> list, final Object obj) {
    final boolean isScriptArray  = isArray(obj);
    final boolean isScriptObject = isScriptArray || obj instanceof ScriptObject;
    if (isScriptArray || obj instanceof Iterable || obj instanceof JSObject || (obj != null && obj.getClass().isArray())) {
        final Iterator<Object> iter = arrayLikeIterator(obj, true);
        if (iter.hasNext()) {
            for (int i = 0; iter.hasNext(); ++i) {
                final Object value = iter.next();
                if (value == ScriptRuntime.UNDEFINED && isScriptObject && !((ScriptObject)obj).has(i)) {
                    // TODO: eventually rewrite arrayLikeIterator to use a three-state enum for handling
                    // UNDEFINED instead of an "includeUndefined" boolean with states SKIP, INCLUDE,
                    // RETURN_EMPTY. Until then, this is how we'll make sure that empty elements don't make it
                    // into the concatenated array.
                    list.add(ScriptRuntime.EMPTY);
                } else {
                    list.add(value);
                }
            }
        } else if (!isScriptArray) {
            list.add(obj); // add empty object, but not an empty array
        }
    } else {
        // single element, add it
        list.add(obj);
    }
}
 
Example 7
Project: openjdk-jdk10   File: JSObjectLinker.java   Source Code and License 6 votes vote down vote up
@Override
public GuardedInvocation getGuardedInvocation(final LinkRequest request, final LinkerServices linkerServices) throws Exception {
    final Object self = request.getReceiver();
    final CallSiteDescriptor desc = request.getCallSiteDescriptor();
    if (self == null || !canLinkTypeStatic(self.getClass())) {
        return null;
    }

    GuardedInvocation inv;
    if (self instanceof JSObject) {
        inv = lookup(desc, request, linkerServices);
        inv = inv.replaceMethods(linkerServices.filterInternalObjects(inv.getInvocation()), inv.getGuard());
    } else if (self instanceof Map || self instanceof Bindings) {
        // guard to make sure the Map or Bindings does not turn into JSObject later!
        final GuardedInvocation beanInv = nashornBeansLinker.getGuardedInvocation(request, linkerServices);
        inv = new GuardedInvocation(beanInv.getInvocation(),
            NashornGuards.combineGuards(beanInv.getGuard(), NashornGuards.getNotJSObjectGuard()));
    } else {
        throw new AssertionError("got instanceof: " + self.getClass()); // Should never reach here.
    }

    return Bootstrap.asTypeSafeReturn(inv, linkerServices, desc);
}
 
Example 8
Project: openjdk-jdk10   File: JSObjectLinker.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unused")
private static Object get(final MethodHandle fallback, final Object jsobj, final Object key)
    throws Throwable {
    if (key instanceof Integer) {
        return ((JSObject)jsobj).getSlot((Integer)key);
    } else if (key instanceof Number) {
        final int index = getIndex((Number)key);
        if (index > -1) {
            return ((JSObject)jsobj).getSlot(index);
        } else {
            return ((JSObject)jsobj).getMember(JSType.toString(key));
        }
    } else if (isString(key)) {
        final String name = key.toString();
        // get with method name and signature. delegate it to beans linker!
        if (name.indexOf('(') != -1) {
            return fallback.invokeExact(jsobj, (Object) name);
        }
        return ((JSObject)jsobj).getMember(name);
    }
    return null;
}
 
Example 9
Project: openjdk-jdk10   File: ScriptRuntime.java   Source Code and License 6 votes vote down vote up
/**
 * Returns an iterator over property values used in the {@code for each...in} statement. Aside from built-in JS
 * objects, it also operates on Java arrays, any {@link Iterable}, as well as on {@link Map} objects, iterating over
 * map values.
 * @param obj object to iterate on.
 * @return iterator over the object's property values.
 */
public static Iterator<?> toValueIterator(final Object obj) {
    if (obj instanceof ScriptObject) {
        return ((ScriptObject)obj).valueIterator();
    }

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

    final Iterator<?> itr = iteratorForJavaArrayOrList(obj);
    if (itr != null) {
        return itr;
    }

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

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

    return Collections.emptyIterator();
}
 
Example 10
Project: openjdk-jdk10   File: ScriptRuntime.java   Source Code and License 6 votes vote down vote up
/**
 * ECMA 11.8.6 - The strict instanceof operator - generic implementation
 *
 * @param obj first object to compare
 * @param clazz type to check against
 *
 * @return true if {@code obj} is an instanceof {@code clazz}
 */
public static boolean INSTANCEOF(final Object obj, final Object clazz) {
    if (clazz instanceof ScriptFunction) {
        if (obj instanceof ScriptObject) {
            return ((ScriptObject)clazz).isInstance((ScriptObject)obj);
        }
        return false;
    }

    if (clazz instanceof StaticClass) {
        return ((StaticClass)clazz).getRepresentedClass().isInstance(obj);
    }

    if (clazz instanceof JSObject) {
        return ((JSObject)clazz).isInstance(obj);
    }

    // provide for reverse hook
    if (obj instanceof JSObject) {
        return ((JSObject)obj).isInstanceOf(clazz);
    }

    throw typeError("instanceof.on.non.object");
}
 
Example 11
Project: openjdk-jdk10   File: HistoryObject.java   Source Code and License 6 votes vote down vote up
@Override
public Object getMember(final String name) {
    switch (name) {
        case "clear":
            return (Runnable)hist::clear;
        case "forEach":
            return (Function<JSObject, Object>)this::iterate;
        case "load":
            return (Consumer<Object>)this::load;
        case "print":
            return (Runnable)this::print;
        case "save":
            return (Consumer<Object>)this::save;
        case "size":
            return hist.size();
        case "toString":
            return (Supplier<String>)this::toString;
    }
    return UNDEFINED;
}
 
Example 12
Project: jdk8u_nashorn   File: ScriptRuntime.java   Source Code and License 6 votes vote down vote up
/**
 * ECMA 11.8.6 - The in operator - generic implementation
 *
 * @param property property to check for
 * @param obj object in which to check for property
 *
 * @return true if objects are equal
 */
public static boolean IN(final Object property, final Object obj) {
    final JSType rvalType = JSType.ofNoFunction(obj);

    if (rvalType == JSType.OBJECT) {
        if (obj instanceof ScriptObject) {
            return ((ScriptObject)obj).has(property);
        }

        if (obj instanceof JSObject) {
            return ((JSObject)obj).hasMember(Objects.toString(property));
        }

        return false;
    }

    throw typeError("in.with.non.object", rvalType.toString().toLowerCase(Locale.ENGLISH));
}
 
Example 13
Project: openjdk9   File: ScriptRuntime.java   Source Code and License 6 votes vote down vote up
/**
 * Returns an iterator over property values used in the {@code for each...in} statement. Aside from built-in JS
 * objects, it also operates on Java arrays, any {@link Iterable}, as well as on {@link Map} objects, iterating over
 * map values.
 * @param obj object to iterate on.
 * @return iterator over the object's property values.
 */
public static Iterator<?> toValueIterator(final Object obj) {
    if (obj instanceof ScriptObject) {
        return ((ScriptObject)obj).valueIterator();
    }

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

    final Iterator<?> itr = iteratorForJavaArrayOrList(obj);
    if (itr != null) {
        return itr;
    }

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

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

    return Collections.emptyIterator();
}
 
Example 14
Project: openjdk9   File: ScriptRuntime.java   Source Code and License 6 votes vote down vote up
/**
 * ECMA 11.8.6 - The in operator - generic implementation
 *
 * @param property property to check for
 * @param obj object in which to check for property
 *
 * @return true if objects are equal
 */
public static boolean IN(final Object property, final Object obj) {
    final JSType rvalType = JSType.ofNoFunction(obj);

    if (rvalType == JSType.OBJECT) {
        if (obj instanceof ScriptObject) {
            return ((ScriptObject)obj).has(property);
        }

        if (obj instanceof JSObject) {
            return ((JSObject)obj).hasMember(Objects.toString(property));
        }

        return false;
    }

    throw typeError("in.with.non.object", rvalType.toString().toLowerCase(Locale.ENGLISH));
}
 
Example 15
Project: openjdk9   File: ScriptRuntime.java   Source Code and License 6 votes vote down vote up
/**
 * ECMA 11.8.6 - The strict instanceof operator - generic implementation
 *
 * @param obj first object to compare
 * @param clazz type to check against
 *
 * @return true if {@code obj} is an instanceof {@code clazz}
 */
public static boolean INSTANCEOF(final Object obj, final Object clazz) {
    if (clazz instanceof ScriptFunction) {
        if (obj instanceof ScriptObject) {
            return ((ScriptObject)clazz).isInstance((ScriptObject)obj);
        }
        return false;
    }

    if (clazz instanceof StaticClass) {
        return ((StaticClass)clazz).getRepresentedClass().isInstance(obj);
    }

    if (clazz instanceof JSObject) {
        return ((JSObject)clazz).isInstance(obj);
    }

    // provide for reverse hook
    if (obj instanceof JSObject) {
        return ((JSObject)obj).isInstanceOf(clazz);
    }

    throw typeError("instanceof.on.non.object");
}
 
Example 16
Project: lookaside_java-1.8.0-openjdk   File: JSObjectLinker.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unused")
private static Object get(final MethodHandle fallback, final Object jsobj, final Object key)
    throws Throwable {
    if (key instanceof Integer) {
        return ((JSObject)jsobj).getSlot((Integer)key);
    } else if (key instanceof Number) {
        final int index = getIndex((Number)key);
        if (index > -1) {
            return ((JSObject)jsobj).getSlot(index);
        }
    } else if (isString(key)) {
        final String name = key.toString();
        // get with method name and signature. delegate it to beans linker!
        if (name.indexOf('(') != -1) {
            return fallback.invokeExact(jsobj, (Object) name);
        }
        return ((JSObject)jsobj).getMember(name);
    }
    return null;
}
 
Example 17
Project: hillview   File: JSVirtualRowSnapshot.java   Source Code and License 6 votes vote down vote up
@Override
@Nullable
public Object get(Object key) {
    IColumn col = this.getColumn((String)key);
    if (col.getDescription().kind == ContentsKind.Date) {
        double dateEncoding = super.getDouble((String)key);
        // https://stackoverflow.com/questions/33110942/supply-javascript-date-to-nashorn-script
        try {
            JSObject object =
                    (JSObject)this.engine.eval("new Date(" + Double.toString(dateEncoding) + ")");
            return object;
        } catch (ScriptException e) {
            throw new RuntimeException(e);
        }
    }

    Object result = super.get(key);
    if (result == null)
        return result;
    return result;
}
 
Example 18
Project: kaziranga   File: NativeFunction.java   Source Code and License 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 19
Project: jdk8u_nashorn   File: ScriptRuntime.java   Source Code and License 6 votes vote down vote up
/**
 * ECMA 11.8.6 - The strict instanceof operator - generic implementation
 *
 * @param obj first object to compare
 * @param clazz type to check against
 *
 * @return true if {@code obj} is an instanceof {@code clazz}
 */
public static boolean INSTANCEOF(final Object obj, final Object clazz) {
    if (clazz instanceof ScriptFunction) {
        if (obj instanceof ScriptObject) {
            return ((ScriptObject)clazz).isInstance((ScriptObject)obj);
        }
        return false;
    }

    if (clazz instanceof StaticClass) {
        return ((StaticClass)clazz).getRepresentedClass().isInstance(obj);
    }

    if (clazz instanceof JSObject) {
        return ((JSObject)clazz).isInstance(obj);
    }

    // provide for reverse hook
    if (obj instanceof JSObject) {
        return ((JSObject)obj).isInstanceOf(clazz);
    }

    throw typeError("instanceof.on.non.object");
}
 
Example 20
Project: kaziranga   File: JSObjectLinker.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unused")
private static Object get(final MethodHandle fallback, final Object jsobj, final Object key)
    throws Throwable {
    if (key instanceof Integer) {
        return ((JSObject)jsobj).getSlot((Integer)key);
    } else if (key instanceof Number) {
        final int index = getIndex((Number)key);
        if (index > -1) {
            return ((JSObject)jsobj).getSlot(index);
        }
    } else if (isString(key)) {
        final String name = key.toString();
        // get with method name and signature. delegate it to beans linker!
        if (name.indexOf('(') != -1) {
            return fallback.invokeExact(jsobj, (Object) name);
        }
        return ((JSObject)jsobj).getMember(name);
    }
    return null;
}
 
Example 21
Project: jdk8u_nashorn   File: JSObjectLinker.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unused")
private static Object get(final MethodHandle fallback, final Object jsobj, final Object key)
    throws Throwable {
    if (key instanceof Integer) {
        return ((JSObject)jsobj).getSlot((Integer)key);
    } else if (key instanceof Number) {
        final int index = getIndex((Number)key);
        if (index > -1) {
            return ((JSObject)jsobj).getSlot(index);
        } else {
            return ((JSObject)jsobj).getMember(JSType.toString(key));
        }
    } else if (isString(key)) {
        final String name = key.toString();
        // get with method name and signature. delegate it to beans linker!
        if (name.indexOf('(') != -1) {
            return fallback.invokeExact(jsobj, (Object) name);
        }
        return ((JSObject)jsobj).getMember(name);
    }
    return null;
}
 
Example 22
Project: kaziranga   File: ScriptRuntime.java   Source Code and License 6 votes vote down vote up
/**
 * ECMA 11.8.6 - The in operator - generic implementation
 *
 * @param property property to check for
 * @param obj object in which to check for property
 *
 * @return true if objects are equal
 */
public static boolean IN(final Object property, final Object obj) {
    final JSType rvalType = JSType.ofNoFunction(obj);

    if (rvalType == JSType.OBJECT) {
        if (obj instanceof ScriptObject) {
            return ((ScriptObject)obj).has(property);
        }

        if (obj instanceof JSObject) {
            return ((JSObject)obj).hasMember(Objects.toString(property));
        }

        return false;
    }

    throw typeError("in.with.non.object", rvalType.toString().toLowerCase(Locale.ENGLISH));
}
 
Example 23
Project: kaziranga   File: ScriptRuntime.java   Source Code and License 6 votes vote down vote up
/**
 * ECMA 11.8.6 - The strict instanceof operator - generic implementation
 *
 * @param obj first object to compare
 * @param clazz type to check against
 *
 * @return true if {@code obj} is an instanceof {@code clazz}
 */
public static boolean INSTANCEOF(final Object obj, final Object clazz) {
    if (clazz instanceof ScriptFunction) {
        if (obj instanceof ScriptObject) {
            return ((ScriptObject)clazz).isInstance((ScriptObject)obj);
        }
        return false;
    }

    if (clazz instanceof StaticClass) {
        return ((StaticClass)clazz).getRepresentedClass().isInstance(obj);
    }

    if (clazz instanceof JSObject) {
        return ((JSObject)clazz).isInstance(obj);
    }

    // provide for reverse hook
    if (obj instanceof JSObject) {
        return ((JSObject)obj).isInstanceOf(clazz);
    }

    throw typeError("instanceof.on.non.object");
}
 
Example 24
Project: lookaside_java-1.8.0-openjdk   File: ScriptRuntime.java   Source Code and License 6 votes vote down vote up
/**
 * ECMA 11.8.6 - The strict instanceof operator - generic implementation
 *
 * @param obj first object to compare
 * @param clazz type to check against
 *
 * @return true if {@code obj} is an instanceof {@code clazz}
 */
public static boolean INSTANCEOF(final Object obj, final Object clazz) {
    if (clazz instanceof ScriptFunction) {
        if (obj instanceof ScriptObject) {
            return ((ScriptObject)clazz).isInstance((ScriptObject)obj);
        }
        return false;
    }

    if (clazz instanceof StaticClass) {
        return ((StaticClass)clazz).getRepresentedClass().isInstance(obj);
    }

    if (clazz instanceof JSObject) {
        return ((JSObject)clazz).isInstance(obj);
    }

    // provide for reverse hook
    if (obj instanceof JSObject) {
        return ((JSObject)obj).isInstanceOf(clazz);
    }

    throw typeError("instanceof.on.non.object");
}
 
Example 25
Project: sonar-analyzer-commons   File: JsonParser.java   Source Code and License 5 votes vote down vote up
JsonParser() {
  try {
    nashornParser = (JSObject) new ScriptEngineManager().getEngineByName("nashorn").eval("JSON.parse");
  } catch (ScriptException e) {
    throw new IllegalStateException("Can not get 'JSON.parse' from 'nashorn' script engine.", e);
  }
}
 
Example 26
Project: centraldogma   File: Plugin.java   Source Code and License 5 votes vote down vote up
boolean hasFunction(String funcName) {
    Object member = plugin.get(funcName);
    if (!(member instanceof JSObject)) {
        return false;
    }

    return ((JSObject) member).isFunction();
}
 
Example 27
Project: OpenJSharp   File: NativeFunction.java   Source Code and License 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 28
Project: OpenJSharp   File: NashornLinker.java   Source Code and License 5 votes vote down vote up
private static GuardedInvocation getMirrorConverter(final Class<?> sourceType, final Class<?> targetType) {
    // Could've also used (targetType.isAssignableFrom(ScriptObjectMirror.class) && targetType != Object.class) but
    // it's probably better to explicitly spell out the supported target types
    if (targetType == Map.class || targetType == Bindings.class || targetType == JSObject.class || targetType == ScriptObjectMirror.class) {
        if(ScriptObject.class.isAssignableFrom(sourceType)) {
            return new GuardedInvocation(CREATE_MIRROR);
        }
        return new GuardedInvocation(CREATE_MIRROR, IS_SCRIPT_OBJECT);
    }
    return null;
}
 
Example 29
Project: OpenJSharp   File: JSObjectLinker.java   Source Code and License 5 votes vote down vote up
static boolean canLinkTypeStatic(final Class<?> type) {
    // can link JSObject also handles Map, Bindings to make
    // sure those are not JSObjects.
    return Map.class.isAssignableFrom(type) ||
           Bindings.class.isAssignableFrom(type) ||
           JSObject.class.isAssignableFrom(type);
}
 
Example 30
Project: OpenJSharp   File: JSObjectLinker.java   Source Code and License 5 votes vote down vote up
@Override
public GuardedTypeConversion convertToType(final Class<?> sourceType, final Class<?> targetType) throws Exception {
    final boolean sourceIsAlwaysJSObject = JSObject.class.isAssignableFrom(sourceType);
    if(!sourceIsAlwaysJSObject && !sourceType.isAssignableFrom(JSObject.class)) {
        return null;
    }

    final MethodHandle converter = CONVERTERS.get(targetType);
    if(converter == null) {
        return null;
    }

    return new GuardedTypeConversion(new GuardedInvocation(converter, sourceIsAlwaysJSObject ? null : IS_JSOBJECT_GUARD).asType(MethodType.methodType(targetType, sourceType)), true);
}
 
Example 31
Project: OpenJSharp   File: JSObjectLinker.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unused")
private static void put(final Object jsobj, final Object key, final Object value) {
    if (key instanceof Integer) {
        ((JSObject)jsobj).setSlot((Integer)key, value);
    } else if (key instanceof Number) {
        ((JSObject)jsobj).setSlot(getIndex((Number)key), value);
    } else if (key instanceof String) {
        ((JSObject)jsobj).setMember((String)key, value);
    }
}
 
Example 32
Project: OpenJSharp   File: JSObjectLinker.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unused")
private static Object callToApply(final MethodHandle mh, final JSObject obj, final Object thiz, final Object... args) {
    assert args.length >= 2;
    final Object   receiver  = args[0];
    final Object[] arguments = new Object[args.length - 1];
    System.arraycopy(args, 1, arguments, 0, arguments.length);
    try {
        return mh.invokeExact(obj, thiz, new Object[] { receiver, arguments });
    } catch (final RuntimeException | Error e) {
        throw e;
    } catch (final Throwable e) {
        throw new RuntimeException(e);
    }
}
 
Example 33
Project: OpenJSharp   File: Bootstrap.java   Source Code and License 5 votes vote down vote up
/**
 * Returns true if the given object is a strict callable
 * @param callable the callable object to be checked for strictness
 * @return true if the obj is a strict callable, false if it is a non-strict callable.
 * @throws ECMAException with {@code TypeError} if the object is not a callable.
 */
public static boolean isStrictCallable(final Object callable) {
    if (callable instanceof ScriptFunction) {
        return ((ScriptFunction)callable).isStrict();
    } else if (isJSObjectFunction(callable)) {
        return ((JSObject)callable).isStrictFunction();
    } else if (callable instanceof BoundCallable) {
        return isStrictCallable(((BoundCallable)callable).getCallable());
    } else if (BeansLinker.isDynamicMethod(callable) || callable instanceof StaticClass) {
        return false;
    }
    throw notFunction(callable);
}
 
Example 34
Project: OpenJSharp   File: ArrayLikeIterator.java   Source Code and License 5 votes vote down vote up
/**
 * ArrayLikeIterator factory
 * @param object object over which to do reverse element iteration
 * @param includeUndefined should undefined elements be included in the iteration
 * @return iterator
 */
public static ArrayLikeIterator<Object> arrayLikeIterator(final Object object, final boolean includeUndefined) {
    Object obj = object;

    if (ScriptObject.isArray(obj)) {
        return new ScriptArrayIterator((ScriptObject) obj, includeUndefined);
    }

    obj = JSType.toScriptObject(obj);
    if (obj instanceof ScriptObject) {
        return new ScriptObjectIterator((ScriptObject)obj, includeUndefined);
    }

    if (obj instanceof JSObject) {
        return new JSObjectIterator((JSObject)obj, includeUndefined);
    }

    if (obj instanceof List) {
        return new JavaListIterator((List<?>)obj, includeUndefined);
    }

    if (obj != null && obj.getClass().isArray()) {
        return new JavaArrayIterator(obj, includeUndefined);
    }

    return new EmptyArrayLikeIterator();
}
 
Example 35
Project: OpenJSharp   File: ArrayLikeIterator.java   Source Code and License 5 votes vote down vote up
/**
 * ArrayLikeIterator factory (reverse order)
 * @param object object over which to do reverse element iteration
 * @param includeUndefined should undefined elements be included in the iteration
 * @return iterator
 */
public static ArrayLikeIterator<Object> reverseArrayLikeIterator(final Object object, final boolean includeUndefined) {
    Object obj = object;

    if (ScriptObject.isArray(obj)) {
        return new ReverseScriptArrayIterator((ScriptObject) obj, includeUndefined);
    }

    obj = JSType.toScriptObject(obj);
    if (obj instanceof ScriptObject) {
        return new ReverseScriptObjectIterator((ScriptObject)obj, includeUndefined);
    }

    if (obj instanceof JSObject) {
        return new ReverseJSObjectIterator((JSObject)obj, includeUndefined);
    }

    if (obj instanceof List) {
        return new ReverseJavaListIterator((List<?>)obj, includeUndefined);
    }

    if (obj != null && obj.getClass().isArray()) {
        return new ReverseJavaArrayIterator(obj, includeUndefined);
    }

    return new EmptyArrayLikeIterator();
}
 
Example 36
Project: OpenJSharp   File: ScriptRuntime.java   Source Code and License 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 37
Project: OpenJSharp   File: ScriptRuntime.java   Source Code and License 5 votes vote down vote up
/**
 * ECMA 11.4.3 The typeof Operator - generic implementation
 *
 * @param object   the object from which to retrieve property to type check
 * @param property property in object to check
 *
 * @return type name
 */
public static Object TYPEOF(final Object object, final Object property) {
    Object obj = object;

    if (property != null) {
        if (obj instanceof ScriptObject) {
            obj = ((ScriptObject)obj).get(property);
            if(Global.isLocationPropertyPlaceholder(obj)) {
                if(CompilerConstants.__LINE__.name().equals(property)) {
                    obj = Integer.valueOf(0);
                } else {
                    obj = "";
                }
            }
        } else if (object instanceof Undefined) {
            obj = ((Undefined)obj).get(property);
        } else if (object == null) {
            throw typeError("cant.get.property", safeToString(property), "null");
        } else if (JSType.isPrimitive(obj)) {
            obj = ((ScriptObject)JSType.toScriptObject(obj)).get(property);
        } else if (obj instanceof JSObject) {
            obj = ((JSObject)obj).getMember(property.toString());
        } else {
            obj = UNDEFINED;
        }
    }

    return JSType.of(obj).typeName();
}
 
Example 38
Project: OpenJSharp   File: ScriptRuntime.java   Source Code and License 5 votes vote down vote up
/**
 * ECMA 11.4.1 - delete operation, generic implementation
 *
 * @param obj       object with property to delete
 * @param property  property to delete
 * @param strict    are we in strict mode
 *
 * @return true if property was successfully found and deleted
 */
public static boolean DELETE(final Object obj, final Object property, final Object strict) {
    if (obj instanceof ScriptObject) {
        return ((ScriptObject)obj).delete(property, Boolean.TRUE.equals(strict));
    }

    if (obj instanceof Undefined) {
        return ((Undefined)obj).delete(property, false);
    }

    if (obj == null) {
        throw typeError("cant.delete.property", safeToString(property), "null");
    }

    if (obj instanceof ScriptObjectMirror) {
        return ((ScriptObjectMirror)obj).delete(property);
    }

    if (JSType.isPrimitive(obj)) {
        return ((ScriptObject) JSType.toScriptObject(obj)).delete(property, Boolean.TRUE.equals(strict));
    }

    if (obj instanceof JSObject) {
        ((JSObject)obj).removeMember(Objects.toString(property));
        return true;
    }

    // if object is not reference type, vacuously delete is successful.
    return true;
}
 
Example 39
Project: OpenJSharp   File: ListAdapter.java   Source Code and License 5 votes vote down vote up
/**
 * Factory to create a ListAdapter for a given script object.
 *
 * @param obj script object to wrap as a ListAdapter
 * @return A ListAdapter wrapper object
 */
public static ListAdapter create(final Object obj) {
    if (obj instanceof ScriptObject) {
        final Object mirror = ScriptObjectMirror.wrap(obj, Context.getGlobal());
        return new JSObjectListAdapter((JSObject)mirror);
    } else if (obj instanceof JSObject) {
        return new JSObjectListAdapter((JSObject)obj);
    } else {
        throw new IllegalArgumentException("ScriptObject or JSObject expected");
    }
}
 
Example 40
Project: openjdk-jdk10   File: NativeFunction.java   Source Code and License 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");
}