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

The following are top voted examples for showing how to use jdk.nashorn.internal.runtime.JSType. 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: NativeMath.java   Source Code and License 6 votes vote down vote up
/**
 * ECMA 15.8.2.11 max(x)
 *
 * @param self  self reference
 * @param args  arguments
 *
 * @return the largest of the arguments, {@link Double#NEGATIVE_INFINITY} if no args given, or identity if one arg is given
 */
@Function(arity = 2, attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static double max(final Object self, final Object... args) {
    switch (args.length) {
    case 0:
        return Double.NEGATIVE_INFINITY;
    case 1:
        return JSType.toNumber(args[0]);
    default:
        double res = JSType.toNumber(args[0]);
        for (int i = 1; i < args.length; i++) {
            res = Math.max(res, JSType.toNumber(args[i]));
        }
        return res;
    }
}
 
Example 2
Project: openjdk-jdk10   File: JSTypeTest.java   Source Code and License 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 3
Project: openjdk-jdk10   File: NativeArray.java   Source Code and License 6 votes vote down vote up
/**
 * ECMA 15.4.4.5 Array.prototype.join (separator)
 *
 * @param self      self reference
 * @param separator element separator
 * @return string representation after join
 */
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static String join(final Object self, final Object separator) {
    final StringBuilder    sb   = new StringBuilder();
    final Iterator<Object> iter = arrayLikeIterator(self, true);
    final String           sep  = separator == ScriptRuntime.UNDEFINED ? "," : JSType.toString(separator);

    while (iter.hasNext()) {
        final Object obj = iter.next();

        if (obj != null && obj != ScriptRuntime.UNDEFINED) {
            sb.append(JSType.toString(obj));
        }

        if (iter.hasNext()) {
            sb.append(sep);
        }
    }

    return sb.toString();
}
 
Example 4
Project: openjdk-jdk10   File: NativeObject.java   Source Code and License 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 5
Project: openjdk-jdk10   File: NativeString.java   Source Code and License 6 votes vote down vote up
/**
 * ECMA 15.5.4.14 String.prototype.split (separator, limit)
 *
 * @param self      self reference
 * @param separator separator for split
 * @param limit     limit for splits
 * @return array object in which splits have been placed
 */
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static ScriptObject split(final Object self, final Object separator, final Object limit) {
    final String str = checkObjectToString(self);
    final long lim = limit == UNDEFINED ? JSType.MAX_UINT : JSType.toUint32(limit);

    if (separator == UNDEFINED) {
        return lim == 0 ? new NativeArray() : new NativeArray(new Object[]{str});
    }

    if (separator instanceof NativeRegExp) {
        return ((NativeRegExp) separator).split(str, lim);
    }

    // when separator is a string, it is treated as a literal search string to be used for splitting.
    return splitString(str, JSType.toString(separator), lim);
}
 
Example 6
Project: openjdk-jdk10   File: NativeArray.java   Source Code and License 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 7
Project: openjdk-jdk10   File: GenericPropertyDescriptor.java   Source Code and License 6 votes vote down vote up
@Override
public PropertyDescriptor fillFrom(final ScriptObject sobj) {
    if (sobj.has(CONFIGURABLE)) {
        this.configurable = JSType.toBoolean(sobj.get(CONFIGURABLE));
    } else {
        delete(CONFIGURABLE, false);
    }

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

    return this;
}
 
Example 8
Project: openjdk-jdk10   File: NativeMath.java   Source Code and License 6 votes vote down vote up
/**
 * ECMA 15.8.2.12 min(x)
 *
 * @param self  self reference
 * @param args  arguments
 *
 * @return the smallest of the arguments, {@link Double#NEGATIVE_INFINITY} if no args given, or identity if one arg is given
 */
@Function(arity = 2, attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static double min(final Object self, final Object... args) {
    switch (args.length) {
    case 0:
        return Double.POSITIVE_INFINITY;
    case 1:
        return JSType.toNumber(args[0]);
    default:
        double res = JSType.toNumber(args[0]);
        for (int i = 1; i < args.length; i++) {
            res = Math.min(res, JSType.toNumber(args[i]));
        }
        return res;
    }
}
 
Example 9
Project: OpenJSharp   File: NativeDate.java   Source Code and License 6 votes vote down vote up
private static double[] convertCtorArgs(final Object[] args) {
    final double[] d = new double[7];
    boolean nullReturn = false;

    // should not bailout on first NaN or infinite. Need to convert all
    // subsequent args for possible side-effects via valueOf/toString overrides
    // on argument objects.
    for (int i = 0; i < d.length; i++) {
        if (i < args.length) {
            final double darg = JSType.toNumber(args[i]);
            if (isNaN(darg) || isInfinite(darg)) {
                nullReturn = true;
            }

            d[i] = (long)darg;
        } else {
            d[i] = i == 2 ? 1 : 0; // day in month defaults to 1
        }
    }

    if (0 <= d[0] && d[0] <= 99) {
        d[0] += 1900;
    }

    return nullReturn? null : d;
}
 
Example 10
Project: OpenJSharp   File: ScriptObjectMirror.java   Source Code and License 5 votes vote down vote up
@Override
public double toNumber() {
    return inGlobal(new Callable<Double>() {
        @Override public Double call() {
            return JSType.toNumber(sobj);
        }
    });
}
 
Example 11
Project: OpenJSharp   File: NativeString.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unused")
private static Object get(final Object self, final Object key) {
    final CharSequence cs = JSType.toCharSequence(self);
    final Object primitiveKey = JSType.toPrimitive(key, String.class);
    final int index = ArrayIndex.getArrayIndex(primitiveKey);
    if (index >= 0 && index < cs.length()) {
        return String.valueOf(cs.charAt(index));
    }
    return ((ScriptObject) Global.toObject(self)).get(primitiveKey);
}
 
Example 12
Project: openjdk-jdk10   File: Shell.java   Source Code and License 5 votes vote down vote up
/**
 * Converts {@code result} to a printable string. The reason we don't use {@link JSType#toString(Object)}
 * or {@link ScriptRuntime#safeToString(Object)} is that we want to be able to render Symbol values
 * even if they occur within an Array, and therefore have to implement our own Array to String
 * conversion.
 *
 * @param result the result
 * @param global the global object
 * @return the string representation
 */
protected static String toString(final Object result, final Global global) {
    if (result instanceof Symbol) {
        // Normal implicit conversion of symbol to string would throw TypeError
        return result.toString();
    }

    if (result instanceof NativeSymbol) {
        return JSType.toPrimitive(result).toString();
    }

    if (isArrayWithDefaultToString(result, global)) {
        // This should yield the same string as Array.prototype.toString but
        // will not throw if the array contents include symbols.
        final StringBuilder sb = new StringBuilder();
        final Iterator<Object> iter = ArrayLikeIterator.arrayLikeIterator(result, true);

        while (iter.hasNext()) {
            final Object obj = iter.next();

            if (obj != null && obj != ScriptRuntime.UNDEFINED) {
                sb.append(toString(obj, global));
            }

            if (iter.hasNext()) {
                sb.append(',');
            }
        }

        return sb.toString();
    }

    return JSType.toString(result);
}
 
Example 13
Project: OpenJSharp   File: LengthNotWritableFilter.java   Source Code and License 5 votes vote down vote up
@Override
public int getIntOptimistic(final int index, final int programPoint) {
    if (index >= length()) {
        return JSType.toInt32Optimistic(get(index), programPoint);
    }
    return underlying.getIntOptimistic(index, programPoint);
}
 
Example 14
Project: openjdk-jdk10   File: DataPropertyDescriptor.java   Source Code and License 5 votes vote down vote up
@Override
public PropertyDescriptor fillFrom(final ScriptObject sobj) {
    if (sobj.has(CONFIGURABLE)) {
        this.configurable = JSType.toBoolean(sobj.get(CONFIGURABLE));
    } else {
        delete(CONFIGURABLE, false);
    }

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

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

    if (sobj.has(VALUE)) {
        this.value = sobj.get(VALUE);
    } else {
        delete(VALUE, false);
    }

    return this;
}
 
Example 15
Project: openjdk-jdk10   File: NativeObject.java   Source Code and License 5 votes vote down vote up
/**
 * ECMA 15.2.4.5 Object.prototype.hasOwnProperty (V)
 *
 * @param self self reference
 * @param v property to check for
 * @return true if property exists in object
 */
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static boolean hasOwnProperty(final Object self, final Object v) {
    // Convert ScriptObjects to primitive with String.class hint
    // but no need to convert other primitives to string.
    final Object key = JSType.toPrimitive(v, String.class);
    final Object obj = Global.toObject(self);

    return obj instanceof ScriptObject && ((ScriptObject)obj).hasOwnProperty(key);
}
 
Example 16
Project: openjdk-jdk10   File: NativeSyntaxError.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("LeakingThisInConstructor")
NativeSyntaxError(final Object msg, final Global global) {
    super(global.getSyntaxErrorPrototype(), $nasgenmap$);
    if (msg != UNDEFINED) {
        this.instMessage = JSType.toString(msg);
    } else {
        this.delete(NativeError.MESSAGE, false);
    }
    NativeError.initException(this);
}
 
Example 17
Project: openjdk-jdk10   File: Global.java   Source Code and License 5 votes vote down vote up
/**
 * Convert given object to NativeRegExp type.
 *
 * @param obj object to be converted
 * @return NativeRegExp instance
 */
public static NativeRegExp toRegExp(final Object obj) {
    if (obj instanceof NativeRegExp) {
        return (NativeRegExp)obj;
    }
    return new NativeRegExp(JSType.toString(obj));
}
 
Example 18
Project: OpenJSharp   File: NativeString.java   Source Code and License 5 votes vote down vote up
/**
 * return a List of own keys associated with the object.
 * @param all True if to include non-enumerable keys.
 * @param nonEnumerable set of non-enumerable properties seen already.Used
 * to filter out shadowed, but enumerable properties from proto children.
 * @return Array of keys.
 */
@Override
protected String[] getOwnKeys(final boolean all, final Set<String> nonEnumerable) {
    final List<Object> keys = new ArrayList<>();

    // add string index keys
    for (int i = 0; i < value.length(); i++) {
        keys.add(JSType.toString(i));
    }

    // add super class properties
    keys.addAll(Arrays.asList(super.getOwnKeys(all, nonEnumerable)));
    return keys.toArray(new String[keys.size()]);
}
 
Example 19
Project: OpenJSharp   File: NativeObject.java   Source Code and License 5 votes vote down vote up
/**
 * ECMA 5.2.3.7 Object.defineProperties ( O, Properties )
 *
 * @param self  self reference
 * @param obj   object in which to define properties
 * @param props properties
 * @return object
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static ScriptObject defineProperties(final Object self, final Object obj, final Object props) {
    final ScriptObject sobj     = Global.checkObject(obj);
    final Object       propsObj = Global.toObject(props);

    if (propsObj instanceof ScriptObject) {
        final Object[] keys = ((ScriptObject)propsObj).getOwnKeys(false);
        for (final Object key : keys) {
            final String prop = JSType.toString(key);
            sobj.defineOwnProperty(prop, ((ScriptObject)propsObj).get(prop), true);
        }
    }
    return sobj;
}
 
Example 20
Project: OpenJSharp   File: JavaArgumentConverters.java   Source Code and License 5 votes vote down vote up
private static Long toLong(final Object obj0) {
    // TODO - Order tests for performance.
    for (Object obj = obj0; ;) {
        if (obj == null) {
            return null;
        } else if (obj instanceof Long) {
            return (Long) obj;
        } else if (obj instanceof Integer) {
            return ((Integer)obj).longValue();
        } else if (obj instanceof Double) {
            final Double d = (Double)obj;
            if(Double.isInfinite(d.doubleValue())) {
                return 0L;
            }
            return d.longValue();
        } else if (obj instanceof Float) {
            final Float f = (Float)obj;
            if(Float.isInfinite(f.floatValue())) {
                return 0L;
            }
            return f.longValue();
        } else if (obj instanceof Number) {
            return ((Number)obj).longValue();
        } else if (obj instanceof String || obj instanceof ConsString) {
            return JSType.toLong(obj);
        } else if (obj instanceof Boolean) {
            return (Boolean)obj ? 1L : 0L;
        } else if (obj instanceof ScriptObject) {
            obj = JSType.toPrimitive(obj, Number.class);
            continue;
        } else if (obj == UNDEFINED) {
            return null; // null or 0L?
        }
        throw assertUnexpectedType(obj);
    }
}
 
Example 21
Project: OpenJSharp   File: NativeReferenceError.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("LeakingThisInConstructor")
private NativeReferenceError(final Object msg, final ScriptObject proto, final PropertyMap map) {
    super(proto, map);
    if (msg != UNDEFINED) {
        this.instMessage = JSType.toString(msg);
    } else {
        this.delete(NativeError.MESSAGE, false);
    }
    NativeError.initException(this);
}
 
Example 22
Project: openjdk-jdk10   File: Lower.java   Source Code and License 5 votes vote down vote up
@Override
public Node leaveCaseNode(final CaseNode caseNode) {
    // Try to represent the case test as an integer
    final Node test = caseNode.getTest();
    if (test instanceof LiteralNode) {
        final LiteralNode<?> lit = (LiteralNode<?>)test;
        if (lit.isNumeric() && !(lit.getValue() instanceof Integer)) {
            if (JSType.isRepresentableAsInt(lit.getNumber())) {
                return caseNode.setTest((Expression)LiteralNode.newInstance(lit, lit.getInt32()).accept(this));
            }
        }
    }
    return caseNode;
}
 
Example 23
Project: openjdk-jdk10   File: MethodEmitter.java   Source Code and License 5 votes vote down vote up
/**
 * Load a key value in the proper form.
 *
 * @param key
 */
//TODO move this and break it apart
MethodEmitter loadKey(final Object key) {
    if (key instanceof IdentNode) {
        method.visitLdcInsn(((IdentNode) key).getName());
    } else if (key instanceof LiteralNode) {
        method.visitLdcInsn(((LiteralNode<?>)key).getString());
    } else {
        method.visitLdcInsn(JSType.toString(key));
    }
    pushType(Type.OBJECT); //STRING
    return this;
}
 
Example 24
Project: OpenJSharp   File: NativeString.java   Source Code and License 5 votes vote down vote up
/**
 * ECMA 15.5.4.13 String.prototype.slice (start, end)
 *
 * @param self  self reference
 * @param start start position for slice
 * @param end   end position for slice
 * @return sliced out substring
 */
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static String slice(final Object self, final Object start, final Object end) {

    final String str      = checkObjectToString(self);
    if (end == UNDEFINED) {
        return slice(str, JSType.toInteger(start));
    }
    return slice(str, JSType.toInteger(start), JSType.toInteger(end));
}
 
Example 25
Project: openjdk-jdk10   File: LengthNotWritableFilter.java   Source Code and License 5 votes vote down vote up
@Override
public double getDouble(final int index) {
    if (index >= length()) {
        return JSType.toNumber(get(index));
    }
    return underlying.getDouble(index);
}
 
Example 26
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 27
Project: OpenJSharp   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 28
Project: openjdk-jdk10   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 29
Project: openjdk-jdk10   File: NativeDataView.java   Source Code and License 5 votes vote down vote up
/**
 * Set 32-bit float at the given byteOffset
 *
 * @param self DataView object
 * @param byteOffset byte offset to write at
 * @param value float 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 setFloat32(final Object self, final Object byteOffset, final Object value, final Object littleEndian) {
    try {
        getBuffer(self, littleEndian).putFloat((int)JSType.toUint32(byteOffset), (float)JSType.toNumber(value));
        return UNDEFINED;
    } catch (final IllegalArgumentException iae) {
        throw rangeError(iae, "dataview.offset");
    }
}
 
Example 30
Project: openjdk-jdk10   File: NativeDataView.java   Source Code and License 5 votes vote down vote up
/**
 * Set 8-bit signed int at the given byteOffset
 *
 * @param self DataView object
 * @param byteOffset byte offset to read from
 * @param value byte value to set
 * @return undefined
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 2)
public static Object setInt8(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 31
Project: openjdk-jdk10   File: NativeDataView.java   Source Code and License 5 votes vote down vote up
/**
 * Get 32-bit unsigned int from given byteOffset
 *
 * @param self DataView object
 * @param byteOffset byte offset to read from
 * @return 32-bit unsigned int value at the byteOffset
 */
@SpecializedFunction
public static double getUint32(final Object self, final int byteOffset) {
    try {
        return JSType.toUint32(getBuffer(self, false).getInt(JSType.toInt32(byteOffset)));
    } catch (final IllegalArgumentException iae) {
        throw rangeError(iae, "dataview.offset");
    }
}
 
Example 32
Project: openjdk-jdk10   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 33
Project: openjdk-jdk10   File: NativeDataView.java   Source Code and License 5 votes vote down vote up
/**
 * Get 64-bit float value 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 64-bit float value at the byteOffset
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1)
public static double getFloat64(final Object self, final Object byteOffset, final Object littleEndian) {
    try {
        return getBuffer(self, littleEndian).getDouble(JSType.toInt32(byteOffset));
    } catch (final IllegalArgumentException iae) {
        throw rangeError(iae, "dataview.offset");
    }
}
 
Example 34
Project: OpenJSharp   File: LongType.java   Source Code and License 5 votes vote down vote up
@Override
public Type rem(final MethodVisitor method, final int programPoint) {
    if (programPoint == INVALID_PROGRAM_POINT) {
        JSType.REM_ZERO_LONG.invoke(method);
    } else {
        method.visitInvokeDynamicInsn("lrem", "(JJ)J", MATHBOOTSTRAP, programPoint);
    }
    return LONG;
}
 
Example 35
Project: OpenJSharp   File: NativeJSAdapter.java   Source Code and License 5 votes vote down vote up
@Override
public boolean delete(final long key, final boolean strict) {
    if (overrides && super.hasOwnProperty(key)) {
        return super.delete(key, strict);
    }

    return JSType.toBoolean(callAdaptee(Boolean.TRUE, __delete__, key, strict));
}
 
Example 36
Project: OpenJSharp   File: NativeJSAdapter.java   Source Code and License 5 votes vote down vote up
@Override
public boolean delete(final double key, final boolean strict) {
    if (overrides && super.hasOwnProperty(key)) {
        return super.delete(key, strict);
    }

    return JSType.toBoolean(callAdaptee(Boolean.TRUE, __delete__, key, strict));
}
 
Example 37
Project: openjdk-jdk10   File: IntType.java   Source Code and License 5 votes vote down vote up
@Override
public Type rem(final MethodVisitor method, final int programPoint) {
    if (programPoint == INVALID_PROGRAM_POINT) {
        JSType.REM_ZERO.invoke(method);
    } else {
        ldc(method, programPoint);
        JSType.REM_EXACT.invoke(method);
    }
    return INT;
}
 
Example 38
Project: openjdk-jdk10   File: NativeString.java   Source Code and License 5 votes vote down vote up
private static Object get(final Object self, final int key) {
    final CharSequence cs = JSType.toCharSequence(self);
    if (key >= 0 && key < cs.length()) {
        return String.valueOf(cs.charAt(key));
    }
    return ((ScriptObject) Global.toObject(self)).get(key);
}
 
Example 39
Project: openjdk-jdk10   File: NativeMap.java   Source Code and License 5 votes vote down vote up
/**
 * Returns a canonicalized key object by converting numbers to their narrowest representation and
 * ConsStrings to strings. Conversion of Double to Integer also takes care of converting -0 to 0
 * as required by step 6 of ECMA6 23.1.3.9.
 *
 * @param key a key
 * @return the canonical key
 */
static Object convertKey(final Object key) {
    if (key instanceof ConsString) {
        return key.toString();
    }
    if (key instanceof Double) {
        final Double d = (Double) key;
        if (JSType.isRepresentableAsInt(d.doubleValue())) {
            return d.intValue();
        }
    }
    return key;
}
 
Example 40
Project: OpenJSharp   File: NativeEvalError.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("LeakingThisInConstructor")
private NativeEvalError(final Object msg, final ScriptObject proto, final PropertyMap map) {
    super(proto, map);
    if (msg != UNDEFINED) {
        this.instMessage = JSType.toString(msg);
    } else {
        this.delete(NativeError.MESSAGE, false);
    }
    NativeError.initException(this);
}
 
Example 41
Project: openjdk-jdk10   File: ShellFunctions.java   Source Code and License 5 votes vote down vote up
/**
 * Nashorn extension: global.input (shell-interactive-mode-only)
 * Read one or more lines of input from the standard input till the
 * given end marker is seen in standard input.
 *
 * @param self   self reference
 * @param endMarker String used as end marker for input
 * @param prompt String used as input prompt
 *
 * @return line that was read
 *
 * @throws IOException if an exception occurs
 */
public static Object input(final Object self, final Object endMarker, final Object prompt) throws IOException {
    final String endMarkerStr = (endMarker != UNDEFINED)? JSType.toString(endMarker) : "";
    final String promptStr = (prompt != UNDEFINED)? JSType.toString(prompt)  : ">> ";
    final StringBuilder buf = new StringBuilder();
    while (true) {
        final String line = ScriptingFunctions.readLine(promptStr);
        if (line == null || line.equals(endMarkerStr)) {
            break;
        }
        buf.append(line);
        buf.append('\n');
    }
    return buf.toString();
}
 
Example 42
Project: OpenJSharp   File: NativeSyntaxError.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("LeakingThisInConstructor")
NativeSyntaxError(final Object msg, final Global global) {
    super(global.getSyntaxErrorPrototype(), $nasgenmap$);
    if (msg != UNDEFINED) {
        this.instMessage = JSType.toString(msg);
    } else {
        this.delete(NativeError.MESSAGE, false);
    }
    NativeError.initException(this);
}
 
Example 43
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 44
Project: openjdk-jdk10   File: ParserImpl.java   Source Code and License 5 votes vote down vote up
private CompilationUnitTree parseModule(final ScriptObjectMirror scriptObj, final DiagnosticListener listener) throws NashornException {
    final Map<?, ?> map = Objects.requireNonNull(scriptObj);
    if (map.containsKey("script") && map.containsKey("name")) {
        final String script = JSType.toString(map.get("script"));
        final String name = JSType.toString(map.get("name"));
        final Source src = Source.sourceFor(name, script);
        return makeModule(src, listener);
    } else {
        throw new IllegalArgumentException("can't find 'script' and 'name' properties");
    }
}
 
Example 45
Project: openjdk-jdk10   File: NativeArrayBuffer.java   Source Code and License 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 46
Project: OpenJSharp   File: LengthNotWritableFilter.java   Source Code and License 5 votes vote down vote up
@Override
public long getLong(final int index) {
    if (index >= length()) {
        return JSType.toLong(get(index));
    }
    return underlying.getLong(index);
}
 
Example 47
Project: OpenJSharp   File: NativeArray.java   Source Code and License 5 votes vote down vote up
@Override
public Object getLength() {
    final long length = JSType.toUint32(getArray().length());
    if (length < Integer.MAX_VALUE) {
        return (int)length;
    }
    return length;
}
 
Example 48
Project: OpenJSharp   File: NativeArray.java   Source Code and License 5 votes vote down vote up
/**
 * We need to check if we are dealing with a continuous non empty array data here,
 * as pop with a primitive return value returns undefined for arrays with length 0
 */
@Override
public boolean canLink(final Object self, final CallSiteDescriptor desc, final LinkRequest request) {
    final ContinuousArrayData data = getContinuousNonEmptyArrayData(self);
    if (data != null) {
        final Class<?> elementType = data.getElementType();
        final Class<?> returnType  = desc.getMethodType().returnType();
        final boolean  typeFits    = JSType.getAccessorTypeIndex(returnType) >= JSType.getAccessorTypeIndex(elementType);
        return typeFits;
    }
    return false;
}
 
Example 49
Project: openjdk-jdk10   File: JSTypeTest.java   Source Code and License 5 votes vote down vote up
/**
 * Test of toBoolean method, of class Runtime.
 */
@Test
public void testToBoolean() {
    assertFalse(JSType.toBoolean(ScriptRuntime.UNDEFINED));
    assertFalse(JSType.toBoolean(null));
    assertFalse(JSType.toBoolean(Boolean.FALSE));
    assertTrue(JSType.toBoolean(Boolean.TRUE));
    assertFalse(JSType.toBoolean(-0.0));
    assertFalse(JSType.toBoolean(0.0));
    assertFalse(JSType.toBoolean(Double.NaN));
    assertTrue(JSType.toBoolean(3.14));
    assertFalse(JSType.toBoolean(""));
    assertTrue(JSType.toBoolean("javascript"));
    assertTrue(JSType.toBoolean(new Object()));
}
 
Example 50
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 51
Project: OpenJSharp   File: NativeArray.java   Source Code and License 5 votes vote down vote up
/**
 * ECMA 15.4.4.10 Array.prototype.slice ( start [ , end ] )
 *
 * @param self  self reference
 * @param start start of slice (inclusive)
 * @param end   end of slice (optional, exclusive)
 * @return sliced array
 */
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static Object slice(final Object self, final Object start, final Object end) {
    final Object       obj                 = Global.toObject(self);
    if (!(obj instanceof ScriptObject)) {
        return ScriptRuntime.UNDEFINED;
    }

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

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

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

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

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

    return copy;
}
 
Example 52
Project: OpenJSharp   File: Lexer.java   Source Code and License 4 votes vote down vote up
/**
 * Return value of token given its token descriptor.
 *
 * @param token  Token descriptor.
 * @return JavaScript value.
 */
Object getValueOf(final long token, final boolean strict) {
    final int start = Token.descPosition(token);
    final int len   = Token.descLength(token);

    switch (Token.descType(token)) {
    case DECIMAL:
        return Lexer.valueOf(source.getString(start, len), 10); // number
    case OCTAL:
        return Lexer.valueOf(source.getString(start, len), 8); // number
    case HEXADECIMAL:
        return Lexer.valueOf(source.getString(start + 2, len - 2), 16); // number
    case FLOATING:
        final String str   = source.getString(start, len);
        final double value = Double.valueOf(str);
        if (str.indexOf('.') != -1) {
            return value; //number
        }
        //anything without an explicit decimal point is still subject to a
        //"representable as int or long" check. Then the programmer does not
        //explicitly code something as a double. For example new Color(int, int, int)
        //and new Color(float, float, float) will get ambiguous for cases like
        //new Color(1.0, 1.5, 1.5) if we don't respect the decimal point.
        //yet we don't want e.g. 1e6 to be a double unnecessarily
        if (JSType.isRepresentableAsInt(value) && !JSType.isNegativeZero(value)) {
            return (int)value;
        } else if (JSType.isRepresentableAsLong(value) && !JSType.isNegativeZero(value)) {
            return (long)value;
        }
        return value;
    case STRING:
        return source.getString(start, len); // String
    case ESCSTRING:
        return valueOfString(start, len, strict); // String
    case IDENT:
        return valueOfIdent(start, len); // String
    case REGEX:
        return valueOfPattern(start, len); // RegexToken::LexerToken
    case XML:
        return valueOfXML(start, len); // XMLToken::LexerToken
    case DIRECTIVE_COMMENT:
        return source.getString(start, len);
    default:
        break;
    }

    return null;
}
 
Example 53
Project: OpenJSharp   File: NativeDataView.java   Source Code and License 4 votes vote down vote up
/**
 * Create a new DataView object using the passed ArrayBuffer for its
 * storage. Optional byteOffset and byteLength can be used to limit the
 * section of the buffer referenced. The byteOffset indicates the offset in
 * bytes from the start of the ArrayBuffer, and the byteLength is the number
 * of bytes from the offset that this DataView will reference. If both
 * byteOffset and byteLength are omitted, the DataView spans the entire
 * ArrayBuffer range. If the byteLength is omitted, the DataView extends from
 * the given byteOffset until the end of the ArrayBuffer.
 *
 * If the given byteOffset and byteLength references an area beyond the end
 * of the ArrayBuffer an exception is raised.

 * @param newObj if this constructor was invoked with 'new' or not
 * @param self   constructor function object
 * @param args   arguments to the constructor
 * @return newly constructed DataView object
 */
@Constructor(arity = 1)
public static NativeDataView constructor(final boolean newObj, final Object self, final Object... args) {
    if (args.length == 0 || !(args[0] instanceof NativeArrayBuffer)) {
        throw typeError("not.an.arraybuffer.in.dataview");
    }

    final NativeArrayBuffer arrBuf = (NativeArrayBuffer)args[0];
    switch (args.length) {
    case 1:
        return new NativeDataView(arrBuf);
    case 2:
        return new NativeDataView(arrBuf, JSType.toInt32(args[1]));
    default:
        return new NativeDataView(arrBuf, JSType.toInt32(args[1]), JSType.toInt32(args[2]));
    }
}
 
Example 54
Project: OpenJSharp   File: NativeString.java   Source Code and License 4 votes vote down vote up
@Override
public int getInt(final int key, final int programPoint) {
    return JSType.toInt32MaybeOptimistic(get(key), programPoint);
}
 
Example 55
Project: OpenJSharp   File: NativeString.java   Source Code and License 4 votes vote down vote up
@Override
public long getLong(final long key, final int programPoint) {
    return JSType.toLongMaybeOptimistic(get(key), programPoint);
}
 
Example 56
Project: OpenJSharp   File: NativeString.java   Source Code and License 4 votes vote down vote up
@Override
public long getLong(final int key, final int programPoint) {
    return JSType.toLongMaybeOptimistic(get(key), programPoint);
}
 
Example 57
Project: OpenJSharp   File: CodeGenerator.java   Source Code and License 4 votes vote down vote up
private void toUint() {
    JSType.TO_UINT32_I.invoke(method);
}
 
Example 58
Project: openjdk-jdk10   File: DataPropertyDescriptor.java   Source Code and License 4 votes vote down vote up
@Override
public boolean isConfigurable() {
    return JSType.toBoolean(configurable);
}
 
Example 59
Project: OpenJSharp   File: NativeString.java   Source Code and License 4 votes vote down vote up
@Override
public boolean has(final Object key) {
    final Object primitiveKey = JSType.toPrimitive(key, String.class);
    final int index = ArrayIndex.getArrayIndex(primitiveKey);
    return isValidStringIndex(index) || super.has(primitiveKey);
}
 
Example 60
Project: openjdk-jdk10   File: NativeJava.java   Source Code and License 4 votes vote down vote up
/**
 * Given a script object and a Java type, converts the script object into the desired Java type. Currently it
 * performs shallow creation of Java arrays, as well as wrapping of objects in Lists, Dequeues, Queues,
 * and Collections. If conversion is not possible or fails for some reason, TypeError is thrown.
 * Example:
 * <pre>
 * var anArray = [1, "13", false]
 * var javaIntArray = Java.to(anArray, "int[]")
 * print(javaIntArray[0]) // prints 1
 * print(javaIntArray[1]) // prints 13, as string "13" was converted to number 13 as per ECMAScript ToNumber conversion
 * print(javaIntArray[2]) // prints 0, as boolean false was converted to number 0 as per ECMAScript ToNumber conversion
 * </pre>
 * @param self not used
 * @param obj the script object. Can be null.
 * @param objType either a {@link #type(Object, Object) type object} or a String describing the type of the Java
 * object to create. Can not be null. If undefined, a "default" conversion is presumed (allowing the argument to be
 * omitted).
 * @return a Java object whose value corresponds to the original script object's value. Specifically, for array
 * target types, returns a Java array of the same type with contents converted to the array's component type.
 * Converts recursively when the target type is multidimensional array. For {@link List}, {@link Deque},
 * {@link Queue}, or {@link Collection}, returns a live wrapper around the object, see {@link ListAdapter} for
 * details. Returns null if obj is null.
 * @throws ClassNotFoundException if the class described by objType is not found
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static Object to(final Object self, final Object obj, final Object objType) throws ClassNotFoundException {
    if (obj == null) {
        return null;
    }

    if (!(obj instanceof ScriptObject) && !(obj instanceof JSObject)) {
        throw typeError("not.an.object", ScriptRuntime.safeToString(obj));
    }

    final Class<?> targetClass;
    if(objType == UNDEFINED) {
        targetClass = Object[].class;
    } else {
        final StaticClass targetType;
        if(objType instanceof StaticClass) {
            targetType = (StaticClass)objType;
        } else {
            targetType = type(objType);
        }
        targetClass = targetType.getRepresentedClass();
    }

    if(targetClass.isArray()) {
        try {
            if (self instanceof SecureLookupSupplier) {
                return JSType.toJavaArrayWithLookup(obj, targetClass.getComponentType(), (SecureLookupSupplier)self);
            }
            return JSType.toJavaArray(obj, targetClass.getComponentType());
        } catch (final Exception exp) {
            throw typeError(exp, "java.array.conversion.failed", targetClass.getName());
        }
    }

    if (targetClass == List.class || targetClass == Deque.class || targetClass == Queue.class || targetClass == Collection.class) {
        return ListAdapter.create(obj);
    }

    throw typeError("unsupported.java.to.type", targetClass.getName());
}