jdk.nashorn.internal.runtime.ScriptObject Java Examples

The following examples show how to use jdk.nashorn.internal.runtime.ScriptObject. 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: ScriptObjectMirror.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void putAll(final Map<? extends String, ? extends Object> map) {
    Objects.requireNonNull(map);
    final ScriptObject oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != global);
    inGlobal(new Callable<Object>() {
        @Override public Object call() {
            for (final Map.Entry<? extends String, ? extends Object> entry : map.entrySet()) {
                final Object value = entry.getValue();
                final Object modValue = globalChanged? wrapLikeMe(value, oldGlobal) : value;
                final String key = entry.getKey();
                checkKey(key);
                sobj.set(key, unwrap(modValue, global), getCallSiteFlags());
            }
            return null;
        }
    });
}
 
Example #2
Source File: NativeString.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 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 #3
Source File: NativeArray.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * ECMA 15.4.4.2 Array.prototype.toString ( )
 *
 * @param self self reference
 * @return string representation of array
 */
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static Object toString(final Object self) {
    final Object obj = Global.toObject(self);
    if (obj instanceof ScriptObject) {
        final InvokeByName joinInvoker = getJOIN();
        final ScriptObject sobj = (ScriptObject)obj;
        try {
            final Object join = joinInvoker.getGetter().invokeExact(sobj);
            if (Bootstrap.isCallable(join)) {
                return joinInvoker.getInvoker().invokeExact(join, sobj);
            }
        } catch (final RuntimeException | Error e) {
            throw e;
        } catch (final Throwable t) {
            throw new RuntimeException(t);
        }
    }

    // FIXME: should lookup Object.prototype.toString and call that?
    return ScriptRuntime.builtinObjectToString(self);
}
 
Example #4
Source File: CodeGenerator.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
private void popBlockScope(final Block block) {
    final Label exitLabel     = new Label("block_exit");
    final Label recoveryLabel = new Label("block_catch");
    final Label skipLabel     = new Label("skip_catch");

    /* pop scope a la try-finally */
    method.loadCompilerConstant(SCOPE);
    method.invoke(ScriptObject.GET_PROTO);
    method.storeCompilerConstant(SCOPE);
    method._goto(skipLabel);
    method.label(exitLabel);

    method._catch(recoveryLabel);
    method.loadCompilerConstant(SCOPE);
    method.invoke(ScriptObject.GET_PROTO);
    method.storeCompilerConstant(SCOPE);
    method.athrow();
    method.label(skipLabel);
    method._try(block.getEntryLabel(), exitLabel, recoveryLabel, Throwable.class);
}
 
Example #5
Source File: MethodEmitter.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Helper function to generate a function signature based on stack contents
 * and argument count and return type
 *
 * @param returnType return type
 * @param argCount   argument count
 *
 * @return function signature for stack contents
 */
private String getDynamicSignature(final Type returnType, final int argCount) {
    final Type[]         paramTypes = new Type[argCount];

    int pos = 0;
    for (int i = argCount - 1; i >= 0; i--) {
        Type pt = stack.peek(pos++);
        // "erase" specific ScriptObject subtype info - except for NativeArray.
        // NativeArray is used for array/List/Deque conversion for Java calls.
        if (ScriptObject.class.isAssignableFrom(pt.getTypeClass()) &&
            !NativeArray.class.isAssignableFrom(pt.getTypeClass())) {
            pt = Type.SCRIPT_OBJECT;
        }
        paramTypes[i] = pt;
    }
    final String descriptor = Type.getMethodDescriptor(returnType, paramTypes);
    for (int i = 0; i < argCount; i++) {
        popType(paramTypes[argCount - i - 1]);
    }

    return descriptor;
}
 
Example #6
Source File: NativeArray.java    From openjdk-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 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)) {
            if (sobj.getArray().length() + args.length <= JSType.MAX_UINT) {
                final ArrayData newData = sobj.getArray().push(true, args);
                sobj.setArray(newData);
                return newData.length();
            }
            //fallthru
        }

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

        return len;
    } catch (final ClassCastException | NullPointerException e) {
        throw typeError("not.an.object", ScriptRuntime.safeToString(self));
    }
}
 
