ScriptObject.java revision 1015:8a4af0397070
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, null); 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, null); 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, null); 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, request); 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) : 1999 "return type mismatch for getter " + mh.type().returnType() + " != " + returnType; 2000 if (!(property instanceof UserAccessorProperty)) { 2001 // Add a filter that replaces the self object with the prototype owning the property. 2002 mh = addProtoFilter(mh, find.getProtoChainLength()); 2003 } 2004 protoSwitchPoint = getProtoSwitchPoint(name, owner); 2005 } else { 2006 protoSwitchPoint = null; 2007 } 2008 2009 assert OBJECT_FIELDS_ONLY || guard != null : "we always need a map guard here"; 2010 2011 final GuardedInvocation inv = new GuardedInvocation(mh, guard, protoSwitchPoint, exception); 2012 return inv.addSwitchPoint(reservedNameSwitchPoint); 2013 } 2014 2015 private static GuardedInvocation findMegaMorphicGetMethod(final CallSiteDescriptor desc, final String name, final boolean isMethod) { 2016 Context.getContextTrusted().getLogger(ObjectClassGenerator.class).warning("Megamorphic getter: " + desc + " " + name + " " +isMethod); 2017 final MethodHandle invoker = MH.insertArguments(MEGAMORPHIC_GET, 1, name, isMethod); 2018 final MethodHandle guard = getScriptObjectGuard(desc.getMethodType(), true); 2019 return new GuardedInvocation(invoker, guard); 2020 } 2021 2022 @SuppressWarnings("unused") 2023 private Object megamorphicGet(final String key, final boolean isMethod) { 2024 final FindProperty find = findProperty(key, true); 2025 if (find != null) { 2026 return find.getObjectValue(); 2027 } 2028 2029 return isMethod ? getNoSuchMethod(key, INVALID_PROGRAM_POINT) : invokeNoSuchProperty(key, INVALID_PROGRAM_POINT); 2030 } 2031 2032 // Marks a property as declared and sets its value. Used as slow path for block-scoped LET and CONST 2033 @SuppressWarnings("unused") 2034 private void declareAndSet(final String key, final Object value) { 2035 final PropertyMap map = getMap(); 2036 final FindProperty find = findProperty(key, false); 2037 assert find != null; 2038 2039 final Property property = find.getProperty(); 2040 assert property != null; 2041 assert property.needsDeclaration(); 2042 2043 final PropertyMap newMap = map.replaceProperty(property, property.removeFlags(Property.NEEDS_DECLARATION)); 2044 setMap(newMap); 2045 set(key, value, true); 2046 } 2047 2048 /** 2049 * Find the appropriate GETINDEX method for an invoke dynamic call. 2050 * 2051 * @param desc the call site descriptor 2052 * @param request the link request 2053 * 2054 * @return GuardedInvocation to be invoked at call site. 2055 */ 2056 protected GuardedInvocation findGetIndexMethod(final CallSiteDescriptor desc, final LinkRequest request) { 2057 final MethodType callType = desc.getMethodType(); 2058 final Class<?> returnType = callType.returnType(); 2059 final Class<?> returnClass = returnType.isPrimitive() ? returnType : Object.class; 2060 final Class<?> keyClass = callType.parameterType(1); 2061 final boolean explicitInstanceOfCheck = explicitInstanceOfCheck(desc, request); 2062 2063 final String name; 2064 if (returnClass.isPrimitive()) { 2065 //turn e.g. get with a double into getDouble 2066 final String returnTypeName = returnClass.getName(); 2067 name = "get" + Character.toUpperCase(returnTypeName.charAt(0)) + returnTypeName.substring(1, returnTypeName.length()); 2068 } else { 2069 name = "get"; 2070 } 2071 2072 final MethodHandle mh = findGetIndexMethodHandle(returnClass, name, keyClass, desc); 2073 return new GuardedInvocation(mh, getScriptObjectGuard(callType, explicitInstanceOfCheck), (SwitchPoint)null, explicitInstanceOfCheck ? null : ClassCastException.class); 2074 } 2075 2076 private static MethodHandle getScriptObjectGuard(final MethodType type, final boolean explicitInstanceOfCheck) { 2077 return ScriptObject.class.isAssignableFrom(type.parameterType(0)) ? null : NashornGuards.getScriptObjectGuard(explicitInstanceOfCheck); 2078 } 2079 2080 /** 2081 * Find a handle for a getIndex method 2082 * @param returnType return type for getter 2083 * @param name name 2084 * @param elementType index type for getter 2085 * @param desc call site descriptor 2086 * @return method handle for getter 2087 */ 2088 protected MethodHandle findGetIndexMethodHandle(final Class<?> returnType, final String name, final Class<?> elementType, final CallSiteDescriptor desc) { 2089 if (!returnType.isPrimitive()) { 2090 return findOwnMH_V(getClass(), name, returnType, elementType); 2091 } 2092 2093 return MH.insertArguments( 2094 findOwnMH_V(getClass(), name, returnType, elementType, int.class), 2095 2, 2096 NashornCallSiteDescriptor.isOptimistic(desc) ? 2097 NashornCallSiteDescriptor.getProgramPoint(desc) : 2098 INVALID_PROGRAM_POINT); 2099 } 2100 2101 /** 2102 * Get a switch point for a property with the given {@code name} that will be invalidated when 2103 * the property definition is changed in this object's prototype chain. Returns {@code null} if 2104 * the property is defined in this object itself. 2105 * 2106 * @param name the property name 2107 * @param owner the property owner, null if property is not defined 2108 * @return a SwitchPoint or null 2109 */ 2110 public final SwitchPoint getProtoSwitchPoint(final String name, final ScriptObject owner) { 2111 if (owner == this || getProto() == null) { 2112 return null; 2113 } 2114 2115 for (ScriptObject obj = this; obj != owner && obj.getProto() != null; obj = obj.getProto()) { 2116 final ScriptObject parent = obj.getProto(); 2117 parent.getMap().addListener(name, obj.getMap()); 2118 } 2119 2120 return getMap().getSwitchPoint(name); 2121 } 2122 2123 /** 2124 * Find the appropriate SET method for an invoke dynamic call. 2125 * 2126 * @param desc the call site descriptor 2127 * @param request the link request 2128 * 2129 * @return GuardedInvocation to be invoked at call site. 2130 */ 2131 protected GuardedInvocation findSetMethod(final CallSiteDescriptor desc, final LinkRequest request) { 2132 final String name = desc.getNameToken(CallSiteDescriptor.NAME_OPERAND); 2133 2134 if (request.isCallSiteUnstable() || hasWithScope()) { 2135 return findMegaMorphicSetMethod(desc, name); 2136 } 2137 2138 final boolean scope = isScope(); 2139 final boolean explicitInstanceOfCheck = explicitInstanceOfCheck(desc, request); 2140 2141 /* 2142 * If doing property set on a scope object, we should stop proto search on the first 2143 * non-scope object. Without this, for example, when assigning "toString" on global scope, 2144 * we'll end up assigning it on it's proto - which is Object.prototype.toString !! 2145 * 2146 * toString = function() { print("global toString"); } // don't affect Object.prototype.toString 2147 */ 2148 FindProperty find = findProperty(name, true, scope, this); 2149 2150 // If it's not a scope search, then we don't want any inherited properties except those with user defined accessors. 2151 if (!scope && find != null && find.isInherited() && !(find.getProperty() instanceof UserAccessorProperty)) { 2152 // We should still check if inherited data property is not writable 2153 if (isExtensible() && !find.getProperty().isWritable()) { 2154 return createEmptySetMethod(desc, explicitInstanceOfCheck, "property.not.writable", false); 2155 } 2156 // Otherwise, forget the found property 2157 find = null; 2158 } 2159 2160 if (find != null) { 2161 if (!find.getProperty().isWritable() && !NashornCallSiteDescriptor.isDeclaration(desc)) { 2162 // Existing, non-writable property 2163 return createEmptySetMethod(desc, explicitInstanceOfCheck, "property.not.writable", true); 2164 } 2165 } else { 2166 if (!isExtensible()) { 2167 return createEmptySetMethod(desc, explicitInstanceOfCheck, "object.non.extensible", false); 2168 } 2169 } 2170 2171 final GuardedInvocation inv = new SetMethodCreator(this, find, desc, request).createGuardedInvocation(); 2172 2173 final GuardedInvocation cinv = Global.getConstants().findSetMethod(find, this, inv, desc, request); 2174 if (cinv != null) { 2175 return cinv; 2176 } 2177 2178 return inv; 2179 } 2180 2181 private GuardedInvocation createEmptySetMethod(final CallSiteDescriptor desc, final boolean explicitInstanceOfCheck, final String strictErrorMessage, final boolean canBeFastScope) { 2182 final String name = desc.getNameToken(CallSiteDescriptor.NAME_OPERAND); 2183 if (NashornCallSiteDescriptor.isStrict(desc)) { 2184 throw typeError(strictErrorMessage, name, ScriptRuntime.safeToString(this)); 2185 } 2186 assert canBeFastScope || !NashornCallSiteDescriptor.isFastScope(desc); 2187 return new GuardedInvocation( 2188 Lookup.EMPTY_SETTER, 2189 NashornGuards.getMapGuard(getMap(), explicitInstanceOfCheck), 2190 getProtoSwitchPoint(name, null), 2191 explicitInstanceOfCheck ? null : ClassCastException.class); 2192 } 2193 2194 @SuppressWarnings("unused") 2195 private boolean extensionCheck(final boolean isStrict, final String name) { 2196 if (isExtensible()) { 2197 return true; //go on and do the set. this is our guard 2198 } else if (isStrict) { 2199 //throw an error for attempting to do the set in strict mode 2200 throw typeError("object.non.extensible", name, ScriptRuntime.safeToString(this)); 2201 } else { 2202 //not extensible, non strict - this is a nop 2203 return false; 2204 } 2205 } 2206 2207 private GuardedInvocation findMegaMorphicSetMethod(final CallSiteDescriptor desc, final String name) { 2208 final MethodType type = desc.getMethodType().insertParameterTypes(1, Object.class); 2209 //never bother with ClassCastExceptionGuard for megamorphic callsites 2210 final GuardedInvocation inv = findSetIndexMethod(getClass(), false, type, NashornCallSiteDescriptor.isStrict(desc)); 2211 return inv.replaceMethods(MH.insertArguments(inv.getInvocation(), 1, name), inv.getGuard()); 2212 } 2213 2214 @SuppressWarnings("unused") 2215 private static Object globalFilter(final Object object) { 2216 ScriptObject sobj = (ScriptObject) object; 2217 while (sobj != null && !(sobj instanceof Global)) { 2218 sobj = sobj.getProto(); 2219 } 2220 return sobj; 2221 } 2222 2223 /** 2224 * Lookup function for the set index method, available for subclasses as well, e.g. {@link NativeArray} 2225 * provides special quick accessor linkage for continuous arrays that are represented as Java arrays 2226 * 2227 * @param desc call site descriptor 2228 * @param request link request 2229 * 2230 * @return GuardedInvocation to be invoked at call site. 2231 */ 2232 protected GuardedInvocation findSetIndexMethod(final CallSiteDescriptor desc, final LinkRequest request) { // array, index, value 2233 return findSetIndexMethod(getClass(), explicitInstanceOfCheck(desc, request), desc.getMethodType(), NashornCallSiteDescriptor.isStrict(desc)); 2234 } 2235 2236 /** 2237 * Find the appropriate SETINDEX method for an invoke dynamic call. 2238 * 2239 * @param callType the method type at the call site 2240 * @param isStrict are we in strict mode? 2241 * 2242 * @return GuardedInvocation to be invoked at call site. 2243 */ 2244 private static GuardedInvocation findSetIndexMethod(final Class<? extends ScriptObject> clazz, final boolean explicitInstanceOfCheck, final MethodType callType, final boolean isStrict) { 2245 assert callType.parameterCount() == 3; 2246 final Class<?> keyClass = callType.parameterType(1); 2247 final Class<?> valueClass = callType.parameterType(2); 2248 2249 MethodHandle methodHandle = findOwnMH_V(clazz, "set", void.class, keyClass, valueClass, boolean.class); 2250 methodHandle = MH.insertArguments(methodHandle, 3, isStrict); 2251 2252 return new GuardedInvocation(methodHandle, getScriptObjectGuard(callType, explicitInstanceOfCheck), (SwitchPoint)null, explicitInstanceOfCheck ? null : ClassCastException.class); 2253 } 2254 2255 /** 2256 * Fall back if a function property is not found. 2257 * @param desc The call site descriptor 2258 * @param request the link request 2259 * @return GuardedInvocation to be invoked at call site. 2260 */ 2261 public GuardedInvocation noSuchMethod(final CallSiteDescriptor desc, final LinkRequest request) { 2262 final String name = desc.getNameToken(2); 2263 final FindProperty find = findProperty(NO_SUCH_METHOD_NAME, true); 2264 final boolean scopeCall = isScope() && NashornCallSiteDescriptor.isScope(desc); 2265 2266 if (find == null) { 2267 return noSuchProperty(desc, request); 2268 } 2269 2270 final boolean explicitInstanceOfCheck = explicitInstanceOfCheck(desc, request); 2271 2272 final Object value = find.getObjectValue(); 2273 if (!(value instanceof ScriptFunction)) { 2274 return createEmptyGetter(desc, explicitInstanceOfCheck, name); 2275 } 2276 2277 final ScriptFunction func = (ScriptFunction)value; 2278 final Object thiz = scopeCall && func.isStrict() ? ScriptRuntime.UNDEFINED : this; 2279 // TODO: It'd be awesome if we could bind "name" without binding "this". 2280 return new GuardedInvocation( 2281 MH.dropArguments( 2282 MH.constant( 2283 ScriptFunction.class, 2284 func.makeBoundFunction(thiz, new Object[] { name })), 2285 0, 2286 Object.class), 2287 NashornGuards.getMapGuard(getMap(), explicitInstanceOfCheck), 2288 (SwitchPoint)null, 2289 explicitInstanceOfCheck ? null : ClassCastException.class); 2290 } 2291 2292 /** 2293 * Fall back if a property is not found. 2294 * @param desc the call site descriptor. 2295 * @param request the link request 2296 * @return GuardedInvocation to be invoked at call site. 2297 */ 2298 public GuardedInvocation noSuchProperty(final CallSiteDescriptor desc, final LinkRequest request) { 2299 final String name = desc.getNameToken(CallSiteDescriptor.NAME_OPERAND); 2300 final FindProperty find = findProperty(NO_SUCH_PROPERTY_NAME, true); 2301 final boolean scopeAccess = isScope() && NashornCallSiteDescriptor.isScope(desc); 2302 2303 if (find != null) { 2304 final Object value = find.getObjectValue(); 2305 ScriptFunction func = null; 2306 MethodHandle mh = null; 2307 2308 if (value instanceof ScriptFunction) { 2309 func = (ScriptFunction)value; 2310 mh = getCallMethodHandle(func, desc.getMethodType(), name); 2311 } 2312 2313 if (mh != null) { 2314 assert func != null; 2315 if (scopeAccess && func.isStrict()) { 2316 mh = bindTo(mh, UNDEFINED); 2317 } 2318 2319 return new GuardedInvocation( 2320 mh, 2321 find.isSelf()? 2322 getKnownFunctionPropertyGuardSelf( 2323 getMap(), 2324 find.getGetter(Object.class, INVALID_PROGRAM_POINT, request), 2325 func) 2326 : 2327 //TODO this always does a scriptobject check 2328 getKnownFunctionPropertyGuardProto( 2329 getMap(), 2330 find.getGetter(Object.class, INVALID_PROGRAM_POINT, request), 2331 find.getProtoChainLength(), 2332 func), 2333 getProtoSwitchPoint(NO_SUCH_PROPERTY_NAME, find.getOwner()), 2334 //TODO this doesn't need a ClassCastException as guard always checks script object 2335 null); 2336 } 2337 } 2338 2339 if (scopeAccess) { 2340 throw referenceError("not.defined", name); 2341 } 2342 2343 return createEmptyGetter(desc, explicitInstanceOfCheck(desc, request), name); 2344 } 2345 2346 /** 2347 * Invoke fall back if a property is not found. 2348 * @param name Name of property. 2349 * @param programPoint program point 2350 * @return Result from call. 2351 */ 2352 protected Object invokeNoSuchProperty(final String name, final int programPoint) { 2353 final FindProperty find = findProperty(NO_SUCH_PROPERTY_NAME, true); 2354 2355 Object ret = UNDEFINED; 2356 2357 if (find != null) { 2358 final Object func = find.getObjectValue(); 2359 2360 if (func instanceof ScriptFunction) { 2361 ret = ScriptRuntime.apply((ScriptFunction)func, this, name); 2362 } 2363 } 2364 2365 if (isValid(programPoint)) { 2366 throw new UnwarrantedOptimismException(ret, programPoint); 2367 } 2368 2369 return ret; 2370 } 2371 2372 2373 /** 2374 * Get __noSuchMethod__ as a function bound to this object and {@code name} if it is defined. 2375 * @param name the method name 2376 * @return the bound function, or undefined 2377 */ 2378 private Object getNoSuchMethod(final String name, final int programPoint) { 2379 final FindProperty find = findProperty(NO_SUCH_METHOD_NAME, true); 2380 2381 if (find == null) { 2382 return invokeNoSuchProperty(name, programPoint); 2383 } 2384 2385 final Object value = find.getObjectValue(); 2386 if (!(value instanceof ScriptFunction)) { 2387 return UNDEFINED; 2388 } 2389 2390 return ((ScriptFunction)value).makeBoundFunction(this, new Object[] {name}); 2391 } 2392 2393 private GuardedInvocation createEmptyGetter(final CallSiteDescriptor desc, final boolean explicitInstanceOfCheck, final String name) { 2394 if (NashornCallSiteDescriptor.isOptimistic(desc)) { 2395 throw new UnwarrantedOptimismException(UNDEFINED, NashornCallSiteDescriptor.getProgramPoint(desc), Type.OBJECT); 2396 } 2397 2398 return new GuardedInvocation(Lookup.emptyGetter(desc.getMethodType().returnType()), 2399 NashornGuards.getMapGuard(getMap(), explicitInstanceOfCheck), getProtoSwitchPoint(name, null), 2400 explicitInstanceOfCheck ? null : ClassCastException.class); 2401 } 2402 2403 private abstract static class ScriptObjectIterator <T extends Object> implements Iterator<T> { 2404 protected T[] values; 2405 protected final ScriptObject object; 2406 private int index; 2407 2408 ScriptObjectIterator(final ScriptObject object) { 2409 this.object = object; 2410 } 2411 2412 protected abstract void init(); 2413 2414 @Override 2415 public boolean hasNext() { 2416 if (values == null) { 2417 init(); 2418 } 2419 return index < values.length; 2420 } 2421 2422 @Override 2423 public T next() { 2424 if (values == null) { 2425 init(); 2426 } 2427 return values[index++]; 2428 } 2429 2430 @Override 2431 public void remove() { 2432 throw new UnsupportedOperationException(); 2433 } 2434 } 2435 2436 private static class KeyIterator extends ScriptObjectIterator<String> { 2437 KeyIterator(final ScriptObject object) { 2438 super(object); 2439 } 2440 2441 @Override 2442 protected void init() { 2443 final Set<String> keys = new LinkedHashSet<>(); 2444 final Set<String> nonEnumerable = new HashSet<>(); 2445 for (ScriptObject self = object; self != null; self = self.getProto()) { 2446 keys.addAll(Arrays.asList(self.getOwnKeys(false, nonEnumerable))); 2447 } 2448 this.values = keys.toArray(new String[keys.size()]); 2449 } 2450 } 2451 2452 private static class ValueIterator extends ScriptObjectIterator<Object> { 2453 ValueIterator(final ScriptObject object) { 2454 super(object); 2455 } 2456 2457 @Override 2458 protected void init() { 2459 final ArrayList<Object> valueList = new ArrayList<>(); 2460 final Set<String> nonEnumerable = new HashSet<>(); 2461 for (ScriptObject self = object; self != null; self = self.getProto()) { 2462 for (final String key : self.getOwnKeys(false, nonEnumerable)) { 2463 valueList.add(self.get(key)); 2464 } 2465 } 2466 this.values = valueList.toArray(new Object[valueList.size()]); 2467 } 2468 } 2469 2470 /** 2471 * Add a spill property for the given key. 2472 * @param key Property key. 2473 * @param propertyFlags Property flags. 2474 * @return Added property. 2475 */ 2476 private Property addSpillProperty(final String key, final int propertyFlags, final Object value, final boolean hasInitialValue) { 2477 final PropertyMap propertyMap = getMap(); 2478 final int fieldSlot = propertyMap.getFreeFieldSlot(); 2479 2480 Property property; 2481 if (fieldSlot > -1) { 2482 property = hasInitialValue ? 2483 new AccessorProperty(key, propertyFlags, fieldSlot, this, value) : 2484 new AccessorProperty(key, propertyFlags, getClass(), fieldSlot); 2485 property = addOwnProperty(property); 2486 } else { 2487 final int spillSlot = propertyMap.getFreeSpillSlot(); 2488 property = hasInitialValue ? 2489 new SpillProperty(key, propertyFlags, spillSlot, this, value) : 2490 new SpillProperty(key, propertyFlags, spillSlot); 2491 property = addOwnProperty(property); 2492 ensureSpillSize(property.getSlot()); 2493 } 2494 return property; 2495 } 2496 2497 /** 2498 * Add a spill entry for the given key. 2499 * @param key Property key. 2500 * @return Setter method handle. 2501 */ 2502 MethodHandle addSpill(final Class<?> type, final String key) { 2503 return addSpillProperty(key, 0, null, false).getSetter(OBJECT_FIELDS_ONLY ? Object.class : type, getMap()); 2504 } 2505 2506 /** 2507 * Make sure arguments are paired correctly, with respect to more parameters than declared, 2508 * fewer parameters than declared and other things that JavaScript allows. This might involve 2509 * creating collectors. 2510 * 2511 * @param methodHandle method handle for invoke 2512 * @param callType type of the call 2513 * 2514 * @return method handle with adjusted arguments 2515 */ 2516 protected static MethodHandle pairArguments(final MethodHandle methodHandle, final MethodType callType) { 2517 return pairArguments(methodHandle, callType, null); 2518 } 2519 2520 /** 2521 * Make sure arguments are paired correctly, with respect to more parameters than declared, 2522 * fewer parameters than declared and other things that JavaScript allows. This might involve 2523 * creating collectors. 2524 * 2525 * Make sure arguments are paired correctly. 2526 * @param methodHandle MethodHandle to adjust. 2527 * @param callType MethodType of the call site. 2528 * @param callerVarArg true if the caller is vararg, false otherwise, null if it should be inferred from the 2529 * {@code callType}; basically, if the last parameter type of the call site is an array, it'll be considered a 2530 * variable arity call site. These are ordinarily rare; Nashorn code generator creates variable arity call sites 2531 * when the call has more than {@link LinkerCallSite#ARGLIMIT} parameters. 2532 * 2533 * @return method handle with adjusted arguments 2534 */ 2535 public static MethodHandle pairArguments(final MethodHandle methodHandle, final MethodType callType, final Boolean callerVarArg) { 2536 final MethodType methodType = methodHandle.type(); 2537 if (methodType.equals(callType.changeReturnType(methodType.returnType()))) { 2538 return methodHandle; 2539 } 2540 2541 final int parameterCount = methodType.parameterCount(); 2542 final int callCount = callType.parameterCount(); 2543 2544 final boolean isCalleeVarArg = parameterCount > 0 && methodType.parameterType(parameterCount - 1).isArray(); 2545 final boolean isCallerVarArg = callerVarArg != null ? callerVarArg.booleanValue() : callCount > 0 && 2546 callType.parameterType(callCount - 1).isArray(); 2547 2548 if (isCalleeVarArg) { 2549 return isCallerVarArg ? 2550 methodHandle : 2551 MH.asCollector(methodHandle, Object[].class, callCount - parameterCount + 1); 2552 } 2553 2554 if (isCallerVarArg) { 2555 return adaptHandleToVarArgCallSite(methodHandle, callCount); 2556 } 2557 2558 if (callCount < parameterCount) { 2559 final int missingArgs = parameterCount - callCount; 2560 final Object[] fillers = new Object[missingArgs]; 2561 2562 Arrays.fill(fillers, UNDEFINED); 2563 2564 if (isCalleeVarArg) { 2565 fillers[missingArgs - 1] = ScriptRuntime.EMPTY_ARRAY; 2566 } 2567 2568 return MH.insertArguments( 2569 methodHandle, 2570 parameterCount - missingArgs, 2571 fillers); 2572 } 2573 2574 if (callCount > parameterCount) { 2575 final int discardedArgs = callCount - parameterCount; 2576 2577 final Class<?>[] discards = new Class<?>[discardedArgs]; 2578 Arrays.fill(discards, Object.class); 2579 2580 return MH.dropArguments(methodHandle, callCount - discardedArgs, discards); 2581 } 2582 2583 return methodHandle; 2584 } 2585 2586 static MethodHandle adaptHandleToVarArgCallSite(final MethodHandle mh, final int callSiteParamCount) { 2587 final int spreadArgs = mh.type().parameterCount() - callSiteParamCount + 1; 2588 return MH.filterArguments( 2589 MH.asSpreader( 2590 mh, 2591 Object[].class, 2592 spreadArgs), 2593 callSiteParamCount - 1, 2594 MH.insertArguments( 2595 TRUNCATINGFILTER, 2596 0, 2597 spreadArgs) 2598 ); 2599 } 2600 2601 @SuppressWarnings("unused") 2602 private static Object[] truncatingFilter(final int n, final Object[] array) { 2603 final int length = array == null ? 0 : array.length; 2604 if (n == length) { 2605 return array == null ? ScriptRuntime.EMPTY_ARRAY : array; 2606 } 2607 2608 final Object[] newArray = new Object[n]; 2609 2610 if (array != null) { 2611 System.arraycopy(array, 0, newArray, 0, Math.min(n, length)); 2612 } 2613 2614 if (length < n) { 2615 final Object fill = UNDEFINED; 2616 2617 for (int i = length; i < n; i++) { 2618 newArray[i] = fill; 2619 } 2620 } 2621 2622 return newArray; 2623 } 2624 2625 /** 2626 * Numeric length setter for length property 2627 * 2628 * @param newLength new length to set 2629 */ 2630 public final void setLength(final long newLength) { 2631 final long arrayLength = getArray().length(); 2632 if (newLength == arrayLength) { 2633 return; 2634 } 2635 2636 if (newLength > arrayLength) { 2637 setArray(getArray().ensure(newLength - 1)); 2638 if (getArray().canDelete(arrayLength, newLength - 1, false)) { 2639 setArray(getArray().delete(arrayLength, newLength - 1)); 2640 } 2641 return; 2642 } 2643 2644 if (newLength < arrayLength) { 2645 long actualLength = newLength; 2646 2647 // Check for numeric keys in property map and delete them or adjust length, depending on whether 2648 // they're defined as configurable. See ES5 #15.4.5.2 2649 if (getMap().containsArrayKeys()) { 2650 2651 for (long l = arrayLength - 1; l >= newLength; l--) { 2652 final FindProperty find = findProperty(JSType.toString(l), false); 2653 2654 if (find != null) { 2655 2656 if (find.getProperty().isConfigurable()) { 2657 deleteOwnProperty(find.getProperty()); 2658 } else { 2659 actualLength = l + 1; 2660 break; 2661 } 2662 } 2663 } 2664 } 2665 2666 setArray(getArray().shrink(actualLength)); 2667 getArray().setLength(actualLength); 2668 } 2669 } 2670 2671 private int getInt(final int index, final String key, final int programPoint) { 2672 if (isValidArrayIndex(index)) { 2673 for (ScriptObject object = this; ; ) { 2674 if (object.getMap().containsArrayKeys()) { 2675 final FindProperty find = object.findProperty(key, false, false, this); 2676 2677 if (find != null) { 2678 return getIntValue(find, programPoint); 2679 } 2680 } 2681 2682 if ((object = object.getProto()) == null) { 2683 break; 2684 } 2685 2686 final ArrayData array = object.getArray(); 2687 2688 if (array.has(index)) { 2689 return isValid(programPoint) ? 2690 array.getIntOptimistic(index, programPoint) : 2691 array.getInt(index); 2692 } 2693 } 2694 } else { 2695 final FindProperty find = findProperty(key, true); 2696 2697 if (find != null) { 2698 return getIntValue(find, programPoint); 2699 } 2700 } 2701 2702 return JSType.toInt32(invokeNoSuchProperty(key, programPoint)); 2703 } 2704 2705 @Override 2706 public int getInt(final Object key, final int programPoint) { 2707 final Object primitiveKey = JSType.toPrimitive(key, String.class); 2708 final int index = getArrayIndex(primitiveKey); 2709 final ArrayData array = getArray(); 2710 2711 if (array.has(index)) { 2712 return isValid(programPoint) ? array.getIntOptimistic(index, programPoint) : array.getInt(index); 2713 } 2714 2715 return getInt(index, JSType.toString(primitiveKey), programPoint); 2716 } 2717 2718 @Override 2719 public int getInt(final double key, final int programPoint) { 2720 final int index = getArrayIndex(key); 2721 final ArrayData array = getArray(); 2722 2723 if (array.has(index)) { 2724 return isValid(programPoint) ? array.getIntOptimistic(index, programPoint) : array.getInt(index); 2725 } 2726 2727 return getInt(index, JSType.toString(key), programPoint); 2728 } 2729 2730 @Override 2731 public int getInt(final long key, final int programPoint) { 2732 final int index = getArrayIndex(key); 2733 final ArrayData array = getArray(); 2734 2735 if (array.has(index)) { 2736 return isValid(programPoint) ? array.getIntOptimistic(index, programPoint) : array.getInt(index); 2737 } 2738 2739 return getInt(index, JSType.toString(key), programPoint); 2740 } 2741 2742 @Override 2743 public int getInt(final int key, final int programPoint) { 2744 final int index = getArrayIndex(key); 2745 final ArrayData array = getArray(); 2746 2747 if (array.has(index)) { 2748 return isValid(programPoint) ? array.getIntOptimistic(key, programPoint) : array.getInt(key); 2749 } 2750 2751 return getInt(index, JSType.toString(key), programPoint); 2752 } 2753 2754 private long getLong(final int index, final String key, final int programPoint) { 2755 if (isValidArrayIndex(index)) { 2756 for (ScriptObject object = this; ; ) { 2757 if (object.getMap().containsArrayKeys()) { 2758 final FindProperty find = object.findProperty(key, false, false, this); 2759 if (find != null) { 2760 return getLongValue(find, programPoint); 2761 } 2762 } 2763 2764 if ((object = object.getProto()) == null) { 2765 break; 2766 } 2767 2768 final ArrayData array = object.getArray(); 2769 2770 if (array.has(index)) { 2771 return isValid(programPoint) ? 2772 array.getLongOptimistic(index, programPoint) : 2773 array.getLong(index); 2774 } 2775 } 2776 } else { 2777 final FindProperty find = findProperty(key, true); 2778 2779 if (find != null) { 2780 return getLongValue(find, programPoint); 2781 } 2782 } 2783 2784 return JSType.toLong(invokeNoSuchProperty(key, programPoint)); 2785 } 2786 2787 @Override 2788 public long getLong(final Object key, final int programPoint) { 2789 final Object primitiveKey = JSType.toPrimitive(key, String.class); 2790 final int index = getArrayIndex(primitiveKey); 2791 final ArrayData array = getArray(); 2792 2793 if (array.has(index)) { 2794 return isValid(programPoint) ? array.getLongOptimistic(index, programPoint) : array.getLong(index); 2795 } 2796 2797 return getLong(index, JSType.toString(primitiveKey), programPoint); 2798 } 2799 2800 @Override 2801 public long getLong(final double key, final int programPoint) { 2802 final int index = getArrayIndex(key); 2803 final ArrayData array = getArray(); 2804 2805 if (array.has(index)) { 2806 return isValid(programPoint) ? array.getLongOptimistic(index, programPoint) : array.getLong(index); 2807 } 2808 2809 return getLong(index, JSType.toString(key), programPoint); 2810 } 2811 2812 @Override 2813 public long getLong(final long key, final int programPoint) { 2814 final int index = getArrayIndex(key); 2815 final ArrayData array = getArray(); 2816 2817 if (array.has(index)) { 2818 return isValid(programPoint) ? array.getLongOptimistic(index, programPoint) : array.getLong(index); 2819 } 2820 2821 return getLong(index, JSType.toString(key), programPoint); 2822 } 2823 2824 @Override 2825 public long getLong(final int key, final int programPoint) { 2826 final int index = getArrayIndex(key); 2827 final ArrayData array = getArray(); 2828 2829 if (array.has(index)) { 2830 return isValid(programPoint) ? array.getLongOptimistic(key, programPoint) : array.getLong(key); 2831 } 2832 2833 return getLong(index, JSType.toString(key), programPoint); 2834 } 2835 2836 private double getDouble(final int index, final String key, final int programPoint) { 2837 if (isValidArrayIndex(index)) { 2838 for (ScriptObject object = this; ; ) { 2839 if (object.getMap().containsArrayKeys()) { 2840 final FindProperty find = object.findProperty(key, false, false, this); 2841 if (find != null) { 2842 return getDoubleValue(find, programPoint); 2843 } 2844 } 2845 2846 if ((object = object.getProto()) == null) { 2847 break; 2848 } 2849 2850 final ArrayData array = object.getArray(); 2851 2852 if (array.has(index)) { 2853 return isValid(programPoint) ? 2854 array.getDoubleOptimistic(index, programPoint) : 2855 array.getDouble(index); 2856 } 2857 } 2858 } else { 2859 final FindProperty find = findProperty(key, true); 2860 2861 if (find != null) { 2862 return getDoubleValue(find, programPoint); 2863 } 2864 } 2865 2866 return JSType.toNumber(invokeNoSuchProperty(key, INVALID_PROGRAM_POINT)); 2867 } 2868 2869 @Override 2870 public double getDouble(final Object key, final int programPoint) { 2871 final Object primitiveKey = JSType.toPrimitive(key, String.class); 2872 final int index = getArrayIndex(primitiveKey); 2873 final ArrayData array = getArray(); 2874 2875 if (array.has(index)) { 2876 return isValid(programPoint) ? array.getDoubleOptimistic(index, programPoint) : array.getDouble(index); 2877 } 2878 2879 return getDouble(index, JSType.toString(primitiveKey), programPoint); 2880 } 2881 2882 @Override 2883 public double getDouble(final double key, final int programPoint) { 2884 final int index = getArrayIndex(key); 2885 final ArrayData array = getArray(); 2886 2887 if (array.has(index)) { 2888 return isValid(programPoint) ? array.getDoubleOptimistic(index, programPoint) : array.getDouble(index); 2889 } 2890 2891 return getDouble(index, JSType.toString(key), programPoint); 2892 } 2893 2894 @Override 2895 public double getDouble(final long key, final int programPoint) { 2896 final int index = getArrayIndex(key); 2897 final ArrayData array = getArray(); 2898 2899 if (array.has(index)) { 2900 return isValid(programPoint) ? array.getDoubleOptimistic(index, programPoint) : array.getDouble(index); 2901 } 2902 2903 return getDouble(index, JSType.toString(key), programPoint); 2904 } 2905 2906 @Override 2907 public double getDouble(final int key, final int programPoint) { 2908 final int index = getArrayIndex(key); 2909 final ArrayData array = getArray(); 2910 2911 if (array.has(index)) { 2912 return isValid(programPoint) ? array.getDoubleOptimistic(key, programPoint) : array.getDouble(key); 2913 } 2914 2915 return getDouble(index, JSType.toString(key), programPoint); 2916 } 2917 2918 private Object get(final int index, final String key) { 2919 if (isValidArrayIndex(index)) { 2920 for (ScriptObject object = this; ; ) { 2921 if (object.getMap().containsArrayKeys()) { 2922 final FindProperty find = object.findProperty(key, false, false, this); 2923 2924 if (find != null) { 2925 return find.getObjectValue(); 2926 } 2927 } 2928 2929 if ((object = object.getProto()) == null) { 2930 break; 2931 } 2932 2933 final ArrayData array = object.getArray(); 2934 2935 if (array.has(index)) { 2936 return array.getObject(index); 2937 } 2938 } 2939 } else { 2940 final FindProperty find = findProperty(key, true); 2941 2942 if (find != null) { 2943 return find.getObjectValue(); 2944 } 2945 } 2946 2947 return invokeNoSuchProperty(key, INVALID_PROGRAM_POINT); 2948 } 2949 2950 @Override 2951 public Object get(final Object key) { 2952 final Object primitiveKey = JSType.toPrimitive(key, String.class); 2953 final int index = getArrayIndex(primitiveKey); 2954 final ArrayData array = getArray(); 2955 2956 if (array.has(index)) { 2957 return array.getObject(index); 2958 } 2959 2960 return get(index, JSType.toString(primitiveKey)); 2961 } 2962 2963 @Override 2964 public Object get(final double key) { 2965 final int index = getArrayIndex(key); 2966 final ArrayData array = getArray(); 2967 2968 if (array.has(index)) { 2969 return array.getObject(index); 2970 } 2971 2972 return get(index, JSType.toString(key)); 2973 } 2974 2975 @Override 2976 public Object get(final long key) { 2977 final int index = getArrayIndex(key); 2978 final ArrayData array = getArray(); 2979 2980 if (array.has(index)) { 2981 return array.getObject(index); 2982 } 2983 2984 return get(index, JSType.toString(key)); 2985 } 2986 2987 @Override 2988 public Object get(final int key) { 2989 final int index = getArrayIndex(key); 2990 final ArrayData array = getArray(); 2991 2992 if (array.has(index)) { 2993 return array.getObject(index); 2994 } 2995 2996 return get(index, JSType.toString(key)); 2997 } 2998 2999 private boolean doesNotHaveCheckArrayKeys(final long longIndex, final int value, final boolean strict) { 3000 if (getMap().containsArrayKeys()) { 3001 final String key = JSType.toString(longIndex); 3002 final FindProperty find = findProperty(key, true); 3003 if (find != null) { 3004 setObject(find, strict, key, value); 3005 return true; 3006 } 3007 } 3008 return false; 3009 } 3010 3011 private boolean doesNotHaveCheckArrayKeys(final long longIndex, final long value, final boolean strict) { 3012 if (getMap().containsArrayKeys()) { 3013 final String key = JSType.toString(longIndex); 3014 final FindProperty find = findProperty(key, true); 3015 if (find != null) { 3016 setObject(find, strict, key, value); 3017 return true; 3018 } 3019 } 3020 return false; 3021 } 3022 3023 private boolean doesNotHaveCheckArrayKeys(final long longIndex, final double value, final boolean strict) { 3024 if (getMap().containsArrayKeys()) { 3025 final String key = JSType.toString(longIndex); 3026 final FindProperty find = findProperty(key, true); 3027 if (find != null) { 3028 setObject(find, strict, key, value); 3029 return true; 3030 } 3031 } 3032 return false; 3033 } 3034 3035 private boolean doesNotHaveCheckArrayKeys(final long longIndex, final Object value, final boolean strict) { 3036 if (getMap().containsArrayKeys()) { 3037 final String key = JSType.toString(longIndex); 3038 final FindProperty find = findProperty(key, true); 3039 if (find != null) { 3040 setObject(find, strict, key, value); 3041 return true; 3042 } 3043 } 3044 return false; 3045 } 3046 3047 //value agnostic 3048 private boolean doesNotHaveEnsureLength(final long longIndex, final long oldLength, final boolean strict) { 3049 if (longIndex >= oldLength) { 3050 if (!isExtensible()) { 3051 if (strict) { 3052 throw typeError("object.non.extensible", JSType.toString(longIndex), ScriptRuntime.safeToString(this)); 3053 } 3054 return true; 3055 } 3056 setArray(getArray().ensure(longIndex)); 3057 } 3058 return false; 3059 } 3060 3061 private void doesNotHaveEnsureDelete(final long longIndex, final long oldLength, final boolean strict) { 3062 if (longIndex > oldLength) { 3063 ArrayData array = getArray(); 3064 if (array.canDelete(oldLength, longIndex - 1, strict)) { 3065 array = array.delete(oldLength, longIndex - 1); 3066 } 3067 setArray(array); 3068 } 3069 } 3070 3071 private void doesNotHave(final int index, final int value, final boolean strict) { 3072 final long oldLength = getArray().length(); 3073 final long longIndex = ArrayIndex.toLongIndex(index); 3074 if (!doesNotHaveCheckArrayKeys(longIndex, value, strict) && !doesNotHaveEnsureLength(longIndex, oldLength, strict)) { 3075 setArray(getArray().set(index, value, strict)); 3076 doesNotHaveEnsureDelete(longIndex, oldLength, strict); 3077 } 3078 } 3079 3080 private void doesNotHave(final int index, final long value, final boolean strict) { 3081 final long oldLength = getArray().length(); 3082 final long longIndex = ArrayIndex.toLongIndex(index); 3083 if (!doesNotHaveCheckArrayKeys(longIndex, value, strict) && !doesNotHaveEnsureLength(longIndex, oldLength, strict)) { 3084 setArray(getArray().set(index, value, strict)); 3085 doesNotHaveEnsureDelete(longIndex, oldLength, strict); 3086 } 3087 } 3088 3089 private void doesNotHave(final int index, final double value, final boolean strict) { 3090 final long oldLength = getArray().length(); 3091 final long longIndex = ArrayIndex.toLongIndex(index); 3092 if (!doesNotHaveCheckArrayKeys(longIndex, value, strict) && !doesNotHaveEnsureLength(longIndex, oldLength, strict)) { 3093 setArray(getArray().set(index, value, strict)); 3094 doesNotHaveEnsureDelete(longIndex, oldLength, strict); 3095 } 3096 } 3097 3098 private void doesNotHave(final int index, final Object value, final boolean strict) { 3099 final long oldLength = getArray().length(); 3100 final long longIndex = ArrayIndex.toLongIndex(index); 3101 if (!doesNotHaveCheckArrayKeys(longIndex, value, strict) && !doesNotHaveEnsureLength(longIndex, oldLength, strict)) { 3102 setArray(getArray().set(index, value, strict)); 3103 doesNotHaveEnsureDelete(longIndex, oldLength, strict); 3104 } 3105 } 3106 3107 /** 3108 * This is the most generic of all Object setters. Most of the others use this in some form. 3109 * TODO: should be further specialized 3110 * 3111 * @param find found property 3112 * @param strict are we in strict mode 3113 * @param key property key 3114 * @param value property value 3115 */ 3116 public final void setObject(final FindProperty find, final boolean strict, final String key, final Object value) { 3117 FindProperty f = find; 3118 3119 if (f != null && f.isInherited() && !(f.getProperty() instanceof UserAccessorProperty) && !isScope()) { 3120 // Setting a property should not modify the property in prototype unless this is a scope object. 3121 f = null; 3122 } 3123 3124 if (f != null) { 3125 if (!f.getProperty().isWritable()) { 3126 if (strict) { 3127 throw typeError("property.not.writable", key, ScriptRuntime.safeToString(this)); 3128 } 3129 3130 return; 3131 } 3132 3133 f.setValue(value, strict); 3134 3135 } else if (!isExtensible()) { 3136 if (strict) { 3137 throw typeError("object.non.extensible", key, ScriptRuntime.safeToString(this)); 3138 } 3139 } else { 3140 ScriptObject sobj = this; 3141 // undefined scope properties are set in the global object. 3142 if (isScope()) { 3143 while (sobj != null && !(sobj instanceof Global)) { 3144 sobj = sobj.getProto(); 3145 } 3146 assert sobj != null : "no parent global object in scope"; 3147 } 3148 //this will unbox any Number object to its primitive type in case the 3149 //property supports primitive types, so it doesn't matter that it comes 3150 //in as an Object. 3151 sobj.addSpillProperty(key, 0, value, true); 3152 } 3153 } 3154 3155 @Override 3156 public void set(final Object key, final int value, final boolean strict) { 3157 final Object primitiveKey = JSType.toPrimitive(key, String.class); 3158 final int index = getArrayIndex(primitiveKey); 3159 3160 if (isValidArrayIndex(index)) { 3161 if (getArray().has(index)) { 3162 setArray(getArray().set(index, value, strict)); 3163 } else { 3164 doesNotHave(index, value, strict); 3165 } 3166 3167 return; 3168 } 3169 3170 final String propName = JSType.toString(primitiveKey); 3171 setObject(findProperty(propName, true), strict, propName, JSType.toObject(value)); 3172 } 3173 3174 @Override 3175 public void set(final Object key, final long value, final boolean strict) { 3176 final Object primitiveKey = JSType.toPrimitive(key, String.class); 3177 final int index = getArrayIndex(primitiveKey); 3178 3179 if (isValidArrayIndex(index)) { 3180 if (getArray().has(index)) { 3181 setArray(getArray().set(index, value, strict)); 3182 } else { 3183 doesNotHave(index, value, strict); 3184 } 3185 3186 return; 3187 } 3188 3189 final String propName = JSType.toString(primitiveKey); 3190 setObject(findProperty(propName, true), strict, propName, JSType.toObject(value)); 3191 } 3192 3193 @Override 3194 public void set(final Object key, final double value, final boolean strict) { 3195 final Object primitiveKey = JSType.toPrimitive(key, String.class); 3196 final int index = getArrayIndex(primitiveKey); 3197 3198 if (isValidArrayIndex(index)) { 3199 if (getArray().has(index)) { 3200 setArray(getArray().set(index, value, strict)); 3201 } else { 3202 doesNotHave(index, value, strict); 3203 } 3204 3205 return; 3206 } 3207 3208 final String propName = JSType.toString(primitiveKey); 3209 setObject(findProperty(propName, true), strict, propName, JSType.toObject(value)); 3210 } 3211 3212 @Override 3213 public void set(final Object key, final Object value, final boolean strict) { 3214 final Object primitiveKey = JSType.toPrimitive(key, String.class); 3215 final int index = getArrayIndex(primitiveKey); 3216 3217 if (isValidArrayIndex(index)) { 3218 if (getArray().has(index)) { 3219 setArray(getArray().set(index, value, strict)); 3220 } else { 3221 doesNotHave(index, value, strict); 3222 } 3223 3224 return; 3225 } 3226 3227 final String propName = JSType.toString(primitiveKey); 3228 setObject(findProperty(propName, true), strict, propName, value); 3229 } 3230 3231 @Override 3232 public void set(final double key, final int value, final boolean strict) { 3233 final int index = getArrayIndex(key); 3234 3235 if (isValidArrayIndex(index)) { 3236 if (getArray().has(index)) { 3237 setArray(getArray().set(index, value, strict)); 3238 } else { 3239 doesNotHave(index, value, strict); 3240 } 3241 3242 return; 3243 } 3244 3245 final String propName = JSType.toString(key); 3246 setObject(findProperty(propName, true), strict, propName, JSType.toObject(value)); 3247 } 3248 3249 @Override 3250 public void set(final double key, final long value, final boolean strict) { 3251 final int index = getArrayIndex(key); 3252 3253 if (isValidArrayIndex(index)) { 3254 if (getArray().has(index)) { 3255 setArray(getArray().set(index, value, strict)); 3256 } else { 3257 doesNotHave(index, value, strict); 3258 } 3259 3260 return; 3261 } 3262 3263 final String propName = JSType.toString(key); 3264 setObject(findProperty(propName, true), strict, propName, JSType.toObject(value)); 3265 } 3266 3267 @Override 3268 public void set(final double key, final double value, final boolean strict) { 3269 final int index = getArrayIndex(key); 3270 3271 if (isValidArrayIndex(index)) { 3272 if (getArray().has(index)) { 3273 setArray(getArray().set(index, value, strict)); 3274 } else { 3275 doesNotHave(index, value, strict); 3276 } 3277 3278 return; 3279 } 3280 3281 final String propName = JSType.toString(key); 3282 setObject(findProperty(propName, true), strict, propName, JSType.toObject(value)); 3283 } 3284 3285 @Override 3286 public void set(final double key, final Object value, final boolean strict) { 3287 final int index = getArrayIndex(key); 3288 3289 if (isValidArrayIndex(index)) { 3290 if (getArray().has(index)) { 3291 setArray(getArray().set(index, value, strict)); 3292 } else { 3293 doesNotHave(index, value, strict); 3294 } 3295 3296 return; 3297 } 3298 3299 final String propName = JSType.toString(key); 3300 setObject(findProperty(propName, true), strict, propName, value); 3301 } 3302 3303 @Override 3304 public void set(final long key, final int value, final boolean strict) { 3305 final int index = getArrayIndex(key); 3306 3307 if (isValidArrayIndex(index)) { 3308 if (getArray().has(index)) { 3309 setArray(getArray().set(index, value, strict)); 3310 } else { 3311 doesNotHave(index, value, strict); 3312 } 3313 3314 return; 3315 } 3316 3317 final String propName = JSType.toString(key); 3318 setObject(findProperty(propName, true), strict, propName, JSType.toObject(value)); 3319 } 3320 3321 @Override 3322 public void set(final long key, final long value, final boolean strict) { 3323 final int index = getArrayIndex(key); 3324 3325 if (isValidArrayIndex(index)) { 3326 if (getArray().has(index)) { 3327 setArray(getArray().set(index, value, strict)); 3328 } else { 3329 doesNotHave(index, value, strict); 3330 } 3331 3332 return; 3333 } 3334 3335 final String propName = JSType.toString(key); 3336 setObject(findProperty(propName, true), strict, propName, JSType.toObject(value)); 3337 } 3338 3339 @Override 3340 public void set(final long key, final double value, final boolean strict) { 3341 final int index = getArrayIndex(key); 3342 3343 if (isValidArrayIndex(index)) { 3344 if (getArray().has(index)) { 3345 setArray(getArray().set(index, value, strict)); 3346 } else { 3347 doesNotHave(index, value, strict); 3348 } 3349 3350 return; 3351 } 3352 3353 final String propName = JSType.toString(key); 3354 setObject(findProperty(propName, true), strict, propName, JSType.toObject(value)); 3355 } 3356 3357 @Override 3358 public void set(final long key, final Object value, final boolean strict) { 3359 final int index = getArrayIndex(key); 3360 3361 if (isValidArrayIndex(index)) { 3362 if (getArray().has(index)) { 3363 setArray(getArray().set(index, value, strict)); 3364 } else { 3365 doesNotHave(index, value, strict); 3366 } 3367 3368 return; 3369 } 3370 3371 final String propName = JSType.toString(key); 3372 setObject(findProperty(propName, true), strict, propName, value); 3373 } 3374 3375 @Override 3376 public void set(final int key, final int value, final boolean strict) { 3377 final int index = getArrayIndex(key); 3378 if (isValidArrayIndex(index)) { 3379 if (getArray().has(index)) { 3380 setArray(getArray().set(index, value, strict)); 3381 } else { 3382 doesNotHave(index, value, strict); 3383 } 3384 return; 3385 } 3386 3387 final String propName = JSType.toString(key); 3388 setObject(findProperty(propName, true), strict, propName, JSType.toObject(value)); 3389 } 3390 3391 @Override 3392 public void set(final int key, final long value, final boolean strict) { 3393 final int index = getArrayIndex(key); 3394 3395 if (isValidArrayIndex(index)) { 3396 if (getArray().has(index)) { 3397 setArray(getArray().set(index, value, strict)); 3398 } else { 3399 doesNotHave(index, value, strict); 3400 } 3401 3402 return; 3403 } 3404 3405 final String propName = JSType.toString(key); 3406 setObject(findProperty(propName, true), strict, propName, JSType.toObject(value)); 3407 } 3408 3409 @Override 3410 public void set(final int key, final double value, final boolean strict) { 3411 final int index = getArrayIndex(key); 3412 3413 if (isValidArrayIndex(index)) { 3414 if (getArray().has(index)) { 3415 setArray(getArray().set(index, value, strict)); 3416 } else { 3417 doesNotHave(index, value, strict); 3418 } 3419 3420 return; 3421 } 3422 3423 final String propName = JSType.toString(key); 3424 setObject(findProperty(propName, true), strict, propName, JSType.toObject(value)); 3425 } 3426 3427 @Override 3428 public void set(final int key, final Object value, final boolean strict) { 3429 final int index = getArrayIndex(key); 3430 3431 if (isValidArrayIndex(index)) { 3432 if (getArray().has(index)) { 3433 setArray(getArray().set(index, value, strict)); 3434 } else { 3435 doesNotHave(index, value, strict); 3436 } 3437 3438 return; 3439 } 3440 3441 final String propName = JSType.toString(key); 3442 setObject(findProperty(propName, true), strict, propName, value); 3443 } 3444 3445 @Override 3446 public boolean has(final Object key) { 3447 final Object primitiveKey = JSType.toPrimitive(key); 3448 final int index = getArrayIndex(primitiveKey); 3449 return isValidArrayIndex(index) ? hasArrayProperty(index) : hasProperty(JSType.toString(primitiveKey), true); 3450 } 3451 3452 @Override 3453 public boolean has(final double key) { 3454 final int index = getArrayIndex(key); 3455 return isValidArrayIndex(index) ? hasArrayProperty(index) : hasProperty(JSType.toString(key), true); 3456 } 3457 3458 @Override 3459 public boolean has(final long key) { 3460 final int index = getArrayIndex(key); 3461 return isValidArrayIndex(index) ? hasArrayProperty(index) : hasProperty(JSType.toString(key), true); 3462 } 3463 3464 @Override 3465 public boolean has(final int key) { 3466 final int index = getArrayIndex(key); 3467 return isValidArrayIndex(index) ? hasArrayProperty(index) : hasProperty(JSType.toString(key), true); 3468 } 3469 3470 private boolean hasArrayProperty(final int index) { 3471 boolean hasArrayKeys = false; 3472 3473 for (ScriptObject self = this; self != null; self = self.getProto()) { 3474 if (self.getArray().has(index)) { 3475 return true; 3476 } 3477 hasArrayKeys = hasArrayKeys || self.getMap().containsArrayKeys(); 3478 } 3479 3480 return hasArrayKeys && hasProperty(ArrayIndex.toKey(index), true); 3481 } 3482 3483 @Override 3484 public boolean hasOwnProperty(final Object key) { 3485 final Object primitiveKey = JSType.toPrimitive(key, String.class); 3486 final int index = getArrayIndex(primitiveKey); 3487 return isValidArrayIndex(index) ? hasOwnArrayProperty(index) : hasProperty(JSType.toString(primitiveKey), false); 3488 } 3489 3490 @Override 3491 public boolean hasOwnProperty(final int key) { 3492 final int index = getArrayIndex(key); 3493 return isValidArrayIndex(index) ? hasOwnArrayProperty(index) : hasProperty(JSType.toString(key), false); 3494 } 3495 3496 @Override 3497 public boolean hasOwnProperty(final long key) { 3498 final int index = getArrayIndex(key); 3499 return isValidArrayIndex(index) ? hasOwnArrayProperty(index) : hasProperty(JSType.toString(key), false); 3500 } 3501 3502 @Override 3503 public boolean hasOwnProperty(final double key) { 3504 final int index = getArrayIndex(key); 3505 return isValidArrayIndex(index) ? hasOwnArrayProperty(index) : hasProperty(JSType.toString(key), false); 3506 } 3507 3508 private boolean hasOwnArrayProperty(final int index) { 3509 return getArray().has(index) || getMap().containsArrayKeys() && hasProperty(ArrayIndex.toKey(index), false); 3510 } 3511 3512 @Override 3513 public boolean delete(final int key, final boolean strict) { 3514 final int index = getArrayIndex(key); 3515 final ArrayData array = getArray(); 3516 3517 if (array.has(index)) { 3518 if (array.canDelete(index, strict)) { 3519 setArray(array.delete(index)); 3520 return true; 3521 } 3522 return false; 3523 } 3524 3525 return deleteObject(JSType.toObject(key), strict); 3526 } 3527 3528 @Override 3529 public boolean delete(final long key, final boolean strict) { 3530 final int index = getArrayIndex(key); 3531 final ArrayData array = getArray(); 3532 3533 if (array.has(index)) { 3534 if (array.canDelete(index, strict)) { 3535 setArray(array.delete(index)); 3536 return true; 3537 } 3538 return false; 3539 } 3540 3541 return deleteObject(JSType.toObject(key), strict); 3542 } 3543 3544 @Override 3545 public boolean delete(final double key, final boolean strict) { 3546 final int index = getArrayIndex(key); 3547 final ArrayData array = getArray(); 3548 3549 if (array.has(index)) { 3550 if (array.canDelete(index, strict)) { 3551 setArray(array.delete(index)); 3552 return true; 3553 } 3554 return false; 3555 } 3556 3557 return deleteObject(JSType.toObject(key), strict); 3558 } 3559 3560 @Override 3561 public boolean delete(final Object key, final boolean strict) { 3562 final Object primitiveKey = JSType.toPrimitive(key, String.class); 3563 final int index = getArrayIndex(primitiveKey); 3564 final ArrayData array = getArray(); 3565 3566 if (array.has(index)) { 3567 if (array.canDelete(index, strict)) { 3568 setArray(array.delete(index)); 3569 return true; 3570 } 3571 return false; 3572 } 3573 3574 return deleteObject(primitiveKey, strict); 3575 } 3576 3577 private boolean deleteObject(final Object key, final boolean strict) { 3578 final String propName = JSType.toString(key); 3579 final FindProperty find = findProperty(propName, false); 3580 3581 if (find == null) { 3582 return true; 3583 } 3584 3585 if (!find.getProperty().isConfigurable()) { 3586 if (strict) { 3587 throw typeError("cant.delete.property", propName, ScriptRuntime.safeToString(this)); 3588 } 3589 return false; 3590 } 3591 3592 final Property prop = find.getProperty(); 3593 deleteOwnProperty(prop); 3594 3595 return true; 3596 } 3597 3598 /** 3599 * Make a new UserAccessorProperty property. getter and setter functions are stored in 3600 * this ScriptObject and slot values are used in property object. 3601 * 3602 * @param key the property name 3603 * @param propertyFlags attribute flags of the property 3604 * @param getter getter function for the property 3605 * @param setter setter function for the property 3606 * @return the newly created UserAccessorProperty 3607 */ 3608 protected final UserAccessorProperty newUserAccessors(final String key, final int propertyFlags, final ScriptFunction getter, final ScriptFunction setter) { 3609 final UserAccessorProperty uc = getMap().newUserAccessors(key, propertyFlags); 3610 //property.getSetter(Object.class, getMap()); 3611 uc.setAccessors(this, getMap(), new UserAccessorProperty.Accessors(getter, setter)); 3612 return uc; 3613 } 3614 3615 Object ensureSpillSize(final int slot) { 3616 if (slot < spillLength) { 3617 return this; 3618 } 3619 final int newLength = alignUp(slot + 1, SPILL_RATE); 3620 final Object[] newObjectSpill = new Object[newLength]; 3621 final long[] newPrimitiveSpill = OBJECT_FIELDS_ONLY ? null : new long[newLength]; 3622 3623 if (objectSpill != null) { 3624 System.arraycopy(objectSpill, 0, newObjectSpill, 0, spillLength); 3625 if (!OBJECT_FIELDS_ONLY) { 3626 System.arraycopy(primitiveSpill, 0, newPrimitiveSpill, 0, spillLength); 3627 } 3628 } 3629 3630 this.primitiveSpill = newPrimitiveSpill; 3631 this.objectSpill = newObjectSpill; 3632 this.spillLength = newLength; 3633 3634 return this; 3635 } 3636 3637 private static MethodHandle findOwnMH_V(final Class<? extends ScriptObject> clazz, final String name, final Class<?> rtype, final Class<?>... types) { 3638 // TODO: figure out how can it work for NativeArray$Prototype etc. 3639 return MH.findVirtual(MethodHandles.lookup(), ScriptObject.class, name, MH.type(rtype, types)); 3640 } 3641 3642 private static MethodHandle findOwnMH_V(final String name, final Class<?> rtype, final Class<?>... types) { 3643 return findOwnMH_V(ScriptObject.class, name, rtype, types); 3644 } 3645 3646 private static MethodHandle findOwnMH_S(final String name, final Class<?> rtype, final Class<?>... types) { 3647 return MH.findStatic(MethodHandles.lookup(), ScriptObject.class, name, MH.type(rtype, types)); 3648 } 3649 3650 private static MethodHandle getKnownFunctionPropertyGuardSelf(final PropertyMap map, final MethodHandle getter, final ScriptFunction func) { 3651 return MH.insertArguments(KNOWNFUNCPROPGUARDSELF, 1, map, getter, func); 3652 } 3653 3654 @SuppressWarnings("unused") 3655 private static boolean knownFunctionPropertyGuardSelf(final Object self, final PropertyMap map, final MethodHandle getter, final ScriptFunction func) { 3656 if (self instanceof ScriptObject && ((ScriptObject)self).getMap() == map) { 3657 try { 3658 return getter.invokeExact(self) == func; 3659 } catch (final RuntimeException | Error e) { 3660 throw e; 3661 } catch (final Throwable t) { 3662 throw new RuntimeException(t); 3663 } 3664 } 3665 3666 return false; 3667 } 3668 3669 private static MethodHandle getKnownFunctionPropertyGuardProto(final PropertyMap map, final MethodHandle getter, final int depth, final ScriptFunction func) { 3670 return MH.insertArguments(KNOWNFUNCPROPGUARDPROTO, 1, map, getter, depth, func); 3671 } 3672 3673 private static ScriptObject getProto(final ScriptObject self, final int depth) { 3674 ScriptObject proto = self; 3675 for (int d = 0; d < depth; d++) { 3676 proto = proto.getProto(); 3677 if (proto == null) { 3678 return null; 3679 } 3680 } 3681 3682 return proto; 3683 } 3684 3685 @SuppressWarnings("unused") 3686 private static boolean knownFunctionPropertyGuardProto(final Object self, final PropertyMap map, final MethodHandle getter, final int depth, final ScriptFunction func) { 3687 if (self instanceof ScriptObject && ((ScriptObject)self).getMap() == map) { 3688 final ScriptObject proto = getProto((ScriptObject)self, depth); 3689 if (proto == null) { 3690 return false; 3691 } 3692 try { 3693 return getter.invokeExact((Object)proto) == func; 3694 } catch (final RuntimeException | Error e) { 3695 throw e; 3696 } catch (final Throwable t) { 3697 throw new RuntimeException(t); 3698 } 3699 } 3700 3701 return false; 3702 } 3703 3704 /** This is updated only in debug mode - counts number of {@code ScriptObject} instances created */ 3705 private static int count; 3706 3707 /** This is updated only in debug mode - counts number of {@code ScriptObject} instances created that are scope */ 3708 private static int scopeCount; 3709 3710 /** 3711 * Get number of {@code ScriptObject} instances created. If not running in debug 3712 * mode this is always 0 3713 * 3714 * @return number of ScriptObjects created 3715 */ 3716 public static int getCount() { 3717 return count; 3718 } 3719 3720 /** 3721 * Get number of scope {@code ScriptObject} instances created. If not running in debug 3722 * mode this is always 0 3723 * 3724 * @return number of scope ScriptObjects created 3725 */ 3726 public static int getScopeCount() { 3727 return scopeCount; 3728 } 3729 3730} 3731