Java Code Examples for jdk.nashorn.internal.runtime.ScriptObject#set()

The following examples show how to use jdk.nashorn.internal.runtime.ScriptObject#set() . 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: NativeArray.java    From TencentKona-8 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 2
Source File: NativeArray.java    From TencentKona-8 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 double 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 File: NativeArray.java    From jdk8u_nashorn 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 4
Source File: NativeArray.java    From openjdk-jdk8u-backup 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 5
Source File: NativeError.java    From nashorn with GNU General Public License v2.0 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) {
    Global.checkObject(errorObj);
    final ScriptObject sobj = (ScriptObject)errorObj;
    final ECMAException exp = new ECMAException(sobj, null);
    sobj.set("stack", getScriptStackString(sobj, exp), false);
    return UNDEFINED;
}
 
Example 6
Source File: NativeArray.java    From nashorn with GNU General Public License v2.0 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, true);
            return ScriptRuntime.UNDEFINED;
        }

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

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

        return element;
    } catch (final ClassCastException | NullPointerException e) {
        throw typeError("not.an.object", ScriptRuntime.safeToString(self));
    }
}
 
Example 7
Source File: Global.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private void initErrorObjects() {
    // Error objects
    this.builtinError = initConstructor("Error", ScriptFunction.class);
    final ScriptObject errorProto = getErrorPrototype();

    // Nashorn specific accessors on Error.prototype - stack, lineNumber, columnNumber and fileName
    final ScriptFunction getStack = ScriptFunction.createBuiltin("getStack", NativeError.GET_STACK);
    final ScriptFunction setStack = ScriptFunction.createBuiltin("setStack", NativeError.SET_STACK);
    errorProto.addOwnProperty("stack", Attribute.NOT_ENUMERABLE, getStack, setStack);
    final ScriptFunction getLineNumber = ScriptFunction.createBuiltin("getLineNumber", NativeError.GET_LINENUMBER);
    final ScriptFunction setLineNumber = ScriptFunction.createBuiltin("setLineNumber", NativeError.SET_LINENUMBER);
    errorProto.addOwnProperty("lineNumber", Attribute.NOT_ENUMERABLE, getLineNumber, setLineNumber);
    final ScriptFunction getColumnNumber = ScriptFunction.createBuiltin("getColumnNumber", NativeError.GET_COLUMNNUMBER);
    final ScriptFunction setColumnNumber = ScriptFunction.createBuiltin("setColumnNumber", NativeError.SET_COLUMNNUMBER);
    errorProto.addOwnProperty("columnNumber", Attribute.NOT_ENUMERABLE, getColumnNumber, setColumnNumber);
    final ScriptFunction getFileName = ScriptFunction.createBuiltin("getFileName", NativeError.GET_FILENAME);
    final ScriptFunction setFileName = ScriptFunction.createBuiltin("setFileName", NativeError.SET_FILENAME);
    errorProto.addOwnProperty("fileName", Attribute.NOT_ENUMERABLE, getFileName, setFileName);

    // ECMA 15.11.4.2 Error.prototype.name
    // Error.prototype.name = "Error";
    errorProto.set(NativeError.NAME, "Error", 0);
    // ECMA 15.11.4.3 Error.prototype.message
    // Error.prototype.message = "";
    errorProto.set(NativeError.MESSAGE, "", 0);

    tagBuiltinProperties("Error", builtinError);

    this.builtinReferenceError = initErrorSubtype("ReferenceError", errorProto);
    this.builtinSyntaxError = initErrorSubtype("SyntaxError", errorProto);
    this.builtinTypeError = initErrorSubtype("TypeError", errorProto);
}
 