Example #7
Source File: NativeError.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Nashorn extension: Error.prototype.stack
 * "stack" property is a string typed value containing JavaScript stack frames.
 * Each frame information is separated bv "\n" character.
 *
 * @param self  self reference
 *
 * @return      value of "stack" property
 */
public static Object getStack(final Object self) {
    final ScriptObject sobj = Global.checkObject(self);
    if (sobj.has(STACK)) {
        return sobj.get(STACK);
    }

    final Object exception = ECMAException.getException(sobj);
    if (exception instanceof Throwable) {
        final Object value = getScriptStackString(sobj, (Throwable)exception);
        if (sobj.hasOwnProperty(STACK)) {
            sobj.put(STACK, value, false);
        } else {
            sobj.addOwnProperty(STACK, Attribute.NOT_ENUMERABLE, value);
        }

        return value;
    }

    return UNDEFINED;
}
 
Example #8
Source File: NativeArray.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * ECMA 15.4.4.2 Array.prototype.toString ( )
 *
 * @param self self reference
 * @return string representation of array
 */
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static Object toString(final Object self) {
    final Object obj = Global.toObject(self);
    if (obj instanceof ScriptObject) {
        final InvokeByName joinInvoker = getJOIN();
        final ScriptObject sobj = (ScriptObject)obj;
        try {
            final Object join = joinInvoker.getGetter().invokeExact(sobj);
            if (Bootstrap.isCallable(join)) {
                return joinInvoker.getInvoker().invokeExact(join, sobj);
            }
        } catch (final RuntimeException | Error e) {
            throw e;
        } catch (final Throwable t) {
            throw new RuntimeException(t);
        }
    }

    // FIXME: should lookup Object.prototype.toString and call that?
    return ScriptRuntime.builtinObjectToString(self);
}
 
Example #9
Source File: NativeArray.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * ECMA 15.4.4.2 Array.prototype.toString ( )
 *
 * @param self self reference
 * @return string representation of array
 */
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static Object toString(final Object self) {
    final Object obj = Global.toObject(self);
    if (obj instanceof ScriptObject) {
        final InvokeByName joinInvoker = getJOIN();
        final ScriptObject sobj = (ScriptObject)obj;
        try {
            final Object join = joinInvoker.getGetter().invokeExact(sobj);
            if (Bootstrap.isCallable(join)) {
                return joinInvoker.getInvoker().invokeExact(join, sobj);
            }
        } catch (final RuntimeException | Error e) {
            throw e;
        } catch (final Throwable t) {
            throw new RuntimeException(t);
        }
    }

    // FIXME: should lookup Object.prototype.toString and call that?
    return ScriptRuntime.builtinObjectToString(self);
}
 
Example #10
Source File: Compiler.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private Compiler(
        final Context context,
        final CodeInstaller installer,
        final Source source,
        final ErrorManager errors,
        final boolean isStrict,
        final boolean isOnDemand,
        final RecompilableScriptFunctionData compiledFunction,
        final TypeMap types,
        final Map<Integer, Type> invalidatedProgramPoints,
        final Object typeInformationFile,
        final int[] continuationEntryPoints,
        final ScriptObject runtimeScope) {
    this.context                  = context;
    this.env                      = context.getEnv();
    this.installer                = installer;
    this.constantData             = new ConstantData();
    this.compileUnits             = CompileUnit.createCompileUnitSet();
    this.bytecode                 = new LinkedHashMap<>();
    this.log                      = initLogger(context);
    this.source                   = source;
    this.errors                   = errors;
    this.sourceName               = FunctionNode.getSourceName(source);
    this.onDemand                 = isOnDemand;
    this.compiledFunction         = compiledFunction;
    this.types                    = types;
    this.invalidatedProgramPoints = invalidatedProgramPoints == null ? new HashMap<Integer, Type>() : invalidatedProgramPoints;
    this.typeInformationFile      = typeInformationFile;
    this.continuationEntryPoints  = continuationEntryPoints == null ? null: continuationEntryPoints.clone();
    this.typeEvaluator            = new TypeEvaluator(this, runtimeScope);
    this.firstCompileUnitName     = firstCompileUnitName();
    this.strict                   = isStrict;

    this.optimistic = env._optimistic_types;
}
 
