Java Code Examples for jdk.nashorn.internal.objects.annotations.Attribute

The following are top voted examples for showing how to use jdk.nashorn.internal.objects.annotations.Attribute. 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: NativeDebug.java   Source Code and License 6 votes vote down vote up
/**
 * Expands the event queue capacity, or truncates if capacity is lower than
 * current capacity. Then only the newest entries are kept
 * @param self self reference
 * @param newCapacity new capacity
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static void expandEventQueueCapacity(final Object self, final Object newCapacity) {
    final LinkedList<RuntimeEvent<?>> q = getEventQueue(self);
    final int nc = JSType.toInt32(newCapacity);
    while (q.size() > nc) {
        q.removeFirst();
    }
    setEventQueueCapacity(self, nc);
}
 
Example 2
Project: OpenJSharp   File: NativeArray.java   Source Code and License 6 votes vote down vote up
/**
 * ECMA 15.4.4.19 Array.prototype.map ( callbackfn [ , thisArg ] )
 *
 * @param self        self reference
 * @param callbackfn  callback function per element
 * @param thisArg     this argument
 * @return array with elements transformed by map function
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1)
public static NativeArray map(final Object self, final Object callbackfn, final Object thisArg) {
    return new IteratorAction<NativeArray>(Global.toObject(self), callbackfn, thisArg, null) {
        private final MethodHandle mapInvoker = getMAP_CALLBACK_INVOKER();

        @Override
        protected boolean forEach(final Object val, final long i) throws Throwable {
            final Object r = mapInvoker.invokeExact(callbackfn, thisArg, val, i, self);
            result.defineOwnProperty(ArrayIndex.getArrayIndex(index), r);
            return true;
        }

        @Override
        public void applyLoopBegin(final ArrayLikeIterator<Object> iter0) {
            // map return array should be of same length as source array
            // even if callback reduces source array length
            result = new NativeArray(iter0.getLength());
        }
    }.apply();
}
 
Example 3
Project: openjdk-jdk10   File: NativeDataView.java   Source Code and License 5 votes vote down vote up
/**
 * Get 8-bit unsigned int from given byteOffset
 *
 * @param self DataView object
 * @param byteOffset byte offset to read from
 * @return 8-bit unsigned int value at the byteOffset
 */
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static int getUint8(final Object self, final Object byteOffset) {
    try {
        return 0xFF & getBuffer(self).get(JSType.toInt32(byteOffset));
    } catch (final IllegalArgumentException iae) {
        throw rangeError(iae, "dataview.offset");
    }
}
 
Example 4
Project: OpenJSharp   File: NativeString.java   Source Code and License 5 votes vote down vote up
/**
 * ECMA 15.5.4.5 String.prototype.charCodeAt (pos)
 * @param self self reference
 * @param pos  position in string
 * @return number representing charcode at position
 */
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static double charCodeAt(final Object self, final Object pos) {
    final String str = checkObjectToString(self);
    final int    idx = JSType.toInteger(pos);
    return idx < 0 || idx >= str.length() ? Double.NaN : str.charAt(idx);
}
 
Example 5
Project: OpenJSharp   File: NativeString.java   Source Code and License 5 votes vote down vote up
/**
 * ECMA 15.5.4.9 String.prototype.localeCompare (that)
 * @param self self reference
 * @param that comparison object
 * @return result of locale sensitive comparison operation between {@code self} and {@code that}
 */
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static double localeCompare(final Object self, final Object that) {

    final String   str      = checkObjectToString(self);
    final Collator collator = Collator.getInstance(Global.getEnv()._locale);

    collator.setStrength(Collator.IDENTICAL);
    collator.setDecomposition(Collator.CANONICAL_DECOMPOSITION);

    return collator.compare(str, JSType.toString(that));
}
 