Example 8
Source File: Global.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private void initErrorObjects() {
    // Error objects
    this.builtinError = initConstructor("Error", ScriptFunction.class);
    final ScriptObject errorProto = getErrorPrototype();

    // Nashorn specific accessors on Error.prototype - stack, lineNumber, columnNumber and fileName
    final ScriptFunction getStack = ScriptFunction.createBuiltin("getStack", NativeError.GET_STACK);
    final ScriptFunction setStack = ScriptFunction.createBuiltin("setStack", NativeError.SET_STACK);
    errorProto.addOwnProperty("stack", Attribute.NOT_ENUMERABLE, getStack, setStack);
    final ScriptFunction getLineNumber = ScriptFunction.createBuiltin("getLineNumber", NativeError.GET_LINENUMBER);
    final ScriptFunction setLineNumber = ScriptFunction.createBuiltin("setLineNumber", NativeError.SET_LINENUMBER);
    errorProto.addOwnProperty("lineNumber", Attribute.NOT_ENUMERABLE, getLineNumber, setLineNumber);
    final ScriptFunction getColumnNumber = ScriptFunction.createBuiltin("getColumnNumber", NativeError.GET_COLUMNNUMBER);
    final ScriptFunction setColumnNumber = ScriptFunction.createBuiltin("setColumnNumber", NativeError.SET_COLUMNNUMBER);
    errorProto.addOwnProperty("columnNumber", Attribute.NOT_ENUMERABLE, getColumnNumber, setColumnNumber);
    final ScriptFunction getFileName = ScriptFunction.createBuiltin("getFileName", NativeError.GET_FILENAME);
    final ScriptFunction setFileName = ScriptFunction.createBuiltin("setFileName", NativeError.SET_FILENAME);
    errorProto.addOwnProperty("fileName", Attribute.NOT_ENUMERABLE, getFileName, setFileName);

    // ECMA 15.11.4.2 Error.prototype.name
    // Error.prototype.name = "Error";
    errorProto.set(NativeError.NAME, "Error", 0);
    // ECMA 15.11.4.3 Error.prototype.message
    // Error.prototype.message = "";
    errorProto.set(NativeError.MESSAGE, "", 0);

    tagBuiltinProperties("Error", builtinError);

    this.builtinReferenceError = initErrorSubtype("ReferenceError", errorProto);
    this.builtinSyntaxError = initErrorSubtype("SyntaxError", errorProto);
    this.builtinTypeError = initErrorSubtype("TypeError", errorProto);
}
 
Example 9
Source File: NativeArray.java    From openjdk-8 with GNU General Public License v2.0 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, true);
            return ScriptRuntime.UNDEFINED;
        }

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

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

        return element;
    } catch (final ClassCastException | NullPointerException e) {
        throw typeError("not.an.object", ScriptRuntime.safeToString(self));
    }
}
 
Example 10
Source File: Global.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private static void copyOptions(final ScriptObject options, final ScriptEnvironment scriptEnv) {
    for (final Field f : scriptEnv.getClass().getFields()) {
        try {
            options.set(f.getName(), f.get(scriptEnv), 0);
        } catch (final IllegalArgumentException | IllegalAccessException exp) {
            throw new RuntimeException(exp);
        }
    }
}
 
Example 11
Source File: NativeArray.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * ECMA 15.4.4.13 Array.prototype.unshift ( [ item1 [ , item2 [ , ... ] ] ] )
 *
 * @param self  self reference
 * @param items items for unshift
 * @return unshifted array
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1)
public static Object unshift(final Object self, final Object... items) {
    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());

    if (items == null) {
        return ScriptRuntime.UNDEFINED;
    }

    if (bulkable(sobj)) {
        sobj.getArray().shiftRight(items.length);

        for (int j = 0; j < items.length; j++) {
            sobj.setArray(sobj.getArray().set(j, items[j], true));
        }
    } else {
        for (long k = len; k > 0; k--) {
            final long from = k - 1;
            final long to = k + items.length - 1;

            if (sobj.has(from)) {
                final Object fromValue = sobj.get(from);
                sobj.set(to, fromValue, CALLSITE_STRICT);
            } else {
                sobj.delete(to, true);
            }
        }

        for (int j = 0; j < items.length; j++) {
            sobj.set(j, items[j], CALLSITE_STRICT);
        }
    }

    final long newLength = len + items.length;
    sobj.set("length", newLength, CALLSITE_STRICT);

    return JSType.toNarrowestNumber(newLength);
}
 