Example #11
Source File: NativeError.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * ECMA 15.11.4.4 Error.prototype.toString ( )
 *
 * @param self  self reference
 *
 * @return this NativeError as a string
 */
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static Object toString(final Object self) {
    // Step 1 and 2 : check if 'self' is object it not throw TypeError
    Global.checkObject(self);

    final ScriptObject sobj = (ScriptObject)self;

    // Step 3 & 4 : get "name" and convert to String.
    // But if message is undefined make it "Error".
    Object name = sobj.get("name");
    if (name == UNDEFINED) {
        name = "Error";
    } else {
        name = JSType.toString(name);
    }

    // Steps 5, 6, & 7 : get "message" and convert to String.
    // if 'message' is undefined make it "" (empty String).
    Object msg = sobj.get("message");
    if (msg == UNDEFINED) {
        msg = "";
    } else {
        msg = JSType.toString(msg);
    }

    // Step 8 : if name is empty, return msg
    if (((String)name).isEmpty()) {
        return msg;
    }

    // Step 9 : if message is empty, return name
    if (((String)msg).isEmpty()) {
        return name;
    }
    // Step 10 : return name + ": " + msg
    return name + ": " + msg;
}
 
Example #12
Source File: Global.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean isError(final ScriptObject sobj) {
    final ScriptObject errorProto = getErrorPrototype();
    ScriptObject proto = sobj.getProto();
    while (proto != null) {
        if (proto == errorProto) {
            return true;
        }
        proto = proto.getProto();
    }
    return false;
}
 
Example #13
Source File: ClassEmitter.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructor from the compiler.
 *
 * @param env           Script environment
 * @param sourceName    Source name
 * @param unitClassName Compile unit class name.
 * @param strictMode    Should we generate this method in strict mode
 */
ClassEmitter(final Context context, final String sourceName, final String unitClassName, final boolean strictMode) {
    this(context,
         new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS) {
            private static final String OBJECT_CLASS  = "java/lang/Object";

            @Override
            protected String getCommonSuperClass(final String type1, final String type2) {
                try {
                    return super.getCommonSuperClass(type1, type2);
                } catch (final RuntimeException e) {
                    if (isScriptObject(Compiler.SCRIPTS_PACKAGE, type1) && isScriptObject(Compiler.SCRIPTS_PACKAGE, type2)) {
                        return className(ScriptObject.class);
                    }
                    return OBJECT_CLASS;
                }
            }
        });

    this.unitClassName        = unitClassName;
    this.constantMethodNeeded = new HashSet<>();

    cw.visit(V1_7, ACC_PUBLIC | ACC_SUPER, unitClassName, null, pathName(jdk.nashorn.internal.scripts.JS.class.getName()), null);
    cw.visitSource(sourceName, null);

    defineCommonStatics(strictMode);
}
 
Example #14
Source File: NativeObject.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Nashorn extension: setIndexedPropertiesToExternalArrayData
 *
 * @param self self reference
 * @param obj object whose index properties are backed by buffer
 * @param buf external buffer - should be a nio ByteBuffer
 * @return the 'obj' object
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static ScriptObject setIndexedPropertiesToExternalArrayData(final Object self, final Object obj, final Object buf) {
    Global.checkObject(obj);
    final ScriptObject sobj = (ScriptObject)obj;
    if (buf instanceof ByteBuffer) {
        sobj.setArray(ArrayData.allocate((ByteBuffer)buf));
    } else {
        throw typeError("not.a.bytebuffer", "setIndexedPropertiesToExternalArrayData's buf argument");
    }
    return sobj;
}
 
Example #15
Source File: ClassEmitter.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Inspect class name and decide whether we are generating a ScriptObject class.
 *
 * @param scriptPrefix the script class prefix for the current script
 * @param type         the type to check
 *
 * @return {@code true} if type is ScriptObject
 */
private static boolean isScriptObject(final String scriptPrefix, final String type) {
    if (type.startsWith(scriptPrefix)) {
        return true;
    } else if (type.equals(CompilerConstants.className(ScriptObject.class))) {
        return true;
    } else if (type.startsWith(Compiler.OBJECTS_PACKAGE)) {
        return true;
    }

    return false;
}
 
