jdk.nashorn.internal.runtime.ScriptRuntime Java Examples

The following examples show how to use jdk.nashorn.internal.runtime.ScriptRuntime. 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: NativeObject.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * ECMA 15.2.4.3 Object.prototype.toLocaleString ( )
 *
 * @param self self reference
 * @return localized ToString
 */
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static Object toLocaleString(final Object self) {
    final Object obj = JSType.toScriptObject(self);
    if (obj instanceof ScriptObject) {
        final InvokeByName toStringInvoker = getTO_STRING();
        final ScriptObject sobj = (ScriptObject)obj;
        try {
            final Object toString = toStringInvoker.getGetter().invokeExact(sobj);

            if (Bootstrap.isCallable(toString)) {
                return toStringInvoker.getInvoker().invokeExact(toString, sobj);
            }
        } catch (final RuntimeException | Error e) {
            throw e;
        } catch (final Throwable t) {
            throw new RuntimeException(t);
        }

        throw typeError("not.a.function", "toString");
    }

    return ScriptRuntime.builtinObjectToString(self);
}
 
Example #2
Source File: NativeJSAdapter.java    From jdk8u_nashorn with GNU General Public License v2.0 6 votes vote down vote up
@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 File: JSTypeTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test of toString method, of class Runtime.
 */
@Test
public void testToString_Object() {
    assertEquals(JSType.toString(ScriptRuntime.UNDEFINED), "undefined");
    assertEquals(JSType.toString(null), "null");
    assertEquals(JSType.toString(Boolean.TRUE), "true");
    assertEquals(JSType.toString(Boolean.FALSE), "false");
    assertEquals(JSType.toString(""), "");
    assertEquals(JSType.toString("nashorn"), "nashorn");
    assertEquals(JSType.toString(Double.NaN), "NaN");
    assertEquals(JSType.toString(Double.POSITIVE_INFINITY), "Infinity");
    assertEquals(JSType.toString(Double.NEGATIVE_INFINITY), "-Infinity");
    assertEquals(JSType.toString(0.0), "0");
    // FIXME: add more number-to-string test cases
    // FIXME: add case for Object type (JSObject with getDefaultValue)
}
 
Example #4
Source File: NativeFunction.java    From openjdk-8 with 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) {
    if (!(self instanceof ScriptFunction) && !(self instanceof JSObject)) {
        throw typeError("not.a.function", ScriptRuntime.safeToString(self));
    }

    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 #5
Source File: NativeArray.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * ECMA 15.4.4.7 Array.prototype.push (args...) specialized for single object argument
 *
 * @param self self reference
 * @param arg argument to push
 * @return array after pushes
 */
@SpecializedFunction
public static long push(final Object self, final Object arg) {
    try {
        final ScriptObject sobj = (ScriptObject)self;
        final ArrayData arrayData = sobj.getArray();
        final long length = arrayData.length();
        if (bulkable(sobj) && length < JSType.MAX_UINT) {
            sobj.setArray(arrayData.push(true, arg));
            return length + 1;
        }

        long len = JSType.toUint32(sobj.getLength());
        sobj.set(len++, arg, CALLSITE_STRICT);
        sobj.set("length", len, CALLSITE_STRICT);
        return len;
    } catch (final ClassCastException | NullPointerException e) {
        throw typeError("not.an.object", ScriptRuntime.safeToString(self));
    }
}
 
Example #6
Source File: NativeArray.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * ECMA 15.4.4.7 Array.prototype.push (args...)
 *
 * @param self self reference
 * @param args arguments to push
 * @return array length after pushes
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1)
public static Object push(final Object self, final Object... args) {
    try {
        final ScriptObject sobj   = (ScriptObject)self;

        if (bulkable(sobj) && sobj.getArray().length() + args.length <= JSType.MAX_UINT) {
            final ArrayData newData = sobj.getArray().push(true, args);
            sobj.setArray(newData);
            return JSType.toNarrowestNumber(newData.length());
        }

        long len = JSType.toUint32(sobj.getLength());
        for (final Object element : args) {
            sobj.set(len++, element, CALLSITE_STRICT);
        }
        sobj.set("length", len, CALLSITE_STRICT);

        return JSType.toNarrowestNumber(len);
    } catch (final ClassCastException | NullPointerException e) {
        throw typeError(Context.getGlobal(), e, "not.an.object", ScriptRuntime.safeToString(self));
    }
}
 