Example 12
Source File: NativeJSON.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * ECMA 15.12.3 stringify ( value [ , replacer [ , space ] ] )
 *
 * @param self     self reference
 * @param value    ECMA script value (usually object or array)
 * @param replacer either a function or an array of strings and numbers
 * @param space    optional parameter - allows result to have whitespace injection
 *
 * @return a string in JSON format
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static Object stringify(final Object self, final Object value, final Object replacer, final Object space) {
    // The stringify method takes a value and an optional replacer, and an optional
    // space parameter, and returns a JSON text. The replacer can be a function
    // that can replace values, or an array of strings that will select the keys.

    // A default replacer method can be provided. Use of the space parameter can
    // produce text that is more easily readable.

    final StringifyState state = new StringifyState();

    // If there is a replacer, it must be a function or an array.
    if (Bootstrap.isCallable(replacer)) {
        state.replacerFunction = replacer;
    } else if (isArray(replacer) ||
            isJSObjectArray(replacer) ||
            replacer instanceof Iterable ||
            (replacer != null && replacer.getClass().isArray())) {

        state.propertyList = new ArrayList<>();

        final Iterator<Object> iter = ArrayLikeIterator.arrayLikeIterator(replacer);

        while (iter.hasNext()) {
            String item = null;
            final Object v = iter.next();

            if (v instanceof String) {
                item = (String) v;
            } else if (v instanceof ConsString) {
                item = v.toString();
            } else if (v instanceof Number ||
                    v instanceof NativeNumber ||
                    v instanceof NativeString) {
                item = JSType.toString(v);
            }

            if (item != null) {
                state.propertyList.add(item);
            }
        }
    }

    // If the space parameter is a number, make an indent
    // string containing that many spaces.

    String gap;

    // modifiable 'space' - parameter is final
    Object modSpace = space;
    if (modSpace instanceof NativeNumber) {
        modSpace = JSType.toNumber(JSType.toPrimitive(modSpace, Number.class));
    } else if (modSpace instanceof NativeString) {
        modSpace = JSType.toString(JSType.toPrimitive(modSpace, String.class));
    }

    if (modSpace instanceof Number) {
        final int indent = Math.min(10, JSType.toInteger(modSpace));
        if (indent < 1) {
            gap = "";
        } else {
            final StringBuilder sb = new StringBuilder();
            for (int i = 0; i < indent; i++) {
                sb.append(' ');
            }
            gap = sb.toString();
        }
    } else if (JSType.isString(modSpace)) {
        final String str = modSpace.toString();
        gap = str.substring(0, Math.min(10, str.length()));
    } else {
        gap = "";
    }

    state.gap = gap;

    final ScriptObject wrapper = Global.newEmptyInstance();
    wrapper.set("", value, 0);

    return str("", wrapper, state);
}
 
