NativeArray.java revision 1605:7d884d7c0834
1219567Smarius/* 2219567Smarius * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved. 3146392Smarius * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4146392Smarius * 5146392Smarius * This code is free software; you can redistribute it and/or modify it 6146392Smarius * under the terms of the GNU General Public License version 2 only, as 7146392Smarius * published by the Free Software Foundation. Oracle designates this 8146392Smarius * particular file as subject to the "Classpath" exception as provided 9146392Smarius * by Oracle in the LICENSE file that accompanied this code. 10146392Smarius * 11146392Smarius * This code is distributed in the hope that it will be useful, but WITHOUT 12146392Smarius * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13146392Smarius * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14146392Smarius * version 2 for more details (a copy is included in the LICENSE file that 15146392Smarius * accompanied this code). 16146392Smarius * 17146392Smarius * You should have received a copy of the GNU General Public License version 18146392Smarius * 2 along with this work; if not, write to the Free Software Foundation, 19146392Smarius * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20146392Smarius * 21146392Smarius * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22146392Smarius * or visit www.oracle.com if you need additional information or have any 23146392Smarius * questions. 24146392Smarius */ 25146392Smarius 26146392Smariuspackage jdk.nashorn.internal.objects; 27146392Smarius 28146392Smariusimport static jdk.nashorn.internal.runtime.ECMAErrors.rangeError; 29146392Smariusimport static jdk.nashorn.internal.runtime.ECMAErrors.typeError; 30146392Smariusimport static jdk.nashorn.internal.runtime.PropertyDescriptor.VALUE; 31146392Smariusimport static jdk.nashorn.internal.runtime.PropertyDescriptor.WRITABLE; 32146392Smariusimport static jdk.nashorn.internal.runtime.arrays.ArrayIndex.isValidArrayIndex; 33146392Smariusimport static jdk.nashorn.internal.runtime.arrays.ArrayLikeIterator.arrayLikeIterator; 34146392Smariusimport static jdk.nashorn.internal.runtime.arrays.ArrayLikeIterator.reverseArrayLikeIterator; 35146392Smariusimport static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_STRICT; 36146392Smarius 37146392Smariusimport java.lang.invoke.MethodHandle; 38146392Smariusimport java.util.ArrayList; 39146392Smariusimport java.util.Arrays; 40146392Smariusimport java.util.Collections; 41146392Smariusimport java.util.Comparator; 42146392Smariusimport java.util.Iterator; 43146392Smariusimport java.util.List; 44146392Smariusimport java.util.concurrent.Callable; 45146392Smariusimport jdk.dynalink.CallSiteDescriptor; 46146392Smariusimport jdk.dynalink.linker.GuardedInvocation; 47146392Smariusimport jdk.dynalink.linker.LinkRequest; 48146392Smariusimport jdk.nashorn.api.scripting.JSObject; 49146392Smariusimport jdk.nashorn.internal.objects.annotations.Attribute; 50146392Smariusimport jdk.nashorn.internal.objects.annotations.Constructor; 51146392Smariusimport jdk.nashorn.internal.objects.annotations.Function; 52146392Smariusimport jdk.nashorn.internal.objects.annotations.Getter; 53146392Smariusimport jdk.nashorn.internal.objects.annotations.ScriptClass; 54146392Smariusimport jdk.nashorn.internal.objects.annotations.Setter; 55146392Smariusimport jdk.nashorn.internal.objects.annotations.SpecializedFunction; 56146392Smariusimport jdk.nashorn.internal.objects.annotations.SpecializedFunction.LinkLogic; 57146392Smariusimport jdk.nashorn.internal.objects.annotations.Where; 58146392Smariusimport jdk.nashorn.internal.runtime.Context; 59146392Smariusimport jdk.nashorn.internal.runtime.Debug; 60146392Smariusimport jdk.nashorn.internal.runtime.JSType; 61146392Smariusimport jdk.nashorn.internal.runtime.OptimisticBuiltins; 62146392Smariusimport jdk.nashorn.internal.runtime.PropertyDescriptor; 63146392Smariusimport jdk.nashorn.internal.runtime.PropertyMap; 64146392Smariusimport jdk.nashorn.internal.runtime.ScriptFunction; 65146392Smariusimport jdk.nashorn.internal.runtime.ScriptObject; 66146392Smariusimport jdk.nashorn.internal.runtime.ScriptRuntime; 67146392Smariusimport jdk.nashorn.internal.runtime.Undefined; 68146392Smariusimport jdk.nashorn.internal.runtime.arrays.ArrayData; 69152684Smariusimport jdk.nashorn.internal.runtime.arrays.ArrayIndex; 70146392Smariusimport jdk.nashorn.internal.runtime.arrays.ArrayLikeIterator; 71146392Smariusimport jdk.nashorn.internal.runtime.arrays.ContinuousArrayData; 72146392Smariusimport jdk.nashorn.internal.runtime.arrays.IntElements; 73146392Smariusimport jdk.nashorn.internal.runtime.arrays.IteratorAction; 74146392Smariusimport jdk.nashorn.internal.runtime.arrays.NumericElements; 75146392Smariusimport jdk.nashorn.internal.runtime.linker.Bootstrap; 76146392Smariusimport jdk.nashorn.internal.runtime.linker.InvokeByName; 77146392Smarius 78146392Smarius/** 79146392Smarius * Runtime representation of a JavaScript array. NativeArray only holds numeric 80146392Smarius * keyed values. All other values are stored in spill. 81146392Smarius */ 82146392Smarius@ScriptClass("Array") 83152684Smariuspublic final class NativeArray extends ScriptObject implements OptimisticBuiltins { 84146392Smarius private static final Object JOIN = new Object(); 85146392Smarius private static final Object EVERY_CALLBACK_INVOKER = new Object(); 86146392Smarius private static final Object SOME_CALLBACK_INVOKER = new Object(); 87146392Smarius private static final Object FOREACH_CALLBACK_INVOKER = new Object(); 88146392Smarius private static final Object MAP_CALLBACK_INVOKER = new Object(); 89146392Smarius private static final Object FILTER_CALLBACK_INVOKER = new Object(); 90146392Smarius private static final Object REDUCE_CALLBACK_INVOKER = new Object(); 91146392Smarius private static final Object CALL_CMP = new Object(); 92146392Smarius private static final Object TO_LOCALE_STRING = new Object(); 93146392Smarius 94146392Smarius /* 95146392Smarius * Constructors. 96146392Smarius */ 97146392Smarius NativeArray() { 98146392Smarius this(ArrayData.initialArray()); 99146392Smarius } 100152684Smarius 101146392Smarius NativeArray(final long length) { 102152684Smarius this(ArrayData.allocate(length)); 103152684Smarius } 104146392Smarius 105152684Smarius NativeArray(final int[] array) { 106146392Smarius this(ArrayData.allocate(array)); 107146392Smarius } 108166147Smarius 109146392Smarius NativeArray(final double[] array) { 110146392Smarius this(ArrayData.allocate(array)); 111154870Smarius } 112154870Smarius 113154870Smarius NativeArray(final long[] array) { 114146392Smarius this(ArrayData.allocate(array.length)); 115146392Smarius 116146392Smarius ArrayData arrayData = this.getArray(); 117146392Smarius Class<?> widest = int.class; 118146392Smarius 119146392Smarius for (int index = 0; index < array.length; index++) { 120146392Smarius final long value = array[index]; 121225931Smarius 122190099Smarius if (widest == int.class && JSType.isRepresentableAsInt(value)) { 123190099Smarius arrayData = arrayData.set(index, (int) value, false); 124190099Smarius } else if (widest != Object.class && JSType.isRepresentableAsDouble(value)) { 125190099Smarius arrayData = arrayData.set(index, (double) value, false); 126146392Smarius widest = double.class; 127190114Smarius } else { 128146392Smarius arrayData = arrayData.set(index, (Object) value, false); 129146392Smarius widest = Object.class; 130152684Smarius } 131152684Smarius } 132152684Smarius 133152684Smarius this.setArray(arrayData); 134152684Smarius } 135152684Smarius 136146392Smarius NativeArray(final Object[] array) { 137227848Smarius this(ArrayData.allocate(array.length)); 138146392Smarius 139146392Smarius ArrayData arrayData = this.getArray(); 140146392Smarius 141146392Smarius for (int index = 0; index < array.length; index++) { 142146392Smarius final Object value = array[index]; 143146392Smarius 144146392Smarius if (value == ScriptRuntime.EMPTY) { 145146392Smarius arrayData = arrayData.delete(index); 146200874Smarius } else { 147200874Smarius arrayData = arrayData.set(index, value, false); 148200874Smarius } 149200874Smarius } 150200874Smarius 151200874Smarius this.setArray(arrayData); 152200874Smarius } 153182062Smarius 154182062Smarius NativeArray(final ArrayData arrayData) { 155146392Smarius this(arrayData, Global.instance()); 156146392Smarius } 157146392Smarius 158146392Smarius NativeArray(final ArrayData arrayData, final Global global) { 159146392Smarius super(global.getArrayPrototype(), $nasgenmap$); 160146392Smarius setArray(arrayData); 161146392Smarius setIsArray(); 162146392Smarius } 163146392Smarius 164166147Smarius @Override 165166147Smarius protected GuardedInvocation findGetIndexMethod(final CallSiteDescriptor desc, final LinkRequest request) { 166146392Smarius final GuardedInvocation inv = getArray().findFastGetIndexMethod(getArray().getClass(), desc, request); 167166147Smarius if (inv != null) { 168146392Smarius return inv; 169146392Smarius } 170146392Smarius return super.findGetIndexMethod(desc, request); 171146392Smarius } 172146392Smarius 173146392Smarius @Override 174146392Smarius protected GuardedInvocation findSetIndexMethod(final CallSiteDescriptor desc, final LinkRequest request) { 175146392Smarius final GuardedInvocation inv = getArray().findFastSetIndexMethod(getArray().getClass(), desc, request); 176146392Smarius if (inv != null) { 177146392Smarius return inv; 178152684Smarius } 179146392Smarius 180146392Smarius return super.findSetIndexMethod(desc, request); 181182876Smarius } 182146392Smarius 183146392Smarius private static InvokeByName getJOIN() { 184146392Smarius return Global.instance().getInvokeByName(JOIN, 185146392Smarius new Callable<InvokeByName>() { 186146392Smarius @Override 187146392Smarius public InvokeByName call() { 188146392Smarius return new InvokeByName("join", ScriptObject.class); 189146392Smarius } 190146392Smarius }); 191182876Smarius } 192182876Smarius 193146392Smarius private static MethodHandle createIteratorCallbackInvoker(final Object key, final Class<?> rtype) { 194146392Smarius return Global.instance().getDynamicInvoker(key, 195146392Smarius new Callable<MethodHandle>() { 196146392Smarius @Override 197146392Smarius public MethodHandle call() { 198146392Smarius return Bootstrap.createDynamicCallInvoker(rtype, Object.class, Object.class, Object.class, 199146392Smarius double.class, Object.class); 200146392Smarius } 201146392Smarius }); 202146392Smarius } 203146392Smarius 204146392Smarius private static MethodHandle getEVERY_CALLBACK_INVOKER() { 205146392Smarius return createIteratorCallbackInvoker(EVERY_CALLBACK_INVOKER, boolean.class); 206146392Smarius } 207146392Smarius 208146392Smarius private static MethodHandle getSOME_CALLBACK_INVOKER() { 209146392Smarius return createIteratorCallbackInvoker(SOME_CALLBACK_INVOKER, boolean.class); 210146392Smarius } 211146392Smarius 212146392Smarius private static MethodHandle getFOREACH_CALLBACK_INVOKER() { 213146392Smarius return createIteratorCallbackInvoker(FOREACH_CALLBACK_INVOKER, void.class); 214146392Smarius } 215146392Smarius 216146392Smarius private static MethodHandle getMAP_CALLBACK_INVOKER() { 217146392Smarius return createIteratorCallbackInvoker(MAP_CALLBACK_INVOKER, Object.class); 218146392Smarius } 219300173Sgonzo 220146392Smarius private static MethodHandle getFILTER_CALLBACK_INVOKER() { 221146392Smarius return createIteratorCallbackInvoker(FILTER_CALLBACK_INVOKER, boolean.class); 222146392Smarius } 223146392Smarius 224146392Smarius private static MethodHandle getREDUCE_CALLBACK_INVOKER() { 225146392Smarius return Global.instance().getDynamicInvoker(REDUCE_CALLBACK_INVOKER, 226146392Smarius new Callable<MethodHandle>() { 227146392Smarius @Override 228146392Smarius public MethodHandle call() { 229146392Smarius return Bootstrap.createDynamicCallInvoker(Object.class, Object.class, 230146392Smarius Undefined.class, Object.class, Object.class, double.class, Object.class); 231166147Smarius } 232166147Smarius }); 233146392Smarius } 234146392Smarius 235146392Smarius private static MethodHandle getCALL_CMP() { 236226948Smarius return Global.instance().getDynamicInvoker(CALL_CMP, 237226948Smarius new Callable<MethodHandle>() { 238226948Smarius @Override 239146392Smarius public MethodHandle call() { 240146392Smarius return Bootstrap.createDynamicCallInvoker(double.class, 241146392Smarius ScriptFunction.class, Object.class, Object.class, Object.class); 242146392Smarius } 243146392Smarius }); 244146392Smarius } 245146392Smarius 246146392Smarius private static InvokeByName getTO_LOCALE_STRING() { 247182876Smarius return Global.instance().getInvokeByName(TO_LOCALE_STRING, 248182876Smarius new Callable<InvokeByName>() { 249182876Smarius @Override 250146392Smarius public InvokeByName call() { 251146392Smarius return new InvokeByName("toLocaleString", ScriptObject.class, String.class); 252146392Smarius } 253182876Smarius }); 254146392Smarius } 255152684Smarius 256146392Smarius // initialized by nasgen 257182876Smarius private static PropertyMap $nasgenmap$; 258152684Smarius 259152684Smarius @Override 260152684Smarius public String getClassName() { 261146392Smarius return "Array"; 262146392Smarius } 263146392Smarius 264146392Smarius @Override 265146392Smarius public Object getLength() { 266152684Smarius final long length = getArray().length(); 267146392Smarius assert length >= 0L; 268146392Smarius if (length <= Integer.MAX_VALUE) { 269146392Smarius return (int)length; 270146392Smarius } 271182876Smarius return length; 272146392Smarius } 273152684Smarius 274146392Smarius private boolean defineLength(final long oldLen, final PropertyDescriptor oldLenDesc, final PropertyDescriptor desc, final boolean reject) { 275146392Smarius // Step 3a 276182876Smarius if (!desc.has(VALUE)) { 277182876Smarius return super.defineOwnProperty("length", desc, reject); 278146392Smarius } 279146392Smarius 280146392Smarius // Step 3b 281146392Smarius final PropertyDescriptor newLenDesc = desc; 282152684Smarius 283146392Smarius // Step 3c and 3d - get new length and convert to long 284146392Smarius final long newLen = NativeArray.validLength(newLenDesc.getValue()); 285146392Smarius 286146392Smarius // Step 3e - note that we need to convert to int or double as long is not considered a JS number type anymore 287146392Smarius newLenDesc.setValue(JSType.toNarrowestNumber(newLen)); 288146392Smarius 289146392Smarius // Step 3f 290152684Smarius // increasing array length - just need to set new length value (and attributes if any) and return 291152684Smarius if (newLen >= oldLen) { 292146392Smarius return super.defineOwnProperty("length", newLenDesc, reject); 293152684Smarius } 294146392Smarius 295146392Smarius // Step 3g 296146392Smarius if (!oldLenDesc.isWritable()) { 297146392Smarius if (reject) { 298152684Smarius throw typeError("property.not.writable", "length", ScriptRuntime.safeToString(this)); 299152684Smarius } 300152684Smarius return false; 301146392Smarius } 302146392Smarius 303146392Smarius // Step 3h and 3i 304146392Smarius final boolean newWritable = !newLenDesc.has(WRITABLE) || newLenDesc.isWritable(); 305146392Smarius if (!newWritable) { 306146392Smarius newLenDesc.setWritable(true); 307146392Smarius } 308146392Smarius 309146392Smarius // Step 3j and 3k 310152684Smarius final boolean succeeded = super.defineOwnProperty("length", newLenDesc, reject); 311152684Smarius if (!succeeded) { 312300173Sgonzo return false; 313152684Smarius } 314146392Smarius 315146392Smarius // Step 3l 316146392Smarius // make sure that length is set till the point we can delete the old elements 317146392Smarius long o = oldLen; 318146392Smarius while (newLen < o) { 319146392Smarius o--; 320300173Sgonzo final boolean deleteSucceeded = delete(o, false); 321146392Smarius if (!deleteSucceeded) { 322146392Smarius newLenDesc.setValue(o + 1); 323152684Smarius if (!newWritable) { 324152684Smarius newLenDesc.setWritable(false); 325146392Smarius } 326146392Smarius super.defineOwnProperty("length", newLenDesc, false); 327146392Smarius if (reject) { 328146392Smarius throw typeError("property.not.writable", "length", ScriptRuntime.safeToString(this)); 329146392Smarius } 330146392Smarius return false; 331146392Smarius } 332146392Smarius } 333146392Smarius 334146392Smarius // Step 3m 335146392Smarius if (!newWritable) { 336146392Smarius // make 'length' property not writable 337146392Smarius final ScriptObject newDesc = Global.newEmptyInstance(); 338146392Smarius newDesc.set(WRITABLE, false, 0); 339146392Smarius return super.defineOwnProperty("length", newDesc, false); 340146392Smarius } 341146392Smarius 342146392Smarius return true; 343146392Smarius } 344146392Smarius 345146392Smarius /** 346300173Sgonzo * ECMA 15.4.5.1 [[DefineOwnProperty]] ( P, Desc, Throw ) 347146392Smarius */ 348146392Smarius @Override 349152684Smarius public boolean defineOwnProperty(final Object key, final Object propertyDesc, final boolean reject) { 350152684Smarius final PropertyDescriptor desc = toPropertyDescriptor(Global.instance(), propertyDesc); 351152684Smarius 352152684Smarius // never be undefined as "length" is always defined and can't be deleted for arrays 353146392Smarius // Step 1 354146392Smarius final PropertyDescriptor oldLenDesc = (PropertyDescriptor) super.getOwnPropertyDescriptor("length"); 355146392Smarius 356146392Smarius // Step 2 357146392Smarius // get old length and convert to long. Always a Long/Uint32 but we take the safe road. 358146392Smarius final long oldLen = JSType.toUint32(oldLenDesc.getValue()); 359146392Smarius 360152684Smarius // Step 3 361146392Smarius if ("length".equals(key)) { 362146392Smarius // check for length being made non-writable 363146392Smarius final boolean result = defineLength(oldLen, oldLenDesc, desc, reject); 364146392Smarius if (desc.has(WRITABLE) && !desc.isWritable()) { 365146392Smarius setIsLengthNotWritable(); 366146392Smarius } 367146392Smarius return result; 368146392Smarius } 369146392Smarius 370152684Smarius // Step 4a 371146392Smarius final int index = ArrayIndex.getArrayIndex(key); 372146392Smarius if (ArrayIndex.isValidArrayIndex(index)) { 373146392Smarius final long longIndex = ArrayIndex.toLongIndex(index); 374146392Smarius // Step 4b 375146392Smarius // setting an element beyond current length, but 'length' is not writable 376146392Smarius if (longIndex >= oldLen && !oldLenDesc.isWritable()) { 377146392Smarius if (reject) { 378152684Smarius throw typeError("property.not.writable", Long.toString(longIndex), ScriptRuntime.safeToString(this)); 379146392Smarius } 380152684Smarius return false; 381152684Smarius } 382152684Smarius 383152684Smarius // Step 4c 384152684Smarius // set the new array element 385146392Smarius final boolean succeeded = super.defineOwnProperty(key, desc, false); 386146392Smarius 387146392Smarius // Step 4d 388146392Smarius if (!succeeded) { 389146392Smarius if (reject) { 390146392Smarius throw typeError("cant.redefine.property", key.toString(), ScriptRuntime.safeToString(this)); 391146392Smarius } 392146392Smarius return false; 393146392Smarius } 394146392Smarius 395146392Smarius // Step 4e -- adjust new length based on new element index that is set 396152684Smarius if (longIndex >= oldLen) { 397152684Smarius oldLenDesc.setValue(longIndex + 1); 398146392Smarius super.defineOwnProperty("length", oldLenDesc, false); 399152684Smarius } 400146392Smarius 401152684Smarius // Step 4f 402152684Smarius return true; 403146392Smarius } 404146392Smarius 405152684Smarius // not an index property 406152684Smarius return super.defineOwnProperty(key, desc, reject); 407146392Smarius } 408152684Smarius 409146392Smarius /** 410152684Smarius * Spec. mentions use of [[DefineOwnProperty]] for indexed properties in 411152684Smarius * certain places (eg. Array.prototype.map, filter). We can not use ScriptObject.set 412297199Sjhibbits * method in such cases. This is because set method uses inherited setters (if any) 413297199Sjhibbits * from any object in proto chain such as Array.prototype, Object.prototype. 414152684Smarius * This method directly sets a particular element value in the current object. 415146392Smarius * 416 * @param index key for property 417 * @param value value to define 418 */ 419 @Override 420 public final void defineOwnProperty(final int index, final Object value) { 421 assert isValidArrayIndex(index) : "invalid array index"; 422 final long longIndex = ArrayIndex.toLongIndex(index); 423 if (longIndex >= getArray().length()) { 424 // make array big enough to hold.. 425 setArray(getArray().ensure(longIndex)); 426 } 427 setArray(getArray().set(index, value, false)); 428 } 429 430 /** 431 * Return the array contents upcasted as an ObjectArray, regardless of 432 * representation 433 * 434 * @return an object array 435 */ 436 public Object[] asObjectArray() { 437 return getArray().asObjectArray(); 438 } 439 440 @Override 441 public void setIsLengthNotWritable() { 442 super.setIsLengthNotWritable(); 443 setArray(ArrayData.setIsLengthNotWritable(getArray())); 444 } 445 446 /** 447 * ECMA 15.4.3.2 Array.isArray ( arg ) 448 * 449 * @param self self reference 450 * @param arg argument - object to check 451 * @return true if argument is an array 452 */ 453 @Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR) 454 public static boolean isArray(final Object self, final Object arg) { 455 return isArray(arg) || (arg instanceof JSObject && ((JSObject)arg).isArray()); 456 } 457 458 /** 459 * Length getter 460 * @param self self reference 461 * @return the length of the object 462 */ 463 @Getter(attributes = Attribute.NOT_ENUMERABLE | Attribute.NOT_CONFIGURABLE) 464 public static Object length(final Object self) { 465 if (isArray(self)) { 466 final long length = ((ScriptObject) self).getArray().length(); 467 assert length >= 0L; 468 // Cast to the narrowest supported numeric type to help optimistic type calculator 469 if (length <= Integer.MAX_VALUE) { 470 return (int) length; 471 } 472 return (double) length; 473 } 474 475 return 0; 476 } 477 478 /** 479 * Length setter 480 * @param self self reference 481 * @param length new length property 482 */ 483 @Setter(attributes = Attribute.NOT_ENUMERABLE | Attribute.NOT_CONFIGURABLE) 484 public static void length(final Object self, final Object length) { 485 if (isArray(self)) { 486 ((ScriptObject)self).setLength(validLength(length)); 487 } 488 } 489 490 /** 491 * Prototype length getter 492 * @param self self reference 493 * @return the length of the object 494 */ 495 @Getter(name = "length", where = Where.PROTOTYPE, attributes = Attribute.NOT_ENUMERABLE | Attribute.NOT_CONFIGURABLE) 496 public static Object getProtoLength(final Object self) { 497 return length(self); // Same as instance getter but we can't make nasgen use the same method for prototype 498 } 499 500 /** 501 * Prototype length setter 502 * @param self self reference 503 * @param length new length property 504 */ 505 @Setter(name = "length", where = Where.PROTOTYPE, attributes = Attribute.NOT_ENUMERABLE | Attribute.NOT_CONFIGURABLE) 506 public static void setProtoLength(final Object self, final Object length) { 507 length(self, length); // Same as instance setter but we can't make nasgen use the same method for prototype 508 } 509 510 static long validLength(final Object length) { 511 // ES5 15.4.5.1, steps 3.c and 3.d require two ToNumber conversions here 512 final double doubleLength = JSType.toNumber(length); 513 if (doubleLength != JSType.toUint32(length)) { 514 throw rangeError("inappropriate.array.length", ScriptRuntime.safeToString(length)); 515 } 516 return (long) doubleLength; 517 } 518 519 /** 520 * ECMA 15.4.4.2 Array.prototype.toString ( ) 521 * 522 * @param self self reference 523 * @return string representation of array 524 */ 525 @Function(attributes = Attribute.NOT_ENUMERABLE) 526 public static Object toString(final Object self) { 527 final Object obj = Global.toObject(self); 528 if (obj instanceof ScriptObject) { 529 final InvokeByName joinInvoker = getJOIN(); 530 final ScriptObject sobj = (ScriptObject)obj; 531 try { 532 final Object join = joinInvoker.getGetter().invokeExact(sobj); 533 if (Bootstrap.isCallable(join)) { 534 return joinInvoker.getInvoker().invokeExact(join, sobj); 535 } 536 } catch (final RuntimeException | Error e) { 537 throw e; 538 } catch (final Throwable t) { 539 throw new RuntimeException(t); 540 } 541 } 542 543 // FIXME: should lookup Object.prototype.toString and call that? 544 return ScriptRuntime.builtinObjectToString(self); 545 } 546 547 /** 548 * Assert that an array is numeric, if not throw type error 549 * @param self self array to check 550 * @return true if numeric 551 */ 552 @Function(attributes = Attribute.NOT_ENUMERABLE) 553 public static Object assertNumeric(final Object self) { 554 if(!(self instanceof NativeArray && ((NativeArray)self).getArray().getOptimisticType().isNumeric())) { 555 throw typeError("not.a.numeric.array", ScriptRuntime.safeToString(self)); 556 } 557 return Boolean.TRUE; 558 } 559 560 /** 561 * ECMA 15.4.4.3 Array.prototype.toLocaleString ( ) 562 * 563 * @param self self reference 564 * @return locale specific string representation for array 565 */ 566 @Function(attributes = Attribute.NOT_ENUMERABLE) 567 public static String toLocaleString(final Object self) { 568 final StringBuilder sb = new StringBuilder(); 569 final Iterator<Object> iter = arrayLikeIterator(self, true); 570 571 while (iter.hasNext()) { 572 final Object obj = iter.next(); 573 574 if (obj != null && obj != ScriptRuntime.UNDEFINED) { 575 final Object val = JSType.toScriptObject(obj); 576 577 try { 578 if (val instanceof ScriptObject) { 579 final InvokeByName localeInvoker = getTO_LOCALE_STRING(); 580 final ScriptObject sobj = (ScriptObject)val; 581 final Object toLocaleString = localeInvoker.getGetter().invokeExact(sobj); 582 583 if (Bootstrap.isCallable(toLocaleString)) { 584 sb.append((String)localeInvoker.getInvoker().invokeExact(toLocaleString, sobj)); 585 } else { 586 throw typeError("not.a.function", "toLocaleString"); 587 } 588 } 589 } catch (final Error|RuntimeException t) { 590 throw t; 591 } catch (final Throwable t) { 592 throw new RuntimeException(t); 593 } 594 } 595 596 if (iter.hasNext()) { 597 sb.append(","); 598 } 599 } 600 601 return sb.toString(); 602 } 603 604 /** 605 * ECMA 15.4.2.2 new Array (len) 606 * 607 * @param newObj was the new operator used to instantiate this array 608 * @param self self reference 609 * @param args arguments (length) 610 * @return the new NativeArray 611 */ 612 @Constructor(arity = 1) 613 public static NativeArray construct(final boolean newObj, final Object self, final Object... args) { 614 switch (args.length) { 615 case 0: 616 return new NativeArray(0); 617 case 1: 618 final Object len = args[0]; 619 if (len instanceof Number) { 620 long length; 621 if (len instanceof Integer || len instanceof Long) { 622 length = ((Number) len).longValue(); 623 if (length >= 0 && length < JSType.MAX_UINT) { 624 return new NativeArray(length); 625 } 626 } 627 628 length = JSType.toUint32(len); 629 630 /* 631 * If the argument len is a Number and ToUint32(len) is equal to 632 * len, then the length property of the newly constructed object 633 * is set to ToUint32(len). If the argument len is a Number and 634 * ToUint32(len) is not equal to len, a RangeError exception is 635 * thrown. 636 */ 637 final double numberLength = ((Number) len).doubleValue(); 638 if (length != numberLength) { 639 throw rangeError("inappropriate.array.length", JSType.toString(numberLength)); 640 } 641 642 return new NativeArray(length); 643 } 644 /* 645 * If the argument len is not a Number, then the length property of 646 * the newly constructed object is set to 1 and the 0 property of 647 * the newly constructed object is set to len 648 */ 649 return new NativeArray(new Object[]{args[0]}); 650 //fallthru 651 default: 652 return new NativeArray(args); 653 } 654 } 655 656 /** 657 * ECMA 15.4.2.2 new Array (len) 658 * 659 * Specialized constructor for zero arguments - empty array 660 * 661 * @param newObj was the new operator used to instantiate this array 662 * @param self self reference 663 * @return the new NativeArray 664 */ 665 @SpecializedFunction(isConstructor=true) 666 public static NativeArray construct(final boolean newObj, final Object self) { 667 return new NativeArray(0); 668 } 669 670 /** 671 * ECMA 15.4.2.2 new Array (len) 672 * 673 * Specialized constructor for zero arguments - empty array 674 * 675 * @param newObj was the new operator used to instantiate this array 676 * @param self self reference 677 * @param element first element 678 * @return the new NativeArray 679 */ 680 @SpecializedFunction(isConstructor=true) 681 public static Object construct(final boolean newObj, final Object self, final boolean element) { 682 return new NativeArray(new Object[] { element }); 683 } 684 685 /** 686 * ECMA 15.4.2.2 new Array (len) 687 * 688 * Specialized constructor for one integer argument (length) 689 * 690 * @param newObj was the new operator used to instantiate this array 691 * @param self self reference 692 * @param length array length 693 * @return the new NativeArray 694 */ 695 @SpecializedFunction(isConstructor=true) 696 public static NativeArray construct(final boolean newObj, final Object self, final int length) { 697 if (length >= 0) { 698 return new NativeArray(length); 699 } 700 701 return construct(newObj, self, new Object[]{length}); 702 } 703 704 /** 705 * ECMA 15.4.2.2 new Array (len) 706 * 707 * Specialized constructor for one long argument (length) 708 * 709 * @param newObj was the new operator used to instantiate this array 710 * @param self self reference 711 * @param length array length 712 * @return the new NativeArray 713 */ 714 @SpecializedFunction(isConstructor=true) 715 public static NativeArray construct(final boolean newObj, final Object self, final long length) { 716 if (length >= 0L && length <= JSType.MAX_UINT) { 717 return new NativeArray(length); 718 } 719 720 return construct(newObj, self, new Object[]{length}); 721 } 722 723 /** 724 * ECMA 15.4.2.2 new Array (len) 725 * 726 * Specialized constructor for one double argument (length) 727 * 728 * @param newObj was the new operator used to instantiate this array 729 * @param self self reference 730 * @param length array length 731 * @return the new NativeArray 732 */ 733 @SpecializedFunction(isConstructor=true) 734 public static NativeArray construct(final boolean newObj, final Object self, final double length) { 735 final long uint32length = JSType.toUint32(length); 736 737 if (uint32length == length) { 738 return new NativeArray(uint32length); 739 } 740 741 return construct(newObj, self, new Object[]{length}); 742 } 743 744 /** 745 * ECMA 15.4.4.4 Array.prototype.concat ( [ item1 [ , item2 [ , ... ] ] ] ) 746 * 747 * @param self self reference 748 * @param arg argument 749 * @return resulting NativeArray 750 */ 751 @SpecializedFunction(linkLogic=ConcatLinkLogic.class) 752 public static NativeArray concat(final Object self, final int arg) { 753 final ContinuousArrayData newData = getContinuousArrayDataCCE(self, Integer.class).copy(); //get at least an integer data copy of this data 754 newData.fastPush(arg); //add an integer to its end 755 return new NativeArray(newData); 756 } 757 758 /** 759 * ECMA 15.4.4.4 Array.prototype.concat ( [ item1 [ , item2 [ , ... ] ] ] ) 760 * 761 * @param self self reference 762 * @param arg argument 763 * @return resulting NativeArray 764 */ 765 @SpecializedFunction(linkLogic=ConcatLinkLogic.class) 766 public static NativeArray concat(final Object self, final long arg) { 767 final ContinuousArrayData newData = getContinuousArrayDataCCE(self, Long.class).copy(); //get at least a long array data copy of this data 768 newData.fastPush(arg); //add a long at the end 769 return new NativeArray(newData); 770 } 771 772 /** 773 * ECMA 15.4.4.4 Array.prototype.concat ( [ item1 [ , item2 [ , ... ] ] ] ) 774 * 775 * @param self self reference 776 * @param arg argument 777 * @return resulting NativeArray 778 */ 779 @SpecializedFunction(linkLogic=ConcatLinkLogic.class) 780 public static NativeArray concat(final Object self, final double arg) { 781 final ContinuousArrayData newData = getContinuousArrayDataCCE(self, Double.class).copy(); //get at least a number array data copy of this data 782 newData.fastPush(arg); //add a double at the end 783 return new NativeArray(newData); 784 } 785 786 /** 787 * ECMA 15.4.4.4 Array.prototype.concat ( [ item1 [ , item2 [ , ... ] ] ] ) 788 * 789 * @param self self reference 790 * @param arg argument 791 * @return resulting NativeArray 792 */ 793 @SpecializedFunction(linkLogic=ConcatLinkLogic.class) 794 public static NativeArray concat(final Object self, final Object arg) { 795 //arg is [NativeArray] of same type. 796 final ContinuousArrayData selfData = getContinuousArrayDataCCE(self); 797 final ContinuousArrayData newData; 798 799 if (arg instanceof NativeArray) { 800 final ContinuousArrayData argData = (ContinuousArrayData)((NativeArray)arg).getArray(); 801 if (argData.isEmpty()) { 802 newData = selfData.copy(); 803 } else if (selfData.isEmpty()) { 804 newData = argData.copy(); 805 } else { 806 final Class<?> widestElementType = selfData.widest(argData).getBoxedElementType(); 807 newData = ((ContinuousArrayData)selfData.convert(widestElementType)).fastConcat((ContinuousArrayData)argData.convert(widestElementType)); 808 } 809 } else { 810 newData = getContinuousArrayDataCCE(self, Object.class).copy(); 811 newData.fastPush(arg); 812 } 813 814 return new NativeArray(newData); 815 } 816 817 /** 818 * ECMA 15.4.4.4 Array.prototype.concat ( [ item1 [ , item2 [ , ... ] ] ] ) 819 * 820 * @param self self reference 821 * @param args arguments 822 * @return resulting NativeArray 823 */ 824 @Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1) 825 public static NativeArray concat(final Object self, final Object... args) { 826 final ArrayList<Object> list = new ArrayList<>(); 827 828 concatToList(list, Global.toObject(self)); 829 830 for (final Object obj : args) { 831 concatToList(list, obj); 832 } 833 834 return new NativeArray(list.toArray()); 835 } 836 837 private static void concatToList(final ArrayList<Object> list, final Object obj) { 838 final boolean isScriptArray = isArray(obj); 839 final boolean isScriptObject = isScriptArray || obj instanceof ScriptObject; 840 if (isScriptArray || obj instanceof Iterable || (obj != null && obj.getClass().isArray())) { 841 final Iterator<Object> iter = arrayLikeIterator(obj, true); 842 if (iter.hasNext()) { 843 for (int i = 0; iter.hasNext(); ++i) { 844 final Object value = iter.next(); 845 final boolean lacksIndex = obj != null && !((ScriptObject)obj).has(i); 846 if (value == ScriptRuntime.UNDEFINED && isScriptObject && lacksIndex) { 847 // TODO: eventually rewrite arrayLikeIterator to use a three-state enum for handling 848 // UNDEFINED instead of an "includeUndefined" boolean with states SKIP, INCLUDE, 849 // RETURN_EMPTY. Until then, this is how we'll make sure that empty elements don't make it 850 // into the concatenated array. 851 list.add(ScriptRuntime.EMPTY); 852 } else { 853 list.add(value); 854 } 855 } 856 } else if (!isScriptArray) { 857 list.add(obj); // add empty object, but not an empty array 858 } 859 } else { 860 // single element, add it 861 list.add(obj); 862 } 863 } 864 865 /** 866 * ECMA 15.4.4.5 Array.prototype.join (separator) 867 * 868 * @param self self reference 869 * @param separator element separator 870 * @return string representation after join 871 */ 872 @Function(attributes = Attribute.NOT_ENUMERABLE) 873 public static String join(final Object self, final Object separator) { 874 final StringBuilder sb = new StringBuilder(); 875 final Iterator<Object> iter = arrayLikeIterator(self, true); 876 final String sep = separator == ScriptRuntime.UNDEFINED ? "," : JSType.toString(separator); 877 878 while (iter.hasNext()) { 879 final Object obj = iter.next(); 880 881 if (obj != null && obj != ScriptRuntime.UNDEFINED) { 882 sb.append(JSType.toString(obj)); 883 } 884 885 if (iter.hasNext()) { 886 sb.append(sep); 887 } 888 } 889 890 return sb.toString(); 891 } 892 893 /** 894 * Specialization of pop for ContinuousArrayData 895 * The link guard checks that the array is continuous AND not empty. 896 * The runtime guard checks that the guard is continuous (CCE otherwise) 897 * 898 * Primitive specialization, {@link LinkLogic} 899 * 900 * @param self self reference 901 * @return element popped 902 * @throws ClassCastException if array is empty, facilitating Undefined return value 903 */ 904 @SpecializedFunction(name="pop", linkLogic=PopLinkLogic.class) 905 public static int popInt(final Object self) { 906 //must be non empty IntArrayData 907 return getContinuousNonEmptyArrayDataCCE(self, IntElements.class).fastPopInt(); 908 } 909 910 /** 911 * Specialization of pop for ContinuousArrayData 912 * 913 * Primitive specialization, {@link LinkLogic} 914 * 915 * @param self self reference 916 * @return element popped 917 * @throws ClassCastException if array is empty, facilitating Undefined return value 918 */ 919 @SpecializedFunction(name="pop", linkLogic=PopLinkLogic.class) 920 public static double popDouble(final Object self) { 921 //must be non empty int long or double array data 922 return getContinuousNonEmptyArrayDataCCE(self, NumericElements.class).fastPopDouble(); 923 } 924 925 /** 926 * Specialization of pop for ContinuousArrayData 927 * 928 * Primitive specialization, {@link LinkLogic} 929 * 930 * @param self self reference 931 * @return element popped 932 * @throws ClassCastException if array is empty, facilitating Undefined return value 933 */ 934 @SpecializedFunction(name="pop", linkLogic=PopLinkLogic.class) 935 public static Object popObject(final Object self) { 936 //can be any data, because the numeric ones will throw cce and force relink 937 return getContinuousArrayDataCCE(self, null).fastPopObject(); 938 } 939 940 /** 941 * ECMA 15.4.4.6 Array.prototype.pop () 942 * 943 * @param self self reference 944 * @return array after pop 945 */ 946 @Function(attributes = Attribute.NOT_ENUMERABLE) 947 public static Object pop(final Object self) { 948 try { 949 final ScriptObject sobj = (ScriptObject)self; 950 951 if (bulkable(sobj)) { 952 return sobj.getArray().pop(); 953 } 954 955 final long len = JSType.toUint32(sobj.getLength()); 956 957 if (len == 0) { 958 sobj.set("length", 0, CALLSITE_STRICT); 959 return ScriptRuntime.UNDEFINED; 960 } 961 962 final long index = len - 1; 963 final Object element = sobj.get(index); 964 965 sobj.delete(index, true); 966 sobj.set("length", index, CALLSITE_STRICT); 967 968 return element; 969 } catch (final ClassCastException | NullPointerException e) { 970 throw typeError("not.an.object", ScriptRuntime.safeToString(self)); 971 } 972 } 973 974 /** 975 * ECMA 15.4.4.7 Array.prototype.push (args...) 976 * 977 * Primitive specialization, {@link LinkLogic} 978 * 979 * @param self self reference 980 * @param arg a primitive to push 981 * @return array length after push 982 */ 983 @SpecializedFunction(linkLogic=PushLinkLogic.class) 984 public static double push(final Object self, final int arg) { 985 return getContinuousArrayDataCCE(self, Integer.class).fastPush(arg); 986 } 987 988 /** 989 * ECMA 15.4.4.7 Array.prototype.push (args...) 990 * 991 * Primitive specialization, {@link LinkLogic} 992 * 993 * @param self self reference 994 * @param arg a primitive to push 995 * @return array length after push 996 */ 997 @SpecializedFunction(linkLogic=PushLinkLogic.class) 998 public static double push(final Object self, final long arg) { 999 return getContinuousArrayDataCCE(self, Long.class).fastPush(arg); 1000 } 1001 1002 /** 1003 * ECMA 15.4.4.7 Array.prototype.push (args...) 1004 * 1005 * Primitive specialization, {@link LinkLogic} 1006 * 1007 * @param self self reference 1008 * @param arg a primitive to push 1009 * @return array length after push 1010 */ 1011 @SpecializedFunction(linkLogic=PushLinkLogic.class) 1012 public static double push(final Object self, final double arg) { 1013 return getContinuousArrayDataCCE(self, Double.class).fastPush(arg); 1014 } 1015 1016 /** 1017 * ECMA 15.4.4.7 Array.prototype.push (args...) 1018 * 1019 * Primitive specialization, {@link LinkLogic} 1020 * 1021 * @param self self reference 1022 * @param arg a primitive to push 1023 * @return array length after push 1024 */ 1025 @SpecializedFunction(name="push", linkLogic=PushLinkLogic.class) 1026 public static double pushObject(final Object self, final Object arg) { 1027 return getContinuousArrayDataCCE(self, Object.class).fastPush(arg); 1028 } 1029 1030 /** 1031 * ECMA 15.4.4.7 Array.prototype.push (args...) 1032 * 1033 * @param self self reference 1034 * @param args arguments to push 1035 * @return array length after pushes 1036 */ 1037 @Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1) 1038 public static Object push(final Object self, final Object... args) { 1039 try { 1040 final ScriptObject sobj = (ScriptObject)self; 1041 1042 if (bulkable(sobj) && sobj.getArray().length() + args.length <= JSType.MAX_UINT) { 1043 final ArrayData newData = sobj.getArray().push(true, args); 1044 sobj.setArray(newData); 1045 return JSType.toNarrowestNumber(newData.length()); 1046 } 1047 1048 long len = JSType.toUint32(sobj.getLength()); 1049 for (final Object element : args) { 1050 sobj.set(len++, element, CALLSITE_STRICT); 1051 } 1052 sobj.set("length", len, CALLSITE_STRICT); 1053 1054 return JSType.toNarrowestNumber(len); 1055 } catch (final ClassCastException | NullPointerException e) { 1056 throw typeError(Context.getGlobal(), e, "not.an.object", ScriptRuntime.safeToString(self)); 1057 } 1058 } 1059 1060 /** 1061 * ECMA 15.4.4.7 Array.prototype.push (args...) specialized for single object argument 1062 * 1063 * @param self self reference 1064 * @param arg argument to push 1065 * @return array after pushes 1066 */ 1067 @SpecializedFunction 1068 public static double push(final Object self, final Object arg) { 1069 try { 1070 final ScriptObject sobj = (ScriptObject)self; 1071 final ArrayData arrayData = sobj.getArray(); 1072 final long length = arrayData.length(); 1073 if (bulkable(sobj) && length < JSType.MAX_UINT) { 1074 sobj.setArray(arrayData.push(true, arg)); 1075 return length + 1; 1076 } 1077 1078 long len = JSType.toUint32(sobj.getLength()); 1079 sobj.set(len++, arg, CALLSITE_STRICT); 1080 sobj.set("length", len, CALLSITE_STRICT); 1081 return len; 1082 } catch (final ClassCastException | NullPointerException e) { 1083 throw typeError("not.an.object", ScriptRuntime.safeToString(self)); 1084 } 1085 } 1086 1087 /** 1088 * ECMA 15.4.4.8 Array.prototype.reverse () 1089 * 1090 * @param self self reference 1091 * @return reversed array 1092 */ 1093 @Function(attributes = Attribute.NOT_ENUMERABLE) 1094 public static Object reverse(final Object self) { 1095 try { 1096 final ScriptObject sobj = (ScriptObject)self; 1097 final long len = JSType.toUint32(sobj.getLength()); 1098 final long middle = len / 2; 1099 1100 for (long lower = 0; lower != middle; lower++) { 1101 final long upper = len - lower - 1; 1102 final Object lowerValue = sobj.get(lower); 1103 final Object upperValue = sobj.get(upper); 1104 final boolean lowerExists = sobj.has(lower); 1105 final boolean upperExists = sobj.has(upper); 1106 1107 if (lowerExists && upperExists) { 1108 sobj.set(lower, upperValue, CALLSITE_STRICT); 1109 sobj.set(upper, lowerValue, CALLSITE_STRICT); 1110 } else if (!lowerExists && upperExists) { 1111 sobj.set(lower, upperValue, CALLSITE_STRICT); 1112 sobj.delete(upper, true); 1113 } else if (lowerExists && !upperExists) { 1114 sobj.delete(lower, true); 1115 sobj.set(upper, lowerValue, CALLSITE_STRICT); 1116 } 1117 } 1118 return sobj; 1119 } catch (final ClassCastException | NullPointerException e) { 1120 throw typeError("not.an.object", ScriptRuntime.safeToString(self)); 1121 } 1122 } 1123 1124 /** 1125 * ECMA 15.4.4.9 Array.prototype.shift () 1126 * 1127 * @param self self reference 1128 * @return shifted array 1129 */ 1130 @Function(attributes = Attribute.NOT_ENUMERABLE) 1131 public static Object shift(final Object self) { 1132 final Object obj = Global.toObject(self); 1133 1134 Object first = ScriptRuntime.UNDEFINED; 1135 1136 if (!(obj instanceof ScriptObject)) { 1137 return first; 1138 } 1139 1140 final ScriptObject sobj = (ScriptObject) obj; 1141 1142 long len = JSType.toUint32(sobj.getLength()); 1143 1144 if (len > 0) { 1145 first = sobj.get(0); 1146 1147 if (bulkable(sobj)) { 1148 sobj.getArray().shiftLeft(1); 1149 } else { 1150 boolean hasPrevious = true; 1151 for (long k = 1; k < len; k++) { 1152 final boolean hasCurrent = sobj.has(k); 1153 if (hasCurrent) { 1154 sobj.set(k - 1, sobj.get(k), CALLSITE_STRICT); 1155 } else if (hasPrevious) { 1156 sobj.delete(k - 1, true); 1157 } 1158 hasPrevious = hasCurrent; 1159 } 1160 } 1161 sobj.delete(--len, true); 1162 } else { 1163 len = 0; 1164 } 1165 1166 sobj.set("length", len, CALLSITE_STRICT); 1167 1168 return first; 1169 } 1170 1171 /** 1172 * ECMA 15.4.4.10 Array.prototype.slice ( start [ , end ] ) 1173 * 1174 * @param self self reference 1175 * @param start start of slice (inclusive) 1176 * @param end end of slice (optional, exclusive) 1177 * @return sliced array 1178 */ 1179 @Function(attributes = Attribute.NOT_ENUMERABLE) 1180 public static Object slice(final Object self, final Object start, final Object end) { 1181 final Object obj = Global.toObject(self); 1182 if (!(obj instanceof ScriptObject)) { 1183 return ScriptRuntime.UNDEFINED; 1184 } 1185 1186 final ScriptObject sobj = (ScriptObject)obj; 1187 final long len = JSType.toUint32(sobj.getLength()); 1188 final long relativeStart = JSType.toLong(start); 1189 final long relativeEnd = end == ScriptRuntime.UNDEFINED ? len : JSType.toLong(end); 1190 1191 long k = relativeStart < 0 ? Math.max(len + relativeStart, 0) : Math.min(relativeStart, len); 1192 final long finale = relativeEnd < 0 ? Math.max(len + relativeEnd, 0) : Math.min(relativeEnd, len); 1193 1194 if (k >= finale) { 1195 return new NativeArray(0); 1196 } 1197 1198 if (bulkable(sobj)) { 1199 return new NativeArray(sobj.getArray().slice(k, finale)); 1200 } 1201 1202 // Construct array with proper length to have a deleted filter on undefined elements 1203 final NativeArray copy = new NativeArray(finale - k); 1204 for (long n = 0; k < finale; n++, k++) { 1205 if (sobj.has(k)) { 1206 copy.defineOwnProperty(ArrayIndex.getArrayIndex(n), sobj.get(k)); 1207 } 1208 } 1209 1210 return copy; 1211 } 1212 1213 private static ScriptFunction compareFunction(final Object comparefn) { 1214 if (comparefn == ScriptRuntime.UNDEFINED) { 1215 return null; 1216 } 1217 1218 if (! (comparefn instanceof ScriptFunction)) { 1219 throw typeError("not.a.function", ScriptRuntime.safeToString(comparefn)); 1220 } 1221 1222 return (ScriptFunction)comparefn; 1223 } 1224 1225 private static Object[] sort(final Object[] array, final Object comparefn) { 1226 final ScriptFunction cmp = compareFunction(comparefn); 1227 1228 final List<Object> list = Arrays.asList(array); 1229 final Object cmpThis = cmp == null || cmp.isStrict() ? ScriptRuntime.UNDEFINED : Global.instance(); 1230 1231 try { 1232 Collections.sort(list, new Comparator<Object>() { 1233 private final MethodHandle call_cmp = getCALL_CMP(); 1234 @Override 1235 public int compare(final Object x, final Object y) { 1236 if (x == ScriptRuntime.UNDEFINED && y == ScriptRuntime.UNDEFINED) { 1237 return 0; 1238 } else if (x == ScriptRuntime.UNDEFINED) { 1239 return 1; 1240 } else if (y == ScriptRuntime.UNDEFINED) { 1241 return -1; 1242 } 1243 1244 if (cmp != null) { 1245 try { 1246 return (int)Math.signum((double)call_cmp.invokeExact(cmp, cmpThis, x, y)); 1247 } catch (final RuntimeException | Error e) { 1248 throw e; 1249 } catch (final Throwable t) { 1250 throw new RuntimeException(t); 1251 } 1252 } 1253 1254 return JSType.toString(x).compareTo(JSType.toString(y)); 1255 } 1256 }); 1257 } catch (final IllegalArgumentException iae) { 1258 // Collections.sort throws IllegalArgumentException when 1259 // Comparison method violates its general contract 1260 1261 // See ECMA spec 15.4.4.11 Array.prototype.sort (comparefn). 1262 // If "comparefn" is not undefined and is not a consistent 1263 // comparison function for the elements of this array, the 1264 // behaviour of sort is implementation-defined. 1265 } 1266 1267 return list.toArray(new Object[array.length]); 1268 } 1269 1270 /** 1271 * ECMA 15.4.4.11 Array.prototype.sort ( comparefn ) 1272 * 1273 * @param self self reference 1274 * @param comparefn element comparison function 1275 * @return sorted array 1276 */ 1277 @Function(attributes = Attribute.NOT_ENUMERABLE) 1278 public static ScriptObject sort(final Object self, final Object comparefn) { 1279 try { 1280 final ScriptObject sobj = (ScriptObject) self; 1281 final long len = JSType.toUint32(sobj.getLength()); 1282 ArrayData array = sobj.getArray(); 1283 1284 if (len > 1) { 1285 // Get only non-missing elements. Missing elements go at the end 1286 // of the sorted array. So, just don't copy these to sort input. 1287 final ArrayList<Object> src = new ArrayList<>(); 1288 1289 for (final Iterator<Long> iter = array.indexIterator(); iter.hasNext(); ) { 1290 final long index = iter.next(); 1291 if (index >= len) { 1292 break; 1293 } 1294 src.add(array.getObject((int)index)); 1295 } 1296 1297 final Object[] sorted = sort(src.toArray(), comparefn); 1298 1299 for (int i = 0; i < sorted.length; i++) { 1300 array = array.set(i, sorted[i], true); 1301 } 1302 1303 // delete missing elements - which are at the end of sorted array 1304 if (sorted.length != len) { 1305 array = array.delete(sorted.length, len - 1); 1306 } 1307 1308 sobj.setArray(array); 1309 } 1310 1311 return sobj; 1312 } catch (final ClassCastException | NullPointerException e) { 1313 throw typeError("not.an.object", ScriptRuntime.safeToString(self)); 1314 } 1315 } 1316 1317 /** 1318 * ECMA 15.4.4.12 Array.prototype.splice ( start, deleteCount [ item1 [ , item2 [ , ... ] ] ] ) 1319 * 1320 * @param self self reference 1321 * @param args arguments 1322 * @return result of splice 1323 */ 1324 @Function(attributes = Attribute.NOT_ENUMERABLE, arity = 2) 1325 public static Object splice(final Object self, final Object... args) { 1326 final Object obj = Global.toObject(self); 1327 1328 if (!(obj instanceof ScriptObject)) { 1329 return ScriptRuntime.UNDEFINED; 1330 } 1331 1332 final Object start = args.length > 0 ? args[0] : ScriptRuntime.UNDEFINED; 1333 final Object deleteCount = args.length > 1 ? args[1] : ScriptRuntime.UNDEFINED; 1334 1335 Object[] items; 1336 1337 if (args.length > 2) { 1338 items = new Object[args.length - 2]; 1339 System.arraycopy(args, 2, items, 0, items.length); 1340 } else { 1341 items = ScriptRuntime.EMPTY_ARRAY; 1342 } 1343 1344 final ScriptObject sobj = (ScriptObject)obj; 1345 final long len = JSType.toUint32(sobj.getLength()); 1346 final long relativeStart = JSType.toLong(start); 1347 1348 final long actualStart = relativeStart < 0 ? Math.max(len + relativeStart, 0) : Math.min(relativeStart, len); 1349 final long actualDeleteCount = Math.min(Math.max(JSType.toLong(deleteCount), 0), len - actualStart); 1350 1351 NativeArray returnValue; 1352 1353 if (actualStart <= Integer.MAX_VALUE && actualDeleteCount <= Integer.MAX_VALUE && bulkable(sobj)) { 1354 try { 1355 returnValue = new NativeArray(sobj.getArray().fastSplice((int)actualStart, (int)actualDeleteCount, items.length)); 1356 1357 // Since this is a dense bulkable array we can use faster defineOwnProperty to copy new elements 1358 int k = (int) actualStart; 1359 for (int i = 0; i < items.length; i++, k++) { 1360 sobj.defineOwnProperty(k, items[i]); 1361 } 1362 } catch (final UnsupportedOperationException uoe) { 1363 returnValue = slowSplice(sobj, actualStart, actualDeleteCount, items, len); 1364 } 1365 } else { 1366 returnValue = slowSplice(sobj, actualStart, actualDeleteCount, items, len); 1367 } 1368 1369 return returnValue; 1370 } 1371 1372 private static NativeArray slowSplice(final ScriptObject sobj, final long start, final long deleteCount, final Object[] items, final long len) { 1373 1374 final NativeArray array = new NativeArray(deleteCount); 1375 1376 for (long k = 0; k < deleteCount; k++) { 1377 final long from = start + k; 1378 1379 if (sobj.has(from)) { 1380 array.defineOwnProperty(ArrayIndex.getArrayIndex(k), sobj.get(from)); 1381 } 1382 } 1383 1384 if (items.length < deleteCount) { 1385 for (long k = start; k < len - deleteCount; k++) { 1386 final long from = k + deleteCount; 1387 final long to = k + items.length; 1388 1389 if (sobj.has(from)) { 1390 sobj.set(to, sobj.get(from), CALLSITE_STRICT); 1391 } else { 1392 sobj.delete(to, true); 1393 } 1394 } 1395 1396 for (long k = len; k > len - deleteCount + items.length; k--) { 1397 sobj.delete(k - 1, true); 1398 } 1399 } else if (items.length > deleteCount) { 1400 for (long k = len - deleteCount; k > start; k--) { 1401 final long from = k + deleteCount - 1; 1402 final long to = k + items.length - 1; 1403 1404 if (sobj.has(from)) { 1405 final Object fromValue = sobj.get(from); 1406 sobj.set(to, fromValue, CALLSITE_STRICT); 1407 } else { 1408 sobj.delete(to, true); 1409 } 1410 } 1411 } 1412 1413 long k = start; 1414 for (int i = 0; i < items.length; i++, k++) { 1415 sobj.set(k, items[i], CALLSITE_STRICT); 1416 } 1417 1418 final long newLength = len - deleteCount + items.length; 1419 sobj.set("length", newLength, CALLSITE_STRICT); 1420 1421 return array; 1422 } 1423 1424 /** 1425 * ECMA 15.4.4.13 Array.prototype.unshift ( [ item1 [ , item2 [ , ... ] ] ] ) 1426 * 1427 * @param self self reference 1428 * @param items items for unshift 1429 * @return unshifted array 1430 */ 1431 @Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1) 1432 public static Object unshift(final Object self, final Object... items) { 1433 final Object obj = Global.toObject(self); 1434 1435 if (!(obj instanceof ScriptObject)) { 1436 return ScriptRuntime.UNDEFINED; 1437 } 1438 1439 final ScriptObject sobj = (ScriptObject)obj; 1440 final long len = JSType.toUint32(sobj.getLength()); 1441 1442 if (items == null) { 1443 return ScriptRuntime.UNDEFINED; 1444 } 1445 1446 if (bulkable(sobj)) { 1447 sobj.getArray().shiftRight(items.length); 1448 1449 for (int j = 0; j < items.length; j++) { 1450 sobj.setArray(sobj.getArray().set(j, items[j], true)); 1451 } 1452 } else { 1453 for (long k = len; k > 0; k--) { 1454 final long from = k - 1; 1455 final long to = k + items.length - 1; 1456 1457 if (sobj.has(from)) { 1458 final Object fromValue = sobj.get(from); 1459 sobj.set(to, fromValue, CALLSITE_STRICT); 1460 } else { 1461 sobj.delete(to, true); 1462 } 1463 } 1464 1465 for (int j = 0; j < items.length; j++) { 1466 sobj.set(j, items[j], CALLSITE_STRICT); 1467 } 1468 } 1469 1470 final long newLength = len + items.length; 1471 sobj.set("length", newLength, CALLSITE_STRICT); 1472 1473 return JSType.toNarrowestNumber(newLength); 1474 } 1475 1476 /** 1477 * ECMA 15.4.4.14 Array.prototype.indexOf ( searchElement [ , fromIndex ] ) 1478 * 1479 * @param self self reference 1480 * @param searchElement element to search for 1481 * @param fromIndex start index of search 1482 * @return index of element, or -1 if not found 1483 */ 1484 @Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1) 1485 public static double indexOf(final Object self, final Object searchElement, final Object fromIndex) { 1486 try { 1487 final ScriptObject sobj = (ScriptObject)Global.toObject(self); 1488 final long len = JSType.toUint32(sobj.getLength()); 1489 if (len == 0) { 1490 return -1; 1491 } 1492 1493 final long n = JSType.toLong(fromIndex); 1494 if (n >= len) { 1495 return -1; 1496 } 1497 1498 1499 for (long k = Math.max(0, n < 0 ? len - Math.abs(n) : n); k < len; k++) { 1500 if (sobj.has(k)) { 1501 if (ScriptRuntime.EQ_STRICT(sobj.get(k), searchElement)) { 1502 return k; 1503 } 1504 } 1505 } 1506 } catch (final ClassCastException | NullPointerException e) { 1507 //fallthru 1508 } 1509 1510 return -1; 1511 } 1512 1513 /** 1514 * ECMA 15.4.4.15 Array.prototype.lastIndexOf ( searchElement [ , fromIndex ] ) 1515 * 1516 * @param self self reference 1517 * @param args arguments: element to search for and optional from index 1518 * @return index of element, or -1 if not found 1519 */ 1520 @Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1) 1521 public static double lastIndexOf(final Object self, final Object... args) { 1522 try { 1523 final ScriptObject sobj = (ScriptObject)Global.toObject(self); 1524 final long len = JSType.toUint32(sobj.getLength()); 1525 1526 if (len == 0) { 1527 return -1; 1528 } 1529 1530 final Object searchElement = args.length > 0 ? args[0] : ScriptRuntime.UNDEFINED; 1531 final long n = args.length > 1 ? JSType.toLong(args[1]) : len - 1; 1532 1533 for (long k = n < 0 ? len - Math.abs(n) : Math.min(n, len - 1); k >= 0; k--) { 1534 if (sobj.has(k)) { 1535 if (ScriptRuntime.EQ_STRICT(sobj.get(k), searchElement)) { 1536 return k; 1537 } 1538 } 1539 } 1540 } catch (final ClassCastException | NullPointerException e) { 1541 throw typeError("not.an.object", ScriptRuntime.safeToString(self)); 1542 } 1543 1544 return -1; 1545 } 1546 1547 /** 1548 * ECMA 15.4.4.16 Array.prototype.every ( callbackfn [ , thisArg ] ) 1549 * 1550 * @param self self reference 1551 * @param callbackfn callback function per element 1552 * @param thisArg this argument 1553 * @return true if callback function return true for every element in the array, false otherwise 1554 */ 1555 @Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1) 1556 public static boolean every(final Object self, final Object callbackfn, final Object thisArg) { 1557 return applyEvery(Global.toObject(self), callbackfn, thisArg); 1558 } 1559 1560 private static boolean applyEvery(final Object self, final Object callbackfn, final Object thisArg) { 1561 return new IteratorAction<Boolean>(Global.toObject(self), callbackfn, thisArg, true) { 1562 private final MethodHandle everyInvoker = getEVERY_CALLBACK_INVOKER(); 1563 1564 @Override 1565 protected boolean forEach(final Object val, final double i) throws Throwable { 1566 return result = (boolean)everyInvoker.invokeExact(callbackfn, thisArg, val, i, self); 1567 } 1568 }.apply(); 1569 } 1570 1571 /** 1572 * ECMA 15.4.4.17 Array.prototype.some ( callbackfn [ , thisArg ] ) 1573 * 1574 * @param self self reference 1575 * @param callbackfn callback function per element 1576 * @param thisArg this argument 1577 * @return true if callback function returned true for any element in the array, false otherwise 1578 */ 1579 @Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1) 1580 public static boolean some(final Object self, final Object callbackfn, final Object thisArg) { 1581 return new IteratorAction<Boolean>(Global.toObject(self), callbackfn, thisArg, false) { 1582 private final MethodHandle someInvoker = getSOME_CALLBACK_INVOKER(); 1583 1584 @Override 1585 protected boolean forEach(final Object val, final double i) throws Throwable { 1586 return !(result = (boolean)someInvoker.invokeExact(callbackfn, thisArg, val, i, self)); 1587 } 1588 }.apply(); 1589 } 1590 1591 /** 1592 * ECMA 15.4.4.18 Array.prototype.forEach ( callbackfn [ , thisArg ] ) 1593 * 1594 * @param self self reference 1595 * @param callbackfn callback function per element 1596 * @param thisArg this argument 1597 * @return undefined 1598 */ 1599 @Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1) 1600 public static Object forEach(final Object self, final Object callbackfn, final Object thisArg) { 1601 return new IteratorAction<Object>(Global.toObject(self), callbackfn, thisArg, ScriptRuntime.UNDEFINED) { 1602 private final MethodHandle forEachInvoker = getFOREACH_CALLBACK_INVOKER(); 1603 1604 @Override 1605 protected boolean forEach(final Object val, final double i) throws Throwable { 1606 forEachInvoker.invokeExact(callbackfn, thisArg, val, i, self); 1607 return true; 1608 } 1609 }.apply(); 1610 } 1611 1612 /** 1613 * ECMA 15.4.4.19 Array.prototype.map ( callbackfn [ , thisArg ] ) 1614 * 1615 * @param self self reference 1616 * @param callbackfn callback function per element 1617 * @param thisArg this argument 1618 * @return array with elements transformed by map function 1619 */ 1620 @Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1) 1621 public static NativeArray map(final Object self, final Object callbackfn, final Object thisArg) { 1622 return new IteratorAction<NativeArray>(Global.toObject(self), callbackfn, thisArg, null) { 1623 private final MethodHandle mapInvoker = getMAP_CALLBACK_INVOKER(); 1624 1625 @Override 1626 protected boolean forEach(final Object val, final double i) throws Throwable { 1627 final Object r = mapInvoker.invokeExact(callbackfn, thisArg, val, i, self); 1628 result.defineOwnProperty(ArrayIndex.getArrayIndex(index), r); 1629 return true; 1630 } 1631 1632 @Override 1633 public void applyLoopBegin(final ArrayLikeIterator<Object> iter0) { 1634 // map return array should be of same length as source array 1635 // even if callback reduces source array length 1636 result = new NativeArray(iter0.getLength()); 1637 } 1638 }.apply(); 1639 } 1640 1641 /** 1642 * ECMA 15.4.4.20 Array.prototype.filter ( callbackfn [ , thisArg ] ) 1643 * 1644 * @param self self reference 1645 * @param callbackfn callback function per element 1646 * @param thisArg this argument 1647 * @return filtered array 1648 */ 1649 @Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1) 1650 public static NativeArray filter(final Object self, final Object callbackfn, final Object thisArg) { 1651 return new IteratorAction<NativeArray>(Global.toObject(self), callbackfn, thisArg, new NativeArray()) { 1652 private long to = 0; 1653 private final MethodHandle filterInvoker = getFILTER_CALLBACK_INVOKER(); 1654 1655 @Override 1656 protected boolean forEach(final Object val, final double i) throws Throwable { 1657 if ((boolean)filterInvoker.invokeExact(callbackfn, thisArg, val, i, self)) { 1658 result.defineOwnProperty(ArrayIndex.getArrayIndex(to++), val); 1659 } 1660 return true; 1661 } 1662 }.apply(); 1663 } 1664 1665 private static Object reduceInner(final ArrayLikeIterator<Object> iter, final Object self, final Object... args) { 1666 final Object callbackfn = args.length > 0 ? args[0] : ScriptRuntime.UNDEFINED; 1667 final boolean initialValuePresent = args.length > 1; 1668 1669 Object initialValue = initialValuePresent ? args[1] : ScriptRuntime.UNDEFINED; 1670 1671 if (callbackfn == ScriptRuntime.UNDEFINED) { 1672 throw typeError("not.a.function", "undefined"); 1673 } 1674 1675 if (!initialValuePresent) { 1676 if (iter.hasNext()) { 1677 initialValue = iter.next(); 1678 } else { 1679 throw typeError("array.reduce.invalid.init"); 1680 } 1681 } 1682 1683 //if initial value is ScriptRuntime.UNDEFINED - step forward once. 1684 return new IteratorAction<Object>(Global.toObject(self), callbackfn, ScriptRuntime.UNDEFINED, initialValue, iter) { 1685 private final MethodHandle reduceInvoker = getREDUCE_CALLBACK_INVOKER(); 1686 1687 @Override 1688 protected boolean forEach(final Object val, final double i) throws Throwable { 1689 // TODO: why can't I declare the second arg as Undefined.class? 1690 result = reduceInvoker.invokeExact(callbackfn, ScriptRuntime.UNDEFINED, result, val, i, self); 1691 return true; 1692 } 1693 }.apply(); 1694 } 1695 1696 /** 1697 * ECMA 15.4.4.21 Array.prototype.reduce ( callbackfn [ , initialValue ] ) 1698 * 1699 * @param self self reference 1700 * @param args arguments to reduce 1701 * @return accumulated result 1702 */ 1703 @Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1) 1704 public static Object reduce(final Object self, final Object... args) { 1705 return reduceInner(arrayLikeIterator(self), self, args); 1706 } 1707 1708 /** 1709 * ECMA 15.4.4.22 Array.prototype.reduceRight ( callbackfn [ , initialValue ] ) 1710 * 1711 * @param self self reference 1712 * @param args arguments to reduce 1713 * @return accumulated result 1714 */ 1715 @Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1) 1716 public static Object reduceRight(final Object self, final Object... args) { 1717 return reduceInner(reverseArrayLikeIterator(self), self, args); 1718 } 1719 1720 /** 1721 * Determine if Java bulk array operations may be used on the underlying 1722 * storage. This is possible only if the object's prototype chain is empty 1723 * or each of the prototypes in the chain is empty. 1724 * 1725 * @param self the object to examine 1726 * @return true if optimizable 1727 */ 1728 private static boolean bulkable(final ScriptObject self) { 1729 return self.isArray() && !hasInheritedArrayEntries(self) && !self.isLengthNotWritable(); 1730 } 1731 1732 private static boolean hasInheritedArrayEntries(final ScriptObject self) { 1733 ScriptObject proto = self.getProto(); 1734 while (proto != null) { 1735 if (proto.hasArrayEntries()) { 1736 return true; 1737 } 1738 proto = proto.getProto(); 1739 } 1740 1741 return false; 1742 } 1743 1744 @Override 1745 public String toString() { 1746 return "NativeArray@" + Debug.id(this) + " [" + getArray().getClass().getSimpleName() + ']'; 1747 } 1748 1749 @Override 1750 public SpecializedFunction.LinkLogic getLinkLogic(final Class<? extends LinkLogic> clazz) { 1751 if (clazz == PushLinkLogic.class) { 1752 return PushLinkLogic.INSTANCE; 1753 } else if (clazz == PopLinkLogic.class) { 1754 return PopLinkLogic.INSTANCE; 1755 } else if (clazz == ConcatLinkLogic.class) { 1756 return ConcatLinkLogic.INSTANCE; 1757 } 1758 return null; 1759 } 1760 1761 @Override 1762 public boolean hasPerInstanceAssumptions() { 1763 return true; //length writable switchpoint 1764 } 1765 1766 /** 1767 * This is an abstract super class that contains common functionality for all 1768 * specialized optimistic builtins in NativeArray. For example, it handles the 1769 * modification switchpoint which is touched when length is written. 1770 */ 1771 private static abstract class ArrayLinkLogic extends SpecializedFunction.LinkLogic { 1772 protected ArrayLinkLogic() { 1773 } 1774 1775 protected static ContinuousArrayData getContinuousArrayData(final Object self) { 1776 try { 1777 //cast to NativeArray, to avoid cases like x = {0:0, 1:1}, x.length = 2, where we can't use the array push/pop 1778 return (ContinuousArrayData)((NativeArray)self).getArray(); 1779 } catch (final Exception e) { 1780 return null; 1781 } 1782 } 1783 1784 /** 1785 * Push and pop callsites can throw ClassCastException as a mechanism to have them 1786 * relinked - this enabled fast checks of the kind of ((IntArrayData)arrayData).push(x) 1787 * for an IntArrayData only push - if this fails, a CCE will be thrown and we will relink 1788 */ 1789 @Override 1790 public Class<? extends Throwable> getRelinkException() { 1791 return ClassCastException.class; 1792 } 1793 } 1794 1795 /** 1796 * This is linker logic for optimistic concatenations 1797 */ 1798 private static final class ConcatLinkLogic extends ArrayLinkLogic { 1799 private static final LinkLogic INSTANCE = new ConcatLinkLogic(); 1800 1801 @Override 1802 public boolean canLink(final Object self, final CallSiteDescriptor desc, final LinkRequest request) { 1803 final Object[] args = request.getArguments(); 1804 1805 if (args.length != 3) { //single argument check 1806 return false; 1807 } 1808 1809 final ContinuousArrayData selfData = getContinuousArrayData(self); 1810 if (selfData == null) { 1811 return false; 1812 } 1813 1814 final Object arg = args[2]; 1815 //args[2] continuousarray or non arraydata, let past non array datas 1816 if (arg instanceof NativeArray) { 1817 final ContinuousArrayData argData = getContinuousArrayData(arg); 1818 if (argData == null) { 1819 return false; 1820 } 1821 } 1822 1823 return true; 1824 } 1825 } 1826 1827 /** 1828 * This is linker logic for optimistic pushes 1829 */ 1830 private static final class PushLinkLogic extends ArrayLinkLogic { 1831 private static final LinkLogic INSTANCE = new PushLinkLogic(); 1832 1833 @Override 1834 public boolean canLink(final Object self, final CallSiteDescriptor desc, final LinkRequest request) { 1835 return getContinuousArrayData(self) != null; 1836 } 1837 } 1838 1839 /** 1840 * This is linker logic for optimistic pops 1841 */ 1842 private static final class PopLinkLogic extends ArrayLinkLogic { 1843 private static final LinkLogic INSTANCE = new PopLinkLogic(); 1844 1845 /** 1846 * We need to check if we are dealing with a continuous non empty array data here, 1847 * as pop with a primitive return value returns undefined for arrays with length 0 1848 */ 1849 @Override 1850 public boolean canLink(final Object self, final CallSiteDescriptor desc, final LinkRequest request) { 1851 final ContinuousArrayData data = getContinuousNonEmptyArrayData(self); 1852 if (data != null) { 1853 final Class<?> elementType = data.getElementType(); 1854 final Class<?> returnType = desc.getMethodType().returnType(); 1855 final boolean typeFits = JSType.getAccessorTypeIndex(returnType) >= JSType.getAccessorTypeIndex(elementType); 1856 return typeFits; 1857 } 1858 return false; 1859 } 1860 1861 private static ContinuousArrayData getContinuousNonEmptyArrayData(final Object self) { 1862 final ContinuousArrayData data = getContinuousArrayData(self); 1863 if (data != null) { 1864 return data.length() == 0 ? null : data; 1865 } 1866 return null; 1867 } 1868 } 1869 1870 //runtime calls for push and pops. they could be used as guards, but they also perform the runtime logic, 1871 //so rather than synthesizing them into a guard method handle that would also perform the push on the 1872 //retrieved receiver, we use this as runtime logic 1873 1874 //TODO - fold these into the Link logics, but I'll do that as a later step, as I want to do a checkin 1875 //where everything works first 1876 1877 private static <T> ContinuousArrayData getContinuousNonEmptyArrayDataCCE(final Object self, final Class<T> clazz) { 1878 try { 1879 @SuppressWarnings("unchecked") 1880 final ContinuousArrayData data = (ContinuousArrayData)(T)((NativeArray)self).getArray(); 1881 if (data.length() != 0L) { 1882 return data; //if length is 0 we cannot pop and have to relink, because then we'd have to return an undefined, which is a wider type than e.g. int 1883 } 1884 } catch (final NullPointerException e) { 1885 //fallthru 1886 } 1887 throw new ClassCastException(); 1888 } 1889 1890 private static ContinuousArrayData getContinuousArrayDataCCE(final Object self) { 1891 try { 1892 return (ContinuousArrayData)((NativeArray)self).getArray(); 1893 } catch (final NullPointerException e) { 1894 throw new ClassCastException(); 1895 } 1896 } 1897 1898 private static ContinuousArrayData getContinuousArrayDataCCE(final Object self, final Class<?> elementType) { 1899 try { 1900 return (ContinuousArrayData)((NativeArray)self).getArray(elementType); //ensure element type can fit "elementType" 1901 } catch (final NullPointerException e) { 1902 throw new ClassCastException(); 1903 } 1904 } 1905} 1906