Example #7
Source File: PrimitiveLookup.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unused")
private static void primitiveSetter(final ScriptObject wrappedSelf, final Object self, final Object key,
                                    final boolean strict, final Object value) {
    // See ES5.1 8.7.2 PutValue (V, W)
    final String name = JSType.toString(key);
    final FindProperty find = wrappedSelf.findProperty(name, true);
    if (find == null || !find.getProperty().isAccessorProperty() || !find.getProperty().hasNativeSetter()) {
        if (strict) {
            if (find == null || !find.getProperty().isAccessorProperty()) {
                throw typeError("property.not.writable", name, ScriptRuntime.safeToString(self));
            } else {
                throw typeError("property.has.no.setter", name, ScriptRuntime.safeToString(self));
            }
        }
        return;
    }
    // property found and is a UserAccessorProperty
    find.setValue(value, strict);
}
 
Example #8
Source File: NashornScriptEngine.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
private Object evalImpl(final ScriptFunction script, final ScriptContext ctxt, final ScriptObject ctxtGlobal) throws ScriptException {
    if (script == null) {
        return null;
    }
    final ScriptObject oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != ctxtGlobal);
    try {
        if (globalChanged) {
            Context.setGlobal(ctxtGlobal);
        }

        // set ScriptContext variables if ctxt is non-null
        if (ctxt != null) {
            setContextVariables(ctxtGlobal, ctxt);
        }
        return ScriptObjectMirror.translateUndefined(ScriptObjectMirror.wrap(ScriptRuntime.apply(script, ctxtGlobal), ctxtGlobal));
    } catch (final Exception e) {
        throwAsScriptException(e);
        throw new AssertionError("should not reach here");
    } finally {
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }
}
 
Example #9
Source File: NashornScriptEngine.java    From nashorn with GNU General Public License v2.0 6 votes vote down vote up
private Object evalImpl(final ScriptFunction script, final ScriptContext ctxt, final ScriptObject ctxtGlobal) throws ScriptException {
    if (script == null) {
        return null;
    }
    final ScriptObject oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != ctxtGlobal);
    try {
        if (globalChanged) {
            Context.setGlobal(ctxtGlobal);
        }

        // set ScriptContext variables if ctxt is non-null
        if (ctxt != null) {
            setContextVariables(ctxtGlobal, ctxt);
        }
        return ScriptObjectMirror.translateUndefined(ScriptObjectMirror.wrap(ScriptRuntime.apply(script, ctxtGlobal), ctxtGlobal));
    } catch (final Exception e) {
        throwAsScriptException(e);
        throw new AssertionError("should not reach here");
    } finally {
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }
}
 
Example #10
Source File: JavaAdapterServices.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 #11
Source File: AccessorPropertyDescriptor.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public PropertyDescriptor fillFrom(final ScriptObject sobj) {
    if (sobj.has(CONFIGURABLE)) {
        this.configurable = JSType.toBoolean(sobj.get(CONFIGURABLE));
    } else {
        delete(CONFIGURABLE, false);
    }

    if (sobj.has(ENUMERABLE)) {
        this.enumerable = JSType.toBoolean(sobj.get(ENUMERABLE));
    } else {
        delete(ENUMERABLE, false);
    }

    if (sobj.has(GET)) {
        final Object getter = sobj.get(GET);
        if (getter == UNDEFINED || getter instanceof ScriptFunction) {
            this.get = getter;
        } else {
            throw typeError("not.a.function", ScriptRuntime.safeToString(getter));
        }
    } else {
        delete(GET, false);
    }

    if (sobj.has(SET)) {
        final Object setter = sobj.get(SET);
        if (setter == UNDEFINED || setter instanceof ScriptFunction) {
            this.set = setter;
        } else {
            throw typeError("not.a.function", ScriptRuntime.safeToString(setter));
        }
    } else {
        delete(SET, false);
    }

    return this;
}
 
Example #12
Source File: NativeFunction.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * ECMA 15.3.4.5 Function.prototype.bind (thisArg [, arg1 [, arg2, ...]])
 *
 * @param self self reference
 * @param args arguments for bind
 * @return function with bound arguments
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1)
public static Object bind(final Object self, final Object... args) {
    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;
    }

    return Bootstrap.bindCallable(self, thiz, arguments);
}
 
Example #13
Source File: IntArrayData.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Object pop() {
    final int len = (int)length();
    if (len == 0) {
        return ScriptRuntime.UNDEFINED;
    }

    final int newLength = len - 1;
    final int elem = array[newLength];
    array[newLength] = 0;
    setLength(newLength);

    return elem;
}
 