Example 13
Source File: NativeArray.java    From jdk8u_nashorn with GNU General Public License v2.0 4 votes vote down vote up
/**
 * ECMA 15.4.4.13 Array.prototype.unshift ( [ item1 [ , item2 [ , ... ] ] ] )
 *
 * @param self  self reference
 * @param items items for unshift
 * @return unshifted array
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1)
public static Object unshift(final Object self, final Object... items) {
    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());

    if (items == null) {
        return ScriptRuntime.UNDEFINED;
    }

    if (bulkable(sobj)) {
        sobj.getArray().shiftRight(items.length);

        for (int j = 0; j < items.length; j++) {
            sobj.setArray(sobj.getArray().set(j, items[j], true));
        }
    } else {
        for (long k = len; k > 0; k--) {
            final long from = k - 1;
            final long to = k + items.length - 1;

            if (sobj.has(from)) {
                final Object fromValue = sobj.get(from);
                sobj.set(to, fromValue, CALLSITE_STRICT);
            } else {
                sobj.delete(to, true);
            }
        }

        for (int j = 0; j < items.length; j++) {
            sobj.set(j, items[j], CALLSITE_STRICT);
        }
    }

    final long newLength = len + items.length;
    sobj.set("length", newLength, CALLSITE_STRICT);

    return JSType.toNarrowestNumber(newLength);
}
 
Example 14
Source File: NativeJSON.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * ECMA 15.12.3 stringify ( value [ , replacer [ , space ] ] )
 *
 * @param self     self reference
 * @param value    ECMA script value (usually object or array)
 * @param replacer either a function or an array of strings and numbers
 * @param space    optional parameter - allows result to have whitespace injection
 *
 * @return a string in JSON format
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static Object stringify(final Object self, final Object value, final Object replacer, final Object space) {
    // The stringify method takes a value and an optional replacer, and an optional
    // space parameter, and returns a JSON text. The replacer can be a function
    // that can replace values, or an array of strings that will select the keys.

    // A default replacer method can be provided. Use of the space parameter can
    // produce text that is more easily readable.

    final StringifyState state = new StringifyState();

    // If there is a replacer, it must be a function or an array.
    if (replacer instanceof ScriptFunction) {
        state.replacerFunction = (ScriptFunction) replacer;
    } else if (isArray(replacer) ||
            replacer instanceof Iterable ||
            (replacer != null && replacer.getClass().isArray())) {

        state.propertyList = new ArrayList<>();

        final Iterator<Object> iter = ArrayLikeIterator.arrayLikeIterator(replacer);

        while (iter.hasNext()) {
            String item = null;
            final Object v = iter.next();

            if (v instanceof String) {
                item = (String) v;
            } else if (v instanceof ConsString) {
                item = v.toString();
            } else if (v instanceof Number ||
                    v instanceof NativeNumber ||
                    v instanceof NativeString) {
                item = JSType.toString(v);
            }

            if (item != null) {
                state.propertyList.add(item);
            }
        }
    }

    // If the space parameter is a number, make an indent
    // string containing that many spaces.

    String gap;

    // modifiable 'space' - parameter is final
    Object modSpace = space;
    if (modSpace instanceof NativeNumber) {
        modSpace = JSType.toNumber(JSType.toPrimitive(modSpace, Number.class));
    } else if (modSpace instanceof NativeString) {
        modSpace = JSType.toString(JSType.toPrimitive(modSpace, String.class));
    }

    if (modSpace instanceof Number) {
        int indent = Math.min(10, JSType.toInteger(modSpace));
        if (indent < 1) {
            gap = "";
        } else {
            final StringBuilder sb = new StringBuilder();
            for (int i = 0; i < indent; i++) {
                sb.append(' ');
            }
            gap = sb.toString();
        }
    } else if (modSpace instanceof String || modSpace instanceof ConsString) {
        final String str = modSpace.toString();
        gap = str.substring(0, Math.min(10, str.length()));
    } else {
        gap = "";
    }

    state.gap = gap;

    final ScriptObject wrapper = Global.newEmptyInstance();
    wrapper.set("", value, false);

    return str("", wrapper, state);
}
 
Example 15
Source File: NativeArray.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * ECMA 15.4.4.9 Array.prototype.shift ()
 *
 * @param self self reference
 * @return shifted array
 */
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static Object shift(final Object self) {
    final Object obj = Global.toObject(self);

    Object first = ScriptRuntime.UNDEFINED;

    if (!(obj instanceof ScriptObject)) {
        return first;
    }

    final ScriptObject sobj   = (ScriptObject) obj;

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

    if (len > 0) {
        first = sobj.get(0);

        if (bulkable(sobj)) {
            sobj.getArray().shiftLeft(1);
        } else {
            boolean hasPrevious = true;
            for (long k = 1; k < len; k++) {
                final boolean hasCurrent = sobj.has(k);
                if (hasCurrent) {
                    sobj.set(k - 1, sobj.get(k), CALLSITE_STRICT);
                } else if (hasPrevious) {
                    sobj.delete(k - 1, true);
                }
                hasPrevious = hasCurrent;
            }
        }
        sobj.delete(--len, true);
    } else {
        len = 0;
    }

    sobj.set("length", len, CALLSITE_STRICT);

    return first;
}
 
Example 16
Source File: NativeArray.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
private boolean defineLength(final long oldLen, final PropertyDescriptor oldLenDesc, final PropertyDescriptor desc, final boolean reject) {
    // Step 3a
    if (!desc.has(VALUE)) {
        return super.defineOwnProperty("length", desc, reject);
    }

    // Step 3b
    final PropertyDescriptor newLenDesc = desc;

    // Step 3c and 3d - get new length and convert to long
    final long newLen = NativeArray.validLength(newLenDesc.getValue());

    // Step 3e - note that we need to convert to int or double as long is not considered a JS number type anymore
    newLenDesc.setValue(JSType.toNarrowestNumber(newLen));

    // Step 3f
    // increasing array length - just need to set new length value (and attributes if any) and return
    if (newLen >= oldLen) {
        return super.defineOwnProperty("length", newLenDesc, reject);
    }

    // Step 3g
    if (!oldLenDesc.isWritable()) {
        if (reject) {
            throw typeError("property.not.writable", "length", ScriptRuntime.safeToString(this));
        }
        return false;
    }

    // Step 3h and 3i
    final boolean newWritable = !newLenDesc.has(WRITABLE) || newLenDesc.isWritable();
    if (!newWritable) {
        newLenDesc.setWritable(true);
    }

    // Step 3j and 3k
    final boolean succeeded = super.defineOwnProperty("length", newLenDesc, reject);
    if (!succeeded) {
        return false;
    }

    // Step 3l
    // make sure that length is set till the point we can delete the old elements
    long o = oldLen;
    while (newLen < o) {
        o--;
        final boolean deleteSucceeded = delete(o, false);
        if (!deleteSucceeded) {
            newLenDesc.setValue(o + 1);
            if (!newWritable) {
                newLenDesc.setWritable(false);
            }
            super.defineOwnProperty("length", newLenDesc, false);
            if (reject) {
                throw typeError("property.not.writable", "length", ScriptRuntime.safeToString(this));
            }
            return false;
        }
    }

    // Step 3m
    if (!newWritable) {
        // make 'length' property not writable
        final ScriptObject newDesc = Global.newEmptyInstance();
        newDesc.set(WRITABLE, false, 0);
        return super.defineOwnProperty("length", newDesc, false);
    }

    return true;
}
 
