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

The following examples show how to use jdk.nashorn.internal.runtime.ScriptRuntime. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: TencentKona-8   Source File: JSTypeTest.java    License: 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 2
Source Project: jdk8u60   Source File: NativeArray.java    License: 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 3
Source Project: hottub   Source File: JavaAdapterServices.java    License: 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 4
@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 5
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 6
Source Project: openjdk-8   Source File: NativeFunction.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * ECMA 15.3.4.4 Function.prototype.call (thisArg [ , arg1 [ , arg2, ... ] ] )
 *
 * @param self self reference
 * @param args arguments for call
 * @return result of call
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1)
public static Object call(final Object self, final Object... args) {
    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 7
Source Project: nashorn   Source File: NashornScriptEngine.java    License: 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 8
Source Project: hottub   Source File: NativeArray.java    License: 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 9
Source Project: openjdk-jdk9   Source File: PrimitiveLookup.java    License: 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 10
Source Project: TencentKona-8   Source File: NativeObject.java    License: 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 11
Source Project: openjdk-8   Source File: NativeArray.java    License: 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 12
/**
 * Slice function
 * @param self   native array buffer
 * @param begin0 start byte index
 * @param end0   end byte index
 * @return new array buffer, sliced
 */
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static NativeArrayBuffer slice(final Object self, final Object begin0, final Object end0) {
    final NativeArrayBuffer arrayBuffer = (NativeArrayBuffer)self;
    final int               byteLength  = arrayBuffer.getByteLength();
    final int               begin       = adjustIndex(JSType.toInt32(begin0), byteLength);
    final int               end         = adjustIndex(end0 != ScriptRuntime.UNDEFINED ? JSType.toInt32(end0) : byteLength, byteLength);
    return new NativeArrayBuffer(arrayBuffer, begin, Math.max(end, begin));
}
 
Example 13
/**
 * ECMA 15.4.4.14 Array.prototype.indexOf ( searchElement [ , fromIndex ] )
 *
 * @param self           self reference
 * @param searchElement  element to search for
 * @param fromIndex      start index of search
 * @return index of element, or -1 if not found
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1)
public static double indexOf(final Object self, final Object searchElement, final Object fromIndex) {
    try {
        final ScriptObject sobj = (ScriptObject)Global.toObject(self);
        final long         len  = JSType.toUint32(sobj.getLength());
        if (len == 0) {
            return -1;
        }

        final long         n = JSType.toLong(fromIndex);
        if (n >= len) {
            return -1;
        }


        for (long k = Math.max(0, n < 0 ? len - Math.abs(n) : n); k < len; k++) {
            if (sobj.has(k)) {
                if (ScriptRuntime.EQ_STRICT(sobj.get(k), searchElement)) {
                    return k;
                }
            }
        }
    } catch (final ClassCastException | NullPointerException e) {
        //fallthru
    }

    return -1;
}
 
Example 14
Source Project: hottub   Source File: NativeArray.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * ECMA 15.4.4.18 Array.prototype.forEach ( callbackfn [ , thisArg ] )
 *
 * @param self        self reference
 * @param callbackfn  callback function per element
 * @param thisArg     this argument
 * @return undefined
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1)
public static Object forEach(final Object self, final Object callbackfn, final Object thisArg) {
    return new IteratorAction<Object>(Global.toObject(self), callbackfn, thisArg, ScriptRuntime.UNDEFINED) {
        private final MethodHandle forEachInvoker = getFOREACH_CALLBACK_INVOKER();

        @Override
        protected boolean forEach(final Object val, final double i) throws Throwable {
            forEachInvoker.invokeExact(callbackfn, thisArg, val, i, self);
            return true;
        }
    }.apply();
}
 
Example 15
Source Project: hottub   Source File: NativeArrayBuffer.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Slice function
 * @param self   native array buffer
 * @param begin0 start byte index
 * @param end0   end byte index
 * @return new array buffer, sliced
 */
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static NativeArrayBuffer slice(final Object self, final Object begin0, final Object end0) {
    final NativeArrayBuffer arrayBuffer = (NativeArrayBuffer)self;
    final int               byteLength  = arrayBuffer.getByteLength();
    final int               begin       = adjustIndex(JSType.toInt32(begin0), byteLength);
    final int               end         = adjustIndex(end0 != ScriptRuntime.UNDEFINED ? JSType.toInt32(end0) : byteLength, byteLength);
    return new NativeArrayBuffer(arrayBuffer, begin, Math.max(end, begin));
}
 
Example 16
@Override
public Object pop() {
    final int index = (int)length() - 1;
    if (super.has(index)) {
        final boolean isDeleted = isDeleted(index);
        final Object value      = super.pop();

        lo = Math.min(index + 1, lo);
        hi = Math.min(index, hi);
        return isDeleted ? ScriptRuntime.UNDEFINED : value;
    }

    return super.pop();
}
 
Example 17
Source Project: TencentKona-8   Source File: NativeDebug.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return the ArrayData class for this ScriptObject
 * @param self self
 * @param obj script object to check
 * @return ArrayData class, or undefined if no ArrayData is present
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static Object getArrayDataClass(final Object self, final Object obj) {
    try {
        return ((ScriptObject)obj).getArray().getClass();
    } catch (final ClassCastException e) {
        return ScriptRuntime.UNDEFINED;
    }
}
 
Example 18
/**
 * "No such property" handler.
 *
 * @param self self reference
 * @param name property name
 * @return value of the missing property
 */
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static Object __noSuchProperty__(final Object self, final Object name) {
    if (! (self instanceof NativeJavaImporter)) {
        throw typeError("not.a.java.importer", ScriptRuntime.safeToString(self));
    }
    return ((NativeJavaImporter)self).createProperty(JSType.toString(name));
}
 
Example 19
Source Project: TencentKona-8   Source File: NativeFunction.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * ECMA 15.3.4.3 Function.prototype.apply (thisArg, argArray)
 *
 * @param self   self reference
 * @param thiz   {@code this} arg for apply
 * @param array  array of argument for apply
 * @return result of apply
 */
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static Object apply(final Object self, final Object thiz, final Object array) {
    checkCallable(self);

    final Object[] args = toApplyArgs(array);

    if (self instanceof ScriptFunction) {
        return ScriptRuntime.apply((ScriptFunction)self, thiz, args);
    } else if (self instanceof JSObject) {
        return ((JSObject)self).call(thiz, args);
    }
    throw new AssertionError("Should not reach here");
}
 
Example 20
Source Project: openjdk-jdk9   Source File: NativeString.java    License: GNU General Public License v2.0 5 votes vote down vote up
private boolean checkDeleteIndex(final int index, final boolean strict) {
    if (isValidStringIndex(index)) {
        if (strict) {
            throw typeError("cant.delete.property", Integer.toString(index), ScriptRuntime.safeToString(this));
        }
        return true;
    }

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

    throw typeError("not.a.function", ScriptRuntime.safeToString(func));
}
 
Example 22
private static Object compareFunction(final Object comparefn) {
    if (comparefn == ScriptRuntime.UNDEFINED) {
        return null;
    }

    if (!Bootstrap.isCallable(comparefn)) {
        throw typeError("not.a.function", ScriptRuntime.safeToString(comparefn));
    }

    return comparefn;
}
 
Example 23
Source Project: jdk8u60   Source File: NativeError.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Nashorn extension: Error.prototype.getStackTrace()
 * "stack" property is an array typed value containing {@link StackTraceElement}
 * objects of JavaScript stack frames.
 *
 * @param self  self reference
 *
 * @return      stack trace as a script array.
 */
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static Object getStackTrace(final Object self) {
    final ScriptObject sobj = Global.checkObject(self);
    final Object exception = ECMAException.getException(sobj);
    Object[] res;
    if (exception instanceof Throwable) {
        res = NashornException.getScriptFrames((Throwable)exception);
    } else {
        res = ScriptRuntime.EMPTY_ARRAY;
    }

    return new NativeArray(res);
}
 
Example 24
/**
 * 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);
}
 
Example 25
Source Project: jdk8u60   Source File: NativeDate.java    License: 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 26
Source Project: nashorn   Source File: NativeArguments.java    License: 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);
}
 
Example 27
Source Project: jdk8u_nashorn   Source File: DebugLogger.java    License: 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 28
Source Project: openjdk-8   Source File: ObjectArrayData.java    License: 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 29
@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 30
Source Project: jdk8u60   Source File: NativeArray.java    License: 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();
}