Example #14
Source File: ScriptObjectMirror.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String toString() {
    return inGlobal(new Callable<String>() {
        @Override
        public String call() {
            return ScriptRuntime.safeToString(sobj);
        }
    });
}
 
Example #15
Source File: NativeArray.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * ECMA 15.4.4.8 Array.prototype.reverse ()
 *
 * @param self self reference
 * @return reversed array
 */
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static Object reverse(final Object self) {
    try {
        final ScriptObject sobj   = (ScriptObject)self;
        final long         len    = JSType.toUint32(sobj.getLength());
        final long         middle = len / 2;

        for (long lower = 0; lower != middle; lower++) {
            final long    upper       = len - lower - 1;
            final Object  lowerValue  = sobj.get(lower);
            final Object  upperValue  = sobj.get(upper);
            final boolean lowerExists = sobj.has(lower);
            final boolean upperExists = sobj.has(upper);

            if (lowerExists && upperExists) {
                sobj.set(lower, upperValue, CALLSITE_STRICT);
                sobj.set(upper, lowerValue, CALLSITE_STRICT);
            } else if (!lowerExists && upperExists) {
                sobj.set(lower, upperValue, CALLSITE_STRICT);
                sobj.delete(upper, true);
            } else if (lowerExists && !upperExists) {
                sobj.delete(lower, true);
                sobj.set(upper, lowerValue, CALLSITE_STRICT);
            }
        }
        return sobj;
    } catch (final ClassCastException | NullPointerException e) {
        throw typeError("not.an.object", ScriptRuntime.safeToString(self));
    }
}
 
