Debian Codegraph @

rhino/src/org/mozilla/javascript/NativeArray.java

raw symbols SCIP
1 /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 package org.mozilla.javascript;
8
9 import org.mozilla.javascript.regexp.NativeRegExp;
10
11 import java.util.Arrays;
12 import java.util.Collection;
13 import java.util.Comparator;
14 import java.util.Iterator;
15 import java.util.List;
16 import java.util.ListIterator;
17 import java.util.NoSuchElementException;
18
19 import static org.mozilla.javascript.ScriptRuntimeES6.requireObjectCoercible;
20
21 /**
22 * This class implements the Array native object.
23 * @author Norris Boyd
24 * @author Mike McCabe
25 */
26 public class NativeArray extends IdScriptableObject implements List
27 {
28 static final long serialVersionUID = 7331366857676127338L;
29
30 /*
31 * Optimization possibilities and open issues:
32 * - Long vs. double schizophrenia. I suspect it might be better
33 * to use double throughout.
34 *
35 * - Functions that need a new Array call "new Array" in the
36 * current scope rather than using a hardwired constructor;
37 * "Array" could be redefined. It turns out that js calls the
38 * equivalent of "new Array" in the current scope, except that it
39 * always gets at least an object back, even when Array == null.
40 */
41
42 private static final Object ARRAY_TAG = "Array";
43 private static final Integer NEGATIVE_ONE = Integer.valueOf(-1);
44
45 static void init(Scriptable scope, boolean sealed)
46 {
47 NativeArray obj = new NativeArray(0);
48 obj.exportAsJSClass(MAX_PROTOTYPE_ID, scope, sealed);
49 }
50
51 static int getMaximumInitialCapacity() {
52 return maximumInitialCapacity;
53 }
54
55 static void setMaximumInitialCapacity(int maximumInitialCapacity) {
56 NativeArray.maximumInitialCapacity = maximumInitialCapacity;
57 }
58
59 public NativeArray(long lengthArg)
60 {
61 denseOnly = lengthArg <= maximumInitialCapacity;
62 if (denseOnly) {
63 int intLength = (int) lengthArg;
64 if (intLength < DEFAULT_INITIAL_CAPACITY)
65 intLength = DEFAULT_INITIAL_CAPACITY;
66 dense = new Object[intLength];
67 Arrays.fill(dense, Scriptable.NOT_FOUND);
68 }
69 length = lengthArg;
70 }
71
72 public NativeArray(Object[] array)
73 {
74 denseOnly = true;
75 dense = array;
76 length = array.length;
77 }
78
79 @Override
80 public String getClassName()
81 {
82 return "Array";
83 }
84
85 private static final int
86 Id_length = 1,
87 MAX_INSTANCE_ID = 1;
88
89 @Override
90 protected int getMaxInstanceId()
91 {
92 return MAX_INSTANCE_ID;
93 }
94
95 @Override
96 protected void setInstanceIdAttributes(int id, int attr) {
97 if (id == Id_length) {
98 lengthAttr = attr;
99 }
100 }
101
102 @Override
103 protected int findInstanceIdInfo(String s)
104 {
105 if (s.equals("length")) {
106 return instanceIdInfo(lengthAttr, Id_length);
107 }
108 return super.findInstanceIdInfo(s);
109 }
110
111 @Override
112 protected String getInstanceIdName(int id)
113 {
114 if (id == Id_length) { return "length"; }
115 return super.getInstanceIdName(id);
116 }
117
118 @Override
119 protected Object getInstanceIdValue(int id)
120 {
121 if (id == Id_length) {
122 return ScriptRuntime.wrapNumber(length);
123 }
124 return super.getInstanceIdValue(id);
125 }
126
127 @Override
128 protected void setInstanceIdValue(int id, Object value)
129 {
130 if (id == Id_length) {
131 setLength(value); return;
132 }
133 super.setInstanceIdValue(id, value);
134 }
135
136 @Override
137 protected void fillConstructorProperties(IdFunctionObject ctor)
138 {
139 addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_join,
140 "join", 1);
141 addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_reverse,
142 "reverse", 0);
143 addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_sort,
144 "sort", 1);
145 addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_push,
146 "push", 1);
147 addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_pop,
148 "pop", 0);
149 addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_shift,
150 "shift", 0);
151 addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_unshift,
152 "unshift", 1);
153 addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_splice,
154 "splice", 2);
155 addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_concat,
156 "concat", 1);
157 addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_slice,
158 "slice", 2);
159 addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_indexOf,
160 "indexOf", 1);
161 addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_lastIndexOf,
162 "lastIndexOf", 1);
163 addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_every,
164 "every", 1);
165 addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_filter,
166 "filter", 1);
167 addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_forEach,
168 "forEach", 1);
169 addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_map,
170 "map", 1);
171 addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_some,
172 "some", 1);
173 addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_find,
174 "find", 1);
175 addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_findIndex,
176 "findIndex", 1);
177 addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_reduce,
178 "reduce", 1);
179 addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_reduceRight,
180 "reduceRight", 1);
181 addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_isArray,
182 "isArray", 1);
183 super.fillConstructorProperties(ctor);
184 }
185
186 @Override
187 protected void initPrototypeId(int id)
188 {
189 if (id == SymbolId_iterator) {
190 initPrototypeMethod(ARRAY_TAG, id, SymbolKey.ITERATOR, "[Symbol.iterator]", 0);
191 return;
192 }
193
194 String s, fnName = null;
195 int arity;
196 switch (id) {
197 case Id_constructor: arity=1; s="constructor"; break;
198 case Id_toString: arity=0; s="toString"; break;
199 case Id_toLocaleString: arity=0; s="toLocaleString"; break;
200 case Id_toSource: arity=0; s="toSource"; break;
201 case Id_join: arity=1; s="join"; break;
202 case Id_reverse: arity=0; s="reverse"; break;
203 case Id_sort: arity=1; s="sort"; break;
204 case Id_push: arity=1; s="push"; break;
205 case Id_pop: arity=0; s="pop"; break;
206 case Id_shift: arity=0; s="shift"; break;
207 case Id_unshift: arity=1; s="unshift"; break;
208 case Id_splice: arity=2; s="splice"; break;
209 case Id_concat: arity=1; s="concat"; break;
210 case Id_slice: arity=2; s="slice"; break;
211 case Id_indexOf: arity=1; s="indexOf"; break;
212 case Id_lastIndexOf: arity=1; s="lastIndexOf"; break;
213 case Id_every: arity=1; s="every"; break;
214 case Id_filter: arity=1; s="filter"; break;
215 case Id_forEach: arity=1; s="forEach"; break;
216 case Id_map: arity=1; s="map"; break;
217 case Id_some: arity=1; s="some"; break;
218 case Id_find: arity=1; s="find"; break;
219 case Id_findIndex: arity=1; s="findIndex"; break;
220 case Id_reduce: arity=1; s="reduce"; break;
221 case Id_reduceRight: arity=1; s="reduceRight"; break;
222 default: throw new IllegalArgumentException(String.valueOf(id));
223 }
224
225 initPrototypeMethod(ARRAY_TAG, id, s, fnName, arity);
226 }
227
228 @Override
229 public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope,
230 Scriptable thisObj, Object[] args)
231 {
232 if (!f.hasTag(ARRAY_TAG)) {
233 return super.execIdCall(f, cx, scope, thisObj, args);
234 }
235 int id = f.methodId();
236 again:
237 for (;;) {
238 switch (id) {
239 case ConstructorId_join:
240 case ConstructorId_reverse:
241 case ConstructorId_sort:
242 case ConstructorId_push:
243 case ConstructorId_pop:
244 case ConstructorId_shift:
245 case ConstructorId_unshift:
246 case ConstructorId_splice:
247 case ConstructorId_concat:
248 case ConstructorId_slice:
249 case ConstructorId_indexOf:
250 case ConstructorId_lastIndexOf:
251 case ConstructorId_every:
252 case ConstructorId_filter:
253 case ConstructorId_forEach:
254 case ConstructorId_map:
255 case ConstructorId_some:
256 case ConstructorId_find:
257 case ConstructorId_findIndex:
258 case ConstructorId_reduce:
259 case ConstructorId_reduceRight: {
260 if (args.length > 0) {
261 thisObj = ScriptRuntime.toObject(cx, scope, args[0]);
262 Object[] newArgs = new Object[args.length-1];
263 for (int i=0; i < newArgs.length; i++)
264 newArgs[i] = args[i+1];
265 args = newArgs;
266 }
267 id = -id;
268 continue again;
269 }
270
271 case ConstructorId_isArray:
272 return args.length > 0 && js_isArray(args[0]);
273
274 case Id_constructor: {
275 boolean inNewExpr = (thisObj == null);
276 if (!inNewExpr) {
277 // IdFunctionObject.construct will set up parent, proto
278 return f.construct(cx, scope, args);
279 }
280 return jsConstructor(cx, scope, args);
281 }
282
283 case Id_toString:
284 return toStringHelper(cx, scope, thisObj,
285 cx.hasFeature(Context.FEATURE_TO_STRING_AS_SOURCE), false);
286
287 case Id_toLocaleString:
288 return toStringHelper(cx, scope, thisObj, false, true);
289
290 case Id_toSource:
291 return toStringHelper(cx, scope, thisObj, true, false);
292
293 case Id_join:
294 return js_join(cx, thisObj, args);
295
296 case Id_reverse:
297 return js_reverse(cx, thisObj, args);
298
299 case Id_sort:
300 return js_sort(cx, scope, thisObj, args);
301
302 case Id_push:
303 return js_push(cx, thisObj, args);
304
305 case Id_pop:
306 return js_pop(cx, thisObj, args);
307
308 case Id_shift:
309 return js_shift(cx, thisObj, args);
310
311 case Id_unshift:
312 return js_unshift(cx, thisObj, args);
313
314 case Id_splice:
315 return js_splice(cx, scope, thisObj, args);
316
317 case Id_concat:
318 return js_concat(cx, scope, thisObj, args);
319
320 case Id_slice:
321 return js_slice(cx, thisObj, args);
322
323 case Id_indexOf:
324 return js_indexOf(cx, thisObj, args);
325
326 case Id_lastIndexOf:
327 return js_lastIndexOf(cx, thisObj, args);
328
329 case Id_every:
330 case Id_filter:
331 case Id_forEach:
332 case Id_map:
333 case Id_some:
334 case Id_find:
335 case Id_findIndex:
336 return iterativeMethod(cx, f, scope, thisObj, args);
337 case Id_reduce:
338 case Id_reduceRight:
339 return reduceMethod(cx, id, scope, thisObj, args);
340
341 case SymbolId_iterator:
342 return new NativeArrayIterator(scope, thisObj);
343 }
344 throw new IllegalArgumentException("Array.prototype has no method: " + f.getFunctionName());
345 }
346 }
347
348 @Override
349 public Object get(int index, Scriptable start)
350 {
351 if (!denseOnly && isGetterOrSetter(null, index, false))
352 return super.get(index, start);
353 if (dense != null && 0 <= index && index < dense.length)
354 return dense[index];
355 return super.get(index, start);
356 }
357
358 @Override
359 public boolean has(int index, Scriptable start)
360 {
361 if (!denseOnly && isGetterOrSetter(null, index, false))
362 return super.has(index, start);
363 if (dense != null && 0 <= index && index < dense.length)
364 return dense[index] != NOT_FOUND;
365 return super.has(index, start);
366 }
367
368 private static long toArrayIndex(Object id) {
369 if (id instanceof String) {
370 return toArrayIndex((String)id);
371 } else if (id instanceof Number) {
372 return toArrayIndex(((Number)id).doubleValue());
373 }
374 return -1;
375 }
376
377 // if id is an array index (ECMA 15.4.0), return the number,
378 // otherwise return -1L
379 private static long toArrayIndex(String id)
380 {
381 long index = toArrayIndex(ScriptRuntime.toNumber(id));
382 // Assume that ScriptRuntime.toString(index) is the same
383 // as java.lang.Long.toString(index) for long
384 if (Long.toString(index).equals(id)) {
385 return index;
386 }
387 return -1;
388 }
389
390 private static long toArrayIndex(double d) {
391 if (d == d) {
392 long index = ScriptRuntime.toUint32(d);
393 if (index == d && index != 4294967295L) {
394 return index;
395 }
396 }
397 return -1;
398 }
399
400 private static int toDenseIndex(Object id) {
401 long index = toArrayIndex(id);
402 return 0 <= index && index < Integer.MAX_VALUE ? (int) index : -1;
403 }
404
405 @Override
406 public void put(String id, Scriptable start, Object value)
407 {
408 super.put(id, start, value);
409 if (start == this) {
410 // If the object is sealed, super will throw exception
411 long index = toArrayIndex(id);
412 if (index >= length) {
413 length = index + 1;
414 denseOnly = false;
415 }
416 }
417 }
418
419 private boolean ensureCapacity(int capacity)
420 {
421 if (capacity > dense.length) {
422 if (capacity > MAX_PRE_GROW_SIZE) {
423 denseOnly = false;
424 return false;
425 }
426 capacity = Math.max(capacity, (int)(dense.length * GROW_FACTOR));
427 Object[] newDense = new Object[capacity];
428 System.arraycopy(dense, 0, newDense, 0, dense.length);
429 Arrays.fill(newDense, dense.length, newDense.length,
430 Scriptable.NOT_FOUND);
431 dense = newDense;
432 }
433 return true;
434 }
435
436 @Override
437 public void put(int index, Scriptable start, Object value)
438 {
439 if (start == this && !isSealed() && dense != null && 0 <= index &&
440 (denseOnly || !isGetterOrSetter(null, index, true)))
441 {
442 if (!isExtensible() && this.length <= index) {
443 return;
444 } else if (index < dense.length) {
445 dense[index] = value;
446 if (this.length <= index)
447 this.length = (long)index + 1;
448 return;
449 } else if (denseOnly && index < dense.length * GROW_FACTOR &&
450 ensureCapacity(index+1))
451 {
452 dense[index] = value;
453 this.length = (long)index + 1;
454 return;
455 } else {
456 denseOnly = false;
457 }
458 }
459 super.put(index, start, value);
460 if (start == this && (lengthAttr & READONLY) == 0) {
461 // only set the array length if given an array index (ECMA 15.4.0)
462 if (this.length <= index) {
463 // avoid overflowing index!
464 this.length = (long)index + 1;
465 }
466 }
467 }
468
469 @Override
470 public void delete(int index)
471 {
472 if (dense != null && 0 <= index && index < dense.length &&
473 !isSealed() && (denseOnly || !isGetterOrSetter(null, index, true)))
474 {
475 dense[index] = NOT_FOUND;
476 } else {
477 super.delete(index);
478 }
479 }
480
481 @Override
482 public Object[] getIds(boolean nonEnumerable, boolean getSymbols)
483 {
484 Object[] superIds = super.getIds(nonEnumerable, getSymbols);
485 if (dense == null) { return superIds; }
486 int N = dense.length;
487 long currentLength = length;
488 if (N > currentLength) {
489 N = (int)currentLength;
490 }
491 if (N == 0) { return superIds; }
492 int superLength = superIds.length;
493 Object[] ids = new Object[N + superLength];
494
495 int presentCount = 0;
496 for (int i = 0; i != N; ++i) {
497 // Replace existing elements by their indexes
498 if (dense[i] != NOT_FOUND) {
499 ids[presentCount] = Integer.valueOf(i);
500 ++presentCount;
501 }
502 }
503 if (presentCount != N) {
504 // dense contains deleted elems, need to shrink the result
505 Object[] tmp = new Object[presentCount + superLength];
506 System.arraycopy(ids, 0, tmp, 0, presentCount);
507 ids = tmp;
508 }
509 System.arraycopy(superIds, 0, ids, presentCount, superLength);
510 return ids;
511 }
512
513 public Integer[] getIndexIds() {
514 Object[] ids = getIds();
515 java.util.List<Integer> indices = new java.util.ArrayList<Integer>(ids.length);
516 for (Object id : ids) {
517 int int32Id = ScriptRuntime.toInt32(id);
518 if (int32Id >= 0 && ScriptRuntime.toString(int32Id).equals(ScriptRuntime.toString(id))) {
519 indices.add(int32Id);
520 }
521 }
522 return indices.toArray(new Integer[indices.size()]);
523 }
524
525 @Override
526 public Object getDefaultValue(Class<?> hint)
527 {
528 if (hint == ScriptRuntime.NumberClass) {
529 Context cx = Context.getContext();
530 if (cx.getLanguageVersion() == Context.VERSION_1_2)
531 return Long.valueOf(length);
532 }
533 return super.getDefaultValue(hint);
534 }
535
536 private ScriptableObject defaultIndexPropertyDescriptor(Object value) {
537 Scriptable scope = getParentScope();
538 if (scope == null) scope = this;
539 ScriptableObject desc = new NativeObject();
540 ScriptRuntime.setBuiltinProtoAndParent(desc, scope, TopLevel.Builtins.Object);
541 desc.defineProperty("value", value, EMPTY);
542 desc.defineProperty("writable", true, EMPTY);
543 desc.defineProperty("enumerable", true, EMPTY);
544 desc.defineProperty("configurable", true, EMPTY);
545 return desc;
546 }
547
548 @Override
549 public int getAttributes(int index) {
550 if (dense != null && index >= 0 && index < dense.length
551 && dense[index] != NOT_FOUND) {
552 return EMPTY;
553 }
554 return super.getAttributes(index);
555 }
556
557 @Override
558 protected ScriptableObject getOwnPropertyDescriptor(Context cx, Object id) {
559 if (dense != null) {
560 int index = toDenseIndex(id);
561 if (0 <= index && index < dense.length && dense[index] != NOT_FOUND) {
562 Object value = dense[index];
563 return defaultIndexPropertyDescriptor(value);
564 }
565 }
566 return super.getOwnPropertyDescriptor(cx, id);
567 }
568
569 @Override
570 protected void defineOwnProperty(Context cx, Object id,
571 ScriptableObject desc,
572 boolean checkValid) {
573 if (dense != null) {
574 Object[] values = dense;
575 dense = null;
576 denseOnly = false;
577 for (int i = 0; i < values.length; i++) {
578 if (values[i] != NOT_FOUND) {
579 put(i, this, values[i]);
580 }
581 }
582 }
583 long index = toArrayIndex(id);
584 if (index >= length) {
585 length = index + 1;
586 }
587 super.defineOwnProperty(cx, id, desc, checkValid);
588 }
589
590 /**
591 * See ECMA 15.4.1,2
592 */
593 private static Object jsConstructor(Context cx, Scriptable scope,
594 Object[] args)
595 {
596 if (args.length == 0)
597 return new NativeArray(0);
598
599 // Only use 1 arg as first element for version 1.2; for
600 // any other version (including 1.3) follow ECMA and use it as
601 // a length.
602 if (cx.getLanguageVersion() == Context.VERSION_1_2) {
603 return new NativeArray(args);
604 } else {
605 Object arg0 = args[0];
606 if (args.length > 1 || !(arg0 instanceof Number)) {
607 return new NativeArray(args);
608 } else {
609 long len = ScriptRuntime.toUint32(arg0);
610 if (len != ((Number)arg0).doubleValue()) {
611 String msg = ScriptRuntime.getMessage0("msg.arraylength.bad");
612 throw ScriptRuntime.constructError("RangeError", msg);
613 }
614 return new NativeArray(len);
615 }
616 }
617 }
618
619 public long getLength() {
620 return length;
621 }
622
623 /** @deprecated Use {@link #getLength()} instead. */
624 @Deprecated
625 public long jsGet_length() {
626 return getLength();
627 }
628
629 /**
630 * Change the value of the internal flag that determines whether all
631 * storage is handed by a dense backing array rather than an associative
632 * store.
633 * @param denseOnly new value for denseOnly flag
634 * @throws IllegalArgumentException if an attempt is made to enable
635 * denseOnly after it was disabled; NativeArray code is not written
636 * to handle switching back to a dense representation
637 */
638 void setDenseOnly(boolean denseOnly) {
639 if (denseOnly && !this.denseOnly)
640 throw new IllegalArgumentException();
641 this.denseOnly = denseOnly;
642 }
643
644 private void setLength(Object val) {
645 /* XXX do we satisfy this?
646 * 15.4.5.1 [[Put]](P, V):
647 * 1. Call the [[CanPut]] method of A with name P.
648 * 2. If Result(1) is false, return.
649 * ?
650 */
651 if ((lengthAttr & READONLY) != 0) {
652 return;
653 }
654
655 double d = ScriptRuntime.toNumber(val);
656 long longVal = ScriptRuntime.toUint32(d);
657 if (longVal != d) {
658 String msg = ScriptRuntime.getMessage0("msg.arraylength.bad");
659 throw ScriptRuntime.constructError("RangeError", msg);
660 }
661
662 if (denseOnly) {
663 if (longVal < length) {
664 // downcast okay because denseOnly
665 Arrays.fill(dense, (int) longVal, dense.length, NOT_FOUND);
666 length = longVal;
667 return;
668 } else if (longVal < MAX_PRE_GROW_SIZE &&
669 longVal < (length * GROW_FACTOR) &&
670 ensureCapacity((int)longVal))
671 {
672 length = longVal;
673 return;
674 } else {
675 denseOnly = false;
676 }
677 }
678 if (longVal < length) {
679 // remove all properties between longVal and length
680 if (length - longVal > 0x1000) {
681 // assume that the representation is sparse
682 Object[] e = getIds(); // will only find in object itself
683 for (int i=0; i < e.length; i++) {
684 Object id = e[i];
685 if (id instanceof String) {
686 // > MAXINT will appear as string
687 String strId = (String)id;
688 long index = toArrayIndex(strId);
689 if (index >= longVal)
690 delete(strId);
691 } else {
692 int index = ((Integer)id).intValue();
693 if (index >= longVal)
694 delete(index);
695 }
696 }
697 } else {
698 // assume a dense representation
699 for (long i = longVal; i < length; i++) {
700 deleteElem(this, i);
701 }
702 }
703 }
704 length = longVal;
705 }
706
707 /* Support for generic Array-ish objects. Most of the Array
708 * functions try to be generic; anything that has a length
709 * property is assumed to be an array.
710 * getLengthProperty returns 0 if obj does not have the length property
711 * or its value is not convertible to a number.
712 */
713 static long getLengthProperty(Context cx, Scriptable obj) {
714 // These will both give numeric lengths within Uint32 range.
715 if (obj instanceof NativeString) {
716 return ((NativeString)obj).getLength();
717 } else if (obj instanceof NativeArray) {
718 return ((NativeArray)obj).getLength();
719 }
720 Object len = ScriptableObject.getProperty(obj, "length");
721 if (len == Scriptable.NOT_FOUND) {
722 // toUint32(undefined) == 0
723 return 0;
724 }
725 return ScriptRuntime.toUint32(len);
726 }
727
728 private static Object setLengthProperty(Context cx, Scriptable target,
729 long length)
730 {
731 Object len = ScriptRuntime.wrapNumber(length);
732 ScriptableObject.putProperty(target, "length", len);
733 return len;
734 }
735
736 /* Utility functions to encapsulate index > Integer.MAX_VALUE
737 * handling. Also avoids unnecessary object creation that would
738 * be necessary to use the general ScriptRuntime.get/setElem
739 * functions... though this is probably premature optimization.
740 */
741 private static void deleteElem(Scriptable target, long index) {
742 int i = (int)index;
743 if (i == index) { target.delete(i); }
744 else { target.delete(Long.toString(index)); }
745 }
746
747 private static Object getElem(Context cx, Scriptable target, long index)
748 {
749 Object elem = getRawElem(target, index);
750 return (elem != Scriptable.NOT_FOUND ? elem : Undefined.instance);
751 }
752
753 // same as getElem, but without converting NOT_FOUND to undefined
754 private static Object getRawElem(Scriptable target, long index) {
755 if (index > Integer.MAX_VALUE) {
756 return ScriptableObject.getProperty(target, Long.toString(index));
757 } else {
758 return ScriptableObject.getProperty(target, (int)index);
759 }
760 }
761
762 private static void defineElem(Context cx, Scriptable target, long index,
763 Object value)
764 {
765 if (index > Integer.MAX_VALUE) {
766 String id = Long.toString(index);
767 target.put(id, target, value);
768 } else {
769 target.put((int)index, target, value);
770 }
771 }
772
773 private static void setElem(Context cx, Scriptable target, long index,
774 Object value)
775 {
776 if (index > Integer.MAX_VALUE) {
777 String id = Long.toString(index);
778 ScriptableObject.putProperty(target, id, value);
779 } else {
780 ScriptableObject.putProperty(target, (int)index, value);
781 }
782 }
783
784 // Similar as setElem(), but triggers deleteElem() if value is NOT_FOUND
785 private static void setRawElem(Context cx, Scriptable target, long index,
786 Object value) {
787 if (value == NOT_FOUND) {
788 deleteElem(target, index);
789 } else {
790 setElem(cx, target, index, value);
791 }
792 }
793
794 private static String toStringHelper(Context cx, Scriptable scope,
795 Scriptable thisObj,
796 boolean toSource, boolean toLocale)
797 {
798 /* It's probably redundant to handle long lengths in this
799 * function; StringBuilders are limited to 2^31 in java.
800 */
801
802 long length = getLengthProperty(cx, thisObj);
803
804 StringBuilder result = new StringBuilder(256);
805
806 // whether to return '4,unquoted,5' or '[4, "quoted", 5]'
807 String separator;
808
809 if (toSource) {
810 result.append('[');
811 separator = ", ";
812 } else {
813 separator = ",";
814 }
815
816 boolean haslast = false;
817 long i = 0;
818
819 boolean toplevel, iterating;
820 if (cx.iterating == null) {
821 toplevel = true;
822 iterating = false;
823 cx.iterating = new ObjToIntMap(31);
824 } else {
825 toplevel = false;
826 iterating = cx.iterating.has(thisObj);
827 }
828
829 // Make sure cx.iterating is set to null when done
830 // so we don't leak memory
831 try {
832 if (!iterating) {
833 cx.iterating.put(thisObj, 0); // stop recursion.
834 // make toSource print null and undefined values in recent versions
835 boolean skipUndefinedAndNull = !toSource
836 || cx.getLanguageVersion() < Context.VERSION_1_5;
837 for (i = 0; i < length; i++) {
838 if (i > 0) result.append(separator);
839 Object elem = getRawElem(thisObj, i);
840 if (elem == NOT_FOUND || (skipUndefinedAndNull &&
841 (elem == null || elem == Undefined.instance))) {
842 haslast = false;
843 continue;
844 }
845 haslast = true;
846
847 if (toSource) {
848 result.append(ScriptRuntime.uneval(cx, scope, elem));
849
850 } else if (elem instanceof String) {
851 String s = (String)elem;
852 if (toSource) {
853 result.append('\"');
854 result.append(ScriptRuntime.escapeString(s));
855 result.append('\"');
856 } else {
857 result.append(s);
858 }
859
860 } else {
861 if (toLocale) {
862 Callable fun;
863 Scriptable funThis;
864 fun = ScriptRuntime.getPropFunctionAndThis(
865 elem, "toLocaleString", cx, scope);
866 funThis = ScriptRuntime.lastStoredScriptable(cx);
867 elem = fun.call(cx, scope, funThis,
868 ScriptRuntime.emptyArgs);
869 }
870 result.append(ScriptRuntime.toString(elem));
871 }
872 }
873 }
874 } finally {
875 if (toplevel) {
876 cx.iterating = null;
877 }
878 }
879
880 if (toSource) {
881 //for [,,].length behavior; we want toString to be symmetric.
882 if (!haslast && i > 0)
883 result.append(", ]");
884 else
885 result.append(']');
886 }
887 return result.toString();
888 }
889
890 /**
891 * See ECMA 15.4.4.3
892 */
893 private static String js_join(Context cx, Scriptable thisObj,
894 Object[] args)
895 {
896 long llength = getLengthProperty(cx, thisObj);
897 int length = (int)llength;
898 if (llength != length) {
899 throw Context.reportRuntimeError1(
900 "msg.arraylength.too.big", String.valueOf(llength));
901 }
902 // if no args, use "," as separator
903 String separator = (args.length < 1 || args[0] == Undefined.instance)
904 ? ","
905 : ScriptRuntime.toString(args[0]);
906 if (thisObj instanceof NativeArray) {
907 NativeArray na = (NativeArray) thisObj;
908 if (na.denseOnly) {
909 StringBuilder sb = new StringBuilder();
910 for (int i = 0; i < length; i++) {
911 if (i != 0) {
912 sb.append(separator);
913 }
914 if (i < na.dense.length) {
915 Object temp = na.dense[i];
916 if (temp != null && temp != Undefined.instance &&
917 temp != Scriptable.NOT_FOUND)
918 {
919 sb.append(ScriptRuntime.toString(temp));
920 }
921 }
922 }
923 return sb.toString();
924 }
925 }
926 if (length == 0) {
927 return "";
928 }
929 String[] buf = new String[length];
930 int total_size = 0;
931 for (int i = 0; i != length; i++) {
932 Object temp = getElem(cx, thisObj, i);
933 if (temp != null && temp != Undefined.instance) {
934 String str = ScriptRuntime.toString(temp);
935 total_size += str.length();
936 buf[i] = str;
937 }
938 }
939 total_size += (length - 1) * separator.length();
940 StringBuilder sb = new StringBuilder(total_size);
941 for (int i = 0; i != length; i++) {
942 if (i != 0) {
943 sb.append(separator);
944 }
945 String str = buf[i];
946 if (str != null) {
947 // str == null for undefined or null
948 sb.append(str);
949 }
950 }
951 return sb.toString();
952 }
953
954 /**
955 * See ECMA 15.4.4.4
956 */
957 private static Scriptable js_reverse(Context cx, Scriptable thisObj,
958 Object[] args)
959 {
960 if (thisObj instanceof NativeArray) {
961 NativeArray na = (NativeArray) thisObj;
962 if (na.denseOnly) {
963 for (int i=0, j=((int)na.length)-1; i < j; i++,j--) {
964 Object temp = na.dense[i];
965 na.dense[i] = na.dense[j];
966 na.dense[j] = temp;
967 }
968 return thisObj;
969 }
970 }
971 long len = getLengthProperty(cx, thisObj);
972
973 long half = len / 2;
974 for(long i=0; i < half; i++) {
975 long j = len - i - 1;
976 Object temp1 = getRawElem(thisObj, i);
977 Object temp2 = getRawElem(thisObj, j);
978 setRawElem(cx, thisObj, i, temp2);
979 setRawElem(cx, thisObj, j, temp1);
980 }
981 return thisObj;
982 }
983
984 /**
985 * See ECMA 15.4.4.5
986 */
987 private static Scriptable js_sort(final Context cx, final Scriptable scope,
988 final Scriptable thisObj, final Object[] args)
989 {
990 final Comparator<Object> comparator;
991 if (args.length > 0 && Undefined.instance != args[0]) {
992 final Callable jsCompareFunction = ScriptRuntime
993 .getValueFunctionAndThis(args[0], cx);
994 final Scriptable funThis = ScriptRuntime.lastStoredScriptable(cx);
995 final Object[] cmpBuf = new Object[2]; // Buffer for cmp arguments
996 comparator = new ElementComparator(
997 new Comparator<Object>() {
998 public int compare(final Object x, final Object y) {
999 // This comparator is invoked only for non-undefined objects
1000 cmpBuf[0] = x;
1001 cmpBuf[1] = y;
1002 Object ret = jsCompareFunction.call(cx, scope, funThis,
1003 cmpBuf);
1004 final double d = ScriptRuntime.toNumber(ret);
1005 if (d < 0) {
1006 return -1;
1007 } else if (d > 0) {
1008 return +1;
1009 }
1010 return 0; // ??? double and 0???
1011 }
1012 });
1013 } else {
1014 comparator = DEFAULT_COMPARATOR;
1015 }
1016
1017 long llength = getLengthProperty(cx, thisObj);
1018 final int length = (int) llength;
1019 if (llength != length) {
1020 throw Context.reportRuntimeError1(
1021 "msg.arraylength.too.big", String.valueOf(llength));
1022 }
1023 // copy the JS array into a working array, so it can be
1024 // sorted cheaply.
1025 final Object[] working = new Object[length];
1026 for (int i = 0; i != length; ++i) {
1027 working[i] = getRawElem(thisObj, i);
1028 }
1029
1030 Sorting.hybridSort(working, comparator);
1031
1032 // copy the working array back into thisObj
1033 for (int i = 0; i < length; ++i) {
1034 setRawElem(cx, thisObj, i, working[i]);
1035 }
1036
1037 return thisObj;
1038 }
1039
1040 private static Object js_push(Context cx, Scriptable thisObj,
1041 Object[] args)
1042 {
1043 if (thisObj instanceof NativeArray) {
1044 NativeArray na = (NativeArray) thisObj;
1045 if (na.denseOnly &&
1046 na.ensureCapacity((int) na.length + args.length))
1047 {
1048 for (int i = 0; i < args.length; i++) {
1049 na.dense[(int)na.length++] = args[i];
1050 }
1051 return ScriptRuntime.wrapNumber(na.length);
1052 }
1053 }
1054 long length = getLengthProperty(cx, thisObj);
1055 for (int i = 0; i < args.length; i++) {
1056 setElem(cx, thisObj, length + i, args[i]);
1057 }
1058
1059 length += args.length;
1060 Object lengthObj = setLengthProperty(cx, thisObj, length);
1061
1062 /*
1063 * If JS1.2, follow Perl4 by returning the last thing pushed.
1064 * Otherwise, return the new array length.
1065 */
1066 if (cx.getLanguageVersion() == Context.VERSION_1_2)
1067 // if JS1.2 && no arguments, return undefined.
1068 return args.length == 0
1069 ? Undefined.instance
1070 : args[args.length - 1];
1071
1072 else
1073 return lengthObj;
1074 }
1075
1076 private static Object js_pop(Context cx, Scriptable thisObj,
1077 Object[] args)
1078 {
1079 Object result;
1080 if (thisObj instanceof NativeArray) {
1081 NativeArray na = (NativeArray) thisObj;
1082 if (na.denseOnly && na.length > 0) {
1083 na.length--;
1084 result = na.dense[(int)na.length];
1085 na.dense[(int)na.length] = NOT_FOUND;
1086 return result;
1087 }
1088 }
1089 long length = getLengthProperty(cx, thisObj);
1090 if (length > 0) {
1091 length--;
1092
1093 // Get the to-be-deleted property's value.
1094 result = getElem(cx, thisObj, length);
1095
1096 // We need to delete the last property, because 'thisObj' may not
1097 // have setLength which does that for us.
1098 deleteElem(thisObj, length);
1099 } else {
1100 result = Undefined.instance;
1101 }
1102 // necessary to match js even when length < 0; js pop will give a
1103 // length property to any target it is called on.
1104 setLengthProperty(cx, thisObj, length);
1105
1106 return result;
1107 }
1108
1109 private static Object js_shift(Context cx, Scriptable thisObj,
1110 Object[] args)
1111 {
1112 if (thisObj instanceof NativeArray) {
1113 NativeArray na = (NativeArray) thisObj;
1114 if (na.denseOnly && na.length > 0) {
1115 na.length--;
1116 Object result = na.dense[0];
1117 System.arraycopy(na.dense, 1, na.dense, 0, (int)na.length);
1118 na.dense[(int)na.length] = NOT_FOUND;
1119 return result == NOT_FOUND ? Undefined.instance : result;
1120 }
1121 }
1122 Object result;
1123 long length = getLengthProperty(cx, thisObj);
1124 if (length > 0) {
1125 long i = 0;
1126 length--;
1127
1128 // Get the to-be-deleted property's value.
1129 result = getElem(cx, thisObj, i);
1130
1131 /*
1132 * Slide down the array above the first element. Leave i
1133 * set to point to the last element.
1134 */
1135 if (length > 0) {
1136 for (i = 1; i <= length; i++) {
1137 Object temp = getRawElem(thisObj, i);
1138 setRawElem(cx, thisObj, i - 1, temp);
1139 }
1140 }
1141 // We need to delete the last property, because 'thisObj' may not
1142 // have setLength which does that for us.
1143 deleteElem(thisObj, length);
1144 } else {
1145 result = Undefined.instance;
1146 }
1147 setLengthProperty(cx, thisObj, length);
1148 return result;
1149 }
1150
1151 private static Object js_unshift(Context cx, Scriptable thisObj,
1152 Object[] args)
1153 {
1154 if (thisObj instanceof NativeArray) {
1155 NativeArray na = (NativeArray) thisObj;
1156 if (na.denseOnly &&
1157 na.ensureCapacity((int)na.length + args.length))
1158 {
1159 System.arraycopy(na.dense, 0, na.dense, args.length,
1160 (int) na.length);
1161 for (int i = 0; i < args.length; i++) {
1162 na.dense[i] = args[i];
1163 }
1164 na.length += args.length;
1165 return ScriptRuntime.wrapNumber(na.length);
1166 }
1167 }
1168 long length = getLengthProperty(cx, thisObj);
1169 int argc = args.length;
1170
1171 if (args.length > 0) {
1172 /* Slide up the array to make room for args at the bottom */
1173 if (length > 0) {
1174 for (long last = length - 1; last >= 0; last--) {
1175 Object temp = getRawElem(thisObj, last);
1176 setRawElem(cx, thisObj, last + argc, temp);
1177 }
1178 }
1179
1180 /* Copy from argv to the bottom of the array. */
1181 for (int i = 0; i < args.length; i++) {
1182 setElem(cx, thisObj, i, args[i]);
1183 }
1184 }
1185 /* Follow Perl by returning the new array length. */
1186 length += args.length;
1187 return setLengthProperty(cx, thisObj, length);
1188 }
1189
1190 private static Object js_splice(Context cx, Scriptable scope,
1191 Scriptable thisObj, Object[] args)
1192 {
1193 NativeArray na = null;
1194 boolean denseMode = false;
1195 if (thisObj instanceof NativeArray) {
1196 na = (NativeArray) thisObj;
1197 denseMode = na.denseOnly;
1198 }
1199
1200 /* create an empty Array to return. */
1201 scope = getTopLevelScope(scope);
1202 int argc = args.length;
1203 if (argc == 0)
1204 return cx.newArray(scope, 0);
1205 long length = getLengthProperty(cx, thisObj);
1206
1207 /* Convert the first argument into a starting index. */
1208 long begin = toSliceIndex(ScriptRuntime.toInteger(args[0]), length);
1209 argc--;
1210
1211 /* Convert the second argument into count */
1212 long count;
1213 if (args.length == 1) {
1214 count = length - begin;
1215 } else {
1216 double dcount = ScriptRuntime.toInteger(args[1]);
1217 if (dcount < 0) {
1218 count = 0;
1219 } else if (dcount > (length - begin)) {
1220 count = length - begin;
1221 } else {
1222 count = (long)dcount;
1223 }
1224 argc--;
1225 }
1226
1227 long end = begin + count;
1228
1229 /* If there are elements to remove, put them into the return value. */
1230 Object result;
1231 if (count != 0) {
1232 if (count == 1
1233 && (cx.getLanguageVersion() == Context.VERSION_1_2))
1234 {
1235 /*
1236 * JS lacks "list context", whereby in Perl one turns the
1237 * single scalar that's spliced out into an array just by
1238 * assigning it to @single instead of $single, or by using it
1239 * as Perl push's first argument, for instance.
1240 *
1241 * JS1.2 emulated Perl too closely and returned a non-Array for
1242 * the single-splice-out case, requiring callers to test and
1243 * wrap in [] if necessary. So JS1.3, default, and other
1244 * versions all return an array of length 1 for uniformity.
1245 */
1246 result = getElem(cx, thisObj, begin);
1247 } else {
1248 if (denseMode) {
1249 int intLen = (int) (end - begin);
1250 Object[] copy = new Object[intLen];
1251 System.arraycopy(na.dense, (int) begin, copy, 0, intLen);
1252 result = cx.newArray(scope, copy);
1253 } else {
1254 Scriptable resultArray = cx.newArray(scope, 0);
1255 for (long last = begin; last != end; last++) {
1256 Object temp = getRawElem(thisObj, last);
1257 if (temp != NOT_FOUND) {
1258 setElem(cx, resultArray, last - begin, temp);
1259 }
1260 }
1261 // Need to set length for sparse result array
1262 setLengthProperty(cx, resultArray, end - begin);
1263 result = resultArray;
1264 }
1265 }
1266 } else { // (count == 0)
1267 if (cx.getLanguageVersion() == Context.VERSION_1_2) {
1268 /* Emulate C JS1.2; if no elements are removed, return undefined. */
1269 result = Undefined.instance;
1270 } else {
1271 result = cx.newArray(scope, 0);
1272 }
1273 }
1274
1275 /* Find the direction (up or down) to copy and make way for argv. */
1276 long delta = argc - count;
1277 if (denseMode && length + delta < Integer.MAX_VALUE &&
1278 na.ensureCapacity((int) (length + delta)))
1279 {
1280 System.arraycopy(na.dense, (int) end, na.dense,
1281 (int) (begin + argc), (int) (length - end));
1282 if (argc > 0) {
1283 System.arraycopy(args, 2, na.dense, (int) begin, argc);
1284 }
1285 if (delta < 0) {
1286 Arrays.fill(na.dense, (int) (length + delta), (int) length,
1287 NOT_FOUND);
1288 }
1289 na.length = length + delta;
1290 return result;
1291 }
1292
1293 if (delta > 0) {
1294 for (long last = length - 1; last >= end; last--) {
1295 Object temp = getRawElem(thisObj, last);
1296 setRawElem(cx, thisObj, last + delta, temp);
1297 }
1298 } else if (delta < 0) {
1299 for (long last = end; last < length; last++) {
1300 Object temp = getRawElem(thisObj, last);
1301 setRawElem(cx, thisObj, last + delta, temp);
1302 }
1303 for (long k = length + delta; k < length; ++k) {
1304 deleteElem(thisObj, k);
1305 }
1306 }
1307
1308 /* Copy from argv into the hole to complete the splice. */
1309 int argoffset = args.length - argc;
1310 for (int i = 0; i < argc; i++) {
1311 setElem(cx, thisObj, begin + i, args[i + argoffset]);
1312 }
1313
1314 /* Update length in case we deleted elements from the end. */
1315 setLengthProperty(cx, thisObj, length + delta);
1316 return result;
1317 }
1318
1319 /*
1320 * See Ecma 262v3 15.4.4.4
1321 */
1322 private static Scriptable js_concat(Context cx, Scriptable scope,
1323 Scriptable thisObj, Object[] args)
1324 {
1325 // create an empty Array to return.
1326 scope = getTopLevelScope(scope);
1327 Scriptable result = cx.newArray(scope, 0);
1328 if (thisObj instanceof NativeArray && result instanceof NativeArray) {
1329 NativeArray denseThis = (NativeArray) thisObj;
1330 NativeArray denseResult = (NativeArray) result;
1331 if (denseThis.denseOnly && denseResult.denseOnly) {
1332 // First calculate length of resulting array
1333 boolean canUseDense = true;
1334 int length = (int) denseThis.length;
1335 for (int i = 0; i < args.length && canUseDense; i++) {
1336 if (args[i] instanceof NativeArray) {
1337 // only try to use dense approach for Array-like
1338 // objects that are actually NativeArrays
1339 final NativeArray arg = (NativeArray) args[i];
1340 canUseDense = arg.denseOnly;
1341 length += arg.length;
1342 } else {
1343 length++;
1344 }
1345 }
1346 if (canUseDense && denseResult.ensureCapacity(length)) {
1347 System.arraycopy(denseThis.dense, 0, denseResult.dense,
1348 0, (int) denseThis.length);
1349 int cursor = (int) denseThis.length;
1350 for (int i = 0; i < args.length && canUseDense; i++) {
1351 if (args[i] instanceof NativeArray) {
1352 NativeArray arg = (NativeArray) args[i];
1353 System.arraycopy(arg.dense, 0,
1354 denseResult.dense, cursor,
1355 (int)arg.length);
1356 cursor += (int)arg.length;
1357 } else {
1358 denseResult.dense[cursor++] = args[i];
1359 }
1360 }
1361 denseResult.length = length;
1362 return result;
1363 }
1364 }
1365 }
1366
1367 long length;
1368 long slot = 0;
1369
1370 /* Put the target in the result array; only add it as an array
1371 * if it looks like one.
1372 */
1373 if (js_isArray(thisObj)) {
1374 length = getLengthProperty(cx, thisObj);
1375
1376 // Copy from the target object into the result
1377 for (slot = 0; slot < length; slot++) {
1378 Object temp = getRawElem(thisObj, slot);
1379 if (temp != NOT_FOUND) {
1380 defineElem(cx, result, slot, temp);
1381 }
1382 }
1383 } else {
1384 defineElem(cx, result, slot++, thisObj);
1385 }
1386
1387 /* Copy from the arguments into the result. If any argument
1388 * has a numeric length property, treat it as an array and add
1389 * elements separately; otherwise, just copy the argument.
1390 */
1391 for (int i = 0; i < args.length; i++) {
1392 if (js_isArray(args[i])) {
1393 // js_isArray => instanceof Scriptable
1394 Scriptable arg = (Scriptable)args[i];
1395 length = getLengthProperty(cx, arg);
1396 for (long j = 0; j < length; j++, slot++) {
1397 Object temp = getRawElem(arg, j);
1398 if (temp != NOT_FOUND) {
1399 defineElem(cx, result, slot, temp);
1400 }
1401 }
1402 } else {
1403 defineElem(cx, result, slot++, args[i]);
1404 }
1405 }
1406 setLengthProperty(cx, result, slot);
1407 return result;
1408 }
1409
1410 private Scriptable js_slice(Context cx, Scriptable thisObj,
1411 Object[] args)
1412 {
1413 Scriptable scope = getTopLevelScope(this);
1414 Scriptable result = cx.newArray(scope, 0);
1415 long length = getLengthProperty(cx, thisObj);
1416
1417 long begin, end;
1418 if (args.length == 0) {
1419 begin = 0;
1420 end = length;
1421 } else {
1422 begin = toSliceIndex(ScriptRuntime.toInteger(args[0]), length);
1423 if (args.length == 1 || args[1] == Undefined.instance) {
1424 end = length;
1425 } else {
1426 end = toSliceIndex(ScriptRuntime.toInteger(args[1]), length);
1427 }
1428 }
1429
1430 for (long slot = begin; slot < end; slot++) {
1431 Object temp = getRawElem(thisObj, slot);
1432 if (temp != NOT_FOUND) {
1433 defineElem(cx, result, slot - begin, temp);
1434 }
1435 }
1436 setLengthProperty(cx, result, Math.max(0, end - begin));
1437
1438 return result;
1439 }
1440
1441 private static long toSliceIndex(double value, long length) {
1442 long result;
1443 if (value < 0.0) {
1444 if (value + length < 0.0) {
1445 result = 0;
1446 } else {
1447 result = (long)(value + length);
1448 }
1449 } else if (value > length) {
1450 result = length;
1451 } else {
1452 result = (long)value;
1453 }
1454 return result;
1455 }
1456
1457 private static Object js_indexOf(Context cx, Scriptable thisObj,
1458 Object[] args)
1459 {
1460 Object compareTo = args.length > 0 ? args[0] : Undefined.instance;
1461 long length = getLengthProperty(cx, thisObj);
1462 /*
1463 * From http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Array:indexOf
1464 * The index at which to begin the search. Defaults to 0, i.e. the
1465 * whole array will be searched. If the index is greater than or
1466 * equal to the length of the array, -1 is returned, i.e. the array
1467 * will not be searched. If negative, it is taken as the offset from
1468 * the end of the array. Note that even when the index is negative,
1469 * the array is still searched from front to back. If the calculated
1470 * index is less than 0, the whole array will be searched.
1471 */
1472 long start;
1473 if (args.length < 2) {
1474 // default
1475 start = 0;
1476 } else {
1477 start = (long)ScriptRuntime.toInteger(args[1]);
1478 if (start < 0) {
1479 start += length;
1480 if (start < 0)
1481 start = 0;
1482 }
1483 if (start > length - 1) return NEGATIVE_ONE;
1484 }
1485 if (thisObj instanceof NativeArray) {
1486 NativeArray na = (NativeArray) thisObj;
1487 if (na.denseOnly) {
1488 Scriptable proto = na.getPrototype();
1489 for (int i=(int)start; i < length; i++) {
1490 Object val = na.dense[i];
1491 if (val == NOT_FOUND && proto != null) {
1492 val = ScriptableObject.getProperty(proto, i);
1493 }
1494 if (val != NOT_FOUND &&
1495 ScriptRuntime.shallowEq(val, compareTo))
1496 {
1497 return Long.valueOf(i);
1498 }
1499 }
1500 return NEGATIVE_ONE;
1501 }
1502 }
1503 for (long i=start; i < length; i++) {
1504 Object val = getRawElem(thisObj, i);
1505 if (val != NOT_FOUND && ScriptRuntime.shallowEq(val, compareTo)) {
1506 return Long.valueOf(i);
1507 }
1508 }
1509 return NEGATIVE_ONE;
1510 }
1511
1512 private static Object js_lastIndexOf(Context cx, Scriptable thisObj,
1513 Object[] args)
1514 {
1515 Object compareTo = args.length > 0 ? args[0] : Undefined.instance;
1516 long length = getLengthProperty(cx, thisObj);
1517 /*
1518 * From http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Array:lastIndexOf
1519 * The index at which to start searching backwards. Defaults to the
1520 * array's length, i.e. the whole array will be searched. If the
1521 * index is greater than or equal to the length of the array, the
1522 * whole array will be searched. If negative, it is taken as the
1523 * offset from the end of the array. Note that even when the index
1524 * is negative, the array is still searched from back to front. If
1525 * the calculated index is less than 0, -1 is returned, i.e. the
1526 * array will not be searched.
1527 */
1528 long start;
1529 if (args.length < 2) {
1530 // default
1531 start = length-1;
1532 } else {
1533 start = (long)ScriptRuntime.toInteger(args[1]);
1534 if (start >= length)
1535 start = length-1;
1536 else if (start < 0)
1537 start += length;
1538 if (start < 0) return NEGATIVE_ONE;
1539 }
1540 if (thisObj instanceof NativeArray) {
1541 NativeArray na = (NativeArray) thisObj;
1542 if (na.denseOnly) {
1543 Scriptable proto = na.getPrototype();
1544 for (int i=(int)start; i >= 0; i--) {
1545 Object val = na.dense[i];
1546 if (val == NOT_FOUND && proto != null) {
1547 val = ScriptableObject.getProperty(proto, i);
1548 }
1549 if (val != NOT_FOUND &&
1550 ScriptRuntime.shallowEq(val, compareTo))
1551 {
1552 return Long.valueOf(i);
1553 }
1554 }
1555 return NEGATIVE_ONE;
1556 }
1557 }
1558 for (long i=start; i >= 0; i--) {
1559 Object val = getRawElem(thisObj, i);
1560 if (val != NOT_FOUND && ScriptRuntime.shallowEq(val, compareTo)) {
1561 return Long.valueOf(i);
1562 }
1563 }
1564 return NEGATIVE_ONE;
1565 }
1566
1567 /**
1568 * Implements the methods "every", "filter", "forEach", "map", and "some".
1569 */
1570 private static Object iterativeMethod(Context cx, IdFunctionObject idFunctionObject, Scriptable scope,
1571 Scriptable thisObj, Object[] args)
1572 {
1573 int id = idFunctionObject.methodId();
1574
1575 if (Id_find == id || Id_findIndex == id) thisObj = requireObjectCoercible(cx, thisObj, idFunctionObject);
1576
1577 long length = getLengthProperty(cx, thisObj);
1578 Object callbackArg = args.length > 0 ? args[0] : Undefined.instance;
1579 if (callbackArg == null || !(callbackArg instanceof Function)) {
1580 throw ScriptRuntime.notFunctionError(callbackArg);
1581 }
1582 if (cx.getLanguageVersion() >= Context.VERSION_ES6 && (callbackArg instanceof NativeRegExp)) {
1583 // Previously, it was allowed to pass RegExp instance as a callback (it implements Function)
1584 // But according to ES2015 21.2.6 Properties of RegExp Instances:
1585 // > RegExp instances are ordinary objects that inherit properties from the RegExp prototype object.
1586 // > RegExp instances have internal slots [[RegExpMatcher]], [[OriginalSource]], and [[OriginalFlags]].
1587 // so, no [[Call]] for RegExp-s
1588 throw ScriptRuntime.notFunctionError(callbackArg);
1589 }
1590
1591 Function f = (Function) callbackArg;
1592 Scriptable parent = ScriptableObject.getTopLevelScope(f);
1593 Scriptable thisArg;
1594 if (args.length < 2 || args[1] == null || args[1] == Undefined.instance) {
1595 thisArg = parent;
1596 } else {
1597 thisArg = ScriptRuntime.toObject(cx, scope, args[1]);
1598 }
1599
1600 Scriptable array = null;
1601 if (id == Id_filter || id == Id_map) {
1602 int resultLength = id == Id_map ? (int) length : 0;
1603 array = cx.newArray(scope, resultLength);
1604 }
1605 long j=0;
1606 for (long i=0; i < length; i++) {
1607 Object[] innerArgs = new Object[3];
1608 Object elem = getRawElem(thisObj, i);
1609 if (elem == Scriptable.NOT_FOUND) {
1610 if (id == Id_find || id == Id_findIndex) {
1611 elem = Undefined.instance;
1612 } else {
1613 continue;
1614 }
1615 }
1616 innerArgs[0] = elem;
1617 innerArgs[1] = Long.valueOf(i);
1618 innerArgs[2] = thisObj;
1619 Object result = f.call(cx, parent, thisArg, innerArgs);
1620 switch (id) {
1621 case Id_every:
1622 if (!ScriptRuntime.toBoolean(result))
1623 return Boolean.FALSE;
1624 break;
1625 case Id_filter:
1626 if (ScriptRuntime.toBoolean(result))
1627 defineElem(cx, array, j++, innerArgs[0]);
1628 break;
1629 case Id_forEach:
1630 break;
1631 case Id_map:
1632 defineElem(cx, array, i, result);
1633 break;
1634 case Id_some:
1635 if (ScriptRuntime.toBoolean(result))
1636 return Boolean.TRUE;
1637 break;
1638 case Id_find:
1639 if (ScriptRuntime.toBoolean(result))
1640 return elem;
1641 break;
1642 case Id_findIndex:
1643 if (ScriptRuntime.toBoolean(result))
1644 return ScriptRuntime.wrapNumber(i);
1645 break;
1646 }
1647 }
1648 switch (id) {
1649 case Id_every:
1650 return Boolean.TRUE;
1651 case Id_filter:
1652 case Id_map:
1653 return array;
1654 case Id_some:
1655 return Boolean.FALSE;
1656 case Id_findIndex:
1657 return ScriptRuntime.wrapNumber(-1);
1658 case Id_forEach:
1659 default:
1660 return Undefined.instance;
1661 }
1662 }
1663
1664 /**
1665 * Implements the methods "reduce" and "reduceRight".
1666 */
1667 private static Object reduceMethod(Context cx, int id, Scriptable scope,
1668 Scriptable thisObj, Object[] args)
1669 {
1670 long length = getLengthProperty(cx, thisObj);
1671 Object callbackArg = args.length > 0 ? args[0] : Undefined.instance;
1672 if (callbackArg == null || !(callbackArg instanceof Function)) {
1673 throw ScriptRuntime.notFunctionError(callbackArg);
1674 }
1675 Function f = (Function) callbackArg;
1676 Scriptable parent = ScriptableObject.getTopLevelScope(f);
1677 // hack to serve both reduce and reduceRight with the same loop
1678 boolean movingLeft = id == Id_reduce;
1679 Object value = args.length > 1 ? args[1] : Scriptable.NOT_FOUND;
1680 for (long i = 0; i < length; i++) {
1681 long index = movingLeft ? i : (length - 1 - i);
1682 Object elem = getRawElem(thisObj, index);
1683 if (elem == Scriptable.NOT_FOUND) {
1684 continue;
1685 }
1686 if (value == Scriptable.NOT_FOUND) {
1687 // no initial value passed, use first element found as inital value
1688 value = elem;
1689 } else {
1690 Object[] innerArgs = { value, elem, index, thisObj };
1691 value = f.call(cx, parent, parent, innerArgs);
1692 }
1693 }
1694 if (value == Scriptable.NOT_FOUND) {
1695 // reproduce spidermonkey error message
1696 throw ScriptRuntime.typeError0("msg.empty.array.reduce");
1697 }
1698 return value;
1699 }
1700
1701 private static boolean js_isArray(Object o) {
1702 if (!(o instanceof Scriptable)) {
1703 return false;
1704 }
1705 return "Array".equals(((Scriptable)o).getClassName());
1706 }
1707
1708 // methods to implement java.util.List
1709
1710 public boolean contains(Object o) {
1711 return indexOf(o) > -1;
1712 }
1713
1714 public Object[] toArray() {
1715 return toArray(ScriptRuntime.emptyArgs);
1716 }
1717
1718 public Object[] toArray(Object[] a) {
1719 long longLen = length;
1720 if (longLen > Integer.MAX_VALUE) {
1721 throw new IllegalStateException();
1722 }
1723 int len = (int) longLen;
1724 Object[] array = a.length >= len ?
1725 a : (Object[]) java.lang.reflect.Array
1726 .newInstance(a.getClass().getComponentType(), len);
1727 for (int i = 0; i < len; i++) {
1728 array[i] = get(i);
1729 }
1730 return array;
1731 }
1732
1733 public boolean containsAll(Collection c) {
1734 for (Object aC : c)
1735 if (!contains(aC))
1736 return false;
1737 return true;
1738 }
1739
1740 @Override
1741 public int size() {
1742 long longLen = length;
1743 if (longLen > Integer.MAX_VALUE) {
1744 throw new IllegalStateException();
1745 }
1746 return (int) longLen;
1747 }
1748
1749 @Override
1750 public boolean isEmpty() {
1751 return length == 0;
1752 }
1753
1754 public Object get(long index) {
1755 if (index < 0 || index >= length) {
1756 throw new IndexOutOfBoundsException();
1757 }
1758 Object value = getRawElem(this, index);
1759 if (value == Scriptable.NOT_FOUND || value == Undefined.instance) {
1760 return null;
1761 } else if (value instanceof Wrapper) {
1762 return ((Wrapper) value).unwrap();
1763 } else {
1764 return value;
1765 }
1766 }
1767
1768 public Object get(int index) {
1769 return get((long) index);
1770 }
1771
1772 public int indexOf(Object o) {
1773 long longLen = length;
1774 if (longLen > Integer.MAX_VALUE) {
1775 throw new IllegalStateException();
1776 }
1777 int len = (int) longLen;
1778 if (o == null) {
1779 for (int i = 0; i < len; i++) {
1780 if (get(i) == null) {
1781 return i;
1782 }
1783 }
1784 } else {
1785 for (int i = 0; i < len; i++) {
1786 if (o.equals(get(i))) {
1787 return i;
1788 }
1789 }
1790 }
1791 return -1;
1792 }
1793
1794 public int lastIndexOf(Object o) {
1795 long longLen = length;
1796 if (longLen > Integer.MAX_VALUE) {
1797 throw new IllegalStateException();
1798 }
1799 int len = (int) longLen;
1800 if (o == null) {
1801 for (int i = len - 1; i >= 0; i--) {
1802 if (get(i) == null) {
1803 return i;
1804 }
1805 }
1806 } else {
1807 for (int i = len - 1; i >= 0; i--) {
1808 if (o.equals(get(i))) {
1809 return i;
1810 }
1811 }
1812 }
1813 return -1;
1814 }
1815
1816 public Iterator iterator() {
1817 return listIterator(0);
1818 }
1819
1820 public ListIterator listIterator() {
1821 return listIterator(0);
1822 }
1823
1824 public ListIterator listIterator(final int start) {
1825 long longLen = length;
1826 if (longLen > Integer.MAX_VALUE) {
1827 throw new IllegalStateException();
1828 }
1829 final int len = (int) longLen;
1830
1831 if (start < 0 || start > len) {
1832 throw new IndexOutOfBoundsException("Index: " + start);
1833 }
1834
1835 return new ListIterator() {
1836
1837 int cursor = start;
1838
1839 public boolean hasNext() {
1840 return cursor < len;
1841 }
1842
1843 public Object next() {
1844 if (cursor == len) {
1845 throw new NoSuchElementException();
1846 }
1847 return get(cursor++);
1848 }
1849
1850 public boolean hasPrevious() {
1851 return cursor > 0;
1852 }
1853
1854 public Object previous() {
1855 if (cursor == 0) {
1856 throw new NoSuchElementException();
1857 }
1858 return get(--cursor);
1859 }
1860
1861 public int nextIndex() {
1862 return cursor;
1863 }
1864
1865 public int previousIndex() {
1866 return cursor - 1;
1867 }
1868
1869 public void remove() {
1870 throw new UnsupportedOperationException();
1871 }
1872
1873 public void add(Object o) {
1874 throw new UnsupportedOperationException();
1875 }
1876
1877 public void set(Object o) {
1878 throw new UnsupportedOperationException();
1879 }
1880 };
1881 }
1882
1883 public boolean add(Object o) {
1884 throw new UnsupportedOperationException();
1885 }
1886
1887 public boolean remove(Object o) {
1888 throw new UnsupportedOperationException();
1889 }
1890
1891 public boolean addAll(Collection c) {
1892 throw new UnsupportedOperationException();
1893 }
1894
1895 public boolean removeAll(Collection c) {
1896 throw new UnsupportedOperationException();
1897 }
1898
1899 public boolean retainAll(Collection c) {
1900 throw new UnsupportedOperationException();
1901 }
1902
1903 public void clear() {
1904 throw new UnsupportedOperationException();
1905 }
1906
1907 public void add(int index, Object element) {
1908 throw new UnsupportedOperationException();
1909 }
1910
1911 public boolean addAll(int index, Collection c) {
1912 throw new UnsupportedOperationException();
1913 }
1914
1915 public Object set(int index, Object element) {
1916 throw new UnsupportedOperationException();
1917 }
1918
1919 public Object remove(int index) {
1920 throw new UnsupportedOperationException();
1921 }
1922
1923 public List subList(int fromIndex, int toIndex) {
1924 throw new UnsupportedOperationException();
1925 }
1926
1927 @Override
1928 protected int findPrototypeId(Symbol k)
1929 {
1930 if (SymbolKey.ITERATOR.equals(k)) {
1931 return SymbolId_iterator;
1932 }
1933 return 0;
1934 }
1935
1936 // Comparators for the js_sort method. Putting them here lets us unit-test them better.
1937
1938 private static final Comparator<Object> STRING_COMPARATOR = new StringLikeComparator();
1939 private static final Comparator<Object> DEFAULT_COMPARATOR = new ElementComparator();
1940
1941 public static final class StringLikeComparator
1942 implements Comparator<Object> {
1943
1944 public int compare(final Object x, final Object y) {
1945 final String a = ScriptRuntime.toString(x);
1946 final String b = ScriptRuntime.toString(y);
1947 return a.compareTo(b);
1948 }
1949 }
1950
1951 public static final class ElementComparator
1952 implements Comparator<Object> {
1953
1954 private final Comparator<Object> child;
1955
1956 public ElementComparator() {
1957 child = STRING_COMPARATOR;
1958 }
1959
1960 public ElementComparator(Comparator<Object> c) {
1961 child = c;
1962 }
1963
1964 public int compare(final Object x, final Object y) {
1965 // Sort NOT_FOUND to very end, Undefined before that, exclusively, as per
1966 // ECMA 22.1.3.25.1.
1967 if (x == Undefined.instance) {
1968 if (y == Undefined.instance) {
1969 return 0;
1970 }
1971 if (y == NOT_FOUND) {
1972 return -1;
1973 }
1974 return 1;
1975 } else if (x == NOT_FOUND) {
1976 return y == NOT_FOUND ? 0 : 1;
1977 }
1978
1979 if (y == NOT_FOUND) {
1980 return -1;
1981 }
1982 if (y == Undefined.instance) {
1983 return -1;
1984 }
1985
1986 return child.compare(x, y);
1987 }
1988 }
1989
1990 // #string_id_map#
1991
1992 @Override
1993 protected int findPrototypeId(String s)
1994 {
1995 int id;
1996 // #generated# Last update: 2016-03-04 20:46:26 GMT
1997 L0: { id = 0; String X = null; int c;
1998 L: switch (s.length()) {
1999 case 3: c=s.charAt(0);
2000 if (c=='m') { if (s.charAt(2)=='p' && s.charAt(1)=='a') {id=Id_map; break L0;} }
2001 else if (c=='p') { if (s.charAt(2)=='p' && s.charAt(1)=='o') {id=Id_pop; break L0;} }
2002 break L;
2003 case 4: switch (s.charAt(2)) {
2004 case 'i': X="join";id=Id_join; break L;
2005 case 'm': X="some";id=Id_some; break L;
2006 case 'n': X="find";id=Id_find; break L;
2007 case 'r': X="sort";id=Id_sort; break L;
2008 case 's': X="push";id=Id_push; break L;
2009 } break L;
2010 case 5: c=s.charAt(1);
2011 if (c=='h') { X="shift";id=Id_shift; }
2012 else if (c=='l') { X="slice";id=Id_slice; }
2013 else if (c=='v') { X="every";id=Id_every; }
2014 break L;
2015 case 6: switch (s.charAt(0)) {
2016 case 'c': X="concat";id=Id_concat; break L;
2017 case 'f': X="filter";id=Id_filter; break L;
2018 case 'r': X="reduce";id=Id_reduce; break L;
2019 case 's': X="splice";id=Id_splice; break L;
2020 } break L;
2021 case 7: switch (s.charAt(0)) {
2022 case 'f': X="forEach";id=Id_forEach; break L;
2023 case 'i': X="indexOf";id=Id_indexOf; break L;
2024 case 'r': X="reverse";id=Id_reverse; break L;
2025 case 'u': X="unshift";id=Id_unshift; break L;
2026 } break L;
2027 case 8: c=s.charAt(3);
2028 if (c=='o') { X="toSource";id=Id_toSource; }
2029 else if (c=='t') { X="toString";id=Id_toString; }
2030 break L;
2031 case 9: X="findIndex";id=Id_findIndex; break L;
2032 case 11: c=s.charAt(0);
2033 if (c=='c') { X="constructor";id=Id_constructor; }
2034 else if (c=='l') { X="lastIndexOf";id=Id_lastIndexOf; }
2035 else if (c=='r') { X="reduceRight";id=Id_reduceRight; }
2036 break L;
2037 case 14: X="toLocaleString";id=Id_toLocaleString; break L;
2038 }
2039 if (X!=null && X!=s && !X.equals(s)) id = 0;
2040 break L0;
2041 }
2042 // #/generated#
2043 return id;
2044 }
2045
2046 private static final int
2047 Id_constructor = 1,
2048 Id_toString = 2,
2049 Id_toLocaleString = 3,
2050 Id_toSource = 4,
2051 Id_join = 5,
2052 Id_reverse = 6,
2053 Id_sort = 7,
2054 Id_push = 8,
2055 Id_pop = 9,
2056 Id_shift = 10,
2057 Id_unshift = 11,
2058 Id_splice = 12,
2059 Id_concat = 13,
2060 Id_slice = 14,
2061 Id_indexOf = 15,
2062 Id_lastIndexOf = 16,
2063 Id_every = 17,
2064 Id_filter = 18,
2065 Id_forEach = 19,
2066 Id_map = 20,
2067 Id_some = 21,
2068 Id_find = 22,
2069 Id_findIndex = 23,
2070 Id_reduce = 24,
2071 Id_reduceRight = 25,
2072 SymbolId_iterator = 26,
2073
2074 MAX_PROTOTYPE_ID = SymbolId_iterator;
2075
2076 // #/string_id_map#
2077
2078 private static final int
2079 ConstructorId_join = -Id_join,
2080 ConstructorId_reverse = -Id_reverse,
2081 ConstructorId_sort = -Id_sort,
2082 ConstructorId_push = -Id_push,
2083 ConstructorId_pop = -Id_pop,
2084 ConstructorId_shift = -Id_shift,
2085 ConstructorId_unshift = -Id_unshift,
2086 ConstructorId_splice = -Id_splice,
2087 ConstructorId_concat = -Id_concat,
2088 ConstructorId_slice = -Id_slice,
2089 ConstructorId_indexOf = -Id_indexOf,
2090 ConstructorId_lastIndexOf = -Id_lastIndexOf,
2091 ConstructorId_every = -Id_every,
2092 ConstructorId_filter = -Id_filter,
2093 ConstructorId_forEach = -Id_forEach,
2094 ConstructorId_map = -Id_map,
2095 ConstructorId_some = -Id_some,
2096 ConstructorId_find = -Id_find,
2097 ConstructorId_findIndex = -Id_findIndex,
2098 ConstructorId_reduce = -Id_reduce,
2099 ConstructorId_reduceRight = -Id_reduceRight,
2100 ConstructorId_isArray = -26;
2101
2102 /**
2103 * Internal representation of the JavaScript array's length property.
2104 */
2105 private long length;
2106
2107 /**
2108 * Attributes of the array's length property
2109 */
2110 private int lengthAttr = DONTENUM | PERMANENT;
2111
2112 /**
2113 * Fast storage for dense arrays. Sparse arrays will use the superclass's
2114 * hashtable storage scheme.
2115 */
2116 private Object[] dense;
2117
2118 /**
2119 * True if all numeric properties are stored in <code>dense</code>.
2120 */
2121 private boolean denseOnly;
2122
2123 /**
2124 * The maximum size of <code>dense</code> that will be allocated initially.
2125 */
2126 private static int maximumInitialCapacity = 10000;
2127
2128 /**
2129 * The default capacity for <code>dense</code>.
2130 */
2131 private static final int DEFAULT_INITIAL_CAPACITY = 10;
2132
2133 /**
2134 * The factor to grow <code>dense</code> by.
2135 */
2136 private static final double GROW_FACTOR = 1.5;
2137 private static final int MAX_PRE_GROW_SIZE = (int)(Integer.MAX_VALUE / GROW_FACTOR);
2138 }