Example 6
Project: openjdk-jdk10   File: NativeDate.java   Source Code and License 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 7
Project: OpenJSharp   File: NativeObject.java   Source Code and License 5 votes vote down vote up
/**
 * ECMA 15.2.3.4 Object.getOwnPropertyNames ( O )
 *
 * @param self self reference
 * @param obj  object to query for property names
 * @return array of property names
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static ScriptObject getOwnPropertyNames(final Object self, final Object obj) {
    if (obj instanceof ScriptObject) {
        return new NativeArray(((ScriptObject)obj).getOwnKeys(true));
    } else if (obj instanceof ScriptObjectMirror) {
        return new NativeArray(((ScriptObjectMirror)obj).getOwnKeys(true));
    } else {
        throw notAnObject(obj);
    }
}
 
Example 8
Project: openjdk-jdk10   File: NativeError.java   Source Code and License 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 9
Project: OpenJSharp   File: NativeString.java   Source Code and License 5 votes vote down vote up
/**
 * ECMA 15.5.4.15 String.prototype.substring (start, end)
 *
 * @param self  self reference
 * @param start start position of substring
 * @param end   end position of substring
 * @return substring given start and end indexes
 */
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static String substring(final Object self, final Object start, final Object end) {

    final String str = checkObjectToString(self);
    if (end == UNDEFINED) {
        return substring(str, JSType.toInteger(start));
    }
    return substring(str, JSType.toInteger(start), JSType.toInteger(end));
}
 
Example 10
Project: OpenJSharp   File: NativeDataView.java   Source Code and License 5 votes vote down vote up
/**
 * Set 64-bit float at the given byteOffset
 *
 * @param self DataView object
 * @param byteOffset byte offset to write at
 * @param value double value to set
 * @param littleEndian (optional) flag indicating whether to write in little endian order
 * @return undefined
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 2)
public static Object setFloat64(final Object self, final Object byteOffset, final Object value, final Object littleEndian) {
    try {
        getBuffer(self, littleEndian).putDouble((int)JSType.toUint32(byteOffset), JSType.toNumber(value));
        return UNDEFINED;
    } catch (final IllegalArgumentException iae) {
        throw rangeError(iae, "dataview.offset");
    }
}
 
Example 11
Project: openjdk-jdk10   File: NativeDebug.java   Source Code and License 5 votes vote down vote up
/**
 * Expands the event queue capacity, or truncates if capacity is lower than
 * current capacity. Then only the newest entries are kept
 * @param self self reference
 * @param newCapacity new capacity
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static void expandEventQueueCapacity(final Object self, final Object newCapacity) {
    final LinkedList<RuntimeEvent<?>> q = getEventQueue(self);
    final int nc = JSType.toInt32(newCapacity);
    while (q.size() > nc) {
        q.removeFirst();
    }
    setEventQueueCapacity(self, nc);
}
 
Example 12
Project: openjdk-jdk10   File: NativeDataView.java   Source Code and License 5 votes vote down vote up
/**
 * Get 16-bit signed int from given byteOffset
 *
 * @param self DataView object
 * @param byteOffset byte offset to read from
 * @param littleEndian (optional) flag indicating whether to read in little endian order
 * @return 16-bit signed int value at the byteOffset
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1)
public static int getInt16(final Object self, final Object byteOffset, final Object littleEndian) {
    try {
        return getBuffer(self, littleEndian).getShort(JSType.toInt32(byteOffset));
    } catch (final IllegalArgumentException iae) {
        throw rangeError(iae, "dataview.offset");
    }
}
 
Example 13
Project: OpenJSharp   File: NativeMath.java   Source Code and License 5 votes vote down vote up
/**
 * ECMA 15.8.2.15 round(x)
 *
 * @param self  self reference
 * @param x     argument
 *
 * @return x rounded
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static double round(final Object self, final Object x) {
    final double d = JSType.toNumber(x);
    if (Math.getExponent(d) >= 52) {
        return d;
    }
    return Math.copySign(Math.floor(d + 0.5), d);
}
 
Example 14
Project: OpenJSharp   File: NativeDataView.java   Source Code and License 5 votes vote down vote up
/**
 * Set 32-bit signed int at the given byteOffset
 *
 * @param self DataView object
 * @param byteOffset byte offset to write at
 * @param value int value to set
 * @param littleEndian (optional) flag indicating whether to write in little endian order
 * @return undefined
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 2)
public static Object setInt32(final Object self, final Object byteOffset, final Object value, final Object littleEndian) {
    try {
        getBuffer(self, littleEndian).putInt(JSType.toInt32(byteOffset), JSType.toInt32(value));
        return UNDEFINED;
    } catch (final IllegalArgumentException iae) {
        throw rangeError(iae, "dataview.offset");
    }
}
 
Example 15
Project: OpenJSharp   File: NativeDebug.java   Source Code and License 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 16
Project: OpenJSharp   File: NativeDataView.java   Source Code and License 5 votes vote down vote up
/**
 * Set 16-bit unsigned int at the given byteOffset
 *
 * @param self DataView object
 * @param byteOffset byte offset to write at
 * @param value short value to set
 * @param littleEndian (optional) flag indicating whether to write in little endian order
 * @return undefined
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 2)
public static Object setUint16(final Object self, final Object byteOffset, final Object value, final Object littleEndian) {
    try {
        getBuffer(self, littleEndian).putShort(JSType.toInt32(byteOffset), (short)JSType.toInt32(value));
        return UNDEFINED;
    } catch (final IllegalArgumentException iae) {
        throw rangeError(iae, "dataview.offset");
    }
}
 
Example 17
Project: OpenJSharp   File: NativeObject.java   Source Code and License 5 votes vote down vote up
/**
 * ECMA 15.2.3.13 Object.isExtensible ( O )
 *
 * @param self self reference
 * @param obj check whether an object is extensible
 * @return true if object is extensible, false otherwise
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static boolean isExtensible(final Object self, final Object obj) {
    if (obj instanceof ScriptObject) {
        return ((ScriptObject)obj).isExtensible();
    } else if (obj instanceof ScriptObjectMirror) {
        return ((ScriptObjectMirror)obj).isExtensible();
    } else {
        throw notAnObject(obj);
    }
}
 
Example 18
Project: OpenJSharp   File: NativeArray.java   Source Code and License 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 19
Project: openjdk-jdk10   File: Global.java   Source Code and License 5 votes vote down vote up
/**
 * Getter for the WeakMap property.
 *
 * @param self self reference
 * @return  the value of the WeakMap property
 */