Example #16
Source File: NativeDate.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * ECMA 15.9.5.44 Date.prototype.toJSON ( key )
 *
 * Provides a string representation of this Date for use by {@link NativeJSON#stringify(Object, Object, Object, Object)}
 *
 * @param self self reference
 * @param key ignored
 * @return JSON representation of this date
 */
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static Object toJSON(final Object self, final Object key) {
    // NOTE: Date.prototype.toJSON is generic. Accepts other objects as well.
    final Object selfObj = Global.toObject(self);
    if (!(selfObj instanceof ScriptObject)) {
        return null;
    }
    final ScriptObject sobj  = (ScriptObject)selfObj;
    final Object       value = sobj.getDefaultValue(Number.class);
    if (value instanceof Number) {
        final double num = ((Number)value).doubleValue();
        if (isInfinite(num) || isNaN(num)) {
            return null;
        }
    }

    try {
        final InvokeByName toIsoString = getTO_ISO_STRING();
        final Object func = toIsoString.getGetter().invokeExact(sobj);
        if (Bootstrap.isCallable(func)) {
            return toIsoString.getInvoker().invokeExact(func, sobj, key);
        }
        throw typeError("not.a.function", ScriptRuntime.safeToString(func));
    } catch (final RuntimeException | Error e) {
        throw e;
    } catch (final Throwable t) {
        throw new RuntimeException(t);
    }
}
 
Example #17
Source File: NativeArray.java    From nashorn with GNU General Public License v2.0 5 votes vote down vote up
/**
 * ECMA 15.4.4.10 Array.prototype.slice ( start [ , end ] )
 *
 * @param self  self reference
 * @param start start of slice (inclusive)
 * @param end   end of slice (optional, exclusive)
 * @return sliced array
 */
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static Object slice(final Object self, final Object start, final Object end) {
    final Object       obj                 = Global.toObject(self);
    final ScriptObject sobj                = (ScriptObject)obj;
    final long         len                 = JSType.toUint32(sobj.getLength());
    final long         relativeStart       = JSType.toLong(start);
    final long         relativeEnd         = (end == ScriptRuntime.UNDEFINED) ? len : JSType.toLong(end);

    long k = relativeStart < 0 ? Math.max(len + relativeStart, 0) : Math.min(relativeStart, len);
    final long finale = relativeEnd < 0 ? Math.max(len + relativeEnd, 0) : Math.min(relativeEnd, len);

    if (k >= finale) {
        return new NativeArray(0);
    }

    if (bulkable(sobj)) {
        return new NativeArray(sobj.getArray().slice(k, finale));
    }

    // Construct array with proper length to have a deleted filter on undefined elements
    final NativeArray copy = new NativeArray(finale - k);
    for (long n = 0; k < finale; n++, k++) {
        if (sobj.has(k)) {
            copy.defineOwnProperty(ArrayIndex.getArrayIndex(n), sobj.get(k));
        }
    }

    return copy;
}
 
Example #18
Source File: SparseArrayData.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Object getObject(final int index) {
    if (index >= 0 && index < maxDenseLength) {
        return underlying.getObject(index);
    }

    final Long key = indexToKey(index);
    if (sparseMap.containsKey(key)) {
        return sparseMap.get(key);
    }

    return ScriptRuntime.UNDEFINED;
}
 
Example #19
Source File: NativeArray.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Assert that an array is numeric, if not throw type error
 * @param self self array to check
 * @return true if numeric
 */
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static Object assertNumeric(final Object self) {
    if(!(self instanceof NativeArray && ((NativeArray)self).getArray().getOptimisticType().isNumeric())) {
        throw typeError("not.a.numeric.array", ScriptRuntime.safeToString(self));
    }
    return Boolean.TRUE;
}
 
Example #20
Source File: ScriptObjectMirror.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String toString() {
    return inGlobal(new Callable<String>() {
        @Override
        public String call() {
            return ScriptRuntime.safeToString(sobj);
        }
    });
}
 
Example #21
Source File: LongArrayData.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public ArrayData set(final int index, final Object value, final boolean strict) {
    if (value instanceof Long || value instanceof Integer ||
        value instanceof Byte || value instanceof Short) {
        return set(index, ((Number)value).longValue(), strict);
    } else if (value == ScriptRuntime.UNDEFINED) {
        return new UndefinedArrayFilter(this).set(index, value, strict);
    }

    final ArrayData newData = convert(value == null ? Object.class : value.getClass());
    return newData.set(index, value, strict);
}
 
Example #22
Source File: NativeDebug.java    From jdk8u_nashorn with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return the ArrayData for this ScriptObject
 * @param self self
 * @param obj script object to check
 * @return ArrayData, ArrayDatas have toString methods, return Undefined if data missing
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static Object getArrayData(final Object self, final Object obj) {
    try {
        return ((ScriptObject)obj).getArray();
    } catch (final ClassCastException e) {
        return ScriptRuntime.UNDEFINED;
    }
}
 
Example #23
Source File: NativeArray.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("null")
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 != 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 #24
Source File: DebugLogger.java    From jdk8u_nashorn with GNU General Public License v2.0 5 votes vote down vote up
private static void logEvent(final RuntimeEvent<?> event) {
    if (event != null) {
        final Global global = Context.getGlobal();
        if (global.has("Debug")) {
            final ScriptObject debug = (ScriptObject)global.get("Debug");
            final ScriptFunction addRuntimeEvent = (ScriptFunction)debug.get("addRuntimeEvent");
            ScriptRuntime.apply(addRuntimeEvent, debug, event);
        }
    }
}
 
Example #25
Source File: NativeArray.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * ECMA 15.4.4.10 Array.prototype.slice ( start [ , end ] )
 *
 * @param self  self reference
 * @param start start of slice (inclusive)
 * @param end   end of slice (optional, exclusive)
 * @return sliced array
 */
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static Object slice(final Object self, final Object start, final Object end) {
    final Object       obj                 = Global.toObject(self);
    if (!(obj instanceof ScriptObject)) {
        return ScriptRuntime.UNDEFINED;
    }

    final ScriptObject sobj                = (ScriptObject)obj;
    final long         len                 = JSType.toUint32(sobj.getLength());
    final long         relativeStart       = JSType.toLong(start);
    final long         relativeEnd         = (end == ScriptRuntime.UNDEFINED) ? len : JSType.toLong(end);

    long k = relativeStart < 0 ? Math.max(len + relativeStart, 0) : Math.min(relativeStart, len);
    final long finale = relativeEnd < 0 ? Math.max(len + relativeEnd, 0) : Math.min(relativeEnd, len);

    if (k >= finale) {
        return new NativeArray(0);
    }

    if (bulkable(sobj)) {
        return new NativeArray(sobj.getArray().slice(k, finale));
    }

    // Construct array with proper length to have a deleted filter on undefined elements
    final NativeArray copy = new NativeArray(finale - k);
    for (long n = 0; k < finale; n++, k++) {
        if (sobj.has(k)) {
            copy.defineOwnProperty(ArrayIndex.getArrayIndex(n), sobj.get(k));
        }
    }

    return copy;
}
 
Example #26
Source File: NativeFunction.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Nashorn extension: Function.prototype.toSource
 *
 * @param self self reference
 * @return source for function
 */
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static String toSource(final Object self) {
    if (!(self instanceof ScriptFunction)) {
        throw typeError("not.a.function", ScriptRuntime.safeToString(self));
    }
    return ((ScriptFunction)self).toSource();
}
 
Example #27
Source File: NativeArray.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private static Object reduceInner(final ArrayLikeIterator<Object> iter, final Object self, final Object... args) {
    final Object  callbackfn          = args.length > 0 ? args[0] : ScriptRuntime.UNDEFINED;
    final boolean initialValuePresent = args.length > 1;

    Object initialValue = initialValuePresent ? args[1] : ScriptRuntime.UNDEFINED;

    if (callbackfn == ScriptRuntime.UNDEFINED) {
        throw typeError("not.a.function", "undefined");
    }

    if (!initialValuePresent) {
        if (iter.hasNext()) {
            initialValue = iter.next();
        } else {
            throw typeError("array.reduce.invalid.init");
        }
    }

    //if initial value is ScriptRuntime.UNDEFINED - step forward once.
    return new IteratorAction<Object>(Global.toObject(self), callbackfn, ScriptRuntime.UNDEFINED, initialValue, iter) {
        private final MethodHandle reduceInvoker = getREDUCE_CALLBACK_INVOKER();

        @Override
        protected boolean forEach(final Object val, final long i) throws Throwable {
            // TODO: why can't I declare the second arg as Undefined.class?
            result = reduceInvoker.invokeExact(callbackfn, ScriptRuntime.UNDEFINED, result, val, i, self);
            return true;
        }
    }.apply();
}
 
Example #28
Source File: AccessorPropertyDescriptor.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Override
public PropertyDescriptor fillFrom(final ScriptObject sobj) {
    if (sobj.has(CONFIGURABLE)) {
        this.configurable = JSType.toBoolean(sobj.get(CONFIGURABLE));
    } else {
        delete(CONFIGURABLE, false);
    }

    if (sobj.has(ENUMERABLE)) {
        this.enumerable = JSType.toBoolean(sobj.get(ENUMERABLE));
    } else {
        delete(ENUMERABLE, false);
    }

    if (sobj.has(GET)) {
        final Object getter = sobj.get(GET);
        if (getter == UNDEFINED || getter instanceof ScriptFunction) {
            this.get = getter;
        } else {
            throw typeError("not.a.function", ScriptRuntime.safeToString(getter));
        }
    } else {
        delete(GET, false);
    }

    if (sobj.has(SET)) {
        final Object setter = sobj.get(SET);
        if (setter == UNDEFINED || setter instanceof ScriptFunction) {
            this.set = setter;
        } else {
            throw typeError("not.a.function", ScriptRuntime.safeToString(setter));
        }
    } else {
        delete(SET, false);
    }

    return this;
}
 
Example #29
Source File: ObjectArrayData.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Object pop() {
    if (length() == 0) {
        return ScriptRuntime.UNDEFINED;
    }

    final int newLength = (int) (length() - 1);
    final Object elem = array[newLength];
    setEmpty(newLength);
    setLength(newLength);
    return elem;
}
 
Example #30
Source File: NativeArguments.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * ECMA 15.4.5.1 [[DefineOwnProperty]] ( P, Desc, Throw ) as specialized in
 * ECMA 10.6 for Arguments object.
 */
@Override
public boolean defineOwnProperty(final String key, final Object propertyDesc, final boolean reject) {
    final int index = ArrayIndex.getArrayIndex(key);
    if (index >= 0) {
        final boolean isMapped = isMapped(index);
        final Object oldValue = isMapped ? getArray().getObject(index) : null;

        if (!super.defineOwnProperty(key, propertyDesc, false)) {
            if (reject) {
                throw typeError("cant.redefine.property",  key, ScriptRuntime.safeToString(this));
            }
            return false;
        }

        if (isMapped) {
            // When mapped argument is redefined, if new descriptor is accessor property
            // or data-non-writable property, we have to "unmap" (unlink).
            final PropertyDescriptor desc = toPropertyDescriptor(Global.instance(), propertyDesc);
            if (desc.type() == PropertyDescriptor.ACCESSOR) {
                setDeleted(index, oldValue);
            } else if (desc.has(PropertyDescriptor.WRITABLE) && !desc.isWritable()) {
                // delete and set value from new descriptor if it has one, otherwise use old value
                setDeleted(index, desc.has(PropertyDescriptor.VALUE) ? desc.getValue() : oldValue);
            } else if (desc.has(PropertyDescriptor.VALUE)) {
                setArray(getArray().set(index, desc.getValue(), false));
            }
        }

        return true;
    }

    return super.defineOwnProperty(key, propertyDesc, reject);
}