Example 17
Source File: NativeJSON.java    From jdk8u_nashorn with GNU General Public License v2.0 4 votes vote down vote up
/**
 * ECMA 15.12.3 stringify ( value [ , replacer [ , space ] ] )
 *
 * @param self     self reference
 * @param value    ECMA script value (usually object or array)
 * @param replacer either a function or an array of strings and numbers
 * @param space    optional parameter - allows result to have whitespace injection
 *
 * @return a string in JSON format
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static Object stringify(final Object self, final Object value, final Object replacer, final Object space) {
    // The stringify method takes a value and an optional replacer, and an optional
    // space parameter, and returns a JSON text. The replacer can be a function
    // that can replace values, or an array of strings that will select the keys.

    // A default replacer method can be provided. Use of the space parameter can
    // produce text that is more easily readable.

    final StringifyState state = new StringifyState();

    // If there is a replacer, it must be a function or an array.
    if (Bootstrap.isCallable(replacer)) {
        state.replacerFunction = replacer;
    } else if (isArray(replacer) ||
            isJSObjectArray(replacer) ||
            replacer instanceof Iterable ||
            (replacer != null && replacer.getClass().isArray())) {

        state.propertyList = new ArrayList<>();

        final Iterator<Object> iter = ArrayLikeIterator.arrayLikeIterator(replacer);

        while (iter.hasNext()) {
            String item = null;
            final Object v = iter.next();

            if (v instanceof String) {
                item = (String) v;
            } else if (v instanceof ConsString) {
                item = v.toString();
            } else if (v instanceof Number ||
                    v instanceof NativeNumber ||
                    v instanceof NativeString) {
                item = JSType.toString(v);
            }

            if (item != null) {
                state.propertyList.add(item);
            }
        }
    }

    // If the space parameter is a number, make an indent
    // string containing that many spaces.

    String gap;

    // modifiable 'space' - parameter is final
    Object modSpace = space;
    if (modSpace instanceof NativeNumber) {
        modSpace = JSType.toNumber(JSType.toPrimitive(modSpace, Number.class));
    } else if (modSpace instanceof NativeString) {
        modSpace = JSType.toString(JSType.toPrimitive(modSpace, String.class));
    }

    if (modSpace instanceof Number) {
        final int indent = Math.min(10, JSType.toInteger(modSpace));
        if (indent < 1) {
            gap = "";
        } else {
            final StringBuilder sb = new StringBuilder();
            for (int i = 0; i < indent; i++) {
                sb.append(' ');
            }
            gap = sb.toString();
        }
    } else if (JSType.isString(modSpace)) {
        final String str = modSpace.toString();
        gap = str.substring(0, Math.min(10, str.length()));
    } else {
        gap = "";
    }

    state.gap = gap;

    final ScriptObject wrapper = Global.newEmptyInstance();
    wrapper.set("", value, 0);

    return str("", wrapper, state);
}
 
Example 18
Source File: NativeError.java    From openjdk-8-source with GNU General Public License v2.0 3 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) {
    Global.checkObject(self);
    final ScriptObject sobj = (ScriptObject)self;
    sobj.set(STACK, value, false);
    return value;
}
 
Example 19
Source File: NativeError.java    From openjdk-8 with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Nashorn extension: Error.prototype.columnNumber
 *
 * @param self  self reference
 * @param value value of column number
 *
 * @return value that was set
 */
public static Object setColumnNumber(final Object self, final Object value) {
    Global.checkObject(self);
    final ScriptObject sobj = (ScriptObject)self;
    sobj.set(COLUMNNUMBER, value, false);
    return value;
}
 
Example 20
Source File: NativeError.java    From openjdk-8 with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Nashorn extension: Error.prototype.fileName
 *
 * @param self  self reference
 * @param value value of file name
 *
 * @return value that was set
 */
public static Object setFileName(final Object self, final Object value) {
    Global.checkObject(self);
    final ScriptObject sobj = (ScriptObject)self;
    sobj.set(FILENAME, value, false);
    return value;
}