forked from mozilla/rhino
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathNativeArray.java
More file actions
2517 lines (2223 loc) · 91.3 KB
/
NativeArray.java
File metadata and controls
2517 lines (2223 loc) · 91.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.javascript;
import static org.mozilla.javascript.ArrayLikeAbstractOperations.getRawElem;
import static org.mozilla.javascript.ClassDescriptor.Builder.alias;
import static org.mozilla.javascript.ClassDescriptor.Destination.CTOR;
import static org.mozilla.javascript.ClassDescriptor.Destination.PROTO;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.ConcurrentModificationException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import org.mozilla.javascript.ArrayLikeAbstractOperations.IterativeOperation;
import org.mozilla.javascript.ArrayLikeAbstractOperations.ReduceOperation;
import org.mozilla.javascript.ClassDescriptor.BuiltInJSCodeExec;
import org.mozilla.javascript.xml.XMLObject;
/**
* This class implements the Array native object.
*
* @author Norris Boyd
* @author Mike McCabe
*/
public class NativeArray extends ScriptableObject implements List {
private static final long serialVersionUID = 7331366857676127338L;
/*
* Optimization possibilities and open issues:
* - Long vs. double schizophrenia. I suspect it might be better
* to use double throughout.
*
* - Functions that need a new Array call "new Array" in the
* current scope rather than using a hardwired constructor;
* "Array" could be redefined. It turns out that js calls the
* equivalent of "new Array" in the current scope, except that it
* always gets at least an object back, even when Array == null.
*/
static final long MAX_ARRAY_INDEX = 0xfffffffel;
private static final Object ARRAY_TAG = "Array";
private static final String CLASS_NAME = "Array";
private static final Long NEGATIVE_ONE = Long.valueOf(-1);
private static final String[] UNSCOPABLES = {
"at",
"copyWithin",
"entries",
"fill",
"find",
"findIndex",
"findLast",
"findLastIndex",
"flat",
"flatMap",
"includes",
"keys",
"toReversed",
"toSorted",
"toSpliced",
"values"
};
private static final ClassDescriptor DESCRIPTOR;
static {
DESCRIPTOR =
new ClassDescriptor.Builder(
CLASS_NAME,
1,
NativeArray::jsConstructor,
NativeArray::jsConstructor)
.withMethod(CTOR, "of", 0, NativeArray::js_of)
.withMethod(CTOR, "from", 1, NativeArray::js_from)
.withMethod(CTOR, "isArray", 1, NativeArray::js_isArrayMethod)
// The following need to appear on the constructor for
// historical reasons even though they should not be there
// according to the spec.
/* Special to HtmlUnit's Rhino fork.
.withMethod(CTOR, "join", 1, forCtor(NativeArray::js_join))
.withMethod(CTOR, "reverse", 0, forCtor(NativeArray::js_reverse))
.withMethod(CTOR, "sort", 1, forCtor(NativeArray::js_sort))
.withMethod(CTOR, "push", 1, forCtor(NativeArray::js_push))
.withMethod(CTOR, "pop", 0, forCtor(NativeArray::js_pop))
.withMethod(CTOR, "shift", 0, forCtor(NativeArray::js_shift))
.withMethod(CTOR, "unshift", 1, forCtor(NativeArray::js_unshift))
.withMethod(CTOR, "splice", 2, forCtor(NativeArray::js_splice))
.withMethod(CTOR, "concat", 1, forCtor(NativeArray::js_concat))
.withMethod(CTOR, "slice", 2, forCtor(NativeArray::js_slice))
.withMethod(CTOR, "indexOf", 1, forCtor(NativeArray::js_indexOf))
.withMethod(CTOR, "lastIndexOf", 1, forCtor(NativeArray::js_lastIndexOf))
.withMethod(CTOR, "every", 1, forCtor(NativeArray::js_every))
.withMethod(CTOR, "filter", 1, forCtor(NativeArray::js_filter))
.withMethod(CTOR, "forEach", 1, forCtor(NativeArray::js_forEach))
.withMethod(CTOR, "map", 1, forCtor(NativeArray::js_map))
.withMethod(CTOR, "some", 1, forCtor(NativeArray::js_some))
.withMethod(CTOR, "find", 1, forCtor(NativeArray::js_find))
.withMethod(CTOR, "findIndex", 1, forCtor(NativeArray::js_findIndex))
.withMethod(CTOR, "findLast", 1, forCtor(NativeArray::js_findLast))
.withMethod(
CTOR, "findLastIndex", 1, forCtor(NativeArray::js_findLastIndex))
.withMethod(CTOR, "reduce", 1, forCtor(NativeArray::js_reduce))
.withMethod(CTOR, "reduceRight", 1, forCtor(NativeArray::js_reduceRight))
*/
// The following are all on the prototype in accordance with the spec.
.withMethod(PROTO, "toString", 0, NativeArray::js_toString)
.withMethod(PROTO, "toLocaleString", 0, NativeArray::js_toLocaleString)
.withMethod(PROTO, "toSource", 0, NativeArray::js_toSource)
.withMethod(PROTO, "join", 1, NativeArray::js_join)
.withMethod(PROTO, "reverse", 0, NativeArray::js_reverse)
.withMethod(PROTO, "sort", 1, NativeArray::js_sort)
.withMethod(PROTO, "push", 1, NativeArray::js_push)
.withMethod(PROTO, "pop", 0, NativeArray::js_pop)
.withMethod(PROTO, "shift", 0, NativeArray::js_shift)
.withMethod(PROTO, "unshift", 1, NativeArray::js_unshift)
.withMethod(PROTO, "splice", 2, NativeArray::js_splice)
.withMethod(PROTO, "concat", 1, NativeArray::js_concat)
.withMethod(PROTO, "slice", 2, NativeArray::js_slice)
.withMethod(PROTO, "indexOf", 1, NativeArray::js_indexOf)
.withMethod(PROTO, "lastIndexOf", 1, NativeArray::js_lastIndexOf)
.withMethod(PROTO, "includes", 1, NativeArray::js_includes)
.withMethod(PROTO, "fill", 1, NativeArray::js_fill)
.withMethod(PROTO, "copyWithin", 2, NativeArray::js_copyWithin)
.withMethod(PROTO, "at", 1, NativeArray::js_at)
.withMethod(PROTO, "flat", 0, NativeArray::js_flat)
.withMethod(PROTO, "flatMap", 1, NativeArray::js_flatMap)
.withMethod(PROTO, "every", 1, NativeArray::js_every)
.withMethod(PROTO, "filter", 1, NativeArray::js_filter)
.withMethod(PROTO, "forEach", 1, NativeArray::js_forEach)
.withMethod(PROTO, "map", 1, NativeArray::js_map)
.withMethod(PROTO, "some", 1, NativeArray::js_some)
.withMethod(PROTO, "find", 1, NativeArray::js_find)
.withMethod(PROTO, "findIndex", 1, NativeArray::js_findIndex)
.withMethod(PROTO, "findLast", 1, NativeArray::js_findLast)
.withMethod(PROTO, "findLastIndex", 1, NativeArray::js_findLastIndex)
.withMethod(PROTO, "reduce", 1, NativeArray::js_reduce)
.withMethod(PROTO, "reduceRight", 1, NativeArray::js_reduceRight)
.withMethod(PROTO, "keys", 0, NativeArray::js_keys)
.withMethod(PROTO, "entries", 0, NativeArray::js_entries)
.withMethod(PROTO, "values", 0, NativeArray::js_values)
.withMethod(PROTO, "toReversed", 0, NativeArray::js_toReversed)
.withMethod(PROTO, "toSorted", 1, NativeArray::js_toSorted)
.withMethod(PROTO, "toSpliced", 2, NativeArray::js_toSpliced)
.withMethod(PROTO, "with", 2, NativeArray::js_with)
.withProp(PROTO, SymbolKey.ITERATOR, alias("values", DONTENUM))
.withProp(CTOR, SymbolKey.SPECIES, ScriptRuntimeES6::symbolSpecies)
.withProp(PROTO, SymbolKey.UNSCOPABLES, NativeArray::makeUnscopables)
.build();
}
private static BuiltInJSCodeExec<JSFunction> forCtor(BuiltInJSCodeExec<JSFunction> code) {
return (cx, f, nt, s, thisObj, args) -> {
var realThis = ScriptRuntime.toObject(cx, f.getDeclarationScope(), args[0]);
var realArgs = Arrays.copyOfRange(args, 1, args.length);
return code.execute(cx, f, nt, s, realThis, realArgs);
};
}
static void init(Context cx, Scriptable scope, boolean sealed) {
DESCRIPTOR.buildConstructor(cx, scope, new NativeArray(0), sealed);
}
static int getMaximumInitialCapacity() {
return maximumInitialCapacity;
}
static void setMaximumInitialCapacity(int maximumInitialCapacity) {
NativeArray.maximumInitialCapacity = maximumInitialCapacity;
}
public NativeArray(long lengthArg) {
denseOnly = lengthArg <= maximumInitialCapacity;
if (denseOnly) {
int intLength = (int) lengthArg;
if (intLength < DEFAULT_INITIAL_CAPACITY) intLength = DEFAULT_INITIAL_CAPACITY;
dense = new Object[intLength];
Arrays.fill(dense, Scriptable.NOT_FOUND);
}
length = lengthArg;
createLengthProp();
}
public NativeArray(Object[] array) {
denseOnly = true;
dense = array;
length = array.length;
createLengthProp();
}
@Override
public String getClassName() {
return "Array";
}
@Override
public void setPrototype(Scriptable p) {
super.setPrototype(p);
if (!(p instanceof NativeArray)) {
setDenseOnly(false);
}
}
private static DescriptorInfo makeUnscopables(
Context cx, Scriptable scope, ScriptableObject obj) {
NativeObject res;
res = (NativeObject) cx.newObject(scope);
var desc = ScriptableObject.buildDataDescriptor(true, EMPTY);
for (var k : UNSCOPABLES) {
res.defineOwnProperty(cx, k, desc);
}
res.setPrototype(null); // unscopables don't have any prototype
return new DescriptorInfo(res, DONTENUM | READONLY, true);
}
@Override
public Object get(int index, Scriptable start) {
var slot = denseOnly ? null : getMap().query(null, index);
if (!denseOnly && slot != null && slot.isSetterSlot()) return slot.getValue(start);
if (dense != null && 0 <= index && index < dense.length) return dense[index];
return slot == null ? NOT_FOUND : slot.getValue(start);
}
@Override
public boolean has(int index, Scriptable start) {
var slot = denseOnly ? null : getMap().query(null, index);
if (slot != null) {
return true;
}
if (dense != null && 0 <= index && index < dense.length) return dense[index] != NOT_FOUND;
return false;
}
private static long toArrayIndex(Object id) {
if (id instanceof String) {
return toArrayIndex((String) id);
} else if (id instanceof Number) {
return toArrayIndex(((Number) id).doubleValue());
}
return -1;
}
// if id is an array index (ECMA 15.4.0), return the number,
// otherwise return -1L
private static long toArrayIndex(String id) {
long index = toArrayIndex(ScriptRuntime.toNumber(id));
// Assume that ScriptRuntime.toString(index) is the same
// as java.lang.Long.toString(index) for long
if (Long.toString(index).equals(id)) {
return index;
}
return -1;
}
private static long toArrayIndex(double d) {
if (!Double.isNaN(d)) {
long index = ScriptRuntime.toUint32(d);
if (index == d && index != 4294967295L) {
return index;
}
}
return -1;
}
private static int toDenseIndex(Object id) {
long index = toArrayIndex(id);
return 0 <= index && index < Integer.MAX_VALUE ? (int) index : -1;
}
@Override
public void put(String id, Scriptable start, Object value) {
super.put(id, start, value);
if (start == this) {
// If the object is sealed, super will throw exception
long index = toArrayIndex(id);
if (index >= length) {
length = index + 1;
modCount++;
denseOnly = false;
}
}
}
private boolean ensureCapacity(int capacity) {
if (capacity > dense.length) {
if (capacity > MAX_PRE_GROW_SIZE) {
denseOnly = false;
return false;
}
capacity = Math.max(capacity, (int) (dense.length * GROW_FACTOR));
Object[] newDense = new Object[capacity];
System.arraycopy(dense, 0, newDense, 0, dense.length);
Arrays.fill(newDense, dense.length, newDense.length, Scriptable.NOT_FOUND);
dense = newDense;
}
return true;
}
@Override
public void put(int index, Scriptable start, Object value) {
var slot = denseOnly ? null : getMap().query(null, index);
if (start == this
&& !isSealed()
&& dense != null
&& 0 <= index
&& (denseOnly || (slot == null || !slot.isSetterSlot()))) {
if (!isExtensible() && this.length <= index) {
return;
} else if (index < dense.length) {
dense[index] = value;
if (this.length <= index) {
this.length = (long) index + 1;
this.modCount++;
}
return;
} else if (denseOnly
&& index < dense.length * GROW_FACTOR
&& ensureCapacity(index + 1)) {
dense[index] = value;
this.length = (long) index + 1;
this.modCount++;
return;
} else {
denseOnly = false;
}
}
super.put(index, start, value);
if (start == this && (lengthAttr & READONLY) == 0) {
// only set the array length if given an array index (ECMA 15.4.0)
if (this.length <= index) {
// avoid overflowing index!
this.length = (long) index + 1;
this.modCount++;
}
}
}
@Override
public void delete(int index) {
var slot = denseOnly ? null : getMap().query(null, index);
if (dense != null
&& 0 <= index
&& index < dense.length
&& !isSealed()
&& (denseOnly || (slot == null || !slot.isSetterSlot()))) {
dense[index] = NOT_FOUND;
} else {
super.delete(index);
}
}
public void deleteInternal(CompoundOperationMap<Scriptable> compoundOp, String id) {
compoundOp.compute(this, id, 0, ScriptableObject::checkSlotRemoval);
}
public void deleteInternal(CompoundOperationMap<Scriptable> compoundOp, int index) {
var slot = denseOnly ? null : compoundOp.query(null, index);
if (dense != null
&& 0 <= index
&& index < dense.length
&& !isSealed()
&& (denseOnly || (slot == null || !slot.isSetterSlot()))) {
dense[index] = NOT_FOUND;
} else {
compoundOp.compute(this, null, index, ScriptableObject::checkSlotRemoval);
}
}
@Override
public Object[] getIds(
CompoundOperationMap<Scriptable> map, boolean nonEnumerable, boolean getSymbols) {
Object[] superIds = super.getIds(map, nonEnumerable, getSymbols);
if (dense == null) {
return superIds;
}
int N = dense.length;
long currentLength = length;
if (N > currentLength) {
N = (int) currentLength;
}
if (N == 0) {
return superIds;
}
int superLength = superIds.length;
Object[] ids = new Object[N + superLength];
int presentCount = 0;
for (int i = 0; i != N; ++i) {
// Replace existing elements by their indexes
if (dense[i] != NOT_FOUND) {
ids[presentCount] = Integer.valueOf(i);
++presentCount;
}
}
if (presentCount != N) {
// dense contains deleted elems, need to shrink the result
Object[] tmp = new Object[presentCount + superLength];
System.arraycopy(ids, 0, tmp, 0, presentCount);
ids = tmp;
}
System.arraycopy(superIds, 0, ids, presentCount, superLength);
return ids;
}
public List<Integer> getIndexIds() {
Object[] ids = getIds();
List<Integer> indices = new ArrayList<>(ids.length);
for (Object id : ids) {
int int32Id = ScriptRuntime.toInt32(id);
if (int32Id >= 0
&& ScriptRuntime.toString(int32Id).equals(ScriptRuntime.toString(id))) {
indices.add(Integer.valueOf(int32Id));
}
}
return indices;
}
private DescriptorInfo defaultIndexPropertyDescriptor(Object value) {
return new DescriptorInfo(true, true, true, NOT_FOUND, NOT_FOUND, value);
}
@Override
public int getAttributes(int index) {
if (dense != null && index >= 0 && index < dense.length && dense[index] != NOT_FOUND) {
return EMPTY;
}
return super.getAttributes(index);
}
@Override
protected DescriptorInfo getOwnPropertyDescriptor(Context cx, Object id) {
if (dense != null) {
int index = toDenseIndex(id);
if (0 <= index && index < dense.length && dense[index] != NOT_FOUND) {
Object value = dense[index];
return defaultIndexPropertyDescriptor(value);
}
}
return super.getOwnPropertyDescriptor(cx, id);
}
@Override
protected boolean defineOwnProperty(
Context cx, Object id, DescriptorInfo desc, boolean checkValid) {
long index = toArrayIndex(id);
if (index >= length) {
length = index + 1;
modCount++;
}
if (index != -1 && dense != null) {
Object[] values = dense;
dense = null;
denseOnly = false;
for (int i = 0; i < values.length; i++) {
if (values[i] != NOT_FOUND) {
if (!isExtensible()) {
// Force creating a slot, before calling .put(...) on the next line, which
// would otherwise fail on a array on which preventExtensions() has been
// called
setAttributes(i, 0);
}
put(i, this, values[i]);
}
}
}
super.defineOwnProperty(cx, id, desc, checkValid);
if ("length".equals(id)) {
lengthAttr =
getAttributes("length"); // Update cached attributes value for length property
}
return true;
}
/** See ECMA 15.4.1,2 */
static Scriptable jsConstructor(
Context cx, JSFunction f, Object nt, Scriptable s, Object thisObj, Object[] args) {
NativeArray res;
if (args.length == 0) {
res = new NativeArray(0);
} else {
Object arg0 = args[0];
if (args.length > 1 || !(arg0 instanceof Number)) {
res = new NativeArray(args);
} else {
long len = ScriptRuntime.toUint32(arg0);
if (len != ((Number) arg0).doubleValue()) {
String msg = ScriptRuntime.getMessageById("msg.arraylength.bad");
throw ScriptRuntime.rangeError(msg);
}
res = new NativeArray(len);
}
}
ScriptRuntime.setBuiltinProtoAndParent(res, f, nt, s, TopLevel.Builtins.Array);
return res;
}
private void createLengthProp() {
ScriptableObject.defineBuiltInProperty(
this,
"length",
DONTENUM | PERMANENT,
NativeArray::lengthGetter,
NativeArray::lengthSetter,
NativeArray::lengthAttrSetter,
NativeArray::arraySetLength);
}
private static Object lengthGetter(NativeArray array, Scriptable start) {
return ScriptRuntime.wrapNumber((double) array.length);
}
private static boolean lengthSetter(
NativeArray builtIn,
Object value,
Scriptable owner,
Scriptable start,
boolean isThrow) {
double d = ScriptRuntime.toNumber(value);
try (var map = builtIn.startCompoundOp(true)) {
builtIn.setLength(map, d);
}
return true;
}
private static void lengthAttrSetter(NativeArray builtIn, int attrs) {
builtIn.lengthAttr = attrs;
}
private static Slot<Scriptable> lengthDescSetValue(
ScriptableObject owner,
DescriptorInfo info,
Object key,
Slot<Scriptable> existing,
CompoundOperationMap<Scriptable> map,
Slot<Scriptable> slot) {
((NativeArray) owner).setLength(map, (Double) info.value);
return slot;
}
protected static boolean arraySetLength(
NativeArray builtIn,
BuiltInSlot<NativeArray> current,
Object id,
DescriptorInfo info,
boolean checkValid,
Object key,
int index) {
PropDescValueSetter descSetter = NativeArray::lengthDescSetValue;
// 10.2.4.2 Step 1.
Object value = info.value;
if (value == NOT_FOUND) {
try (var map = builtIn.startCompoundOp(true)) {
return ScriptableObject.defineOrdinaryProperty(
(o, i, k, e, m, s) -> s, builtIn, map, id, info, checkValid, key, index);
}
}
// 10.2.4.2 Steps 2 - 6
long newLength = checkLength(value);
info.value = (double) newLength;
Object writable = info.writable;
// 10.2.4.2 9 is true by definition
try (var map = builtIn.startCompoundOp(true)) {
// 10.2.4.2 10-11
if (newLength >= builtIn.length) {
return ScriptableObject.defineOrdinaryProperty(
descSetter, builtIn, map, id, info, checkValid, key, index);
}
boolean currentWritable = ((current.getAttributes() & READONLY) == 0);
if (!currentWritable) {
throw ScriptRuntime.typeErrorById("msg.change.value.with.writable.false", id);
}
boolean newWritable = true;
if (writable != NOT_FOUND) {
newWritable = isTrue(writable);
info.writable = true;
}
// The standard set path that will be done by this call will
// clear any elements as required.
if (ScriptableObject.defineOrdinaryProperty(
descSetter, builtIn, map, id, info, checkValid, key, index)) {
var currentAttrs = current.getAttributes();
var newAttrs = newWritable ? (currentAttrs & ~READONLY) : (currentAttrs | READONLY);
current.setAttributes(newAttrs);
return true;
}
}
return false;
}
private static Scriptable callConstructorOrCreateArray(
Context cx, JSFunction f, Scriptable s, Object arg, long length, boolean lengthAlways) {
Scriptable result = null;
if (arg instanceof Constructable) {
try {
final Object[] args =
(lengthAlways || (length > 0))
? new Object[] {Long.valueOf(length)}
: ScriptRuntime.emptyArgs;
result = ((Constructable) arg).construct(cx, s, args);
} catch (EcmaError ee) {
if (!"TypeError".equals(ee.getName())) {
throw ee;
}
// If we get here then it is likely that the function we called is not really
// a constructor. Unfortunately there's no better way to tell in Rhino right now.
}
}
if (result == null) {
// "length" below is really a hint so don't worry if it's really large
result = cx.newArray(s, (length > Integer.MAX_VALUE) ? 0 : (int) length);
}
return result;
}
private static Object js_from(
Context cx, JSFunction f, Object nt, Scriptable s, Object thisObj, Object[] args) {
final Scriptable items =
ScriptRuntime.toObject(s, (args.length >= 1) ? args[0] : Undefined.instance);
Object mapArg = (args.length >= 2) ? args[1] : Undefined.instance;
Scriptable thisArg = null;
final boolean mapping = !Undefined.isUndefined(mapArg);
Function mapFn = null;
if (mapping) {
if (!(mapArg instanceof Function)) {
throw ScriptRuntime.typeErrorById("msg.map.function.not");
}
mapFn = (Function) mapArg;
Object callThisArg = args.length >= 3 ? args[2] : Undefined.SCRIPTABLE_UNDEFINED;
thisArg = ScriptRuntime.getThisForScope(mapFn.getDeclarationScope(), callThisArg);
}
Object iteratorProp = ScriptableObject.getProperty(items, SymbolKey.ITERATOR);
if ((iteratorProp != Scriptable.NOT_FOUND) && !Undefined.isUndefined(iteratorProp)) {
final Object iterator = ScriptRuntime.callIterator(items, cx, s);
if (!Undefined.isUndefined(iterator)) {
final Scriptable result = callConstructorOrCreateArray(cx, f, s, thisObj, 0, false);
long k = 0;
try (IteratorLikeIterable it = new IteratorLikeIterable(cx, s, iterator)) {
for (Object temp : it) {
if (mapping) {
temp = mapFn.call(cx, s, thisArg, new Object[] {temp, Long.valueOf(k)});
}
ArrayLikeAbstractOperations.defineElem(cx, result, k, temp);
k++;
}
}
setLengthProperty(cx, result, k);
return result;
}
}
final long length = getLengthProperty(cx, items);
final Scriptable result = callConstructorOrCreateArray(cx, f, s, thisObj, length, true);
for (long k = 0; k < length; k++) {
Object temp = getElem(cx, items, k);
if (mapping) {
temp = mapFn.call(cx, s, thisArg, new Object[] {temp, Long.valueOf(k)});
}
ArrayLikeAbstractOperations.defineElem(cx, result, k, temp);
}
setLengthProperty(cx, result, length);
return result;
}
private static Object js_of(
Context cx, JSFunction f, Object nt, Scriptable s, Object thisObj, Object[] args) {
final Scriptable result =
callConstructorOrCreateArray(cx, f, s, thisObj, args.length, true);
if (cx.getLanguageVersion() >= Context.VERSION_ES6 && result instanceof ScriptableObject) {
var desc = ScriptableObject.buildDataDescriptor(null, EMPTY);
for (int i = 0; i < args.length; i++) {
desc.value = args[i];
((ScriptableObject) result).defineOwnProperty(cx, i, desc);
}
} else {
for (int i = 0; i < args.length; i++) {
ArrayLikeAbstractOperations.defineElem(cx, result, i, args[i]);
}
}
setLengthProperty(cx, result, args.length);
return result;
}
public long getLength() {
return length;
}
/**
* @deprecated Use {@link #getLength()} instead.
*/
@Deprecated
public long jsGet_length() {
return getLength();
}
/**
* Change the value of the internal flag that determines whether all storage is handed by a
* dense backing array rather than an associative store.
*
* @param denseOnly new value for denseOnly flag
* @throws IllegalArgumentException if an attempt is made to enable denseOnly after it was
* disabled; NativeArray code is not written to handle switching back to a dense
* representation
*/
void setDenseOnly(boolean denseOnly) {
if (denseOnly && !this.denseOnly) throw new IllegalArgumentException();
this.denseOnly = denseOnly;
}
boolean getDenseOnly() {
return denseOnly;
}
private boolean setLength(CompoundOperationMap<Scriptable> compoundOp, double d) {
/* XXX do we satisfy this?
* 15.4.5.1 [[Put]](P, V):
* 1. Call the [[CanPut]] method of A with name P.
* 2. If Result(1) is false, return.
* ?
*/
long longVal = ScriptRuntime.toUint32(d);
if ((lengthAttr & READONLY) != 0) {
return false;
}
if (longVal != d) {
String msg = ScriptRuntime.getMessageById("msg.arraylength.bad");
throw ScriptRuntime.rangeError(msg);
}
if (denseOnly) {
if (longVal < length) {
// downcast okay because denseOnly
Arrays.fill(dense, (int) longVal, dense.length, NOT_FOUND);
length = longVal;
modCount++;
return true;
} else if (longVal < MAX_PRE_GROW_SIZE
&& longVal < (length * GROW_FACTOR)
&& ensureCapacity((int) longVal)) {
length = longVal;
modCount++;
return true;
} else {
denseOnly = false;
}
}
if (longVal < length) {
// remove all properties between longVal and length
if (length - longVal > 0x1000) {
// assume that the representation is sparse
Object[] e = getIds(compoundOp, false, false); // will only find in object itself
for (Object id : e) {
if (id instanceof String) {
// > MAXINT will appear as string
String strId = (String) id;
long index = toArrayIndex(strId);
if (index >= longVal) deleteInternal(compoundOp, strId);
} else {
int index = ((Integer) id).intValue();
if (index >= longVal) deleteInternal(compoundOp, index);
}
}
} else {
// assume a dense representation
for (long i = longVal; i < length; i++) {
deleteElem(compoundOp, this, i);
}
}
}
length = longVal;
modCount++;
return true;
}
private static long checkLength(Object val) {
double d = ScriptRuntime.toNumber(val);
long longVal = ScriptRuntime.toUint32(val);
if (longVal != d) {
String msg = ScriptRuntime.getMessageById("msg.arraylength.bad");
throw ScriptRuntime.rangeError(msg);
}
return longVal;
}
/* Support for generic Array-ish objects. Most of the Array
* functions try to be generic; anything that has a length
* property is assumed to be an array.
* getLengthProperty returns 0 if obj does not have the length property
* or its value is not convertible to a number.
*/
public static long getLengthProperty(Context cx, Scriptable obj) {
// These will give numeric lengths within Uint32 range.
if (obj instanceof NativeString) {
return ((NativeString) obj).getLength();
}
if (obj instanceof NativeArray) {
return ((NativeArray) obj).getLength();
}
if (obj instanceof XMLObject) {
Callable lengthFunc = (Callable) obj.get("length", obj);
return ((Number) lengthFunc.call(cx, obj, obj, ScriptRuntime.emptyArgs)).longValue();
}
Object len = ScriptableObject.getProperty(obj, "length");
if (len == Scriptable.NOT_FOUND) {
// toUint32(undefined) == 0
return 0;
}
double doubleLen = ScriptRuntime.toNumber(len);
// ToLength
if (doubleLen > NativeNumber.MAX_SAFE_INTEGER) {
return (long) NativeNumber.MAX_SAFE_INTEGER;
}
if (doubleLen < 0) {
return 0;
}
return (long) doubleLen;
}
private static Object setLengthProperty(Context cx, Scriptable target, long length) {
Object len = ScriptRuntime.wrapNumber((double) length);
ScriptableObject.putProperty(target, "length", len);
return len;
}
/* Utility functions to encapsulate index > Integer.MAX_VALUE
* handling. Also avoids unnecessary object creation that would
* be necessary to use the general ScriptRuntime.get/setElem
* functions... though this is probably premature optimization.
*/
private static void deleteElem(Scriptable target, long index) {
int i = (int) index;
if (i == index) {
target.delete(i);
} else {
target.delete(Long.toString(index));
}
}
/* This version explicitly checks whether the target is sealed. The other implementation which does not take a compound op does not do so explicitly, but it does rely on the underlying `delete` implementation doing that check. */
private static void deleteElem(
CompoundOperationMap<Scriptable> compoundOp, NativeArray target, long index) {
int i = (int) index;
if (i == index) {
checkNotSealed(target, null, i);
target.deleteInternal(compoundOp, i);
} else {
var strIndex = Long.toString(index);
checkNotSealed(target, strIndex, 0);
compoundOp.compute(target, strIndex, 0, ScriptableObject::checkSlotRemoval);
}
}
static Object getElem(Context cx, Scriptable target, long index) {
Object elem = getRawElem(target, index);
return (elem != Scriptable.NOT_FOUND ? elem : Undefined.instance);
}
private static void defineElemOrThrow(Context cx, Scriptable target, long index, Object value) {
if (index > NativeNumber.MAX_SAFE_INTEGER) {
throw ScriptRuntime.typeErrorById("msg.arraylength.too.big", String.valueOf(index));
} else {
ArrayLikeAbstractOperations.defineElem(cx, target, index, value);
}
}
private static void setElem(Context cx, Scriptable target, long index, Object value) {
if (index > Integer.MAX_VALUE) {
String id = Long.toString(index);
ScriptableObject.putProperty(target, id, value);
} else {
ScriptableObject.putProperty(target, (int) index, value);
}
}
// Similar as setElem(), but triggers deleteElem() if value is NOT_FOUND
private static void setRawElem(Context cx, Scriptable target, long index, Object value) {
if (value == NOT_FOUND) {
deleteElem(target, index);
} else {
setElem(cx, target, index, value);
}
}
private static String js_toString(
Context cx, JSFunction f, Object nt, Scriptable s, Object thisObj, Object[] args) {
return toStringHelper(cx, f, nt, s, thisObj, false, false);
}
private static String js_toLocaleString(
Context cx, JSFunction f, Object nt, Scriptable s, Object thisObj, Object[] args) {
return toStringHelper(cx, f, nt, s, thisObj, false, true);
}
private static String js_toSource(
Context cx, JSFunction f, Object nt, Scriptable s, Object thisObj, Object[] args) {
return toStringHelper(cx, f, nt, s, thisObj, true, false);
}
private static String toStringHelper(
Context cx,
JSFunction f,
Object nt,
Scriptable s,
Object thisObj,
boolean toSource,
boolean toLocale) {
Scriptable o = ScriptRuntime.toObject(cx, f.getDeclarationScope(), thisObj);
/* It's probably redundant to handle long lengths in this
* function; StringBuilders are limited to 2^31 in java.
*/
long length = getLengthProperty(cx, o);
StringBuilder result = new StringBuilder(256);
// whether to return '4,unquoted,5' or '[4, "quoted", 5]'
String separator;
if (toSource) {
result.append('[');
separator = ", ";
} else {
separator = ",";
}
boolean haslast = false;
long i = 0;
boolean toplevel, iterating;
if (cx.iterating == null) {
toplevel = true;
iterating = false;
cx.iterating = new HashSet<Object>();
} else {
toplevel = false;
iterating = cx.iterating.contains(o);
}
// Make sure cx.iterating is set to null when done
// so we don't leak memory
try {
if (!iterating) {
// stop recursion
cx.iterating.add(o);
// make toSource print null and undefined values in recent versions
boolean skipUndefinedAndNull =
!toSource || cx.getLanguageVersion() < Context.VERSION_1_5;
for (i = 0; i < length; i++) {
if (i > 0) result.append(separator);
Object elem = getRawElem(o, i);
if (elem == NOT_FOUND
|| (skipUndefinedAndNull
&& (elem == null || elem == Undefined.instance))) {
haslast = false;
continue;
}
haslast = true;