ScriptObject.java revision 1002:2f0161551858
1/*
2 * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package jdk.nashorn.internal.runtime;
27
28import static jdk.nashorn.internal.codegen.CompilerConstants.staticCallNoLookup;
29import static jdk.nashorn.internal.codegen.CompilerConstants.virtualCall;
30import static jdk.nashorn.internal.codegen.CompilerConstants.virtualCallNoLookup;
31import static jdk.nashorn.internal.codegen.ObjectClassGenerator.OBJECT_FIELDS_ONLY;
32import static jdk.nashorn.internal.lookup.Lookup.MH;
33import static jdk.nashorn.internal.runtime.ECMAErrors.referenceError;
34import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
35import static jdk.nashorn.internal.runtime.JSType.UNDEFINED_DOUBLE;
36import static jdk.nashorn.internal.runtime.JSType.UNDEFINED_INT;
37import static jdk.nashorn.internal.runtime.JSType.UNDEFINED_LONG;
38import static jdk.nashorn.internal.runtime.PropertyDescriptor.CONFIGURABLE;
39import static jdk.nashorn.internal.runtime.PropertyDescriptor.ENUMERABLE;
40import static jdk.nashorn.internal.runtime.PropertyDescriptor.GET;
41import static jdk.nashorn.internal.runtime.PropertyDescriptor.SET;
42import static jdk.nashorn.internal.runtime.PropertyDescriptor.VALUE;
43import static jdk.nashorn.internal.runtime.PropertyDescriptor.WRITABLE;
44import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED;
45import static jdk.nashorn.internal.runtime.UnwarrantedOptimismException.INVALID_PROGRAM_POINT;
46import static jdk.nashorn.internal.runtime.UnwarrantedOptimismException.isValid;
47import static jdk.nashorn.internal.runtime.arrays.ArrayIndex.getArrayIndex;
48import static jdk.nashorn.internal.runtime.arrays.ArrayIndex.isValidArrayIndex;
49import static jdk.nashorn.internal.runtime.linker.NashornGuards.explicitInstanceOfCheck;
50
51import java.lang.invoke.MethodHandle;
52import java.lang.invoke.MethodHandles;
53import java.lang.invoke.MethodType;
54import java.lang.invoke.SwitchPoint;
55import java.util.AbstractMap;
56import java.util.ArrayList;
57import java.util.Arrays;
58import java.util.Collection;
59import java.util.Collections;
60import java.util.HashSet;
61import java.util.Iterator;
62import java.util.LinkedHashSet;
63import java.util.List;
64import java.util.Map;
65import java.util.Set;
66import jdk.internal.dynalink.CallSiteDescriptor;
67import jdk.internal.dynalink.linker.GuardedInvocation;
68import jdk.internal.dynalink.linker.LinkRequest;
69import jdk.internal.dynalink.support.CallSiteDescriptorFactory;
70import jdk.nashorn.internal.codegen.CompilerConstants.Call;
71import jdk.nashorn.internal.codegen.ObjectClassGenerator;
72import jdk.nashorn.internal.codegen.types.Type;
73import jdk.nashorn.internal.lookup.Lookup;
74import jdk.nashorn.internal.objects.AccessorPropertyDescriptor;
75import jdk.nashorn.internal.objects.DataPropertyDescriptor;
76import jdk.nashorn.internal.objects.Global;
77import jdk.nashorn.internal.objects.NativeArray;
78import jdk.nashorn.internal.runtime.arrays.ArrayData;
79import jdk.nashorn.internal.runtime.arrays.ArrayIndex;
80import jdk.nashorn.internal.runtime.linker.Bootstrap;
81import jdk.nashorn.internal.runtime.linker.LinkerCallSite;
82import jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor;
83import jdk.nashorn.internal.runtime.linker.NashornGuards;
84
85/**
86 * Base class for generic JavaScript objects.
87 * <p>
88 * Notes:
89 * <ul>
90 * <li>The map is used to identify properties in the object.</li>
91 * <li>If the map is modified then it must be cloned and replaced.  This notifies
92 *     any code that made assumptions about the object that things have changed.
93 *     Ex. CallSites that have been validated must check to see if the map has
94 *     changed (or a map from a different object type) and hence relink the method
95 *     to call.</li>
96 * <li>Modifications of the map include adding/deleting attributes or changing a
97 *     function field value.</li>
98 * </ul>
99 */
100
101public abstract class ScriptObject implements PropertyAccess {
102    /** __proto__ special property name inside object literals. ES6 draft. */
103    public static final String PROTO_PROPERTY_NAME   = "__proto__";
104
105    /** Search fall back routine name for "no such method" */
106    public static final String NO_SUCH_METHOD_NAME   = "__noSuchMethod__";
107
108    /** Search fall back routine name for "no such property" */
109    public static final String NO_SUCH_PROPERTY_NAME = "__noSuchProperty__";
110
111    /** Per ScriptObject flag - is this a scope object? */
112    public static final int IS_SCOPE       = 1 << 0;
113
114    /** Per ScriptObject flag - is this an array object? */
115    public static final int IS_ARRAY       = 1 << 1;
116
117    /** Per ScriptObject flag - is this an arguments object? */
118    public static final int IS_ARGUMENTS   = 1 << 2;
119
120    /** Is length property not-writable? */
121    public static final int IS_LENGTH_NOT_WRITABLE = 1 << 3;
122
123    /** Is this a builtin object? */
124    public static final int IS_BUILTIN = 1 << 4;
125
126    /**
127     * Spill growth rate - by how many elements does {@link ScriptObject#primitiveSpill} and
128     * {@link ScriptObject#objectSpill} when full
129     */
130    public static final int SPILL_RATE = 8;
131
132    /** Map to property information and accessor functions. Ordered by insertion. */
133    private PropertyMap map;
134
135    /** objects proto. */
136    private ScriptObject proto;
137
138    /** Object flags. */
139    private int flags;
140
141    /** Area for primitive properties added to object after instantiation, see {@link AccessorProperty} */
142    protected long[]   primitiveSpill;
143
144    /** Area for reference properties added to object after instantiation, see {@link AccessorProperty} */
145    protected Object[] objectSpill;
146
147    /**
148     * Number of elements in the spill. This may be less than the spill array lengths, if not all of
149     * the allocated memory is in use
150     */
151    private int spillLength;
152
153    /** Indexed array data. */
154    private ArrayData arrayData;
155
156    /** Method handle to retrieve prototype of this object */
157    public static final MethodHandle GETPROTO      = findOwnMH_V("getProto", ScriptObject.class);
158
159    static final MethodHandle MEGAMORPHIC_GET    = findOwnMH_V("megamorphicGet", Object.class, String.class, boolean.class);
160    static final MethodHandle GLOBALFILTER       = findOwnMH_S("globalFilter", Object.class, Object.class);
161    static final MethodHandle DECLARE_AND_SET    = findOwnMH_V("declareAndSet", void.class, String.class, Object.class);
162
163    private static final MethodHandle TRUNCATINGFILTER   = findOwnMH_S("truncatingFilter", Object[].class, int.class, Object[].class);
164    private static final MethodHandle KNOWNFUNCPROPGUARDSELF = findOwnMH_S("knownFunctionPropertyGuardSelf", boolean.class, Object.class, PropertyMap.class, MethodHandle.class, ScriptFunction.class);
165    private static final MethodHandle KNOWNFUNCPROPGUARDPROTO = findOwnMH_S("knownFunctionPropertyGuardProto", boolean.class, Object.class, PropertyMap.class, MethodHandle.class, int.class, ScriptFunction.class);
166
167    private static final ArrayList<MethodHandle> PROTO_FILTERS = new ArrayList<>();
168
169    /** Method handle for getting the array data */
170    public static final Call GET_ARRAY          = virtualCall(MethodHandles.lookup(), ScriptObject.class, "getArray", ArrayData.class);
171
172    /** Method handle for getting the property map - debugging purposes */
173    public static final Call GET_MAP            = virtualCall(MethodHandles.lookup(), ScriptObject.class, "getMap", PropertyMap.class);
174
175    /** Method handle for setting the array data */
176    public static final Call SET_ARRAY          = virtualCall(MethodHandles.lookup(), ScriptObject.class, "setArray", void.class, ArrayData.class);
177
178    /** Method handle for getting a function argument at a given index. Used from MapCreator */
179    public static final Call GET_ARGUMENT       = virtualCall(MethodHandles.lookup(), ScriptObject.class, "getArgument", Object.class, int.class);
180
181    /** Method handle for setting a function argument at a given index. Used from MapCreator */
182    public static final Call SET_ARGUMENT       = virtualCall(MethodHandles.lookup(), ScriptObject.class, "setArgument", void.class, int.class, Object.class);
183
184    /** Method handle for getting the proto of a ScriptObject */
185    public static final Call GET_PROTO          = virtualCallNoLookup(ScriptObject.class, "getProto", ScriptObject.class);
186
187    /** Method handle for getting the proto of a ScriptObject */
188    public static final Call GET_PROTO_DEPTH    = virtualCallNoLookup(ScriptObject.class, "getProto", ScriptObject.class, int.class);
189
190    /** Method handle for setting the proto of a ScriptObject */
191    public static final Call SET_GLOBAL_OBJECT_PROTO = staticCallNoLookup(ScriptObject.class, "setGlobalObjectProto", void.class, ScriptObject.class);
192
193    /** Method handle for setting the proto of a ScriptObject after checking argument */
194    public static final Call SET_PROTO_FROM_LITERAL    = virtualCallNoLookup(ScriptObject.class, "setProtoFromLiteral", void.class, Object.class);
195
196    /** Method handle for setting the user accessors of a ScriptObject */
197    //TODO fastpath this
198    public static final Call SET_USER_ACCESSORS = virtualCall(MethodHandles.lookup(), ScriptObject.class, "setUserAccessors", void.class, String.class, ScriptFunction.class, ScriptFunction.class);
199
200    static final MethodHandle[] SET_SLOW = new MethodHandle[] {
201        findOwnMH_V("set", void.class, Object.class, int.class, boolean.class),
202        findOwnMH_V("set", void.class, Object.class, long.class, boolean.class),
203        findOwnMH_V("set", void.class, Object.class, double.class, boolean.class),
204        findOwnMH_V("set", void.class, Object.class, Object.class, boolean.class)
205    };
206
207    /** Method handle to reset the map of this ScriptObject */
208    public static final Call SET_MAP = virtualCallNoLookup(ScriptObject.class, "setMap", void.class, PropertyMap.class);
209
210    static final MethodHandle CAS_MAP           = findOwnMH_V("compareAndSetMap", boolean.class, PropertyMap.class, PropertyMap.class);
211    static final MethodHandle EXTENSION_CHECK   = findOwnMH_V("extensionCheck", boolean.class, boolean.class, String.class);
212    static final MethodHandle ENSURE_SPILL_SIZE = findOwnMH_V("ensureSpillSize", Object.class, int.class);
213
214    /**
215     * Constructor
216     */
217    public ScriptObject() {
218        this(null);
219    }
220
221    /**
222    * Constructor
223    *
224    * @param map {@link PropertyMap} used to create the initial object
225    */
226    public ScriptObject(final PropertyMap map) {
227        if (Context.DEBUG) {
228            ScriptObject.count++;
229        }
230        this.arrayData = ArrayData.EMPTY_ARRAY;
231        this.setMap(map == null ? PropertyMap.newMap() : map);
232    }
233
234    /**
235     * Constructor that directly sets the prototype to {@code proto} and property map to
236     * {@code map} without invalidating the map as calling {@link #setProto(ScriptObject)}
237     * would do. This should only be used for objects that are always constructed with the
238     * same combination of prototype and property map.
239     *
240     * @param proto the prototype object
241     * @param map intial {@link PropertyMap}
242     */
243    protected ScriptObject(final ScriptObject proto, final PropertyMap map) {
244        this(map);
245        this.proto = proto;
246    }
247
248    /**
249     * Constructor used to instantiate spill properties directly. Used from
250     * SpillObjectCreator.
251     *
252     * @param map            property maps
253     * @param primitiveSpill primitive spills
254     * @param objectSpill    reference spills
255     */
256    public ScriptObject(final PropertyMap map, final long[] primitiveSpill, final Object[] objectSpill) {
257        this(map);
258        this.primitiveSpill = primitiveSpill;
259        this.objectSpill    = objectSpill;
260        assert primitiveSpill.length == objectSpill.length : " primitive spill pool size is not the same length as object spill pool size";
261        this.spillLength = spillAllocationLength(primitiveSpill.length);
262    }
263
264    /**
265     * Check whether this is a global object
266     * @return true if global
267     */
268    protected boolean isGlobal() {
269        return false;
270    }
271
272    private static int alignUp(final int size, final int alignment) {
273        return size + alignment - 1 & ~(alignment - 1);
274    }
275
276    /**
277     * Given a number of properties, return the aligned to SPILL_RATE
278     * buffer size required for the smallest spill pool needed to
279     * house them
280     * @param nProperties number of properties
281     * @return property buffer length, a multiple of SPILL_RATE
282     */
283    public static int spillAllocationLength(final int nProperties) {
284        return alignUp(nProperties, SPILL_RATE);
285    }
286
287    /**
288     * Copy all properties from the source object with their receiver bound to the source.
289     * This function was known as mergeMap
290     *
291     * @param source The source object to copy from.
292     */
293    public void addBoundProperties(final ScriptObject source) {
294        addBoundProperties(source, source.getMap().getProperties());
295    }
296
297    /**
298     * Copy all properties from the array with their receiver bound to the source.
299     *
300     * @param source The source object to copy from.
301     * @param properties The array of properties to copy.
302     */
303    public void addBoundProperties(final ScriptObject source, final Property[] properties) {
304        PropertyMap newMap = this.getMap();
305
306        for (final Property property : properties) {
307            final String key = property.getKey();
308            final Property oldProp = newMap.findProperty(key);
309            if (oldProp == null) {
310                if (property instanceof UserAccessorProperty) {
311                    // Note: we copy accessor functions to this object which is semantically different from binding.
312                    final UserAccessorProperty prop = this.newUserAccessors(key, property.getFlags(), property.getGetterFunction(source), property.getSetterFunction(source));
313                    newMap = newMap.addPropertyNoHistory(prop);
314                } else {
315                    newMap = newMap.addPropertyBind((AccessorProperty)property, source);
316                }
317            } else {
318                // See ECMA section 10.5 Declaration Binding Instantiation
319                // step 5 processing each function declaration.
320                if (property.isFunctionDeclaration() && !oldProp.isConfigurable()) {
321                     if (oldProp instanceof UserAccessorProperty ||
322                         !(oldProp.isWritable() && oldProp.isEnumerable())) {
323                         throw typeError("cant.redefine.property", key, ScriptRuntime.safeToString(this));
324                     }
325                }
326            }
327        }
328
329        this.setMap(newMap);
330    }
331
332    /**
333     * Copy all properties from the array with their receiver bound to the source.
334     *
335     * @param source The source object to copy from.
336     * @param properties The collection of accessor properties to copy.
337     */
338    public void addBoundProperties(final Object source, final AccessorProperty[] properties) {
339        PropertyMap newMap = this.getMap();
340
341        for (final AccessorProperty property : properties) {
342            final String key = property.getKey();
343
344            if (newMap.findProperty(key) == null) {
345                newMap = newMap.addPropertyBind(property, source);
346            }
347        }
348
349        this.setMap(newMap);
350    }
351
352    /**
353     * Bind the method handle to the specified receiver, while preserving its original type (it will just ignore the
354     * first argument in lieu of the bound argument).
355     * @param methodHandle Method handle to bind to.
356     * @param receiver     Object to bind.
357     * @return Bound method handle.
358     */
359    static MethodHandle bindTo(final MethodHandle methodHandle, final Object receiver) {
360        return MH.dropArguments(MH.bindTo(methodHandle, receiver), 0, methodHandle.type().parameterType(0));
361    }
362
363    /**
364     * Return a property iterator.
365     * @return Property iterator.
366     */
367    public Iterator<String> propertyIterator() {
368        return new KeyIterator(this);
369    }
370
371    /**
372     * Return a property value iterator.
373     * @return Property value iterator.
374     */
375    public Iterator<Object> valueIterator() {
376        return new ValueIterator(this);
377    }
378
379    /**
380     * ECMA 8.10.1 IsAccessorDescriptor ( Desc )
381     * @return true if this has a {@link AccessorPropertyDescriptor} with a getter or a setter
382     */
383    public final boolean isAccessorDescriptor() {
384        return has(GET) || has(SET);
385    }
386
387    /**
388     * ECMA 8.10.2 IsDataDescriptor ( Desc )
389     * @return true if this has a {@link DataPropertyDescriptor}, i.e. the object has a property value and is writable
390     */
391    public final boolean isDataDescriptor() {
392        return has(VALUE) || has(WRITABLE);
393    }
394
395    /**
396     * ECMA 8.10.3 IsGenericDescriptor ( Desc )
397     * @return true if this has a descriptor describing an {@link AccessorPropertyDescriptor} or {@link DataPropertyDescriptor}
398     */
399    public final boolean isGenericDescriptor() {
400        return isAccessorDescriptor() || isDataDescriptor();
401    }
402
403    /**
404      * ECMA 8.10.5 ToPropertyDescriptor ( Obj )
405      *
406      * @return property descriptor
407      */
408    public final PropertyDescriptor toPropertyDescriptor() {
409        final Global global = Context.getGlobal();
410
411        final PropertyDescriptor desc;
412        if (isDataDescriptor()) {
413            if (has(SET) || has(GET)) {
414                throw typeError(global, "inconsistent.property.descriptor");
415            }
416
417            desc = global.newDataDescriptor(UNDEFINED, false, false, false);
418        } else if (isAccessorDescriptor()) {
419            if (has(VALUE) || has(WRITABLE)) {
420                throw typeError(global, "inconsistent.property.descriptor");
421            }
422
423            desc = global.newAccessorDescriptor(UNDEFINED, UNDEFINED, false, false);
424        } else {
425            desc = global.newGenericDescriptor(false, false);
426        }
427
428        return desc.fillFrom(this);
429    }
430
431    /**
432     * ECMA 8.10.5 ToPropertyDescriptor ( Obj )
433     *
434     * @param global  global scope object
435     * @param obj object to create property descriptor from
436     *
437     * @return property descriptor
438     */
439    public static PropertyDescriptor toPropertyDescriptor(final Global global, final Object obj) {
440        if (obj instanceof ScriptObject) {
441            return ((ScriptObject)obj).toPropertyDescriptor();
442        }
443
444        throw typeError(global, "not.an.object", ScriptRuntime.safeToString(obj));
445    }
446
447    /**
448     * ECMA 8.12.1 [[GetOwnProperty]] (P)
449     *
450     * @param key property key
451     *
452     * @return Returns the Property Descriptor of the named own property of this
453     * object, or undefined if absent.
454     */
455    public Object getOwnPropertyDescriptor(final String key) {
456        final Property property = getMap().findProperty(key);
457
458        final Global global = Context.getGlobal();
459
460        if (property != null) {
461            final ScriptFunction get   = property.getGetterFunction(this);
462            final ScriptFunction set   = property.getSetterFunction(this);
463
464            final boolean configurable = property.isConfigurable();
465            final boolean enumerable   = property.isEnumerable();
466            final boolean writable     = property.isWritable();
467
468            if (property instanceof UserAccessorProperty) {
469                return global.newAccessorDescriptor(
470                    get != null ?
471                        get :
472                        UNDEFINED,
473                    set != null ?
474                        set :
475                        UNDEFINED,
476                    configurable,
477                    enumerable);
478            }
479
480            return global.newDataDescriptor(getWithProperty(property), configurable, enumerable, writable);
481        }
482
483        final int index = getArrayIndex(key);
484        final ArrayData array = getArray();
485
486        if (array.has(index)) {
487            return array.getDescriptor(global, index);
488        }
489
490        return UNDEFINED;
491    }
492
493    /**
494     * ECMA 8.12.2 [[GetProperty]] (P)
495     *
496     * @param key property key
497     *
498     * @return Returns the fully populated Property Descriptor of the named property
499     * of this object, or undefined if absent.
500     */
501    public Object getPropertyDescriptor(final String key) {
502        final Object res = getOwnPropertyDescriptor(key);
503
504        if (res != UNDEFINED) {
505            return res;
506        } else if (getProto() != null) {
507            return getProto().getOwnPropertyDescriptor(key);
508        } else {
509            return UNDEFINED;
510        }
511    }
512
513    /**
514     * ECMA 8.12.9 [[DefineOwnProperty]] (P, Desc, Throw)
515     *
516     * @param key the property key
517     * @param propertyDesc the property descriptor
518     * @param reject is the property extensible - true means new definitions are rejected
519     *
520     * @return true if property was successfully defined
521     */
522    public boolean defineOwnProperty(final String key, final Object propertyDesc, final boolean reject) {
523        final Global             global  = Context.getGlobal();
524        final PropertyDescriptor desc    = toPropertyDescriptor(global, propertyDesc);
525        final Object             current = getOwnPropertyDescriptor(key);
526        final String             name    = JSType.toString(key);
527
528        if (current == UNDEFINED) {
529            if (isExtensible()) {
530                // add a new own property
531                addOwnProperty(key, desc);
532                return true;
533            }
534            // new property added to non-extensible object
535            if (reject) {
536                throw typeError(global, "object.non.extensible", name, ScriptRuntime.safeToString(this));
537            }
538            return false;
539        }
540
541        // modifying an existing property
542        final PropertyDescriptor currentDesc = (PropertyDescriptor)current;
543        final PropertyDescriptor newDesc     = desc;
544
545        if (newDesc.type() == PropertyDescriptor.GENERIC && !newDesc.has(CONFIGURABLE) && !newDesc.has(ENUMERABLE)) {
546            // every descriptor field is absent
547            return true;
548        }
549
550        if (newDesc.hasAndEquals(currentDesc)) {
551            // every descriptor field of the new is same as the current
552            return true;
553        }
554
555        if (!currentDesc.isConfigurable()) {
556            if (newDesc.has(CONFIGURABLE) && newDesc.isConfigurable()) {
557                // not configurable can not be made configurable
558                if (reject) {
559                    throw typeError(global, "cant.redefine.property", name, ScriptRuntime.safeToString(this));
560                }
561                return false;
562            }
563
564            if (newDesc.has(ENUMERABLE) &&
565                currentDesc.isEnumerable() != newDesc.isEnumerable()) {
566                // cannot make non-enumerable as enumerable or vice-versa
567                if (reject) {
568                    throw typeError(global, "cant.redefine.property", name, ScriptRuntime.safeToString(this));
569                }
570                return false;
571            }
572        }
573
574        int propFlags = Property.mergeFlags(currentDesc, newDesc);
575        Property property = getMap().findProperty(key);
576
577        if (currentDesc.type() == PropertyDescriptor.DATA &&
578                (newDesc.type() == PropertyDescriptor.DATA ||
579                 newDesc.type() == PropertyDescriptor.GENERIC)) {
580            if (!currentDesc.isConfigurable() && !currentDesc.isWritable()) {
581                if (newDesc.has(WRITABLE) && newDesc.isWritable() ||
582                    newDesc.has(VALUE) && !ScriptRuntime.sameValue(currentDesc.getValue(), newDesc.getValue())) {
583                    if (reject) {
584                        throw typeError(global, "cant.redefine.property", name, ScriptRuntime.safeToString(this));
585                    }
586                    return false;
587                }
588            }
589
590            final boolean newValue = newDesc.has(VALUE);
591            final Object value     = newValue ? newDesc.getValue() : currentDesc.getValue();
592
593            if (newValue && property != null) {
594                // Temporarily clear flags.
595                property = modifyOwnProperty(property, 0);
596                set(key, value, false);
597                //this might change the map if we change types of the property
598                //hence we need to read it again. note that we should probably
599                //have the setter return the new property throughout and in
600                //general respect Property return values from modify and add
601                //functions - which we don't seem to do at all here :-(
602                //There is already a bug filed to generify PropertyAccess so we
603                //can have the setter return e.g. a Property
604                property = getMap().findProperty(key);
605            }
606
607            if (property == null) {
608                // promoting an arrayData value to actual property
609                addOwnProperty(key, propFlags, value);
610                checkIntegerKey(key);
611            } else {
612                // Now set the new flags
613                modifyOwnProperty(property, propFlags);
614            }
615        } else if (currentDesc.type() == PropertyDescriptor.ACCESSOR &&
616                   (newDesc.type() == PropertyDescriptor.ACCESSOR ||
617                    newDesc.type() == PropertyDescriptor.GENERIC)) {
618            if (!currentDesc.isConfigurable()) {
619                if (newDesc.has(PropertyDescriptor.GET) && !ScriptRuntime.sameValue(currentDesc.getGetter(), newDesc.getGetter()) ||
620                    newDesc.has(PropertyDescriptor.SET) && !ScriptRuntime.sameValue(currentDesc.getSetter(), newDesc.getSetter())) {
621                    if (reject) {
622                        throw typeError(global, "cant.redefine.property", name, ScriptRuntime.safeToString(this));
623                    }
624                    return false;
625                }
626            }
627            // New set the new features.
628            modifyOwnProperty(property, propFlags,
629                                      newDesc.has(GET) ? newDesc.getGetter() : currentDesc.getGetter(),
630                                      newDesc.has(SET) ? newDesc.getSetter() : currentDesc.getSetter());
631        } else {
632            // changing descriptor type
633            if (!currentDesc.isConfigurable()) {
634                // not configurable can not be made configurable
635                if (reject) {
636                    throw typeError(global, "cant.redefine.property", name, ScriptRuntime.safeToString(this));
637                }
638                return false;
639            }
640
641            propFlags = 0;
642
643            // Preserve only configurable and enumerable from current desc
644            // if those are not overridden in the new property descriptor.
645            boolean value = newDesc.has(CONFIGURABLE) ? newDesc.isConfigurable() : currentDesc.isConfigurable();
646            if (!value) {
647                propFlags |= Property.NOT_CONFIGURABLE;
648            }
649            value = newDesc.has(ENUMERABLE)? newDesc.isEnumerable() : currentDesc.isEnumerable();
650            if (!value) {
651                propFlags |= Property.NOT_ENUMERABLE;
652            }
653
654            final int type = newDesc.type();
655            if (type == PropertyDescriptor.DATA) {
656                // get writable from the new descriptor
657                value = newDesc.has(WRITABLE) && newDesc.isWritable();
658                if (!value) {
659                    propFlags |= Property.NOT_WRITABLE;
660                }
661
662                // delete the old property
663                deleteOwnProperty(property);
664                // add new data property
665                addOwnProperty(key, propFlags, newDesc.getValue());
666            } else if (type == PropertyDescriptor.ACCESSOR) {
667                if (property == null) {
668                    addOwnProperty(key, propFlags,
669                                     newDesc.has(GET) ? newDesc.getGetter() : null,
670                                     newDesc.has(SET) ? newDesc.getSetter() : null);
671                } else {
672                    // Modify old property with the new features.
673                    modifyOwnProperty(property, propFlags,
674                                        newDesc.has(GET) ? newDesc.getGetter() : null,
675                                        newDesc.has(SET) ? newDesc.getSetter() : null);
676                }
677            }
678        }
679
680        checkIntegerKey(key);
681
682        return true;
683    }
684
685    /**
686     * Almost like defineOwnProperty(int,Object) for arrays this one does
687     * not add 'gap' elements (like the array one does).
688     *
689     * @param index key for property
690     * @param value value to define
691     */
692    public void defineOwnProperty(final int index, final Object value) {
693        assert isValidArrayIndex(index) : "invalid array index";
694        final long longIndex = ArrayIndex.toLongIndex(index);
695        doesNotHaveEnsureDelete(longIndex, getArray().length(), false);
696        setArray(getArray().ensure(longIndex));
697        setArray(getArray().set(index, value, false));
698    }
699
700    private void checkIntegerKey(final String key) {
701        final int index = getArrayIndex(key);
702
703        if (isValidArrayIndex(index)) {
704            final ArrayData data = getArray();
705
706            if (data.has(index)) {
707                setArray(data.delete(index));
708            }
709        }
710    }
711
712    /**
713      * Add a new property to the object.
714      *
715      * @param key          property key
716      * @param propertyDesc property descriptor for property
717      */
718    public final void addOwnProperty(final String key, final PropertyDescriptor propertyDesc) {
719        // Already checked that there is no own property with that key.
720        PropertyDescriptor pdesc = propertyDesc;
721
722        final int propFlags = Property.toFlags(pdesc);
723
724        if (pdesc.type() == PropertyDescriptor.GENERIC) {
725            final Global global = Context.getGlobal();
726            final PropertyDescriptor dDesc = global.newDataDescriptor(UNDEFINED, false, false, false);
727
728            dDesc.fillFrom((ScriptObject)pdesc);
729            pdesc = dDesc;
730        }
731
732        final int type = pdesc.type();
733        if (type == PropertyDescriptor.DATA) {
734            addOwnProperty(key, propFlags, pdesc.getValue());
735        } else if (type == PropertyDescriptor.ACCESSOR) {
736            addOwnProperty(key, propFlags,
737                    pdesc.has(GET) ? pdesc.getGetter() : null,
738                    pdesc.has(SET) ? pdesc.getSetter() : null);
739        }
740
741        checkIntegerKey(key);
742    }
743
744    /**
745     * Low level property API (not using property descriptors)
746     * <p>
747     * Find a property in the prototype hierarchy. Note: this is final and not
748     * a good idea to override. If you have to, use
749     * {jdk.nashorn.internal.objects.NativeArray{@link #getProperty(String)} or
750     * {jdk.nashorn.internal.objects.NativeArray{@link #getPropertyDescriptor(String)} as the
751     * overriding way to find array properties
752     *
753     * @see jdk.nashorn.internal.objects.NativeArray
754     *
755     * @param key  Property key.
756     * @param deep Whether the search should look up proto chain.
757     *
758     * @return FindPropertyData or null if not found.
759     */
760    public final FindProperty findProperty(final String key, final boolean deep) {
761        return findProperty(key, deep, false, this);
762    }
763
764    /**
765     * Low level property API (not using property descriptors)
766     * <p>
767     * Find a property in the prototype hierarchy. Note: this is not a good idea
768     * to override except as it was done in {@link WithObject}.
769     * If you have to, use
770     * {jdk.nashorn.internal.objects.NativeArray{@link #getProperty(String)} or
771     * {jdk.nashorn.internal.objects.NativeArray{@link #getPropertyDescriptor(String)} as the
772     * overriding way to find array properties
773     *
774     * @see jdk.nashorn.internal.objects.NativeArray
775     *
776     * @param key  Property key.
777     * @param deep Whether the search should look up proto chain.
778     * @param stopOnNonScope should a deep search stop on the first non-scope object?
779     * @param start the object on which the lookup was originally initiated
780     *
781     * @return FindPropertyData or null if not found.
782     */
783    FindProperty findProperty(final String key, final boolean deep, final boolean stopOnNonScope, final ScriptObject start) {
784        // if doing deep search, stop search on the first non-scope object if asked to do so
785        if (stopOnNonScope && start != this && !isScope()) {
786            return null;
787        }
788
789        final PropertyMap selfMap  = getMap();
790        final Property    property = selfMap.findProperty(key);
791
792        if (property != null) {
793            return new FindProperty(start, this, property);
794        }
795
796        if (deep) {
797            final ScriptObject myProto = getProto();
798            if (myProto != null) {
799                return myProto.findProperty(key, deep, stopOnNonScope, start);
800            }
801        }
802
803        return null;
804    }
805
806    /**
807     * Low level property API. This is similar to {@link #findProperty(String, boolean)} but returns a
808     * {@code boolean} value instead of a {@link FindProperty} object.
809     * @param key  Property key.
810     * @param deep Whether the search should look up proto chain.
811     * @return true if the property was found.
812     */
813    boolean hasProperty(final String key, final boolean deep) {
814        if (getMap().findProperty(key) != null) {
815            return true;
816        }
817
818        if (deep) {
819            final ScriptObject myProto = getProto();
820            if (myProto != null) {
821                return myProto.hasProperty(key, deep);
822            }
823        }
824
825        return false;
826    }
827
828    /**
829     * Add a new property to the object.
830     * <p>
831     * This a more "low level" way that doesn't involve {@link PropertyDescriptor}s
832     *
833     * @param key             Property key.
834     * @param propertyFlags   Property flags.
835     * @param getter          Property getter, or null if not defined
836     * @param setter          Property setter, or null if not defined
837     *
838     * @return New property.
839     */
840    public final Property addOwnProperty(final String key, final int propertyFlags, final ScriptFunction getter, final ScriptFunction setter) {
841        return addOwnProperty(newUserAccessors(key, propertyFlags, getter, setter));
842    }
843
844    /**
845     * Add a new property to the object.
846     * <p>
847     * This a more "low level" way that doesn't involve {@link PropertyDescriptor}s
848     *
849     * @param key             Property key.
850     * @param propertyFlags   Property flags.
851     * @param value           Value of property
852     *
853     * @return New property.
854     */
855    public final Property addOwnProperty(final String key, final int propertyFlags, final Object value) {
856        return addSpillProperty(key, propertyFlags, value, true);
857    }
858
859    /**
860     * Add a new property to the object.
861     * <p>
862     * This a more "low level" way that doesn't involve {@link PropertyDescriptor}s
863     *
864     * @param newProperty property to add
865     *
866     * @return New property.
867     */
868    public final Property addOwnProperty(final Property newProperty) {
869        PropertyMap oldMap = getMap();
870        while (true) {
871            final PropertyMap newMap = oldMap.addProperty(newProperty);
872            if (!compareAndSetMap(oldMap, newMap)) {
873                oldMap = getMap();
874                final Property oldProperty = oldMap.findProperty(newProperty.getKey());
875
876                if (oldProperty != null) {
877                    return oldProperty;
878                }
879            } else {
880                return newProperty;
881            }
882        }
883    }
884
885    private void erasePropertyValue(final Property property) {
886        // Erase the property field value with undefined. If the property is defined
887        // by user-defined accessors, we don't want to call the setter!!
888        if (!(property instanceof UserAccessorProperty)) {
889            assert property != null;
890            property.setValue(this, this, UNDEFINED, false);
891        }
892    }
893
894    /**
895     * Delete a property from the object.
896     *
897     * @param property Property to delete.
898     *
899     * @return true if deleted.
900     */
901    public final boolean deleteOwnProperty(final Property property) {
902        erasePropertyValue(property);
903        PropertyMap oldMap = getMap();
904
905        while (true) {
906            final PropertyMap newMap = oldMap.deleteProperty(property);
907
908            if (newMap == null) {
909                return false;
910            }
911
912            if (!compareAndSetMap(oldMap, newMap)) {
913                oldMap = getMap();
914            } else {
915                // delete getter and setter function references so that we don't leak
916                if (property instanceof UserAccessorProperty) {
917                    ((UserAccessorProperty)property).setAccessors(this, getMap(), null);
918                }
919                Global.getConstants().delete(property.getKey());
920                return true;
921            }
922        }
923
924    }
925
926    /**
927     * Fast initialization functions for ScriptFunctions that are strict, to avoid
928     * creating setters that probably aren't used. Inject directly into the spill pool
929     * the defaults for "arguments" and "caller"
930     *
931     * @param key
932     * @param propertyFlags
933     * @param getter
934     * @param setter
935     */
936    protected final void initUserAccessors(final String key, final int propertyFlags, final ScriptFunction getter, final ScriptFunction setter) {
937        final int slot = spillLength;
938        ensureSpillSize(spillLength); //arguments=slot0, caller=slot0
939        objectSpill[slot] = new UserAccessorProperty.Accessors(getter, setter);
940        final PropertyMap oldMap = getMap();
941        Property    newProperty;
942        PropertyMap newMap;
943        do {
944            newProperty = new UserAccessorProperty(key, propertyFlags, slot);
945            newMap = oldMap.addProperty(newProperty);
946        } while (!compareAndSetMap(oldMap, newMap));
947    }
948
949    /**
950     * Modify a property in the object
951     *
952     * @param oldProperty    property to modify
953     * @param propertyFlags  new property flags
954     * @param getter         getter for {@link UserAccessorProperty}, null if not present or N/A
955     * @param setter         setter for {@link UserAccessorProperty}, null if not present or N/A
956     *
957     * @return new property
958     */
959    public final Property modifyOwnProperty(final Property oldProperty, final int propertyFlags, final ScriptFunction getter, final ScriptFunction setter) {
960        Property newProperty;
961
962        if (oldProperty instanceof UserAccessorProperty) {
963            final UserAccessorProperty uc = (UserAccessorProperty)oldProperty;
964            final int slot = uc.getSlot();
965
966            assert uc.getCurrentType() == Object.class;
967            if (slot >= spillLength) {
968                uc.setAccessors(this, getMap(), new UserAccessorProperty.Accessors(getter, setter));
969            } else {
970                final UserAccessorProperty.Accessors gs = uc.getAccessors(this); //this crashes
971                if (gs == null) {
972                    uc.setAccessors(this, getMap(), new UserAccessorProperty.Accessors(getter, setter));
973                } else {
974                    //reuse existing getter setter for speed
975                    gs.set(getter, setter);
976                    if (uc.getFlags() == propertyFlags) {
977                        return oldProperty;
978                    }
979                }
980            }
981            newProperty = new UserAccessorProperty(uc.getKey(), propertyFlags, slot);
982        } else {
983            // erase old property value and create new user accessor property
984            erasePropertyValue(oldProperty);
985            newProperty = newUserAccessors(oldProperty.getKey(), propertyFlags, getter, setter);
986        }
987
988        return modifyOwnProperty(oldProperty, newProperty);
989    }
990
991    /**
992      * Modify a property in the object
993      *
994      * @param oldProperty    property to modify
995      * @param propertyFlags  new property flags
996      *
997      * @return new property
998      */
999    public final Property modifyOwnProperty(final Property oldProperty, final int propertyFlags) {
1000        return modifyOwnProperty(oldProperty, oldProperty.setFlags(propertyFlags));
1001    }
1002
1003    /**
1004     * Modify a property in the object, replacing a property with a new one
1005     *
1006     * @param oldProperty   property to replace
1007     * @param newProperty   property to replace it with
1008     *
1009     * @return new property
1010     */
1011    private Property modifyOwnProperty(final Property oldProperty, final Property newProperty) {
1012        if (oldProperty == newProperty) {
1013            return newProperty; //nop
1014        }
1015
1016        assert newProperty.getKey().equals(oldProperty.getKey()) : "replacing property with different key";
1017
1018        PropertyMap oldMap = getMap();
1019
1020        while (true) {
1021            final PropertyMap newMap = oldMap.replaceProperty(oldProperty, newProperty);
1022
1023            if (!compareAndSetMap(oldMap, newMap)) {
1024                oldMap = getMap();
1025                final Property oldPropertyLookup = oldMap.findProperty(oldProperty.getKey());
1026
1027                if (oldPropertyLookup != null && oldPropertyLookup.equals(newProperty)) {
1028                    return oldPropertyLookup;
1029                }
1030            } else {
1031                return newProperty;
1032            }
1033        }
1034    }
1035
1036    /**
1037     * Update getter and setter in an object literal.
1038     *
1039     * @param key    Property key.
1040     * @param getter {@link UserAccessorProperty} defined getter, or null if none
1041     * @param setter {@link UserAccessorProperty} defined setter, or null if none
1042     */
1043    public final void setUserAccessors(final String key, final ScriptFunction getter, final ScriptFunction setter) {
1044        final Property oldProperty = getMap().findProperty(key);
1045        if (oldProperty instanceof UserAccessorProperty) {
1046            modifyOwnProperty(oldProperty, oldProperty.getFlags(), getter, setter);
1047        } else {
1048            addOwnProperty(newUserAccessors(key, oldProperty != null ? oldProperty.getFlags() : 0, getter, setter));
1049        }
1050    }
1051
1052    private static int getIntValue(final FindProperty find, final int programPoint) {
1053        final MethodHandle getter = find.getGetter(int.class, programPoint);
1054        if (getter != null) {
1055            try {
1056                return (int)getter.invokeExact((Object)find.getGetterReceiver());
1057            } catch (final Error|RuntimeException e) {
1058                throw e;
1059            } catch (final Throwable e) {
1060                throw new RuntimeException(e);
1061            }
1062        }
1063
1064        return UNDEFINED_INT;
1065    }
1066
1067    private static long getLongValue(final FindProperty find, final int programPoint) {
1068        final MethodHandle getter = find.getGetter(long.class, programPoint);
1069        if (getter != null) {
1070            try {
1071                return (long)getter.invokeExact((Object)find.getGetterReceiver());
1072            } catch (final Error|RuntimeException e) {
1073                throw e;
1074            } catch (final Throwable e) {
1075                throw new RuntimeException(e);
1076            }
1077        }
1078
1079        return UNDEFINED_LONG;
1080    }
1081
1082    private static double getDoubleValue(final FindProperty find, final int programPoint) {
1083        final MethodHandle getter = find.getGetter(double.class, programPoint);
1084        if (getter != null) {
1085            try {
1086                return (double)getter.invokeExact((Object)find.getGetterReceiver());
1087            } catch (final Error|RuntimeException e) {
1088                throw e;
1089            } catch (final Throwable e) {
1090                throw new RuntimeException(e);
1091            }
1092        }
1093
1094        return UNDEFINED_DOUBLE;
1095    }
1096
1097    /**
1098     * Return methodHandle of value function for call.
1099     *
1100     * @param find      data from find property.
1101     * @param type      method type of function.
1102     * @param bindName  null or name to bind to second argument (property not found method.)
1103     *
1104     * @return value of property as a MethodHandle or null.
1105     */
1106    protected MethodHandle getCallMethodHandle(final FindProperty find, final MethodType type, final String bindName) {
1107        return getCallMethodHandle(find.getObjectValue(), type, bindName);
1108    }
1109
1110    /**
1111     * Return methodHandle of value function for call.
1112     *
1113     * @param value     value of receiver, it not a {@link ScriptFunction} this will return null.
1114     * @param type      method type of function.
1115     * @param bindName  null or name to bind to second argument (property not found method.)
1116     *
1117     * @return value of property as a MethodHandle or null.
1118     */
1119    protected static MethodHandle getCallMethodHandle(final Object value, final MethodType type, final String bindName) {
1120        return value instanceof ScriptFunction ? ((ScriptFunction)value).getCallMethodHandle(type, bindName) : null;
1121    }
1122
1123    /**
1124     * Get value using found property.
1125     *
1126     * @param property Found property.
1127     *
1128     * @return Value of property.
1129     */
1130    public final Object getWithProperty(final Property property) {
1131        return new FindProperty(this, this, property).getObjectValue();
1132    }
1133
1134    /**
1135     * Get a property given a key
1136     *
1137     * @param key property key
1138     *
1139     * @return property for key
1140     */
1141    public final Property getProperty(final String key) {
1142        return getMap().findProperty(key);
1143    }
1144
1145    /**
1146     * Overridden by {@link jdk.nashorn.internal.objects.NativeArguments} class (internal use.)
1147     * Used for argument access in a vararg function using parameter name.
1148     * Returns the argument at a given key (index)
1149     *
1150     * @param key argument index
1151     *
1152     * @return the argument at the given position, or undefined if not present
1153     */
1154    public Object getArgument(final int key) {
1155        return get(key);
1156    }
1157
1158    /**
1159     * Overridden by {@link jdk.nashorn.internal.objects.NativeArguments} class (internal use.)
1160     * Used for argument access in a vararg function using parameter name.
1161     * Returns the argument at a given key (index)
1162     *
1163     * @param key   argument index
1164     * @param value the value to write at the given index
1165     */
1166    public void setArgument(final int key, final Object value) {
1167        set(key, value, false);
1168    }
1169
1170    /**
1171     * Return the current context from the object's map.
1172     * @return Current context.
1173     */
1174    protected Context getContext() {
1175        return Context.fromClass(getClass());
1176    }
1177
1178    /**
1179     * Return the map of an object.
1180     * @return PropertyMap object.
1181     */
1182    public final PropertyMap getMap() {
1183        return map;
1184    }
1185
1186    /**
1187     * Set the initial map.
1188     * @param map Initial map.
1189     */
1190    public final void setMap(final PropertyMap map) {
1191        this.map = map;
1192    }
1193
1194    /**
1195     * Conditionally set the new map if the old map is the same.
1196     * @param oldMap Map prior to manipulation.
1197     * @param newMap Replacement map.
1198     * @return true if the operation succeeded.
1199     */
1200    protected final boolean compareAndSetMap(final PropertyMap oldMap, final PropertyMap newMap) {
1201        if (oldMap == this.map) {
1202            this.map = newMap;
1203            return true;
1204        }
1205        return false;
1206     }
1207
1208    /**
1209     * Return the __proto__ of an object.
1210     * @return __proto__ object.
1211     */
1212    public final ScriptObject getProto() {
1213        return proto;
1214    }
1215
1216    /**
1217     * Get the proto of a specific depth
1218     * @param n depth
1219     * @return proto at given depth
1220     */
1221    public final ScriptObject getProto(final int n) {
1222        assert n > 0;
1223        ScriptObject p = getProto();
1224        for (int i = n; i-- > 0;) {
1225            p = p.getProto();
1226        }
1227        return p;
1228    }
1229
1230    /**
1231     * Set the __proto__ of an object.
1232     * @param newProto new __proto__ to set.
1233     */
1234    public final void setProto(final ScriptObject newProto) {
1235        final ScriptObject oldProto = proto;
1236
1237        if (oldProto != newProto) {
1238            proto = newProto;
1239
1240            // Let current listeners know that the protototype has changed and set our map
1241            final PropertyListeners listeners = getMap().getListeners();
1242            if (listeners != null) {
1243                listeners.protoChanged();
1244            }
1245            // Replace our current allocator map with one that is associated with the new prototype.
1246            setMap(getMap().changeProto(newProto));
1247        }
1248    }
1249
1250    /**
1251     * Set the initial __proto__ of this object. This should be used instead of
1252     * {@link #setProto} if it is known that the current property map will not be
1253     * used on a new object with any other parent property map, so we can pass over
1254     * property map invalidation/evolution.
1255     *
1256     * @param initialProto the initial __proto__ to set.
1257     */
1258    public void setInitialProto(final ScriptObject initialProto) {
1259        this.proto = initialProto;
1260    }
1261
1262    /**
1263     * Invoked from generated bytecode to initialize the prototype of object literals to the global Object prototype.
1264     * @param obj the object literal that needs to have its prototype initialized to the global Object prototype.
1265     */
1266    public static void setGlobalObjectProto(final ScriptObject obj) {
1267        obj.setInitialProto(Global.objectPrototype());
1268    }
1269
1270    /**
1271     * Set the __proto__ of an object with checks.
1272     * This is the built-in operation [[SetPrototypeOf]]
1273     * See ES6 draft spec: 9.1.2 [[SetPrototypeOf]] (V)
1274     *
1275     * @param newProto Prototype to set.
1276     */
1277    public final void setPrototypeOf(final Object newProto) {
1278        if (newProto == null || newProto instanceof ScriptObject) {
1279            if (! isExtensible()) {
1280                // okay to set same proto again - even if non-extensible
1281
1282                if (newProto == getProto()) {
1283                    return;
1284                }
1285                throw typeError("__proto__.set.non.extensible", ScriptRuntime.safeToString(this));
1286            }
1287
1288            // check for circularity
1289            ScriptObject p = (ScriptObject)newProto;
1290            while (p != null) {
1291                if (p == this) {
1292                    throw typeError("circular.__proto__.set", ScriptRuntime.safeToString(this));
1293                }
1294                p = p.getProto();
1295            }
1296            setProto((ScriptObject)newProto);
1297        } else {
1298            throw typeError("cant.set.proto.to.non.object", ScriptRuntime.safeToString(this), ScriptRuntime.safeToString(newProto));
1299        }
1300    }
1301
1302    /**
1303     * Set the __proto__ of an object from an object literal.
1304     * See ES6 draft spec: B.3.1 __proto__ Property Names in
1305     * Object Initializers. Step 6 handling of "__proto__".
1306     *
1307     * @param newProto Prototype to set.
1308     */
1309    public final void setProtoFromLiteral(final Object newProto) {
1310        if (newProto == null || newProto instanceof ScriptObject) {
1311            setPrototypeOf(newProto);
1312        } else {
1313            // Some non-object, non-null. Then, we need to set
1314            // Object.prototype as the new __proto__
1315            //
1316            // var obj = { __proto__ : 34 };
1317            // print(obj.__proto__ === Object.prototype); // => true
1318            setPrototypeOf(Global.objectPrototype());
1319        }
1320    }
1321
1322    /**
1323     * return an array of own property keys associated with the object.
1324     *
1325     * @param all True if to include non-enumerable keys.
1326     * @return Array of keys.
1327     */
1328    public final String[] getOwnKeys(final boolean all) {
1329        return getOwnKeys(all, null);
1330    }
1331
1332    /**
1333     * return an array of own property keys associated with the object.
1334     *
1335     * @param all True if to include non-enumerable keys.
1336     * @param nonEnumerable set of non-enumerable properties seen already.Used
1337       to filter out shadowed, but enumerable properties from proto children.
1338     * @return Array of keys.
1339     */
1340    protected String[] getOwnKeys(final boolean all, final Set<String> nonEnumerable) {
1341        final List<Object> keys    = new ArrayList<>();
1342        final PropertyMap  selfMap = this.getMap();
1343
1344        final ArrayData array  = getArray();
1345        final long length      = array.length();
1346
1347        for (long i = 0; i < length; i = array.nextIndex(i)) {
1348            if (array.has((int)i)) {
1349                keys.add(JSType.toString(i));
1350            }
1351        }
1352
1353        for (final Property property : selfMap.getProperties()) {
1354            final boolean enumerable = property.isEnumerable();
1355            final String key = property.getKey();
1356            if (all) {
1357                keys.add(key);
1358            } else if (enumerable) {
1359                // either we don't have non-enumerable filter set or filter set
1360                // does not contain the current property.
1361                if (nonEnumerable == null || !nonEnumerable.contains(key)) {
1362                    keys.add(key);
1363                }
1364            } else {
1365                // store this non-enumerable property for later proto walk
1366                if (nonEnumerable != null) {
1367                    nonEnumerable.add(key);
1368                }
1369            }
1370        }
1371
1372        return keys.toArray(new String[keys.size()]);
1373    }
1374
1375    /**
1376     * Check if this ScriptObject has array entries. This means that someone has
1377     * set values with numeric keys in the object.
1378     *
1379     * @return true if array entries exists.
1380     */
1381    public boolean hasArrayEntries() {
1382        return getArray().length() > 0 || getMap().containsArrayKeys();
1383    }
1384
1385    /**
1386     * Return the valid JavaScript type name descriptor
1387     *
1388     * @return "Object"
1389     */
1390    public String getClassName() {
1391        return "Object";
1392    }
1393
1394    /**
1395     * {@code length} is a well known property. This is its getter.
1396     * Note that this *may* be optimized by other classes
1397     *
1398     * @return length property value for this ScriptObject
1399     */
1400    public Object getLength() {
1401        return get("length");
1402    }
1403
1404    /**
1405     * Stateless toString for ScriptObjects.
1406     *
1407     * @return string description of this object, e.g. {@code [object Object]}
1408     */
1409    public String safeToString() {
1410        return "[object " + getClassName() + "]";
1411    }
1412
1413    /**
1414     * Return the default value of the object with a given preferred type hint.
1415     * The preferred type hints are String.class for type String, Number.class
1416     * for type Number. <p>
1417     *
1418     * A <code>hint</code> of null means "no hint".
1419     *
1420     * ECMA 8.12.8 [[DefaultValue]](hint)
1421     *
1422     * @param typeHint the preferred type hint
1423     * @return the default value
1424     */
1425    public Object getDefaultValue(final Class<?> typeHint) {
1426        // We delegate to Global, as the implementation uses dynamic call sites to invoke object's "toString" and
1427        // "valueOf" methods, and in order to avoid those call sites from becoming megamorphic when multiple contexts
1428        // are being executed in a long-running program, we move the code and their associated dynamic call sites
1429        // (Global.TO_STRING and Global.VALUE_OF) into per-context code.
1430        return Context.getGlobal().getDefaultValue(this, typeHint);
1431    }
1432
1433    /**
1434     * Checking whether a script object is an instance of another. Used
1435     * in {@link ScriptFunction} for hasInstance implementation, walks
1436     * the proto chain
1437     *
1438     * @param instance instace to check
1439     * @return true if 'instance' is an instance of this object
1440     */
1441    public boolean isInstance(final ScriptObject instance) {
1442        return false;
1443    }
1444
1445    /**
1446     * Flag this ScriptObject as non extensible
1447     *
1448     * @return the object after being made non extensible
1449     */
1450    public ScriptObject preventExtensions() {
1451        PropertyMap oldMap = getMap();
1452        while (!compareAndSetMap(oldMap,  getMap().preventExtensions())) {
1453            oldMap = getMap();
1454        }
1455
1456        //invalidate any fast array setters
1457        final ArrayData array = getArray();
1458        if (array != null) {
1459            array.invalidateSetters();
1460        }
1461        return this;
1462    }
1463
1464    /**
1465     * Check whether if an Object (not just a ScriptObject) represents JavaScript array
1466     *
1467     * @param obj object to check
1468     *
1469     * @return true if array
1470     */
1471    public static boolean isArray(final Object obj) {
1472        return obj instanceof ScriptObject && ((ScriptObject)obj).isArray();
1473    }
1474
1475    /**
1476     * Check if this ScriptObject is an array
1477     * @return true if array
1478     */
1479    public final boolean isArray() {
1480        return (flags & IS_ARRAY) != 0;
1481    }
1482
1483    /**
1484     * Flag this ScriptObject as being an array
1485     */
1486    public final void setIsArray() {
1487        flags |= IS_ARRAY;
1488    }
1489
1490    /**
1491     * Check if this ScriptObject is an {@code arguments} vector
1492     * @return true if arguments vector
1493     */
1494    public final boolean isArguments() {
1495        return (flags & IS_ARGUMENTS) != 0;
1496    }
1497
1498    /**
1499     * Flag this ScriptObject as being an {@code arguments} vector
1500     */
1501    public final void setIsArguments() {
1502        flags |= IS_ARGUMENTS;
1503    }
1504
1505    /**
1506     * Check if this object has non-writable length property
1507     *
1508     * @return {@code true} if 'length' property is non-writable
1509     */
1510    public final boolean isLengthNotWritable() {
1511        return (flags & IS_LENGTH_NOT_WRITABLE) != 0;
1512    }
1513
1514    /**
1515     * Flag this object as having non-writable length property
1516     */
1517    public void setIsLengthNotWritable() {
1518        flags |= IS_LENGTH_NOT_WRITABLE;
1519    }
1520
1521    /**
1522     * Get the {@link ArrayData} for this ScriptObject if it is an array
1523     * @return array data
1524     */
1525    public final ArrayData getArray() {
1526        return arrayData;
1527    }
1528
1529    /**
1530     * Set the {@link ArrayData} for this ScriptObject if it is to be an array
1531     * @param arrayData the array data
1532     */
1533    public final void setArray(final ArrayData arrayData) {
1534        this.arrayData = arrayData;
1535    }
1536
1537    /**
1538     * Check if this ScriptObject is extensible
1539     * @return true if extensible
1540     */
1541    public boolean isExtensible() {
1542        return getMap().isExtensible();
1543    }
1544
1545    /**
1546     * ECMAScript 15.2.3.8 - seal implementation
1547     * @return the sealed ScriptObject
1548     */
1549    public ScriptObject seal() {
1550        PropertyMap oldMap = getMap();
1551
1552        while (true) {
1553            final PropertyMap newMap = getMap().seal();
1554
1555            if (!compareAndSetMap(oldMap, newMap)) {
1556                oldMap = getMap();
1557            } else {
1558                setArray(ArrayData.seal(getArray()));
1559                return this;
1560            }
1561        }
1562    }
1563
1564    /**
1565     * Check whether this ScriptObject is sealed
1566     * @return true if sealed
1567     */
1568    public boolean isSealed() {
1569        return getMap().isSealed();
1570    }
1571
1572    /**
1573     * ECMA 15.2.39 - freeze implementation. Freeze this ScriptObject
1574     * @return the frozen ScriptObject
1575     */
1576    public ScriptObject freeze() {
1577        PropertyMap oldMap = getMap();
1578
1579        while (true) {
1580            final PropertyMap newMap = getMap().freeze();
1581
1582            if (!compareAndSetMap(oldMap, newMap)) {
1583                oldMap = getMap();
1584            } else {
1585                setArray(ArrayData.freeze(getArray()));
1586                return this;
1587            }
1588        }
1589    }
1590
1591    /**
1592     * Check whether this ScriptObject is frozen
1593     * @return true if frozen
1594     */
1595    public boolean isFrozen() {
1596        return getMap().isFrozen();
1597    }
1598
1599
1600    /**
1601     * Flag this ScriptObject as scope
1602     */
1603    public final void setIsScope() {
1604        if (Context.DEBUG) {
1605            scopeCount++;
1606        }
1607        flags |= IS_SCOPE;
1608    }
1609
1610    /**
1611     * Check whether this ScriptObject is scope
1612     * @return true if scope
1613     */
1614    public final boolean isScope() {
1615        return (flags & IS_SCOPE) != 0;
1616    }
1617
1618    /**
1619     * Tag this script object as built in
1620     */
1621    public final void setIsBuiltin() {
1622        flags |= IS_BUILTIN;
1623    }
1624
1625    /**
1626     * Check if this script object is built in
1627     * @return true if build in
1628     */
1629    public final boolean isBuiltin() {
1630        return (flags & IS_BUILTIN) != 0;
1631    }
1632
1633    /**
1634     * Clears the properties from a ScriptObject
1635     * (java.util.Map-like method to help ScriptObjectMirror implementation)
1636     *
1637     * @param strict strict mode or not
1638     */
1639    public void clear(final boolean strict) {
1640        final Iterator<String> iter = propertyIterator();
1641        while (iter.hasNext()) {
1642            delete(iter.next(), strict);
1643        }
1644    }
1645
1646    /**
1647     * Checks if a property with a given key is present in a ScriptObject
1648     * (java.util.Map-like method to help ScriptObjectMirror implementation)
1649     *
1650     * @param key the key to check for
1651     * @return true if a property with the given key exists, false otherwise
1652     */
1653    public boolean containsKey(final Object key) {
1654        return has(key);
1655    }
1656
1657    /**
1658     * Checks if a property with a given value is present in a ScriptObject
1659     * (java.util.Map-like method to help ScriptObjectMirror implementation)
1660     *
1661     * @param value value to check for
1662     * @return true if a property with the given value exists, false otherwise
1663     */
1664    public boolean containsValue(final Object value) {
1665        final Iterator<Object> iter = valueIterator();
1666        while (iter.hasNext()) {
1667            if (iter.next().equals(value)) {
1668                return true;
1669            }
1670        }
1671        return false;
1672    }
1673
1674    /**
1675     * Returns the set of {@literal <property, value>} entries that make up this
1676     * ScriptObject's properties
1677     * (java.util.Map-like method to help ScriptObjectMirror implementation)
1678     *
1679     * @return an entry set of all the properties in this object
1680     */
1681    public Set<Map.Entry<Object, Object>> entrySet() {
1682        final Iterator<String> iter = propertyIterator();
1683        final Set<Map.Entry<Object, Object>> entries = new HashSet<>();
1684        while (iter.hasNext()) {
1685            final Object key = iter.next();
1686            entries.add(new AbstractMap.SimpleImmutableEntry<>(key, get(key)));
1687        }
1688        return Collections.unmodifiableSet(entries);
1689    }
1690
1691    /**
1692     * Check whether a ScriptObject contains no properties
1693     * (java.util.Map-like method to help ScriptObjectMirror implementation)
1694     *
1695     * @return true if object has no properties
1696     */
1697    public boolean isEmpty() {
1698        return !propertyIterator().hasNext();
1699    }
1700
1701    /**
1702     * Return the set of keys (property names) for all properties
1703     * in this ScriptObject
1704     * (java.util.Map-like method to help ScriptObjectMirror implementation)
1705     *
1706     * @return keySet of this ScriptObject
1707     */
1708    public Set<Object> keySet() {
1709        final Iterator<String> iter = propertyIterator();
1710        final Set<Object> keySet = new HashSet<>();
1711        while (iter.hasNext()) {
1712            keySet.add(iter.next());
1713        }
1714        return Collections.unmodifiableSet(keySet);
1715    }
1716
1717    /**
1718     * Put a property in the ScriptObject
1719     * (java.util.Map-like method to help ScriptObjectMirror implementation)
1720     *
1721     * @param key property key
1722     * @param value property value
1723     * @param strict strict mode or not
1724     * @return oldValue if property with same key existed already
1725     */
1726    public Object put(final Object key, final Object value, final boolean strict) {
1727        final Object oldValue = get(key);
1728        set(key, value, strict);
1729        return oldValue;
1730    }
1731
1732    /**
1733     * Put several properties in the ScriptObject given a mapping
1734     * of their keys to their values
1735     * (java.util.Map-like method to help ScriptObjectMirror implementation)
1736     *
1737     * @param otherMap a {@literal <key,value>} map of properties to add
1738     * @param strict strict mode or not
1739     */
1740    public void putAll(final Map<?, ?> otherMap, final boolean strict) {
1741        for (final Map.Entry<?, ?> entry : otherMap.entrySet()) {
1742            set(entry.getKey(), entry.getValue(), strict);
1743        }
1744    }
1745
1746    /**
1747     * Remove a property from the ScriptObject.
1748     * (java.util.Map-like method to help ScriptObjectMirror implementation)
1749     *
1750     * @param key the key of the property
1751     * @param strict strict mode or not
1752     * @return the oldValue of the removed property
1753     */
1754    public Object remove(final Object key, final boolean strict) {
1755        final Object oldValue = get(key);
1756        delete(key, strict);
1757        return oldValue;
1758    }
1759
1760    /**
1761     * Return the size of the ScriptObject - i.e. the number of properties
1762     * it contains
1763     * (java.util.Map-like method to help ScriptObjectMirror implementation)
1764     *
1765     * @return number of properties in ScriptObject
1766     */
1767    public int size() {
1768        int n = 0;
1769        for (final Iterator<String> iter = propertyIterator(); iter.hasNext(); iter.next()) {
1770            n++;
1771        }
1772        return n;
1773    }
1774
1775    /**
1776     * Return the values of the properties in the ScriptObject
1777     * (java.util.Map-like method to help ScriptObjectMirror implementation)
1778     *
1779     * @return collection of values for the properties in this ScriptObject
1780     */
1781    public Collection<Object> values() {
1782        final List<Object>     values = new ArrayList<>(size());
1783        final Iterator<Object> iter   = valueIterator();
1784        while (iter.hasNext()) {
1785            values.add(iter.next());
1786        }
1787        return Collections.unmodifiableList(values);
1788    }
1789
1790    /**
1791     * Lookup method that, given a CallSiteDescriptor, looks up the target
1792     * MethodHandle and creates a GuardedInvocation
1793     * with the appropriate guard(s).
1794     *
1795     * @param desc call site descriptor
1796     * @param request the link request
1797     *
1798     * @return GuardedInvocation for the callsite
1799     */
1800    public GuardedInvocation lookup(final CallSiteDescriptor desc, final LinkRequest request) {
1801        final int c = desc.getNameTokenCount();
1802        // JavaScript is "immune" to all currently defined Dynalink composite operation - getProp is the same as getElem
1803        // is the same as getMethod as JavaScript objects have a single namespace for all three. Therefore, we don't
1804        // care about them, and just link to whatever is the first operation.
1805        final String operator = CallSiteDescriptorFactory.tokenizeOperators(desc).get(0);
1806        // NOTE: we support getElem and setItem as JavaScript doesn't distinguish items from properties. Nashorn itself
1807        // emits "dyn:getProp:identifier" for "<expr>.<identifier>" and "dyn:getElem" for "<expr>[<expr>]", but we are
1808        // more flexible here and dispatch not on operation name (getProp vs. getElem), but rather on whether the
1809        // operation has an associated name or not.
1810        switch (operator) {
1811        case "getProp":
1812        case "getElem":
1813        case "getMethod":
1814            return c > 2 ? findGetMethod(desc, request, operator) : findGetIndexMethod(desc, request);
1815        case "setProp":
1816        case "setElem":
1817            return c > 2 ? findSetMethod(desc, request) : findSetIndexMethod(desc, request);
1818        case "call":
1819            return findCallMethod(desc, request);
1820        case "new":
1821            return findNewMethod(desc, request);
1822        case "callMethod":
1823            return findCallMethodMethod(desc, request);
1824        default:
1825            return null;
1826        }
1827    }
1828
1829    /**
1830     * Find the appropriate New method for an invoke dynamic call.
1831     *
1832     * @param desc The invoke dynamic call site descriptor.
1833     * @param request The link request
1834     *
1835     * @return GuardedInvocation to be invoked at call site.
1836     */
1837    protected GuardedInvocation findNewMethod(final CallSiteDescriptor desc, final LinkRequest request) {
1838        return notAFunction();
1839    }
1840
1841    /**
1842     * Find the appropriate CALL method for an invoke dynamic call.
1843     * This generates "not a function" always
1844     *
1845     * @param desc    the call site descriptor.
1846     * @param request the link request
1847     *
1848     * @return GuardedInvocation to be invoed at call site.
1849     */
1850    protected GuardedInvocation findCallMethod(final CallSiteDescriptor desc, final LinkRequest request) {
1851        return notAFunction();
1852    }
1853
1854    private GuardedInvocation notAFunction() {
1855        throw typeError("not.a.function", ScriptRuntime.safeToString(this));
1856    }
1857
1858    /**
1859     * Find an implementation for a "dyn:callMethod" operation. Note that Nashorn internally never uses
1860     * "dyn:callMethod", but instead always emits two call sites in bytecode, one for "dyn:getMethod", and then another
1861     * one for "dyn:call". Explicit support for "dyn:callMethod" is provided for the benefit of potential external
1862     * callers. The implementation itself actually folds a "dyn:getMethod" method handle into a "dyn:call" method handle.
1863     *
1864     * @param desc    the call site descriptor.
1865     * @param request the link request
1866     *
1867     * @return GuardedInvocation to be invoked at call site.
1868     */
1869    protected GuardedInvocation findCallMethodMethod(final CallSiteDescriptor desc, final LinkRequest request) {
1870        // R(P0, P1, ...)
1871        final MethodType callType = desc.getMethodType();
1872        // use type Object(P0) for the getter
1873        final CallSiteDescriptor getterType = desc.changeMethodType(MethodType.methodType(Object.class, callType.parameterType(0)));
1874        final GuardedInvocation getter = findGetMethod(getterType, request, "getMethod");
1875
1876        // Object(P0) => Object(P0, P1, ...)
1877        final MethodHandle argDroppingGetter = MH.dropArguments(getter.getInvocation(), 1, callType.parameterList().subList(1, callType.parameterCount()));
1878        // R(Object, P0, P1, ...)
1879        final MethodHandle invoker = Bootstrap.createDynamicInvoker("dyn:call", callType.insertParameterTypes(0, argDroppingGetter.type().returnType()));
1880        // Fold Object(P0, P1, ...) into R(Object, P0, P1, ...) => R(P0, P1, ...)
1881        return getter.replaceMethods(MH.foldArguments(invoker, argDroppingGetter), getter.getGuard());
1882    }
1883
1884    /**
1885     * Test whether this object contains in its prototype chain or is itself a with-object.
1886     * @return true if a with-object was found
1887     */
1888    final boolean hasWithScope() {
1889        if (isScope()) {
1890            for (ScriptObject obj = this; obj != null; obj = obj.getProto()) {
1891                if (obj instanceof WithObject) {
1892                    return true;
1893                }
1894            }
1895        }
1896        return false;
1897    }
1898
1899    /**
1900     * Add a filter to the first argument of {@code methodHandle} that calls its {@link #getProto()} method
1901     * {@code depth} times.
1902     * @param methodHandle a method handle
1903     * @param depth        distance to target prototype
1904     * @return the filtered method handle
1905     */
1906    static MethodHandle addProtoFilter(final MethodHandle methodHandle, final int depth) {
1907        if (depth == 0) {
1908            return methodHandle;
1909        }
1910        final int listIndex = depth - 1; // We don't need 0-deep walker
1911        MethodHandle filter = listIndex < PROTO_FILTERS.size() ? PROTO_FILTERS.get(listIndex) : null;
1912
1913        if (filter == null) {
1914            filter = addProtoFilter(GETPROTO, depth - 1);
1915            PROTO_FILTERS.add(null);
1916            PROTO_FILTERS.set(listIndex, filter);
1917        }
1918
1919        return MH.filterArguments(methodHandle, 0, filter.asType(filter.type().changeReturnType(methodHandle.type().parameterType(0))));
1920    }
1921
1922    //this will only return true if apply is still builtin
1923    private static SwitchPoint checkReservedName(final CallSiteDescriptor desc, final LinkRequest request) {
1924        final boolean isApplyToCall = NashornCallSiteDescriptor.isApplyToCall(desc);
1925        final String name = desc.getNameToken(CallSiteDescriptor.NAME_OPERAND);
1926        if ("apply".equals(name) && isApplyToCall && Global.instance().isSpecialNameValid(name)) {
1927            assert Global.instance().getChangeCallback("apply") == Global.instance().getChangeCallback("call");
1928            return Global.instance().getChangeCallback("apply");
1929        }
1930        return null;
1931    }
1932
1933    /**
1934     * Find the appropriate GET method for an invoke dynamic call.
1935     *
1936     * @param desc     the call site descriptor
1937     * @param request  the link request
1938     * @param operator operator for get: getProp, getMethod, getElem etc
1939     *
1940     * @return GuardedInvocation to be invoked at call site.
1941     */
1942    protected GuardedInvocation findGetMethod(final CallSiteDescriptor desc, final LinkRequest request, final String operator) {
1943        final boolean explicitInstanceOfCheck = explicitInstanceOfCheck(desc, request);
1944        final String name;
1945        final SwitchPoint reservedNameSwitchPoint;
1946
1947        reservedNameSwitchPoint = checkReservedName(desc, request);
1948        if (reservedNameSwitchPoint != null) {
1949            name = "call"; //turn apply into call, it is the builtin apply and has been modified to explode args
1950        } else {
1951            name = desc.getNameToken(CallSiteDescriptor.NAME_OPERAND);
1952        }
1953
1954        if (request.isCallSiteUnstable() || hasWithScope()) {
1955            return findMegaMorphicGetMethod(desc, name, "getMethod".equals(operator));
1956        }
1957
1958        final FindProperty find = findProperty(name, true);
1959        MethodHandle mh;
1960
1961        if (find == null) {
1962            switch (operator) {
1963            case "getProp":
1964                return noSuchProperty(desc, request);
1965            case "getMethod":
1966                return noSuchMethod(desc, request);
1967            case "getElem":
1968                return createEmptyGetter(desc, explicitInstanceOfCheck, name);
1969            default:
1970                throw new AssertionError(operator); // never invoked with any other operation
1971            }
1972        }
1973
1974        final GuardedInvocation cinv = Global.getConstants().findGetMethod(find, this, desc, request, operator);
1975        if (cinv != null) {
1976            return cinv;
1977        }
1978
1979        final Class<?> returnType = desc.getMethodType().returnType();
1980        final Property property   = find.getProperty();
1981
1982        final int programPoint = NashornCallSiteDescriptor.isOptimistic(desc) ?
1983                NashornCallSiteDescriptor.getProgramPoint(desc) :
1984                UnwarrantedOptimismException.INVALID_PROGRAM_POINT;
1985
1986        mh = find.getGetter(returnType, programPoint);
1987        // Get the appropriate guard for this callsite and property.
1988        final MethodHandle guard = NashornGuards.getGuard(this, property, desc, explicitInstanceOfCheck);
1989        final ScriptObject owner = find.getOwner();
1990        final Class<ClassCastException> exception = explicitInstanceOfCheck ? null : ClassCastException.class;
1991
1992        final SwitchPoint protoSwitchPoint;
1993
1994        if (mh == null) {
1995            mh = Lookup.emptyGetter(returnType);
1996            protoSwitchPoint = getProtoSwitchPoint(name, owner);
1997        } else if (!find.isSelf()) {
1998            assert mh.type().returnType().equals(returnType) : "returntype mismatch for getter " + mh.type().returnType() + " != " + returnType;
1999            if (!property.hasGetterFunction(owner)) {
2000                // Add a filter that replaces the self object with the prototype owning the property.
2001                mh = addProtoFilter(mh, find.getProtoChainLength());
2002            }
2003            protoSwitchPoint = getProtoSwitchPoint(name, owner);
2004        } else {
2005            protoSwitchPoint = null;
2006        }
2007
2008        assert OBJECT_FIELDS_ONLY || guard != null : "we always need a map guard here";
2009
2010        final GuardedInvocation inv = new GuardedInvocation(mh, guard, protoSwitchPoint, exception);
2011        return inv.addSwitchPoint(reservedNameSwitchPoint);
2012    }
2013
2014    private static GuardedInvocation findMegaMorphicGetMethod(final CallSiteDescriptor desc, final String name, final boolean isMethod) {
2015        Context.getContextTrusted().getLogger(ObjectClassGenerator.class).warning("Megamorphic getter: " + desc + " " + name + " " +isMethod);
2016        final MethodHandle invoker = MH.insertArguments(MEGAMORPHIC_GET, 1, name, isMethod);
2017        final MethodHandle guard   = getScriptObjectGuard(desc.getMethodType(), true);
2018        return new GuardedInvocation(invoker, guard);
2019    }
2020
2021    @SuppressWarnings("unused")
2022    private Object megamorphicGet(final String key, final boolean isMethod) {
2023        final FindProperty find = findProperty(key, true);
2024        if (find != null) {
2025            return find.getObjectValue();
2026        }
2027
2028        return isMethod ? getNoSuchMethod(key, INVALID_PROGRAM_POINT) : invokeNoSuchProperty(key, INVALID_PROGRAM_POINT);
2029    }
2030
2031    // Marks a property as declared and sets its value. Used as slow path for block-scoped LET and CONST
2032    @SuppressWarnings("unused")
2033    private void declareAndSet(final String key, final Object value) {
2034        final PropertyMap map = getMap();
2035        final FindProperty find = findProperty(key, false);
2036        assert find != null;
2037
2038        final Property property = find.getProperty();
2039        assert property != null;
2040        assert property.needsDeclaration();
2041
2042        final PropertyMap newMap = map.replaceProperty(property, property.removeFlags(Property.NEEDS_DECLARATION));
2043        setMap(newMap);
2044        set(key, value, true);
2045    }
2046
2047    /**
2048     * Find the appropriate GETINDEX method for an invoke dynamic call.
2049     *
2050     * @param desc    the call site descriptor
2051     * @param request the link request
2052     *
2053     * @return GuardedInvocation to be invoked at call site.
2054     */
2055    protected GuardedInvocation findGetIndexMethod(final CallSiteDescriptor desc, final LinkRequest request) {
2056        final MethodType callType                = desc.getMethodType();
2057        final Class<?>   returnType              = callType.returnType();
2058        final Class<?>   returnClass             = returnType.isPrimitive() ? returnType : Object.class;
2059        final Class<?>   keyClass                = callType.parameterType(1);
2060        final boolean    explicitInstanceOfCheck = explicitInstanceOfCheck(desc, request);
2061
2062        final String name;
2063        if (returnClass.isPrimitive()) {
2064            //turn e.g. get with a double into getDouble
2065            final String returnTypeName = returnClass.getName();
2066            name = "get" + Character.toUpperCase(returnTypeName.charAt(0)) + returnTypeName.substring(1, returnTypeName.length());
2067        } else {
2068            name = "get";
2069        }
2070
2071        final MethodHandle mh = findGetIndexMethodHandle(returnClass, name, keyClass, desc);
2072        return new GuardedInvocation(mh, getScriptObjectGuard(callType, explicitInstanceOfCheck), (SwitchPoint)null, explicitInstanceOfCheck ? null : ClassCastException.class);
2073    }
2074
2075    private static MethodHandle getScriptObjectGuard(final MethodType type, final boolean explicitInstanceOfCheck) {
2076        return ScriptObject.class.isAssignableFrom(type.parameterType(0)) ? null : NashornGuards.getScriptObjectGuard(explicitInstanceOfCheck);
2077    }
2078
2079    /**
2080     * Find a handle for a getIndex method
2081     * @param returnType     return type for getter
2082     * @param name           name
2083     * @param elementType    index type for getter
2084     * @param desc           call site descriptor
2085     * @return method handle for getter
2086     */
2087    protected MethodHandle findGetIndexMethodHandle(final Class<?> returnType, final String name, final Class<?> elementType, final CallSiteDescriptor desc) {
2088        if (!returnType.isPrimitive()) {
2089            return findOwnMH_V(getClass(), name, returnType, elementType);
2090        }
2091
2092        return MH.insertArguments(
2093                findOwnMH_V(getClass(), name, returnType, elementType, int.class),
2094                2,
2095                NashornCallSiteDescriptor.isOptimistic(desc) ?
2096                        NashornCallSiteDescriptor.getProgramPoint(desc) :
2097                        INVALID_PROGRAM_POINT);
2098    }
2099
2100    /**
2101     * Get a switch point for a property with the given {@code name} that will be invalidated when
2102     * the property definition is changed in this object's prototype chain. Returns {@code null} if
2103     * the property is defined in this object itself.
2104     *
2105     * @param name the property name
2106     * @param owner the property owner, null if property is not defined
2107     * @return a SwitchPoint or null
2108     */
2109    public final SwitchPoint getProtoSwitchPoint(final String name, final ScriptObject owner) {
2110        if (owner == this || getProto() == null) {
2111            return null;
2112        }
2113
2114        for (ScriptObject obj = this; obj != owner && obj.getProto() != null; obj = obj.getProto()) {
2115            final ScriptObject parent = obj.getProto();
2116            parent.getMap().addListener(name, obj.getMap());
2117        }
2118
2119        return getMap().getSwitchPoint(name);
2120    }
2121
2122    /**
2123     * Find the appropriate SET method for an invoke dynamic call.
2124     *
2125     * @param desc    the call site descriptor
2126     * @param request the link request
2127     *
2128     * @return GuardedInvocation to be invoked at call site.
2129     */
2130    protected GuardedInvocation findSetMethod(final CallSiteDescriptor desc, final LinkRequest request) {
2131        final String name = desc.getNameToken(CallSiteDescriptor.NAME_OPERAND);
2132
2133        if (request.isCallSiteUnstable() || hasWithScope()) {
2134            return findMegaMorphicSetMethod(desc, name);
2135        }
2136
2137        final boolean scope                   = isScope();
2138        final boolean explicitInstanceOfCheck = explicitInstanceOfCheck(desc, request);
2139
2140        /*
2141         * If doing property set on a scope object, we should stop proto search on the first
2142         * non-scope object. Without this, for example, when assigning "toString" on global scope,
2143         * we'll end up assigning it on it's proto - which is Object.prototype.toString !!
2144         *
2145         * toString = function() { print("global toString"); } // don't affect Object.prototype.toString
2146         */
2147        FindProperty find = findProperty(name, true, scope, this);
2148
2149        // If it's not a scope search, then we don't want any inherited properties except those with user defined accessors.
2150        if (!scope && find != null && find.isInherited() && !(find.getProperty() instanceof UserAccessorProperty)) {
2151            // We should still check if inherited data property is not writable
2152            if (isExtensible() && !find.getProperty().isWritable()) {
2153                return createEmptySetMethod(desc, explicitInstanceOfCheck, "property.not.writable", false);
2154            }
2155            // Otherwise, forget the found property
2156            find = null;
2157        }
2158
2159        if (find != null) {
2160            if (!find.getProperty().isWritable() && !NashornCallSiteDescriptor.isDeclaration(desc)) {
2161                // Existing, non-writable property
2162                return createEmptySetMethod(desc, explicitInstanceOfCheck, "property.not.writable", true);
2163            }
2164        } else {
2165            if (!isExtensible()) {
2166                return createEmptySetMethod(desc, explicitInstanceOfCheck, "object.non.extensible", false);
2167            }
2168        }
2169
2170        final GuardedInvocation inv = new SetMethodCreator(this, find, desc, explicitInstanceOfCheck).createGuardedInvocation();
2171
2172        final GuardedInvocation cinv = Global.getConstants().findSetMethod(find, this, inv, desc, request);
2173        if (cinv != null) {
2174            return cinv;
2175        }
2176
2177        return inv;
2178    }
2179
2180    private GuardedInvocation createEmptySetMethod(final CallSiteDescriptor desc, final boolean explicitInstanceOfCheck, final String strictErrorMessage, final boolean canBeFastScope) {
2181        final String  name = desc.getNameToken(CallSiteDescriptor.NAME_OPERAND);
2182         if (NashornCallSiteDescriptor.isStrict(desc)) {
2183           throw typeError(strictErrorMessage, name, ScriptRuntime.safeToString(this));
2184        }
2185        assert canBeFastScope || !NashornCallSiteDescriptor.isFastScope(desc);
2186        return new GuardedInvocation(
2187                Lookup.EMPTY_SETTER,
2188                NashornGuards.getMapGuard(getMap(), explicitInstanceOfCheck),
2189                getProtoSwitchPoint(name, null),
2190                explicitInstanceOfCheck ? null : ClassCastException.class);
2191    }
2192
2193    @SuppressWarnings("unused")
2194    private boolean extensionCheck(final boolean isStrict, final String name) {
2195        if (isExtensible()) {
2196            return true; //go on and do the set. this is our guard
2197        } else if (isStrict) {
2198            //throw an error for attempting to do the set in strict mode
2199            throw typeError("object.non.extensible", name, ScriptRuntime.safeToString(this));
2200        } else {
2201            //not extensible, non strict - this is a nop
2202            return false;
2203        }
2204    }
2205
2206    private GuardedInvocation findMegaMorphicSetMethod(final CallSiteDescriptor desc, final String name) {
2207        final MethodType        type = desc.getMethodType().insertParameterTypes(1, Object.class);
2208        //never bother with ClassCastExceptionGuard for megamorphic callsites
2209        final GuardedInvocation inv = findSetIndexMethod(getClass(), false, type, NashornCallSiteDescriptor.isStrict(desc));
2210        return inv.replaceMethods(MH.insertArguments(inv.getInvocation(), 1, name), inv.getGuard());
2211    }
2212
2213    @SuppressWarnings("unused")
2214    private static Object globalFilter(final Object object) {
2215        ScriptObject sobj = (ScriptObject) object;
2216        while (sobj != null && !(sobj instanceof Global)) {
2217            sobj = sobj.getProto();
2218        }
2219        return sobj;
2220    }
2221
2222    /**
2223     * Lookup function for the set index method, available for subclasses as well, e.g. {@link NativeArray}
2224     * provides special quick accessor linkage for continuous arrays that are represented as Java arrays
2225     *
2226     * @param desc    call site descriptor
2227     * @param request link request
2228     *
2229     * @return GuardedInvocation to be invoked at call site.
2230     */
2231    protected GuardedInvocation findSetIndexMethod(final CallSiteDescriptor desc, final LinkRequest request) { // array, index, value
2232        return findSetIndexMethod(getClass(), explicitInstanceOfCheck(desc, request), desc.getMethodType(), NashornCallSiteDescriptor.isStrict(desc));
2233    }
2234
2235    /**
2236     * Find the appropriate SETINDEX method for an invoke dynamic call.
2237     *
2238     * @param callType the method type at the call site
2239     * @param isStrict are we in strict mode?
2240     *
2241     * @return GuardedInvocation to be invoked at call site.
2242     */
2243    private static GuardedInvocation findSetIndexMethod(final Class<? extends ScriptObject> clazz, final boolean explicitInstanceOfCheck, final MethodType callType, final boolean isStrict) {
2244        assert callType.parameterCount() == 3;
2245        final Class<?> keyClass   = callType.parameterType(1);
2246        final Class<?> valueClass = callType.parameterType(2);
2247
2248        MethodHandle methodHandle = findOwnMH_V(clazz, "set", void.class, keyClass, valueClass, boolean.class);
2249        methodHandle = MH.insertArguments(methodHandle, 3, isStrict);
2250
2251        return new GuardedInvocation(methodHandle, getScriptObjectGuard(callType, explicitInstanceOfCheck), (SwitchPoint)null, explicitInstanceOfCheck ? null : ClassCastException.class);
2252    }
2253
2254    /**
2255     * Fall back if a function property is not found.
2256     * @param desc The call site descriptor
2257     * @param request the link request
2258     * @return GuardedInvocation to be invoked at call site.
2259     */
2260    public GuardedInvocation noSuchMethod(final CallSiteDescriptor desc, final LinkRequest request) {
2261        final String       name      = desc.getNameToken(2);
2262        final FindProperty find      = findProperty(NO_SUCH_METHOD_NAME, true);
2263        final boolean      scopeCall = isScope() && NashornCallSiteDescriptor.isScope(desc);
2264
2265        if (find == null) {
2266            return noSuchProperty(desc, request);
2267        }
2268
2269        final boolean explicitInstanceOfCheck = explicitInstanceOfCheck(desc, request);
2270
2271        final Object value = find.getObjectValue();
2272        if (!(value instanceof ScriptFunction)) {
2273            return createEmptyGetter(desc, explicitInstanceOfCheck, name);
2274        }
2275
2276        final ScriptFunction func = (ScriptFunction)value;
2277        final Object         thiz = scopeCall && func.isStrict() ? ScriptRuntime.UNDEFINED : this;
2278        // TODO: It'd be awesome if we could bind "name" without binding "this".
2279        return new GuardedInvocation(
2280                MH.dropArguments(
2281                        MH.constant(
2282                                ScriptFunction.class,
2283                                func.makeBoundFunction(thiz, new Object[] { name })),
2284                        0,
2285                        Object.class),
2286                NashornGuards.getMapGuard(getMap(), explicitInstanceOfCheck),
2287                (SwitchPoint)null,
2288                explicitInstanceOfCheck ? null : ClassCastException.class);
2289    }
2290
2291    /**
2292     * Fall back if a property is not found.
2293     * @param desc the call site descriptor.
2294     * @param request the link request
2295     * @return GuardedInvocation to be invoked at call site.
2296     */
2297    public GuardedInvocation noSuchProperty(final CallSiteDescriptor desc, final LinkRequest request) {
2298        final String       name        = desc.getNameToken(CallSiteDescriptor.NAME_OPERAND);
2299        final FindProperty find        = findProperty(NO_SUCH_PROPERTY_NAME, true);
2300        final boolean      scopeAccess = isScope() && NashornCallSiteDescriptor.isScope(desc);
2301
2302        if (find != null) {
2303            final Object   value = find.getObjectValue();
2304            ScriptFunction func  = null;
2305            MethodHandle   mh    = null;
2306
2307            if (value instanceof ScriptFunction) {
2308                func = (ScriptFunction)value;
2309                mh   = getCallMethodHandle(func, desc.getMethodType(), name);
2310            }
2311
2312            if (mh != null) {
2313                assert func != null;
2314                if (scopeAccess && func.isStrict()) {
2315                    mh = bindTo(mh, UNDEFINED);
2316                }
2317
2318                return new GuardedInvocation(
2319                        mh,
2320                        find.isSelf()?
2321                            getKnownFunctionPropertyGuardSelf(
2322                                getMap(),
2323                                find.getGetter(Object.class, INVALID_PROGRAM_POINT),
2324                                func)
2325                            :
2326                            //TODO this always does a scriptobject check
2327                            getKnownFunctionPropertyGuardProto(
2328                                getMap(),
2329                                find.getGetter(Object.class, INVALID_PROGRAM_POINT),
2330                                find.getProtoChainLength(),
2331                                func),
2332                        getProtoSwitchPoint(NO_SUCH_PROPERTY_NAME, find.getOwner()),
2333                        //TODO this doesn't need a ClassCastException as guard always checks script object
2334                        null);
2335            }
2336        }
2337
2338        if (scopeAccess) {
2339            throw referenceError("not.defined", name);
2340        }
2341
2342        return createEmptyGetter(desc, explicitInstanceOfCheck(desc, request), name);
2343    }
2344
2345    /**
2346     * Invoke fall back if a property is not found.
2347     * @param name Name of property.
2348     * @param programPoint program point
2349     * @return Result from call.
2350     */
2351    protected Object invokeNoSuchProperty(final String name, final int programPoint) {
2352        final FindProperty find = findProperty(NO_SUCH_PROPERTY_NAME, true);
2353
2354        Object ret = UNDEFINED;
2355
2356        if (find != null) {
2357            final Object func = find.getObjectValue();
2358
2359            if (func instanceof ScriptFunction) {
2360                ret = ScriptRuntime.apply((ScriptFunction)func, this, name);
2361            }
2362        }
2363
2364        if (isValid(programPoint)) {
2365            throw new UnwarrantedOptimismException(ret, programPoint);
2366        }
2367
2368        return ret;
2369    }
2370
2371
2372    /**
2373     * Get __noSuchMethod__ as a function bound to this object and {@code name} if it is defined.
2374     * @param name the method name
2375     * @return the bound function, or undefined
2376     */
2377    private Object getNoSuchMethod(final String name, final int programPoint) {
2378        final FindProperty find = findProperty(NO_SUCH_METHOD_NAME, true);
2379
2380        if (find == null) {
2381            return invokeNoSuchProperty(name, programPoint);
2382        }
2383
2384        final Object value = find.getObjectValue();
2385        if (!(value instanceof ScriptFunction)) {
2386            return UNDEFINED;
2387        }
2388
2389        return ((ScriptFunction)value).makeBoundFunction(this, new Object[] {name});
2390    }
2391
2392    private GuardedInvocation createEmptyGetter(final CallSiteDescriptor desc, final boolean explicitInstanceOfCheck, final String name) {
2393        if (NashornCallSiteDescriptor.isOptimistic(desc)) {
2394            throw new UnwarrantedOptimismException(UNDEFINED, NashornCallSiteDescriptor.getProgramPoint(desc), Type.OBJECT);
2395        }
2396
2397        return new GuardedInvocation(Lookup.emptyGetter(desc.getMethodType().returnType()),
2398                NashornGuards.getMapGuard(getMap(), explicitInstanceOfCheck), getProtoSwitchPoint(name, null),
2399                explicitInstanceOfCheck ? null : ClassCastException.class);
2400    }
2401
2402    private abstract static class ScriptObjectIterator <T extends Object> implements Iterator<T> {
2403        protected T[] values;
2404        protected final ScriptObject object;
2405        private int index;
2406
2407        ScriptObjectIterator(final ScriptObject object) {
2408            this.object = object;
2409        }
2410
2411        protected abstract void init();
2412
2413        @Override
2414        public boolean hasNext() {
2415            if (values == null) {
2416                init();
2417            }
2418            return index < values.length;
2419        }
2420
2421        @Override
2422        public T next() {
2423            if (values == null) {
2424                init();
2425            }
2426            return values[index++];
2427        }
2428
2429        @Override
2430        public void remove() {
2431            throw new UnsupportedOperationException();
2432        }
2433    }
2434
2435    private static class KeyIterator extends ScriptObjectIterator<String> {
2436        KeyIterator(final ScriptObject object) {
2437            super(object);
2438        }
2439
2440        @Override
2441        protected void init() {
2442            final Set<String> keys = new LinkedHashSet<>();
2443            final Set<String> nonEnumerable = new HashSet<>();
2444            for (ScriptObject self = object; self != null; self = self.getProto()) {
2445                keys.addAll(Arrays.asList(self.getOwnKeys(false, nonEnumerable)));
2446            }
2447            this.values = keys.toArray(new String[keys.size()]);
2448        }
2449    }
2450
2451    private static class ValueIterator extends ScriptObjectIterator<Object> {
2452        ValueIterator(final ScriptObject object) {
2453            super(object);
2454        }
2455
2456        @Override
2457        protected void init() {
2458            final ArrayList<Object> valueList = new ArrayList<>();
2459            final Set<String> nonEnumerable = new HashSet<>();
2460            for (ScriptObject self = object; self != null; self = self.getProto()) {
2461                for (final String key : self.getOwnKeys(false, nonEnumerable)) {
2462                    valueList.add(self.get(key));
2463                }
2464            }
2465            this.values = valueList.toArray(new Object[valueList.size()]);
2466        }
2467    }
2468
2469    /**
2470     * Add a spill property for the given key.
2471     * @param key           Property key.
2472     * @param propertyFlags Property flags.
2473     * @return Added property.
2474     */
2475    private Property addSpillProperty(final String key, final int propertyFlags, final Object value, final boolean hasInitialValue) {
2476        final PropertyMap propertyMap = getMap();
2477        final int fieldSlot  = propertyMap.getFreeFieldSlot();
2478
2479        Property property;
2480        if (fieldSlot > -1) {
2481            property = hasInitialValue ?
2482                new AccessorProperty(key, propertyFlags, fieldSlot, this, value) :
2483                new AccessorProperty(key, propertyFlags, getClass(), fieldSlot);
2484            property = addOwnProperty(property);
2485        } else {
2486            final int spillSlot = propertyMap.getFreeSpillSlot();
2487            property = hasInitialValue ?
2488                new SpillProperty(key, propertyFlags, spillSlot, this, value) :
2489                new SpillProperty(key, propertyFlags, spillSlot);
2490            property = addOwnProperty(property);
2491            ensureSpillSize(property.getSlot());
2492        }
2493        return property;
2494    }
2495
2496    /**
2497     * Add a spill entry for the given key.
2498     * @param key Property key.
2499     * @return Setter method handle.
2500     */
2501    MethodHandle addSpill(final Class<?> type, final String key) {
2502        return addSpillProperty(key, 0, null, false).getSetter(OBJECT_FIELDS_ONLY ? Object.class : type, getMap());
2503    }
2504
2505    /**
2506     * Make sure arguments are paired correctly, with respect to more parameters than declared,
2507     * fewer parameters than declared and other things that JavaScript allows. This might involve
2508     * creating collectors.
2509     *
2510     * @param methodHandle method handle for invoke
2511     * @param callType     type of the call
2512     *
2513     * @return method handle with adjusted arguments
2514     */
2515    protected static MethodHandle pairArguments(final MethodHandle methodHandle, final MethodType callType) {
2516        return pairArguments(methodHandle, callType, null);
2517    }
2518
2519    /**
2520     * Make sure arguments are paired correctly, with respect to more parameters than declared,
2521     * fewer parameters than declared and other things that JavaScript allows. This might involve
2522     * creating collectors.
2523     *
2524     * Make sure arguments are paired correctly.
2525     * @param methodHandle MethodHandle to adjust.
2526     * @param callType     MethodType of the call site.
2527     * @param callerVarArg true if the caller is vararg, false otherwise, null if it should be inferred from the
2528     * {@code callType}; basically, if the last parameter type of the call site is an array, it'll be considered a
2529     * variable arity call site. These are ordinarily rare; Nashorn code generator creates variable arity call sites
2530     * when the call has more than {@link LinkerCallSite#ARGLIMIT} parameters.
2531     *
2532     * @return method handle with adjusted arguments
2533     */
2534    public static MethodHandle pairArguments(final MethodHandle methodHandle, final MethodType callType, final Boolean callerVarArg) {
2535        final MethodType methodType = methodHandle.type();
2536        if (methodType.equals(callType.changeReturnType(methodType.returnType()))) {
2537            return methodHandle;
2538        }
2539
2540        final int parameterCount = methodType.parameterCount();
2541        final int callCount      = callType.parameterCount();
2542
2543        final boolean isCalleeVarArg = parameterCount > 0 && methodType.parameterType(parameterCount - 1).isArray();
2544        final boolean isCallerVarArg = callerVarArg != null ? callerVarArg.booleanValue() : callCount > 0 &&
2545                callType.parameterType(callCount - 1).isArray();
2546
2547        if (isCalleeVarArg) {
2548            return isCallerVarArg ?
2549                methodHandle :
2550                MH.asCollector(methodHandle, Object[].class, callCount - parameterCount + 1);
2551        }
2552
2553        if (isCallerVarArg) {
2554            return adaptHandleToVarArgCallSite(methodHandle, callCount);
2555        }
2556
2557        if (callCount < parameterCount) {
2558            final int      missingArgs = parameterCount - callCount;
2559            final Object[] fillers     = new Object[missingArgs];
2560
2561            Arrays.fill(fillers, UNDEFINED);
2562
2563            if (isCalleeVarArg) {
2564                fillers[missingArgs - 1] = ScriptRuntime.EMPTY_ARRAY;
2565            }
2566
2567            return MH.insertArguments(
2568                methodHandle,
2569                parameterCount - missingArgs,
2570                fillers);
2571        }
2572
2573        if (callCount > parameterCount) {
2574            final int discardedArgs = callCount - parameterCount;
2575
2576            final Class<?>[] discards = new Class<?>[discardedArgs];
2577            Arrays.fill(discards, Object.class);
2578
2579            return MH.dropArguments(methodHandle, callCount - discardedArgs, discards);
2580        }
2581
2582        return methodHandle;
2583    }
2584
2585    static MethodHandle adaptHandleToVarArgCallSite(final MethodHandle mh, final int callSiteParamCount) {
2586        final int spreadArgs = mh.type().parameterCount() - callSiteParamCount + 1;
2587        return MH.filterArguments(
2588            MH.asSpreader(
2589            mh,
2590            Object[].class,
2591            spreadArgs),
2592            callSiteParamCount - 1,
2593            MH.insertArguments(
2594                TRUNCATINGFILTER,
2595                0,
2596                spreadArgs)
2597            );
2598    }
2599
2600    @SuppressWarnings("unused")
2601    private static Object[] truncatingFilter(final int n, final Object[] array) {
2602        final int length = array == null ? 0 : array.length;
2603        if (n == length) {
2604            return array == null ? ScriptRuntime.EMPTY_ARRAY : array;
2605        }
2606
2607        final Object[] newArray = new Object[n];
2608
2609        if (array != null) {
2610            System.arraycopy(array, 0, newArray, 0, Math.min(n, length));
2611        }
2612
2613        if (length < n) {
2614            final Object fill = UNDEFINED;
2615
2616            for (int i = length; i < n; i++) {
2617                newArray[i] = fill;
2618            }
2619        }
2620
2621        return newArray;
2622    }
2623
2624    /**
2625      * Numeric length setter for length property
2626      *
2627      * @param newLength new length to set
2628      */
2629    public final void setLength(final long newLength) {
2630       final long arrayLength = getArray().length();
2631       if (newLength == arrayLength) {
2632           return;
2633       }
2634
2635       if (newLength > arrayLength) {
2636           setArray(getArray().ensure(newLength - 1));
2637            if (getArray().canDelete(arrayLength, newLength - 1, false)) {
2638               setArray(getArray().delete(arrayLength, newLength - 1));
2639           }
2640           return;
2641       }
2642
2643       if (newLength < arrayLength) {
2644           long actualLength = newLength;
2645
2646           // Check for numeric keys in property map and delete them or adjust length, depending on whether
2647           // they're defined as configurable. See ES5 #15.4.5.2
2648           if (getMap().containsArrayKeys()) {
2649
2650               for (long l = arrayLength - 1; l >= newLength; l--) {
2651                   final FindProperty find = findProperty(JSType.toString(l), false);
2652
2653                   if (find != null) {
2654
2655                       if (find.getProperty().isConfigurable()) {
2656                           deleteOwnProperty(find.getProperty());
2657                       } else {
2658                           actualLength = l + 1;
2659                           break;
2660                       }
2661                   }
2662               }
2663           }
2664
2665           setArray(getArray().shrink(actualLength));
2666           getArray().setLength(actualLength);
2667       }
2668    }
2669
2670    private int getInt(final int index, final String key, final int programPoint) {
2671        if (isValidArrayIndex(index)) {
2672            for (ScriptObject object = this; ; ) {
2673                if (object.getMap().containsArrayKeys()) {
2674                    final FindProperty find = object.findProperty(key, false, false, this);
2675
2676                    if (find != null) {
2677                        return getIntValue(find, programPoint);
2678                    }
2679                }
2680
2681                if ((object = object.getProto()) == null) {
2682                    break;
2683                }
2684
2685                final ArrayData array = object.getArray();
2686
2687                if (array.has(index)) {
2688                    return isValid(programPoint) ?
2689                        array.getIntOptimistic(index, programPoint) :
2690                        array.getInt(index);
2691                }
2692            }
2693        } else {
2694            final FindProperty find = findProperty(key, true);
2695
2696            if (find != null) {
2697                return getIntValue(find, programPoint);
2698            }
2699        }
2700
2701        return JSType.toInt32(invokeNoSuchProperty(key, programPoint));
2702    }
2703
2704    @Override
2705    public int getInt(final Object key, final int programPoint) {
2706        final Object    primitiveKey = JSType.toPrimitive(key, String.class);
2707        final int       index        = getArrayIndex(primitiveKey);
2708        final ArrayData array        = getArray();
2709
2710        if (array.has(index)) {
2711            return isValid(programPoint) ? array.getIntOptimistic(index, programPoint) : array.getInt(index);
2712        }
2713
2714        return getInt(index, JSType.toString(primitiveKey), programPoint);
2715    }
2716
2717    @Override
2718    public int getInt(final double key, final int programPoint) {
2719        final int       index = getArrayIndex(key);
2720        final ArrayData array = getArray();
2721
2722        if (array.has(index)) {
2723            return isValid(programPoint) ? array.getIntOptimistic(index, programPoint) : array.getInt(index);
2724        }
2725
2726        return getInt(index, JSType.toString(key), programPoint);
2727    }
2728
2729    @Override
2730    public int getInt(final long key, final int programPoint) {
2731        final int       index = getArrayIndex(key);
2732        final ArrayData array = getArray();
2733
2734        if (array.has(index)) {
2735            return isValid(programPoint) ? array.getIntOptimistic(index, programPoint) : array.getInt(index);
2736        }
2737
2738        return getInt(index, JSType.toString(key), programPoint);
2739    }
2740
2741    @Override
2742    public int getInt(final int key, final int programPoint) {
2743        final int       index = getArrayIndex(key);
2744        final ArrayData array = getArray();
2745
2746        if (array.has(index)) {
2747            return isValid(programPoint) ? array.getIntOptimistic(key, programPoint) : array.getInt(key);
2748        }
2749
2750        return getInt(index, JSType.toString(key), programPoint);
2751    }
2752
2753    private long getLong(final int index, final String key, final int programPoint) {
2754        if (isValidArrayIndex(index)) {
2755            for (ScriptObject object = this; ; ) {
2756                if (object.getMap().containsArrayKeys()) {
2757                    final FindProperty find = object.findProperty(key, false, false, this);
2758                    if (find != null) {
2759                        return getLongValue(find, programPoint);
2760                    }
2761                }
2762
2763                if ((object = object.getProto()) == null) {
2764                    break;
2765                }
2766
2767                final ArrayData array = object.getArray();
2768
2769                if (array.has(index)) {
2770                    return isValid(programPoint) ?
2771                        array.getLongOptimistic(index, programPoint) :
2772                        array.getLong(index);
2773                }
2774            }
2775        } else {
2776            final FindProperty find = findProperty(key, true);
2777
2778            if (find != null) {
2779                return getLongValue(find, programPoint);
2780            }
2781        }
2782
2783        return JSType.toLong(invokeNoSuchProperty(key, programPoint));
2784    }
2785
2786    @Override
2787    public long getLong(final Object key, final int programPoint) {
2788        final Object    primitiveKey = JSType.toPrimitive(key, String.class);
2789        final int       index        = getArrayIndex(primitiveKey);
2790        final ArrayData array        = getArray();
2791
2792        if (array.has(index)) {
2793            return isValid(programPoint) ? array.getLongOptimistic(index, programPoint) : array.getLong(index);
2794        }
2795
2796        return getLong(index, JSType.toString(primitiveKey), programPoint);
2797    }
2798
2799    @Override
2800    public long getLong(final double key, final int programPoint) {
2801        final int       index = getArrayIndex(key);
2802        final ArrayData array = getArray();
2803
2804        if (array.has(index)) {
2805            return isValid(programPoint) ? array.getLongOptimistic(index, programPoint) : array.getLong(index);
2806        }
2807
2808        return getLong(index, JSType.toString(key), programPoint);
2809    }
2810
2811    @Override
2812    public long getLong(final long key, final int programPoint) {
2813        final int       index = getArrayIndex(key);
2814        final ArrayData array = getArray();
2815
2816        if (array.has(index)) {
2817            return isValid(programPoint) ? array.getLongOptimistic(index, programPoint) : array.getLong(index);
2818        }
2819
2820        return getLong(index, JSType.toString(key), programPoint);
2821    }
2822
2823    @Override
2824    public long getLong(final int key, final int programPoint) {
2825        final int       index = getArrayIndex(key);
2826        final ArrayData array = getArray();
2827
2828        if (array.has(index)) {
2829            return isValid(programPoint) ? array.getLongOptimistic(key, programPoint) : array.getLong(key);
2830        }
2831
2832        return getLong(index, JSType.toString(key), programPoint);
2833    }
2834
2835    private double getDouble(final int index, final String key, final int programPoint) {
2836        if (isValidArrayIndex(index)) {
2837            for (ScriptObject object = this; ; ) {
2838                if (object.getMap().containsArrayKeys()) {
2839                    final FindProperty find = object.findProperty(key, false, false, this);
2840                    if (find != null) {
2841                        return getDoubleValue(find, programPoint);
2842                    }
2843                }
2844
2845                if ((object = object.getProto()) == null) {
2846                    break;
2847                }
2848
2849                final ArrayData array = object.getArray();
2850
2851                if (array.has(index)) {
2852                    return isValid(programPoint) ?
2853                        array.getDoubleOptimistic(index, programPoint) :
2854                        array.getDouble(index);
2855                }
2856            }
2857        } else {
2858            final FindProperty find = findProperty(key, true);
2859
2860            if (find != null) {
2861                return getDoubleValue(find, programPoint);
2862            }
2863        }
2864
2865        return JSType.toNumber(invokeNoSuchProperty(key, INVALID_PROGRAM_POINT));
2866    }
2867
2868    @Override
2869    public double getDouble(final Object key, final int programPoint) {
2870        final Object    primitiveKey = JSType.toPrimitive(key, String.class);
2871        final int       index        = getArrayIndex(primitiveKey);
2872        final ArrayData array        = getArray();
2873
2874        if (array.has(index)) {
2875            return isValid(programPoint) ? array.getDoubleOptimistic(index, programPoint) : array.getDouble(index);
2876        }
2877
2878        return getDouble(index, JSType.toString(primitiveKey), programPoint);
2879    }
2880
2881    @Override
2882    public double getDouble(final double key, final int programPoint) {
2883        final int       index = getArrayIndex(key);
2884        final ArrayData array = getArray();
2885
2886        if (array.has(index)) {
2887            return isValid(programPoint) ? array.getDoubleOptimistic(index, programPoint) : array.getDouble(index);
2888        }
2889
2890        return getDouble(index, JSType.toString(key), programPoint);
2891    }
2892
2893    @Override
2894    public double getDouble(final long key, final int programPoint) {
2895        final int       index = getArrayIndex(key);
2896        final ArrayData array = getArray();
2897
2898        if (array.has(index)) {
2899            return isValid(programPoint) ? array.getDoubleOptimistic(index, programPoint) : array.getDouble(index);
2900        }
2901
2902        return getDouble(index, JSType.toString(key), programPoint);
2903    }
2904
2905    @Override
2906    public double getDouble(final int key, final int programPoint) {
2907        final int       index = getArrayIndex(key);
2908        final ArrayData array = getArray();
2909
2910        if (array.has(index)) {
2911            return isValid(programPoint) ? array.getDoubleOptimistic(key, programPoint) : array.getDouble(key);
2912        }
2913
2914        return getDouble(index, JSType.toString(key), programPoint);
2915    }
2916
2917    private Object get(final int index, final String key) {
2918        if (isValidArrayIndex(index)) {
2919            for (ScriptObject object = this; ; ) {
2920                if (object.getMap().containsArrayKeys()) {
2921                    final FindProperty find = object.findProperty(key, false, false, this);
2922
2923                    if (find != null) {
2924                        return find.getObjectValue();
2925                    }
2926                }
2927
2928                if ((object = object.getProto()) == null) {
2929                    break;
2930                }
2931
2932                final ArrayData array = object.getArray();
2933
2934                if (array.has(index)) {
2935                    return array.getObject(index);
2936                }
2937            }
2938        } else {
2939            final FindProperty find = findProperty(key, true);
2940
2941            if (find != null) {
2942                return find.getObjectValue();
2943            }
2944        }
2945
2946        return invokeNoSuchProperty(key, INVALID_PROGRAM_POINT);
2947    }
2948
2949    @Override
2950    public Object get(final Object key) {
2951        final Object    primitiveKey = JSType.toPrimitive(key, String.class);
2952        final int       index        = getArrayIndex(primitiveKey);
2953        final ArrayData array        = getArray();
2954
2955        if (array.has(index)) {
2956            return array.getObject(index);
2957        }
2958
2959        return get(index, JSType.toString(primitiveKey));
2960    }
2961
2962    @Override
2963    public Object get(final double key) {
2964        final int index = getArrayIndex(key);
2965        final ArrayData array = getArray();
2966
2967        if (array.has(index)) {
2968            return array.getObject(index);
2969        }
2970
2971        return get(index, JSType.toString(key));
2972    }
2973
2974    @Override
2975    public Object get(final long key) {
2976        final int index = getArrayIndex(key);
2977        final ArrayData array = getArray();
2978
2979        if (array.has(index)) {
2980            return array.getObject(index);
2981        }
2982
2983        return get(index, JSType.toString(key));
2984    }
2985
2986    @Override
2987    public Object get(final int key) {
2988        final int index = getArrayIndex(key);
2989        final ArrayData array = getArray();
2990
2991        if (array.has(index)) {
2992            return array.getObject(index);
2993        }
2994
2995        return get(index, JSType.toString(key));
2996    }
2997
2998    private boolean doesNotHaveCheckArrayKeys(final long longIndex, final int value, final boolean strict) {
2999        if (getMap().containsArrayKeys()) {
3000            final String       key  = JSType.toString(longIndex);
3001            final FindProperty find = findProperty(key, true);
3002            if (find != null) {
3003                setObject(find, strict, key, value);
3004                return true;
3005            }
3006        }
3007        return false;
3008    }
3009
3010    private boolean doesNotHaveCheckArrayKeys(final long longIndex, final long value, final boolean strict) {
3011        if (getMap().containsArrayKeys()) {
3012            final String       key  = JSType.toString(longIndex);
3013            final FindProperty find = findProperty(key, true);
3014            if (find != null) {
3015                setObject(find, strict, key, value);
3016                return true;
3017            }
3018        }
3019        return false;
3020    }
3021
3022    private boolean doesNotHaveCheckArrayKeys(final long longIndex, final double value, final boolean strict) {
3023         if (getMap().containsArrayKeys()) {
3024            final String       key  = JSType.toString(longIndex);
3025            final FindProperty find = findProperty(key, true);
3026            if (find != null) {
3027                setObject(find, strict, key, value);
3028                return true;
3029            }
3030        }
3031        return false;
3032    }
3033
3034    private boolean doesNotHaveCheckArrayKeys(final long longIndex, final Object value, final boolean strict) {
3035        if (getMap().containsArrayKeys()) {
3036            final String       key  = JSType.toString(longIndex);
3037            final FindProperty find = findProperty(key, true);
3038            if (find != null) {
3039                setObject(find, strict, key, value);
3040                return true;
3041            }
3042        }
3043        return false;
3044    }
3045
3046    //value agnostic
3047    private boolean doesNotHaveEnsureLength(final long longIndex, final long oldLength, final boolean strict) {
3048        if (longIndex >= oldLength) {
3049            if (!isExtensible()) {
3050                if (strict) {
3051                    throw typeError("object.non.extensible", JSType.toString(longIndex), ScriptRuntime.safeToString(this));
3052                }
3053                return true;
3054            }
3055            setArray(getArray().ensure(longIndex));
3056        }
3057        return false;
3058    }
3059
3060    private void doesNotHaveEnsureDelete(final long longIndex, final long oldLength, final boolean strict) {
3061        if (longIndex > oldLength) {
3062            ArrayData array = getArray();
3063            if (array.canDelete(oldLength, longIndex - 1, strict)) {
3064                array = array.delete(oldLength, longIndex - 1);
3065            }
3066            setArray(array);
3067        }
3068    }
3069
3070    private void doesNotHave(final int index, final int value, final boolean strict) {
3071        final long oldLength = getArray().length();
3072        final long longIndex = ArrayIndex.toLongIndex(index);
3073        if (!doesNotHaveCheckArrayKeys(longIndex, value, strict) && !doesNotHaveEnsureLength(longIndex, oldLength, strict)) {
3074            setArray(getArray().set(index, value, strict));
3075            doesNotHaveEnsureDelete(longIndex, oldLength, strict);
3076        }
3077    }
3078
3079    private void doesNotHave(final int index, final long value, final boolean strict) {
3080        final long oldLength = getArray().length();
3081        final long longIndex = ArrayIndex.toLongIndex(index);
3082        if (!doesNotHaveCheckArrayKeys(longIndex, value, strict) && !doesNotHaveEnsureLength(longIndex, oldLength, strict)) {
3083            setArray(getArray().set(index, value, strict));
3084            doesNotHaveEnsureDelete(longIndex, oldLength, strict);
3085        }
3086    }
3087
3088    private void doesNotHave(final int index, final double value, final boolean strict) {
3089        final long oldLength = getArray().length();
3090        final long longIndex = ArrayIndex.toLongIndex(index);
3091        if (!doesNotHaveCheckArrayKeys(longIndex, value, strict) && !doesNotHaveEnsureLength(longIndex, oldLength, strict)) {
3092            setArray(getArray().set(index, value, strict));
3093            doesNotHaveEnsureDelete(longIndex, oldLength, strict);
3094        }
3095    }
3096
3097    private void doesNotHave(final int index, final Object value, final boolean strict) {
3098        final long oldLength = getArray().length();
3099        final long longIndex = ArrayIndex.toLongIndex(index);
3100        if (!doesNotHaveCheckArrayKeys(longIndex, value, strict) && !doesNotHaveEnsureLength(longIndex, oldLength, strict)) {
3101            setArray(getArray().set(index, value, strict));
3102            doesNotHaveEnsureDelete(longIndex, oldLength, strict);
3103        }
3104    }
3105
3106    /**
3107     * This is the most generic of all Object setters. Most of the others use this in some form.
3108     * TODO: should be further specialized
3109     *
3110     * @param find    found property
3111     * @param strict  are we in strict mode
3112     * @param key     property key
3113     * @param value   property value
3114     */
3115    public final void setObject(final FindProperty find, final boolean strict, final String key, final Object value) {
3116        FindProperty f = find;
3117
3118        if (f != null && f.isInherited() && !(f.getProperty() instanceof UserAccessorProperty) && !isScope()) {
3119            // Setting a property should not modify the property in prototype unless this is a scope object.
3120            f = null;
3121        }
3122
3123        if (f != null) {
3124            if (!f.getProperty().isWritable()) {
3125                if (strict) {
3126                    throw typeError("property.not.writable", key, ScriptRuntime.safeToString(this));
3127                }
3128
3129                return;
3130            }
3131
3132            f.setValue(value, strict);
3133
3134        } else if (!isExtensible()) {
3135            if (strict) {
3136                throw typeError("object.non.extensible", key, ScriptRuntime.safeToString(this));
3137            }
3138        } else {
3139            ScriptObject sobj = this;
3140            // undefined scope properties are set in the global object.
3141            if (isScope()) {
3142                while (sobj != null && !(sobj instanceof Global)) {
3143                    sobj = sobj.getProto();
3144                }
3145                assert sobj != null : "no parent global object in scope";
3146            }
3147            //this will unbox any Number object to its primitive type in case the
3148            //property supports primitive types, so it doesn't matter that it comes
3149            //in as an Object.
3150            sobj.addSpillProperty(key, 0, value, true);
3151        }
3152    }
3153
3154    @Override
3155    public void set(final Object key, final int value, final boolean strict) {
3156        final Object primitiveKey = JSType.toPrimitive(key, String.class);
3157        final int    index        = getArrayIndex(primitiveKey);
3158
3159        if (isValidArrayIndex(index)) {
3160            if (getArray().has(index)) {
3161                setArray(getArray().set(index, value, strict));
3162            } else {
3163                doesNotHave(index, value, strict);
3164            }
3165
3166            return;
3167        }
3168
3169        final String propName = JSType.toString(primitiveKey);
3170        setObject(findProperty(propName, true), strict, propName, JSType.toObject(value));
3171    }
3172
3173    @Override
3174    public void set(final Object key, final long value, final boolean strict) {
3175        final Object primitiveKey = JSType.toPrimitive(key, String.class);
3176        final int    index        = getArrayIndex(primitiveKey);
3177
3178        if (isValidArrayIndex(index)) {
3179            if (getArray().has(index)) {
3180                setArray(getArray().set(index, value, strict));
3181            } else {
3182                doesNotHave(index, value, strict);
3183            }
3184
3185            return;
3186        }
3187
3188        final String propName = JSType.toString(primitiveKey);
3189        setObject(findProperty(propName, true), strict, propName, JSType.toObject(value));
3190    }
3191
3192    @Override
3193    public void set(final Object key, final double value, final boolean strict) {
3194        final Object primitiveKey = JSType.toPrimitive(key, String.class);
3195        final int    index        = getArrayIndex(primitiveKey);
3196
3197        if (isValidArrayIndex(index)) {
3198            if (getArray().has(index)) {
3199                setArray(getArray().set(index, value, strict));
3200            } else {
3201                doesNotHave(index, value, strict);
3202            }
3203
3204            return;
3205        }
3206
3207        final String propName = JSType.toString(primitiveKey);
3208        setObject(findProperty(propName, true), strict, propName, JSType.toObject(value));
3209    }
3210
3211    @Override
3212    public void set(final Object key, final Object value, final boolean strict) {
3213        final Object primitiveKey = JSType.toPrimitive(key, String.class);
3214        final int    index        = getArrayIndex(primitiveKey);
3215
3216        if (isValidArrayIndex(index)) {
3217            if (getArray().has(index)) {
3218                setArray(getArray().set(index, value, strict));
3219            } else {
3220                doesNotHave(index, value, strict);
3221            }
3222
3223            return;
3224        }
3225
3226        final String propName = JSType.toString(primitiveKey);
3227        setObject(findProperty(propName, true), strict, propName, value);
3228    }
3229
3230    @Override
3231    public void set(final double key, final int value, final boolean strict) {
3232        final int index = getArrayIndex(key);
3233
3234        if (isValidArrayIndex(index)) {
3235            if (getArray().has(index)) {
3236                setArray(getArray().set(index, value, strict));
3237            } else {
3238                doesNotHave(index, value, strict);
3239            }
3240
3241            return;
3242        }
3243
3244        final String propName = JSType.toString(key);
3245        setObject(findProperty(propName, true), strict, propName, JSType.toObject(value));
3246    }
3247
3248    @Override
3249    public void set(final double key, final long value, final boolean strict) {
3250        final int index = getArrayIndex(key);
3251
3252        if (isValidArrayIndex(index)) {
3253            if (getArray().has(index)) {
3254                setArray(getArray().set(index, value, strict));
3255            } else {
3256                doesNotHave(index, value, strict);
3257            }
3258
3259            return;
3260        }
3261
3262        final String propName = JSType.toString(key);
3263        setObject(findProperty(propName, true), strict, propName, JSType.toObject(value));
3264    }
3265
3266    @Override
3267    public void set(final double key, final double value, final boolean strict) {
3268        final int index = getArrayIndex(key);
3269
3270        if (isValidArrayIndex(index)) {
3271            if (getArray().has(index)) {
3272                setArray(getArray().set(index, value, strict));
3273            } else {
3274                doesNotHave(index, value, strict);
3275            }
3276
3277            return;
3278        }
3279
3280        final String propName = JSType.toString(key);
3281        setObject(findProperty(propName, true), strict, propName, JSType.toObject(value));
3282    }
3283
3284    @Override
3285    public void set(final double key, final Object value, final boolean strict) {
3286        final int index = getArrayIndex(key);
3287
3288        if (isValidArrayIndex(index)) {
3289            if (getArray().has(index)) {
3290                setArray(getArray().set(index, value, strict));
3291            } else {
3292                doesNotHave(index, value, strict);
3293            }
3294
3295            return;
3296        }
3297
3298        final String propName = JSType.toString(key);
3299        setObject(findProperty(propName, true), strict, propName, value);
3300    }
3301
3302    @Override
3303    public void set(final long key, final int value, final boolean strict) {
3304        final int index = getArrayIndex(key);
3305
3306        if (isValidArrayIndex(index)) {
3307            if (getArray().has(index)) {
3308                setArray(getArray().set(index, value, strict));
3309            } else {
3310                doesNotHave(index, value, strict);
3311            }
3312
3313            return;
3314        }
3315
3316        final String propName = JSType.toString(key);
3317        setObject(findProperty(propName, true), strict, propName, JSType.toObject(value));
3318    }
3319
3320    @Override
3321    public void set(final long key, final long value, final boolean strict) {
3322        final int index = getArrayIndex(key);
3323
3324        if (isValidArrayIndex(index)) {
3325            if (getArray().has(index)) {
3326                setArray(getArray().set(index, value, strict));
3327            } else {
3328                doesNotHave(index, value, strict);
3329            }
3330
3331            return;
3332        }
3333
3334        final String propName = JSType.toString(key);
3335        setObject(findProperty(propName, true), strict, propName, JSType.toObject(value));
3336    }
3337
3338    @Override
3339    public void set(final long key, final double value, final boolean strict) {
3340        final int index = getArrayIndex(key);
3341
3342        if (isValidArrayIndex(index)) {
3343            if (getArray().has(index)) {
3344                setArray(getArray().set(index, value, strict));
3345            } else {
3346                doesNotHave(index, value, strict);
3347            }
3348
3349            return;
3350        }
3351
3352        final String propName = JSType.toString(key);
3353        setObject(findProperty(propName, true), strict, propName, JSType.toObject(value));
3354    }
3355
3356    @Override
3357    public void set(final long key, final Object value, final boolean strict) {
3358        final int index = getArrayIndex(key);
3359
3360        if (isValidArrayIndex(index)) {
3361            if (getArray().has(index)) {
3362                setArray(getArray().set(index, value, strict));
3363            } else {
3364                doesNotHave(index, value, strict);
3365            }
3366
3367            return;
3368        }
3369
3370        final String propName = JSType.toString(key);
3371        setObject(findProperty(propName, true), strict, propName, value);
3372    }
3373
3374    @Override
3375    public void set(final int key, final int value, final boolean strict) {
3376        final int index = getArrayIndex(key);
3377        if (isValidArrayIndex(index)) {
3378            if (getArray().has(index)) {
3379                setArray(getArray().set(index, value, strict));
3380            } else {
3381                doesNotHave(index, value, strict);
3382            }
3383            return;
3384        }
3385
3386        final String propName = JSType.toString(key);
3387        setObject(findProperty(propName, true), strict, propName, JSType.toObject(value));
3388    }
3389
3390    @Override
3391    public void set(final int key, final long value, final boolean strict) {
3392        final int index = getArrayIndex(key);
3393
3394        if (isValidArrayIndex(index)) {
3395            if (getArray().has(index)) {
3396                setArray(getArray().set(index, value, strict));
3397            } else {
3398                doesNotHave(index, value, strict);
3399            }
3400
3401            return;
3402        }
3403
3404        final String propName = JSType.toString(key);
3405        setObject(findProperty(propName, true), strict, propName, JSType.toObject(value));
3406    }
3407
3408    @Override
3409    public void set(final int key, final double value, final boolean strict) {
3410        final int index = getArrayIndex(key);
3411
3412        if (isValidArrayIndex(index)) {
3413            if (getArray().has(index)) {
3414                setArray(getArray().set(index, value, strict));
3415            } else {
3416                doesNotHave(index, value, strict);
3417            }
3418
3419            return;
3420        }
3421
3422        final String propName = JSType.toString(key);
3423        setObject(findProperty(propName, true), strict, propName, JSType.toObject(value));
3424    }
3425
3426    @Override
3427    public void set(final int key, final Object value, final boolean strict) {
3428        final int index = getArrayIndex(key);
3429
3430        if (isValidArrayIndex(index)) {
3431            if (getArray().has(index)) {
3432                setArray(getArray().set(index, value, strict));
3433            } else {
3434                doesNotHave(index, value, strict);
3435            }
3436
3437            return;
3438        }
3439
3440        final String propName = JSType.toString(key);
3441        setObject(findProperty(propName, true), strict, propName, value);
3442    }
3443
3444    @Override
3445    public boolean has(final Object key) {
3446        final Object primitiveKey = JSType.toPrimitive(key);
3447        final int    index        = getArrayIndex(primitiveKey);
3448        return isValidArrayIndex(index) ? hasArrayProperty(index) : hasProperty(JSType.toString(primitiveKey), true);
3449    }
3450
3451    @Override
3452    public boolean has(final double key) {
3453        final int index = getArrayIndex(key);
3454        return isValidArrayIndex(index) ? hasArrayProperty(index) : hasProperty(JSType.toString(key), true);
3455    }
3456
3457    @Override
3458    public boolean has(final long key) {
3459        final int index = getArrayIndex(key);
3460        return isValidArrayIndex(index) ? hasArrayProperty(index) : hasProperty(JSType.toString(key), true);
3461    }
3462
3463    @Override
3464    public boolean has(final int key) {
3465        final int index = getArrayIndex(key);
3466        return isValidArrayIndex(index) ? hasArrayProperty(index) : hasProperty(JSType.toString(key), true);
3467    }
3468
3469    private boolean hasArrayProperty(final int index) {
3470        boolean hasArrayKeys = false;
3471
3472        for (ScriptObject self = this; self != null; self = self.getProto()) {
3473            if (self.getArray().has(index)) {
3474                return true;
3475            }
3476            hasArrayKeys = hasArrayKeys || self.getMap().containsArrayKeys();
3477        }
3478
3479        return hasArrayKeys && hasProperty(ArrayIndex.toKey(index), true);
3480    }
3481
3482    @Override
3483    public boolean hasOwnProperty(final Object key) {
3484        final Object primitiveKey = JSType.toPrimitive(key, String.class);
3485        final int    index        = getArrayIndex(primitiveKey);
3486        return isValidArrayIndex(index) ? hasOwnArrayProperty(index) : hasProperty(JSType.toString(primitiveKey), false);
3487    }
3488
3489    @Override
3490    public boolean hasOwnProperty(final int key) {
3491        final int index = getArrayIndex(key);
3492        return isValidArrayIndex(index) ? hasOwnArrayProperty(index) : hasProperty(JSType.toString(key), false);
3493    }
3494
3495    @Override
3496    public boolean hasOwnProperty(final long key) {
3497        final int index = getArrayIndex(key);
3498        return isValidArrayIndex(index) ? hasOwnArrayProperty(index) : hasProperty(JSType.toString(key), false);
3499    }
3500
3501    @Override
3502    public boolean hasOwnProperty(final double key) {
3503        final int index = getArrayIndex(key);
3504        return isValidArrayIndex(index) ? hasOwnArrayProperty(index) : hasProperty(JSType.toString(key), false);
3505    }
3506
3507    private boolean hasOwnArrayProperty(final int index) {
3508        return getArray().has(index) || getMap().containsArrayKeys() && hasProperty(ArrayIndex.toKey(index), false);
3509    }
3510
3511    @Override
3512    public boolean delete(final int key, final boolean strict) {
3513        final int index = getArrayIndex(key);
3514        final ArrayData array = getArray();
3515
3516        if (array.has(index)) {
3517            if (array.canDelete(index, strict)) {
3518                setArray(array.delete(index));
3519                return true;
3520            }
3521            return false;
3522        }
3523
3524        return deleteObject(JSType.toObject(key), strict);
3525    }
3526
3527    @Override
3528    public boolean delete(final long key, final boolean strict) {
3529        final int index = getArrayIndex(key);
3530        final ArrayData array = getArray();
3531
3532        if (array.has(index)) {
3533            if (array.canDelete(index, strict)) {
3534                setArray(array.delete(index));
3535                return true;
3536            }
3537            return false;
3538        }
3539
3540        return deleteObject(JSType.toObject(key), strict);
3541    }
3542
3543    @Override
3544    public boolean delete(final double key, final boolean strict) {
3545        final int index = getArrayIndex(key);
3546        final ArrayData array = getArray();
3547
3548        if (array.has(index)) {
3549            if (array.canDelete(index, strict)) {
3550                setArray(array.delete(index));
3551                return true;
3552            }
3553            return false;
3554        }
3555
3556        return deleteObject(JSType.toObject(key), strict);
3557    }
3558
3559    @Override
3560    public boolean delete(final Object key, final boolean strict) {
3561        final Object    primitiveKey = JSType.toPrimitive(key, String.class);
3562        final int       index        = getArrayIndex(primitiveKey);
3563        final ArrayData array        = getArray();
3564
3565        if (array.has(index)) {
3566            if (array.canDelete(index, strict)) {
3567                setArray(array.delete(index));
3568                return true;
3569            }
3570            return false;
3571        }
3572
3573        return deleteObject(primitiveKey, strict);
3574    }
3575
3576    private boolean deleteObject(final Object key, final boolean strict) {
3577        final String propName = JSType.toString(key);
3578        final FindProperty find = findProperty(propName, false);
3579
3580        if (find == null) {
3581            return true;
3582        }
3583
3584        if (!find.getProperty().isConfigurable()) {
3585            if (strict) {
3586                throw typeError("cant.delete.property", propName, ScriptRuntime.safeToString(this));
3587            }
3588            return false;
3589        }
3590
3591        final Property prop = find.getProperty();
3592        deleteOwnProperty(prop);
3593
3594        return true;
3595    }
3596
3597    /**
3598     * Make a new UserAccessorProperty property. getter and setter functions are stored in
3599     * this ScriptObject and slot values are used in property object.
3600     *
3601     * @param key the property name
3602     * @param propertyFlags attribute flags of the property
3603     * @param getter getter function for the property
3604     * @param setter setter function for the property
3605     * @return the newly created UserAccessorProperty
3606     */
3607    protected final UserAccessorProperty newUserAccessors(final String key, final int propertyFlags, final ScriptFunction getter, final ScriptFunction setter) {
3608        final UserAccessorProperty uc = getMap().newUserAccessors(key, propertyFlags);
3609        //property.getSetter(Object.class, getMap());
3610        uc.setAccessors(this, getMap(), new UserAccessorProperty.Accessors(getter, setter));
3611        return uc;
3612    }
3613
3614    Object ensureSpillSize(final int slot) {
3615        if (slot < spillLength) {
3616            return this;
3617        }
3618        final int newLength = alignUp(slot + 1, SPILL_RATE);
3619        final Object[] newObjectSpill    = new Object[newLength];
3620        final long[]   newPrimitiveSpill = OBJECT_FIELDS_ONLY ? null : new long[newLength];
3621
3622        if (objectSpill != null) {
3623            System.arraycopy(objectSpill, 0, newObjectSpill, 0, spillLength);
3624            if (!OBJECT_FIELDS_ONLY) {
3625                System.arraycopy(primitiveSpill, 0, newPrimitiveSpill, 0, spillLength);
3626            }
3627        }
3628
3629        this.primitiveSpill = newPrimitiveSpill;
3630        this.objectSpill    = newObjectSpill;
3631        this.spillLength = newLength;
3632
3633        return this;
3634    }
3635
3636    private static MethodHandle findOwnMH_V(final Class<? extends ScriptObject> clazz, final String name, final Class<?> rtype, final Class<?>... types) {
3637        // TODO: figure out how can it work for NativeArray$Prototype etc.
3638        return MH.findVirtual(MethodHandles.lookup(), ScriptObject.class, name, MH.type(rtype, types));
3639    }
3640
3641    private static MethodHandle findOwnMH_V(final String name, final Class<?> rtype, final Class<?>... types) {
3642        return findOwnMH_V(ScriptObject.class, name, rtype, types);
3643    }
3644
3645    private static MethodHandle findOwnMH_S(final String name, final Class<?> rtype, final Class<?>... types) {
3646        return MH.findStatic(MethodHandles.lookup(), ScriptObject.class, name, MH.type(rtype, types));
3647    }
3648
3649    private static MethodHandle getKnownFunctionPropertyGuardSelf(final PropertyMap map, final MethodHandle getter, final ScriptFunction func) {
3650        return MH.insertArguments(KNOWNFUNCPROPGUARDSELF, 1, map, getter, func);
3651    }
3652
3653    @SuppressWarnings("unused")
3654    private static boolean knownFunctionPropertyGuardSelf(final Object self, final PropertyMap map, final MethodHandle getter, final ScriptFunction func) {
3655        if (self instanceof ScriptObject && ((ScriptObject)self).getMap() == map) {
3656            try {
3657                return getter.invokeExact(self) == func;
3658            } catch (final RuntimeException | Error e) {
3659                throw e;
3660            } catch (final Throwable t) {
3661                throw new RuntimeException(t);
3662            }
3663        }
3664
3665        return false;
3666    }
3667
3668    private static MethodHandle getKnownFunctionPropertyGuardProto(final PropertyMap map, final MethodHandle getter, final int depth, final ScriptFunction func) {
3669        return MH.insertArguments(KNOWNFUNCPROPGUARDPROTO, 1, map, getter, depth, func);
3670    }
3671
3672    private static ScriptObject getProto(final ScriptObject self, final int depth) {
3673        ScriptObject proto = self;
3674        for (int d = 0; d < depth; d++) {
3675            proto = proto.getProto();
3676            if (proto == null) {
3677                return null;
3678            }
3679        }
3680
3681        return proto;
3682    }
3683
3684    @SuppressWarnings("unused")
3685    private static boolean knownFunctionPropertyGuardProto(final Object self, final PropertyMap map, final MethodHandle getter, final int depth, final ScriptFunction func) {
3686        if (self instanceof ScriptObject && ((ScriptObject)self).getMap() == map) {
3687            final ScriptObject proto = getProto((ScriptObject)self, depth);
3688            if (proto == null) {
3689                return false;
3690            }
3691            try {
3692                return getter.invokeExact((Object)proto) == func;
3693            } catch (final RuntimeException | Error e) {
3694                throw e;
3695            } catch (final Throwable t) {
3696                throw new RuntimeException(t);
3697            }
3698        }
3699
3700        return false;
3701    }
3702
3703    /** This is updated only in debug mode - counts number of {@code ScriptObject} instances created */
3704    private static int count;
3705
3706    /** This is updated only in debug mode - counts number of {@code ScriptObject} instances created that are scope */
3707    private static int scopeCount;
3708
3709    /**
3710     * Get number of {@code ScriptObject} instances created. If not running in debug
3711     * mode this is always 0
3712     *
3713     * @return number of ScriptObjects created
3714     */
3715    public static int getCount() {
3716        return count;
3717    }
3718
3719    /**
3720     * Get number of scope {@code ScriptObject} instances created. If not running in debug
3721     * mode this is always 0
3722     *
3723     * @return number of scope ScriptObjects created
3724     */
3725    public static int getScopeCount() {
3726        return scopeCount;
3727    }
3728
3729}
3730