Example #16
Source File: NativeArray.java    From jdk8u_nashorn with GNU General Public License v2.0 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 double 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 #17
Source File: Global.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private synchronized ScriptFunction getBuiltinRegExp() {
    if (this.builtinRegExp == null) {
        this.builtinRegExp = initConstructorAndSwitchPoint("RegExp", ScriptFunction.class);
        final ScriptObject regExpProto = ScriptFunction.getPrototype(builtinRegExp);
        // initialize default regexp object
        this.DEFAULT_REGEXP = new NativeRegExp("(?:)", "", this, regExpProto);
        // RegExp.prototype should behave like a RegExp object. So copy the
        // properties.
        regExpProto.addBoundProperties(DEFAULT_REGEXP);
    }
    return builtinRegExp;
}
 
Example #18
Source File: Global.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * ECMA 9.9 ToObject implementation
 *
 * @param obj  an item for which to run ToObject
 * @return ToObject version of given item
 */
public static Object toObject(final Object obj) {
    if (obj == null || obj == UNDEFINED) {
        throw typeError("not.an.object", ScriptRuntime.safeToString(obj));
    }

    if (obj instanceof ScriptObject) {
        return obj;
    }

    return instance().wrapAsObject(obj);
}
 
Example #19
Source File: NativeObject.java    From openjdk-jdk9 with GNU General Public License v2.0 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 #20
Source File: ObjectClassGenerator.java    From nashorn with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Allocate and initialize a new <init> method for scopes with arguments.
 * @param classEmitter  Open class emitter.
 * @return Open method emitter.
 */
private static MethodEmitter newInitScopeWithArgumentsMethod(final ClassEmitter classEmitter) {
    final MethodEmitter init = classEmitter.init(PropertyMap.class, ScriptObject.class, ScriptObject.class);
    init.begin();
    init.load(Type.OBJECT, JAVA_THIS.slot());
    init.load(Type.OBJECT, INIT_MAP.slot());
    init.load(Type.OBJECT, INIT_SCOPE.slot());
    init.load(Type.OBJECT, INIT_ARGUMENTS.slot());
    init.invoke(constructorNoLookup(FunctionScope.class, PropertyMap.class, ScriptObject.class, ScriptObject.class));

    return init;
}
 