@Getter(name = "WeakMap", attributes = Attribute.NOT_ENUMERABLE)
public static Object getWeakMap(final Object self) {
    final Global global = Global.instanceFrom(self);
    if (global.weakMap == LAZY_SENTINEL) {
        global.weakMap = global.getBuiltinWeakMap();
    }
    return global.weakMap;
}
 
Example 20
Project: openjdk-jdk10   File: NativeError.java   Source Code and License 5 votes vote down vote up
/**
 * Nashorn extension: Error.captureStackTrace. Capture stack trace at the point of call into the Error object provided.
 *
 * @param self self reference
 * @param errorObj the error object
 * @return undefined
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static Object captureStackTrace(final Object self, final Object errorObj) {
    final ScriptObject sobj = Global.checkObject(errorObj);
    initException(sobj);
    sobj.delete(STACK, false);
    if (! sobj.has("stack")) {
        final ScriptFunction getStack = ScriptFunction.createBuiltin("getStack", GET_STACK);
        final ScriptFunction setStack = ScriptFunction.createBuiltin("setStack", SET_STACK);
        sobj.addOwnProperty("stack", Attribute.NOT_ENUMERABLE, getStack, setStack);
    }
    return UNDEFINED;
}
 
Example 21
Project: openjdk-jdk10   File: NativeArray.java   Source Code and License 5 votes vote down vote up
/**
 * ECMA 15.4.4.4 Array.prototype.concat ( [ item1 [ , item2 [ , ... ] ] ] )
 *
 * @param self self reference
 * @param args arguments
 * @return resulting NativeArray
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1)
public static NativeArray concat(final Object self, final Object... args) {
    final ArrayList<Object> list = new ArrayList<>();

    concatToList(list, Global.toObject(self));

    for (final Object obj : args) {
        concatToList(list, obj);
    }

    return new NativeArray(list.toArray());
}
 
Example 22
Project: openjdk-jdk10   File: NativeRegExpExecResult.java   Source Code and License 5 votes vote down vote up
/**
 * Length getter
 * @param self self reference
 * @return length property value
 */
@Getter(attributes = Attribute.NOT_ENUMERABLE | Attribute.NOT_CONFIGURABLE)
public static Object length(final Object self) {
    if (self instanceof ScriptObject) {
        return (double) JSType.toUint32(((ScriptObject)self).getArray().length());
    }

    return 0;
}
 