Example #21
Source File: JavaArgumentConverters.java    From openjdk-jdk8u with GNU General Public License v2.0 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 (isString(obj)) {
            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 #22
Source File: NativeDate.java    From jdk8u_nashorn with GNU General Public License v2.0 5 votes vote down vote up
private NativeDate(final double time, final ScriptObject proto, final PropertyMap map) {
    super(proto, map);
    final ScriptEnvironment env = Global.getEnv();

    this.time = time;
    this.timezone = env._timezone;
}
 
Example #23
Source File: PrimitiveLookup.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unused")
private static void primitiveSetter(final ScriptObject wrappedSelf, final Object self, final Object key,
                                    final boolean strict, final Object value) {
    // See ES5.1 8.7.2 PutValue (V, W)
    final String name = JSType.toString(key);
    final FindProperty find = wrappedSelf.findProperty(name, true);
    if (find == null || !(find.getProperty() instanceof UserAccessorProperty) || !find.getProperty().isWritable()) {
        if (strict) {
            throw typeError("property.not.writable", name, ScriptRuntime.safeToString(self));
        }
        return;
    }
    // property found and is a UserAccessorProperty
    find.setValue(value, strict);
}
 
Example #24
Source File: ScriptUtils.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Make a script object mirror on given object if needed.
 *
 * @param obj object to be wrapped
 * @return wrapped object
 * @throws IllegalArgumentException if obj cannot be wrapped
 */
public static ScriptObjectMirror wrap(final Object obj) {
    if (obj instanceof ScriptObjectMirror) {
        return (ScriptObjectMirror)obj;
    }

    if (obj instanceof ScriptObject) {
        final ScriptObject sobj = (ScriptObject)obj;
        return (ScriptObjectMirror) ScriptObjectMirror.wrap(sobj, Context.getGlobal());
    }

    throw new IllegalArgumentException();
}
 
Example #25
Source File: TypeEvaluator.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private static Type getPropertyType(final ScriptObject sobj, final String name) {
    final FindProperty find = sobj.findProperty(name, true);
    if (find == null) {
        return null;
    }

    final Property property      = find.getProperty();
    final Class<?> propertyClass = property.getType();
    if (propertyClass == null) {
        // propertyClass == null means its value is Undefined. It is probably not initialized yet, so we won't make
        // a type assumption yet.
        return null;
    } else if (propertyClass.isPrimitive()) {
        return Type.typeFor(propertyClass);
    }

    final ScriptObject owner = find.getOwner();
    if (property.hasGetterFunction(owner)) {
        // Can have side effects, so we can't safely evaluate it; since !propertyClass.isPrimitive(), it's Object.
        return Type.OBJECT;
    }

    // Safely evaluate the property, and return the narrowest type for the actual value (e.g. Type.INT for a boxed
    // integer).
    final Object value = property.needsDeclaration() ? ScriptRuntime.UNDEFINED : property.getObjectValue(owner, owner);
    if (value == ScriptRuntime.UNDEFINED) {
        return null;
    }
    return Type.typeFor(JSType.unboxedFieldType(value));
}
 
Example #26
Source File: NativeArray.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * ECMA 15.4.4.10 Array.prototype.slice ( start [ , end ] )
 *
 * @param self  self reference
 * @param start start of slice (inclusive)
 * @param end   end of slice (optional, exclusive)
 * @return sliced array
 */
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static Object slice(final Object self, final Object start, final Object end) {
    final Object       obj                 = Global.toObject(self);
    if (!(obj instanceof ScriptObject)) {
        return ScriptRuntime.UNDEFINED;
    }

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

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

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

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

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

    return copy;
}
 
Example #27
Source File: Global.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * These classes are generated by nasgen tool and so we have to use
 * reflection to load and create new instance of these classes.
 */
private ScriptObject initConstructor(final String name) {
    try {
        // Assuming class name pattern for built-in JS constructors.
        final StringBuilder sb = new StringBuilder("jdk.nashorn.internal.objects.");

        sb.append("Native");
        sb.append(name);
        sb.append("$Constructor");

        final Class<?>     funcClass = Class.forName(sb.toString());
        final ScriptObject res       = (ScriptObject)funcClass.newInstance();

        if (res instanceof ScriptFunction) {
            // All global constructor prototypes are not-writable,
            // not-enumerable and not-configurable.
            final ScriptFunction func = (ScriptFunction)res;
            func.modifyOwnProperty(func.getProperty("prototype"), Attribute.NON_ENUMERABLE_CONSTANT);
        }

        if (res.getProto() == null) {
            res.setProto(getObjectPrototype());
        }

        return res;

    } catch (final ClassNotFoundException | InstantiationException | IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}
 
Example #28
Source File: NativeJSON.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private static String[] getOwnKeys(final Object obj) {
    if (obj instanceof ScriptObject) {
        return ((ScriptObject)obj).getOwnKeys(false);
    } else if (obj instanceof ScriptObjectMirror) {
        return ((ScriptObjectMirror)obj).getOwnKeys(false);
    } else if (obj instanceof JSObject) {
        // No notion of "own keys" or "proto" for general JSObject! We just
        // return all keys of the object. This will be useful for POJOs
        // implementing JSObject interface.
        return ((JSObject)obj).keySet().toArray(new String[0]);
    } else {
        throw new AssertionError("should not reach here");
    }
}
 
Example #29
Source File: NativeReferenceError.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
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);
    }
}
 
Example #30
Source File: ObjectClassGenerator.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Allocate and initialize a new <init> method.
 *
 * @param classEmitter  Open class emitter.
 *
 * @return Open method emitter.
 */
private static MethodEmitter newInitMethod(final ClassEmitter classEmitter) {
    final MethodEmitter init = classEmitter.init(PropertyMap.class);
    init.begin();
    init.load(Type.OBJECT, JAVA_THIS.slot());
    init.load(Type.OBJECT, INIT_MAP.slot());
    init.invoke(constructorNoLookup(ScriptObject.class, PropertyMap.class));

    return init;
}