Example 23
Project: openjdk-jdk10   File: NativeArray.java   Source Code and License 5 votes vote down vote up
/**
 * 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 24
Project: OpenJSharp   File: NativeDataView.java   Source Code and License 5 votes vote down vote up
/**
 * Set 8-bit unsigned int at the given byteOffset
 *
 * @param self DataView object
 * @param byteOffset byte offset to write at
 * @param value byte value to set
 * @return undefined
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 2)
public static Object setUint8(final Object self, final Object byteOffset, final Object value) {
    try {
        getBuffer(self).put(JSType.toInt32(byteOffset), (byte)JSType.toInt32(value));
        return UNDEFINED;
    } catch (final IllegalArgumentException iae) {
        throw rangeError(iae, "dataview.offset");
    }
}
 
Example 25
Project: openjdk-jdk10   File: NativeDate.java   Source Code and License 5 votes vote down vote up
/**
 * ECMA 15.9.5.41 Date.prototype.setUTCFullYear (year [, month [, date ] ] )
 *
 * @param self self reference
 * @param args UTC full year (optional second and third arguments are month and date)
 * @return time
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 3)
public static double setUTCFullYear(final Object self, final Object... args) {
    final NativeDate nd   = ensureNativeDate(self);
    if (nd.isValidDate()) {
        setFields(nd, YEAR, args, false);
    } else {
        final double[] d = convertArgs(args, 0, YEAR, YEAR, 3);
        nd.setTime(timeClip(makeDate(makeDay(d[0], d[1], d[2]), 0)));
    }
    return nd.getTime();
}
 
Example 26
Project: OpenJSharp   File: NativeError.java   Source Code and License 5 votes vote down vote up
/**
 * Nashorn extension: Error.captureStackTrace. Capture stack trace at the point of call into the Error object provided.
 *
 * @param self self reference
 * @param errorObj the error object
 * @return undefined
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static Object captureStackTrace(final Object self, final Object errorObj) {
    final ScriptObject sobj = Global.checkObject(errorObj);
    initException(sobj);
    sobj.delete(STACK, false);
    if (! sobj.has("stack")) {
        final ScriptFunction getStack = ScriptFunctionImpl.makeFunction("getStack", GET_STACK);
        final ScriptFunction setStack = ScriptFunctionImpl.makeFunction("setStack", SET_STACK);
        sobj.addOwnProperty("stack", Attribute.NOT_ENUMERABLE, getStack, setStack);
    }
    return UNDEFINED;
}
 
Example 27
Project: openjdk-jdk10   File: NativeJava.java   Source Code and License 5 votes vote down vote up
/**
 * Given a Java array or {@link Collection}, returns a JavaScript array with a shallow copy of its contents. Note
 * that in most cases, you can use Java arrays and lists natively in Nashorn; in cases where for some reason you
 * need to have an actual JavaScript native array (e.g. to work with the array comprehensions functions), you will
 * want to use this method. Example:
 * <pre>
 * var File = Java.type("java.io.File")
 * var listHomeDir = new File("~").listFiles()
 * var jsListHome = Java.from(listHomeDir)
 * var jpegModifiedDates = jsListHome
 *     .filter(function(val) { return val.getName().endsWith(".jpg") })
 *     .map(function(val) { return val.lastModified() })
 * </pre>
 * @param self not used
 * @param objArray the java array or collection. Can be null.
 * @return a JavaScript array with the copy of Java array's or collection's contents. Returns null if objArray is
 * null.
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static NativeArray from(final Object self, final Object objArray) {
    if (objArray == null) {
        return null;
    } else if (objArray instanceof Collection) {
        return new NativeArray(((Collection<?>)objArray).toArray());
    } else if (objArray instanceof Object[]) {
        return new NativeArray(((Object[])objArray).clone());
    } else if (objArray instanceof int[]) {
        return new NativeArray(((int[])objArray).clone());
    } else if (objArray instanceof double[]) {
        return new NativeArray(((double[])objArray).clone());
    } else if (objArray instanceof long[]) {
        return new NativeArray(((long[])objArray).clone());
    } else if (objArray instanceof byte[]) {
        return new NativeArray(copyArray((byte[])objArray));
    } else if (objArray instanceof short[]) {
        return new NativeArray(copyArray((short[])objArray));
    } else if (objArray instanceof char[]) {
        return new NativeArray(copyArray((char[])objArray));
    } else if (objArray instanceof float[]) {
        return new NativeArray(copyArray((float[])objArray));
    } else if (objArray instanceof boolean[]) {
        return new NativeArray(copyArray((boolean[])objArray));
    }

    throw typeError("cant.convert.to.javascript.array", objArray.getClass().getName());
}
 
Example 28
Project: OpenJSharp   File: NativeArray.java   Source Code and License 5 votes vote down vote up
/**
 * ECMA 15.4.4.15 Array.prototype.lastIndexOf ( searchElement [ , fromIndex ] )
 *
 * @param self self reference
 * @param args arguments: element to search for and optional from index
 * @return index of element, or -1 if not found
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1)
public static long lastIndexOf(final Object self, final Object... args) {
    try {
        final ScriptObject sobj = (ScriptObject)Global.toObject(self);
        final long         len  = JSType.toUint32(sobj.getLength());

        if (len == 0) {
            return -1;
        }

        final Object searchElement = args.length > 0 ? args[0] : ScriptRuntime.UNDEFINED;
        final long   n             = args.length > 1 ? JSType.toLong(args[1]) : len - 1;

        for (long k = n < 0 ? len - Math.abs(n) : Math.min(n, len - 1); k >= 0; k--) {
            if (sobj.has(k)) {
                if (ScriptRuntime.EQ_STRICT(sobj.get(k), searchElement)) {
                    return k;
                }
            }
        }
    } catch (final ClassCastException | NullPointerException e) {
        throw typeError("not.an.object", ScriptRuntime.safeToString(self));
    }

    return -1;
}
 
Example 29
Project: OpenJSharp   File: NativeError.java   Source Code and License 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 30
Project: openjdk-jdk10   File: Global.java   Source Code and License 5 votes vote down vote up
/**
 * Getter for the URIError property.
 * @param self self reference
 * @return the value of URIError property
 */
@Getter(name = "URIError", attributes = Attribute.NOT_ENUMERABLE)
public static Object getURIError(final Object self) {
    final Global global = Global.instanceFrom(self);
    if (global.uriError == LAZY_SENTINEL) {
        global.uriError = global.getBuiltinURIError();
    }
    return global.uriError;
}
 
Example 31
Project: openjdk-jdk10   File: Global.java   Source Code and License 5 votes vote down vote up
/**
 * Getter for the Symbol property.
 *
 * @param self self reference
 * @return  the value of the Symbol property
 */
@Getter(name = "Symbol", attributes = Attribute.NOT_ENUMERABLE)
public static Object getSymbol(final Object self) {
    final Global global = Global.instanceFrom(self);
    if (global.symbol == LAZY_SENTINEL) {
        global.symbol = global.getBuiltinSymbol();
    }
    return global.symbol;
}
 
Example 32
Project: OpenJSharp   File: NativeArray.java   Source Code and License 5 votes vote down vote up
/**
 * ECMA 15.4.4.11 Array.prototype.sort ( comparefn )
 *
 * @param self       self reference
 * @param comparefn  element comparison function
 * @return sorted array
 */
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static ScriptObject sort(final Object self, final Object comparefn) {
    try {
        final ScriptObject sobj    = (ScriptObject) self;
        final long         len     = JSType.toUint32(sobj.getLength());
        ArrayData          array   = sobj.getArray();

        if (len > 1) {
            // Get only non-missing elements. Missing elements go at the end
            // of the sorted array. So, just don't copy these to sort input.
            final ArrayList<Object> src = new ArrayList<>();

            for (final Iterator<Long> iter = array.indexIterator(); iter.hasNext(); ) {
                final long index = iter.next();
                if (index >= len) {
                    break;
                }
                src.add(array.getObject((int)index));
            }

            final Object[] sorted = sort(src.toArray(), comparefn);

            for (int i = 0; i < sorted.length; i++) {
                array = array.set(i, sorted[i], true);
            }

            // delete missing elements - which are at the end of sorted array
            if (sorted.length != len) {
                array = array.delete(sorted.length, len - 1);
            }

            sobj.setArray(array);
        }

        return sobj;
    } catch (final ClassCastException | NullPointerException e) {
        throw typeError("not.an.object", ScriptRuntime.safeToString(self));
    }
}
 
Example 33
Project: openjdk-jdk10   File: Global.java   Source Code and License 5 votes vote down vote up
/**
 * Getter for the ArrayBuffer property.
 * @param self self reference
 * @return the value of the ArrayBuffer property
 */
@Getter(name = "ArrayBuffer", attributes = Attribute.NOT_ENUMERABLE)
public static Object getArrayBuffer(final Object self) {
    final Global global = Global.instanceFrom(self);
    if (global.arrayBuffer == LAZY_SENTINEL) {
        global.arrayBuffer = global.getBuiltinArrayBuffer();
    }
    return global.arrayBuffer;
}
 
Example 34
Project: openjdk-jdk10   File: NativeArray.java   Source Code and License 5 votes vote down vote up
/**
 * ECMA 15.4.4.17 Array.prototype.some ( callbackfn [ , thisArg ] )
 *
 * @param self        self reference
 * @param callbackfn  callback function per element
 * @param thisArg     this argument
 * @return true if callback function returned true for any element in the array, false otherwise
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1)
public static boolean some(final Object self, final Object callbackfn, final Object thisArg) {
    return new IteratorAction<Boolean>(Global.toObject(self), callbackfn, thisArg, false) {
        private final MethodHandle someInvoker = getSOME_CALLBACK_INVOKER();

        @Override
        protected boolean forEach(final Object val, final double i) throws Throwable {
            return !(result = (boolean)someInvoker.invokeExact(callbackfn, thisArg, val, i, self));
        }
    }.apply();
}
 
Example 35
Project: openjdk-jdk10   File: NativeError.java   Source Code and License 5 votes vote down vote up
/**
 * Nashorn extension
 * Accessed from {@link Global} while setting up the Error.prototype
 *
 * @param self   self reference
 * @param value  value to set "stack" property to, must be {@code ScriptObject}
 *
 * @return value that was set
 */
public static Object setStack(final Object self, final Object value) {
    final ScriptObject sobj = Global.checkObject(self);
    if (sobj.hasOwnProperty(STACK)) {
        sobj.put(STACK, value, false);
    } else {
        sobj.addOwnProperty(STACK, Attribute.NOT_ENUMERABLE, value);
    }
    return value;
}
 
Example 36
Project: openjdk-jdk10   File: NativeString.java   Source Code and License 5 votes vote down vote up
/**
 * ECMA B.2.3 String.prototype.substr (start, length)
 *
 * @param self   self reference
 * @param start  start position
 * @param length length of section
 * @return substring given start and length of section
 */
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static String substr(final Object self, final Object start, final Object length) {
    final String str       = JSType.toString(self);
    final int    strLength = str.length();

    int intStart = JSType.toInteger(start);
    if (intStart < 0) {
        intStart = Math.max(intStart + strLength, 0);
    }

    final int intLen = Math.min(Math.max(length == UNDEFINED ? Integer.MAX_VALUE : JSType.toInteger(length), 0), strLength - intStart);

    return intLen <= 0 ? "" : str.substring(intStart, intStart + intLen);
}
 
Example 37
Project: OpenJSharp   File: NativeNumber.java   Source Code and License 5 votes vote down vote up
/**
 * ECMA 15.7.4.2 Number.prototype.toString ( [ radix ] )
 *
 * @param self  self reference
 * @param radix radix to use for string conversion
 * @return string representation of this Number in the given radix
 */
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static String toString(final Object self, final Object radix) {
    if (radix != UNDEFINED) {
        final int intRadix = JSType.toInteger(radix);
        if (intRadix != 10) {
            if (intRadix < 2 || intRadix > 36) {
                throw rangeError("invalid.radix");
            }
            return JSType.toString(getNumberValue(self), intRadix);
        }
    }

    return JSType.toString(getNumberValue(self));
}
 
Example 38
Project: OpenJSharp   File: NativeJava.java   Source Code and License 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).makeSynchronizedFunction(obj);
    }

    throw typeError("not.a.function", ScriptRuntime.safeToString(func));
}
 
Example 39
Project: OpenJSharp   File: NativeArray.java   Source Code and License 5 votes vote down vote up
/**
 * ECMA 15.4.4.6 Array.prototype.pop ()
 *
 * @param self self reference
 * @return array after pop
 */
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static Object pop(final Object self) {
    try {
        final ScriptObject sobj = (ScriptObject)self;

        if (bulkable(sobj)) {
            return sobj.getArray().pop();
        }

        final long len = JSType.toUint32(sobj.getLength());

        if (len == 0) {
            sobj.set("length", 0, CALLSITE_STRICT);
            return ScriptRuntime.UNDEFINED;
        }

        final long   index   = len - 1;
        final Object element = sobj.get(index);

        sobj.delete(index, true);
        sobj.set("length", index, CALLSITE_STRICT);

        return element;
    } catch (final ClassCastException | NullPointerException e) {
        throw typeError("not.an.object", ScriptRuntime.safeToString(self));
    }
}
 
Example 40
Project: openjdk-jdk10   File: NativeObject.java   Source Code and License 5 votes vote down vote up
/**
 * ECMA 15.2.3.4 Object.getOwnPropertyNames ( O )
 *
 * @param self self reference
 * @param obj  object to query for property names
 * @return array of property names
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static ScriptObject getOwnPropertyNames(final Object self, final Object obj) {
    if (obj instanceof ScriptObject) {
        return new NativeArray(((ScriptObject)obj).getOwnKeys(true));
    } else if (obj instanceof ScriptObjectMirror) {
        return new NativeArray(((ScriptObjectMirror)obj).getOwnKeys(true));
    } else {
        throw notAnObject(obj);
    }
}