-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathArrayPrototype.cpp
More file actions
2225 lines (1902 loc) · 97.5 KB
/
ArrayPrototype.cpp
File metadata and controls
2225 lines (1902 loc) · 97.5 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
/*
* Copyright (C) 1999-2000 Harri Porten (porten@kde.org)
* Copyright (C) 2003-2024 Apple Inc. All rights reserved.
* Copyright (C) 2003 Peter Kelly (pmk@post.com)
* Copyright (C) 2006 Alexey Proskuryakov (ap@nypop.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*
*/
#include "config.h"
#include "ArrayPrototype.h"
#include "ArrayConstructor.h"
#include "ArrayPrototypeInlines.h"
#include "BuiltinNames.h"
#include "CachedCallInlines.h"
#include "IntegrityInlines.h"
#include "InterpreterInlines.h"
#include "JSArrayInlines.h"
#include "JSArrayIterator.h"
#include "JSCBuiltins.h"
#include "JSCInlines.h"
#include "JSCellButterfly.h"
#include "JSStringJoiner.h"
#include "ObjectConstructor.h"
#include "ObjectPrototypeInlines.h"
#include "StableSort.h"
#include "StringRecursionChecker.h"
#include "VMEntryScopeInlines.h"
#include <algorithm>
#include <wtf/Assertions.h>
#include <wtf/StdMap.h>
WTF_ALLOW_UNSAFE_BUFFER_USAGE_BEGIN
namespace JSC {
static JSC_DECLARE_HOST_FUNCTION(arrayProtoFuncToLocaleString);
static JSC_DECLARE_HOST_FUNCTION(arrayProtoFuncJoin);
static JSC_DECLARE_HOST_FUNCTION(arrayProtoFuncKeys);
static JSC_DECLARE_HOST_FUNCTION(arrayProtoFuncEntries);
static JSC_DECLARE_HOST_FUNCTION(arrayProtoFuncPop);
static JSC_DECLARE_HOST_FUNCTION(arrayProtoFuncPush);
static JSC_DECLARE_HOST_FUNCTION(arrayProtoFuncReverse);
static JSC_DECLARE_HOST_FUNCTION(arrayProtoFuncShift);
static JSC_DECLARE_HOST_FUNCTION(arrayProtoFuncSlice);
static JSC_DECLARE_HOST_FUNCTION(arrayProtoFuncSort);
static JSC_DECLARE_HOST_FUNCTION(arrayProtoFuncSplice);
static JSC_DECLARE_HOST_FUNCTION(arrayProtoFuncUnShift);
static JSC_DECLARE_HOST_FUNCTION(arrayProtoFuncIndexOf);
static JSC_DECLARE_HOST_FUNCTION(arrayProtoFuncLastIndexOf);
static JSC_DECLARE_HOST_FUNCTION(arrayProtoFuncConcat);
static JSC_DECLARE_HOST_FUNCTION(arrayProtoFuncFill);
static JSC_DECLARE_HOST_FUNCTION(arrayProtoFuncToReversed);
static JSC_DECLARE_HOST_FUNCTION(arrayProtoFuncToSorted);
static JSC_DECLARE_HOST_FUNCTION(arrayProtoFuncWith);
static JSC_DECLARE_HOST_FUNCTION(arrayProtoFuncIncludes);
static JSC_DECLARE_HOST_FUNCTION(arrayProtoFuncCopyWithin);
static JSC_DECLARE_HOST_FUNCTION(arrayProtoFuncToSpliced);
static JSC_DECLARE_HOST_FUNCTION(arrayProtoFuncFlat);
// ------------------------------ ArrayPrototype ----------------------------
const ClassInfo ArrayPrototype::s_info = { "Array"_s, &JSArray::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(ArrayPrototype) };
ArrayPrototype* ArrayPrototype::create(VM& vm, JSGlobalObject* globalObject, Structure* structure)
{
ArrayPrototype* prototype = new (NotNull, allocateCell<ArrayPrototype>(vm)) ArrayPrototype(vm, structure);
prototype->finishCreation(vm, globalObject);
return prototype;
}
// ECMA 15.4.4
ArrayPrototype::ArrayPrototype(VM& vm, Structure* structure)
: JSArray(vm, structure, nullptr)
{
}
void ArrayPrototype::finishCreation(VM& vm, JSGlobalObject* globalObject)
{
Base::finishCreation(vm);
ASSERT(inherits(info()));
putDirectWithoutTransition(vm, vm.propertyNames->toString, globalObject->arrayProtoToStringFunction(), static_cast<unsigned>(PropertyAttribute::DontEnum));
putDirectWithoutTransition(vm, vm.propertyNames->builtinNames().valuesPublicName(), globalObject->arrayProtoValuesFunction(), static_cast<unsigned>(PropertyAttribute::DontEnum));
putDirectWithoutTransition(vm, vm.propertyNames->iteratorSymbol, globalObject->arrayProtoValuesFunction(), static_cast<unsigned>(PropertyAttribute::DontEnum));
JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->toLocaleString, arrayProtoFuncToLocaleString, static_cast<unsigned>(PropertyAttribute::DontEnum), 0, ImplementationVisibility::Public);
JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->builtinNames().concatPublicName(), arrayProtoFuncConcat, static_cast<unsigned>(PropertyAttribute::DontEnum), 1, ImplementationVisibility::Public);
JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->fill, arrayProtoFuncFill, static_cast<unsigned>(PropertyAttribute::DontEnum), 1, ImplementationVisibility::Public);
JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->join, arrayProtoFuncJoin, static_cast<unsigned>(PropertyAttribute::DontEnum), 1, ImplementationVisibility::Public);
JSC_NATIVE_INTRINSIC_FUNCTION_WITHOUT_TRANSITION("pop"_s, arrayProtoFuncPop, static_cast<unsigned>(PropertyAttribute::DontEnum), 0, ImplementationVisibility::Public, ArrayPopIntrinsic);
JSC_NATIVE_INTRINSIC_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->builtinNames().pushPublicName(), arrayProtoFuncPush, static_cast<unsigned>(PropertyAttribute::DontEnum), 1, ImplementationVisibility::Public, ArrayPushIntrinsic);
JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION("reverse"_s, arrayProtoFuncReverse, static_cast<unsigned>(PropertyAttribute::DontEnum), 0, ImplementationVisibility::Public);
JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->builtinNames().shiftPublicName(), arrayProtoFuncShift, static_cast<unsigned>(PropertyAttribute::DontEnum), 0, ImplementationVisibility::Public);
JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->builtinNames().shiftPrivateName(), arrayProtoFuncShift, PropertyAttribute::DontEnum | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly, 0, ImplementationVisibility::Public);
JSC_NATIVE_INTRINSIC_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->slice, arrayProtoFuncSlice, static_cast<unsigned>(PropertyAttribute::DontEnum), 2, ImplementationVisibility::Public, ArraySliceIntrinsic);
JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->sort, arrayProtoFuncSort, static_cast<unsigned>(PropertyAttribute::DontEnum), 1, ImplementationVisibility::Public);
JSC_NATIVE_INTRINSIC_FUNCTION_WITHOUT_TRANSITION("splice"_s, arrayProtoFuncSplice, static_cast<unsigned>(PropertyAttribute::DontEnum), 2, ImplementationVisibility::Public, ArraySpliceIntrinsic);
JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION("unshift"_s, arrayProtoFuncUnShift, static_cast<unsigned>(PropertyAttribute::DontEnum), 1, ImplementationVisibility::Public);
JSC_BUILTIN_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->builtinNames().everyPublicName(), arrayPrototypeEveryCodeGenerator, static_cast<unsigned>(PropertyAttribute::DontEnum));
JSC_BUILTIN_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->builtinNames().forEachPublicName(), arrayPrototypeForEachCodeGenerator, static_cast<unsigned>(PropertyAttribute::DontEnum));
JSC_BUILTIN_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->builtinNames().somePublicName(), arrayPrototypeSomeCodeGenerator, static_cast<unsigned>(PropertyAttribute::DontEnum));
JSC_NATIVE_INTRINSIC_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->builtinNames().indexOfPublicName(), arrayProtoFuncIndexOf, static_cast<unsigned>(PropertyAttribute::DontEnum), 1, ImplementationVisibility::Public, ArrayIndexOfIntrinsic);
JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION("lastIndexOf"_s, arrayProtoFuncLastIndexOf, static_cast<unsigned>(PropertyAttribute::DontEnum), 1, ImplementationVisibility::Public);
JSC_BUILTIN_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->builtinNames().filterPublicName(), arrayPrototypeFilterCodeGenerator, static_cast<unsigned>(PropertyAttribute::DontEnum));
JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->flat, arrayProtoFuncFlat, static_cast<unsigned>(PropertyAttribute::DontEnum), 0, ImplementationVisibility::Public);
JSC_BUILTIN_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->builtinNames().flatMapPublicName(), arrayPrototypeFlatMapCodeGenerator, static_cast<unsigned>(PropertyAttribute::DontEnum));
JSC_BUILTIN_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->builtinNames().reducePublicName(), arrayPrototypeReduceCodeGenerator, static_cast<unsigned>(PropertyAttribute::DontEnum));
JSC_BUILTIN_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->builtinNames().reduceRightPublicName(), arrayPrototypeReduceRightCodeGenerator, static_cast<unsigned>(PropertyAttribute::DontEnum));
JSC_BUILTIN_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->builtinNames().mapPublicName(), arrayPrototypeMapCodeGenerator, static_cast<unsigned>(PropertyAttribute::DontEnum));
JSC_NATIVE_INTRINSIC_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->builtinNames().keysPublicName(), arrayProtoFuncKeys, static_cast<unsigned>(PropertyAttribute::DontEnum), 0, ImplementationVisibility::Public, ArrayKeysIntrinsic);
JSC_NATIVE_INTRINSIC_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->builtinNames().entriesPublicName(), arrayProtoFuncEntries, static_cast<unsigned>(PropertyAttribute::DontEnum), 0, ImplementationVisibility::Public, ArrayEntriesIntrinsic);
JSC_BUILTIN_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->builtinNames().findPublicName(), arrayPrototypeFindCodeGenerator, static_cast<unsigned>(PropertyAttribute::DontEnum));
JSC_BUILTIN_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->builtinNames().findLastPublicName(), arrayPrototypeFindLastCodeGenerator, static_cast<unsigned>(PropertyAttribute::DontEnum));
JSC_BUILTIN_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->builtinNames().findIndexPublicName(), arrayPrototypeFindIndexCodeGenerator, static_cast<unsigned>(PropertyAttribute::DontEnum));
JSC_BUILTIN_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->builtinNames().findLastIndexPublicName(), arrayPrototypeFindLastIndexCodeGenerator, static_cast<unsigned>(PropertyAttribute::DontEnum));
JSC_NATIVE_INTRINSIC_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->includes, arrayProtoFuncIncludes, static_cast<unsigned>(PropertyAttribute::DontEnum), 1, ImplementationVisibility::Public, ArrayIncludesIntrinsic);
JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->copyWithin, arrayProtoFuncCopyWithin, static_cast<unsigned>(PropertyAttribute::DontEnum), 2, ImplementationVisibility::Public);
JSC_BUILTIN_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->builtinNames().atPublicName(), arrayPrototypeAtCodeGenerator, static_cast<unsigned>(PropertyAttribute::DontEnum));
JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->toReversed, arrayProtoFuncToReversed, static_cast<unsigned>(PropertyAttribute::DontEnum), 0, ImplementationVisibility::Public);
JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->toSorted, arrayProtoFuncToSorted, static_cast<unsigned>(PropertyAttribute::DontEnum), 1, ImplementationVisibility::Public);
JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->toSpliced, arrayProtoFuncToSpliced, static_cast<unsigned>(PropertyAttribute::DontEnum), 2, ImplementationVisibility::Public);
JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->with, arrayProtoFuncWith, static_cast<unsigned>(PropertyAttribute::DontEnum), 2, ImplementationVisibility::Public);
putDirectWithoutTransition(vm, vm.propertyNames->builtinNames().entriesPrivateName(), getDirect(vm, vm.propertyNames->builtinNames().entriesPublicName()), static_cast<unsigned>(PropertyAttribute::ReadOnly));
putDirectWithoutTransition(vm, vm.propertyNames->builtinNames().forEachPrivateName(), getDirect(vm, vm.propertyNames->builtinNames().forEachPublicName()), static_cast<unsigned>(PropertyAttribute::ReadOnly));
putDirectWithoutTransition(vm, vm.propertyNames->builtinNames().includesPrivateName(), getDirect(vm, vm.propertyNames->includes), static_cast<unsigned>(PropertyAttribute::ReadOnly));
putDirectWithoutTransition(vm, vm.propertyNames->builtinNames().indexOfPrivateName(), getDirect(vm, vm.propertyNames->builtinNames().indexOfPublicName()), static_cast<unsigned>(PropertyAttribute::ReadOnly));
putDirectWithoutTransition(vm, vm.propertyNames->builtinNames().keysPrivateName(), getDirect(vm, vm.propertyNames->builtinNames().keysPublicName()), static_cast<unsigned>(PropertyAttribute::ReadOnly));
putDirectWithoutTransition(vm, vm.propertyNames->builtinNames().mapPrivateName(), getDirect(vm, vm.propertyNames->builtinNames().mapPublicName()), static_cast<unsigned>(PropertyAttribute::ReadOnly));
putDirectWithoutTransition(vm, vm.propertyNames->builtinNames().popPrivateName(), getDirect(vm, vm.propertyNames->builtinNames().popPublicName()), static_cast<unsigned>(PropertyAttribute::ReadOnly));
putDirectWithoutTransition(vm, vm.propertyNames->builtinNames().valuesPrivateName(), globalObject->arrayProtoValuesFunction(), static_cast<unsigned>(PropertyAttribute::ReadOnly));
JSObject* unscopables = constructEmptyObject(vm, globalObject->nullPrototypeObjectStructure());
unscopables->convertToDictionary(vm);
const Identifier* const unscopableNames[] = {
&vm.propertyNames->builtinNames().atPublicName(),
&vm.propertyNames->copyWithin,
&vm.propertyNames->builtinNames().entriesPublicName(),
&vm.propertyNames->fill,
&vm.propertyNames->builtinNames().findPublicName(),
&vm.propertyNames->builtinNames().findIndexPublicName(),
&vm.propertyNames->builtinNames().findLastPublicName(),
&vm.propertyNames->builtinNames().findLastIndexPublicName(),
&vm.propertyNames->flat,
&vm.propertyNames->builtinNames().flatMapPublicName(),
&vm.propertyNames->includes,
&vm.propertyNames->builtinNames().keysPublicName(),
&vm.propertyNames->toReversed,
&vm.propertyNames->toSorted,
&vm.propertyNames->toSpliced,
&vm.propertyNames->builtinNames().valuesPublicName()
};
for (const auto* unscopableName : unscopableNames) {
if (unscopableName)
unscopables->putDirect(vm, *unscopableName, jsBoolean(true));
}
putDirectWithoutTransition(vm, vm.propertyNames->unscopablesSymbol, unscopables, PropertyAttribute::DontEnum | PropertyAttribute::ReadOnly);
}
// ------------------------------ Array Functions ----------------------------
enum class RelativeNegativeIndex : bool {
No,
Yes,
};
template <RelativeNegativeIndex relativeNegativeIndex>
static inline uint64_t argumentClampedIndexFromStartOrEnd(JSGlobalObject* globalObject, JSValue value, uint64_t length, uint64_t undefinedValue = 0)
{
if (value.isUndefined())
return undefinedValue;
if (value.isInt32()) [[likely]] {
int64_t indexInt64 = value.asInt32();
if (indexInt64 < 0) {
if constexpr (relativeNegativeIndex == RelativeNegativeIndex::Yes) {
indexInt64 += length;
return indexInt64 < 0 ? 0 : static_cast<uint64_t>(indexInt64);
} else
return 0;
}
uint64_t indexUInt64 = static_cast<uint64_t>(indexInt64);
return std::min(indexUInt64, length);
}
double indexDouble = value.toIntegerOrInfinity(globalObject);
if (indexDouble < 0) {
if constexpr (relativeNegativeIndex == RelativeNegativeIndex::Yes) {
indexDouble += length;
return indexDouble < 0 ? 0 : static_cast<uint64_t>(indexDouble);
} else
return 0;
}
return indexDouble > length ? length : static_cast<uint64_t>(indexDouble);
}
static inline int64_t argumentUnclampedIndexFromStartOrEnd(JSGlobalObject* globalObject, JSValue value, uint64_t length, uint64_t undefinedValue = 0)
{
if (value.isUndefined())
return undefinedValue;
if (value.isInt32()) [[likely]] {
int64_t indexInt64 = value.asInt32();
if (indexInt64 < 0)
indexInt64 += length;
return indexInt64;
}
double indexDouble = value.toIntegerOrInfinity(globalObject);
if (indexDouble < 0)
indexDouble += length;
if (std::isinf(indexDouble)) [[unlikely]]
return std::signbit(indexDouble) ? std::numeric_limits<int64_t>::min() : std::numeric_limits<int64_t>::max();
return static_cast<int64_t>(indexDouble);
}
ALWAYS_INLINE JSString* fastArrayJoin(JSGlobalObject* globalObject, JSObject* thisObject, StringView separator, unsigned length)
{
bool sawHoles = false;
bool genericCase = false;
return fastArrayJoin(globalObject, thisObject, separator, length, sawHoles, genericCase);
}
inline bool canUseDefaultArrayJoinForToString(JSObject* thisObject)
{
JSGlobalObject* globalObject = thisObject->globalObject();
if (!globalObject->arrayJoinWatchpointSet().isStillValid())
return false;
Structure* structure = thisObject->structure();
// This is the fast case. Many arrays will be an original array.
// We are doing very simple check here. If we do more complicated checks like looking into getDirect "join" of thisObject,
// it would be possible that just looking into "join" function will show the same performance.
return globalObject->isOriginalArrayStructure(structure);
}
JSC_DEFINE_HOST_FUNCTION(arrayProtoFuncToString, (JSGlobalObject* globalObject, CallFrame* callFrame))
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSValue thisValue = callFrame->thisValue().toThis(globalObject, ECMAMode::strict());
// 1. Let array be the result of calling ToObject on the this value.
JSObject* thisObject = thisValue.toObject(globalObject);
RETURN_IF_EXCEPTION(scope, { });
Integrity::auditStructureID(thisObject->structureID());
if (!canUseDefaultArrayJoinForToString(thisObject)) [[unlikely]] {
// 2. Let func be the result of calling the [[Get]] internal method of array with argument "join".
JSValue function = thisObject->get(globalObject, vm.propertyNames->join);
RETURN_IF_EXCEPTION(scope, { });
// 3. If IsCallable(func) is false, then let func be the standard built-in method Object.prototype.toString (15.2.4.2).
auto callData = JSC::getCallDataInline(function);
if (callData.type == CallData::Type::None) [[unlikely]]
RELEASE_AND_RETURN(scope, JSValue::encode(objectPrototypeToString(globalObject, thisObject)));
// 4. Return the result of calling the [[Call]] internal method of func providing array as the this value and an empty arguments list.
if (!isJSArray(thisObject) || callData.type != CallData::Type::Native || callData.native.function != arrayProtoFuncJoin)
RELEASE_AND_RETURN(scope, JSValue::encode(call(globalObject, function, callData, thisObject, *vm.emptyList)));
}
ASSERT(isJSArray(thisValue));
RELEASE_AND_RETURN(scope, JSValue::encode(asArray(thisValue)->fastToString(globalObject)));
}
static JSString* toLocaleString(JSGlobalObject* globalObject, JSValue value, JSValue locales, JSValue options)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSValue toLocaleStringMethod = value.get(globalObject, vm.propertyNames->toLocaleString);
RETURN_IF_EXCEPTION(scope, { });
auto callData = JSC::getCallDataInline(toLocaleStringMethod);
if (callData.type == CallData::Type::None) {
throwTypeError(globalObject, scope, "toLocaleString is not callable"_s);
return { };
}
MarkedArgumentBuffer arguments;
arguments.append(locales);
arguments.append(options);
ASSERT(!arguments.hasOverflowed());
JSValue result = call(globalObject, toLocaleStringMethod, callData, value, arguments);
RETURN_IF_EXCEPTION(scope, { });
RELEASE_AND_RETURN(scope, result.toString(globalObject));
}
// https://tc39.es/ecma402/#sup-array.prototype.tolocalestring
JSC_DEFINE_HOST_FUNCTION(arrayProtoFuncToLocaleString, (JSGlobalObject* globalObject, CallFrame* callFrame))
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSValue thisValue = callFrame->thisValue().toThis(globalObject, ECMAMode::strict());
JSValue locales = callFrame->argument(0);
JSValue options = callFrame->argument(1);
// 1. Let array be ? ToObject(this value).
JSObject* thisObject = thisValue.toObject(globalObject);
RETURN_IF_EXCEPTION(scope, { });
StringRecursionChecker checker(globalObject, thisObject);
EXCEPTION_ASSERT(!scope.exception() || checker.earlyReturnValue());
if (JSValue earlyReturnValue = checker.earlyReturnValue())
return JSValue::encode(earlyReturnValue);
// 2. Let len be ? ToLength(? Get(array, "length")).
uint64_t length = toLength(globalObject, thisObject);
RETURN_IF_EXCEPTION(scope, { });
// 3. Let separator be the String value for the list-separator String appropriate for
// the host environment's current locale (this is derived in an implementation-defined way).
const Latin1Character comma = ',';
JSString* separator = jsSingleCharacterString(vm, comma);
// 4. Let R be the empty String.
if (!length)
return JSValue::encode(jsEmptyString(vm));
// 5. Let k be 0.
JSValue element0 = thisObject->getIndex(globalObject, 0);
RETURN_IF_EXCEPTION(scope, { });
// 6. Repeat, while k < len,
// 6.a. If k > 0, then
// 6.a.i. Set R to the string-concatenation of R and separator.
JSString* r = nullptr;
if (element0.isUndefinedOrNull())
r = jsEmptyString(vm);
else {
r = toLocaleString(globalObject, element0, locales, options);
RETURN_IF_EXCEPTION(scope, { });
}
// 8. Let k be 1.
// 9. Repeat, while k < len
// 9.e Increase k by 1..
for (uint64_t k = 1; k < length; ++k) {
// 6.b. Let nextElement be ? Get(array, ! ToString(k)).
JSValue element = thisObject->getIndex(globalObject, k);
RETURN_IF_EXCEPTION(scope, { });
// c. If nextElement is not undefined or null, then
JSString* next = nullptr;
if (element.isUndefinedOrNull())
next = jsEmptyString(vm);
else {
// i. Let S be ? ToString(? Invoke(nextElement, "toLocaleString", « locales, options »)).
// ii. Set R to the string-concatenation of R and S.
next = toLocaleString(globalObject, element, locales, options);
RETURN_IF_EXCEPTION(scope, { });
}
// d. Increase k by 1.
r = jsString(globalObject, r, separator, next);
RETURN_IF_EXCEPTION(scope, { });
}
// 7. Return R.
return JSValue::encode(r);
}
static JSValue slowJoin(JSGlobalObject* globalObject, JSObject* thisObject, JSString* separator, uint64_t length)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
// 5. If len is zero, return the empty String.
if (!length)
return jsEmptyString(vm);
// 6. Let element0 be Get(O, "0").
JSValue element0 = thisObject->getIndex(globalObject, 0);
RETURN_IF_EXCEPTION(scope, { });
// 7. If element0 is undefined or null, let R be the empty String; otherwise, let R be ? ToString(element0).
JSString* r = nullptr;
if (element0.isUndefinedOrNull())
r = jsEmptyString(vm);
else
r = element0.toString(globalObject);
RETURN_IF_EXCEPTION(scope, { });
// 8. Let k be 1.
// 9. Repeat, while k < len
// 9.e Increase k by 1..
for (uint64_t k = 1; k < length; ++k) {
// b. Let element be ? Get(O, ! ToString(k)).
JSValue element = thisObject->getIndex(globalObject, k);
RETURN_IF_EXCEPTION(scope, { });
// c. If element is undefined or null, let next be the empty String; otherwise, let next be ? ToString(element).
JSString* next = nullptr;
if (element.isUndefinedOrNull()) {
if (!separator->length())
continue;
next = jsEmptyString(vm);
} else
next = element.toString(globalObject);
RETURN_IF_EXCEPTION(scope, { });
// a. Let S be the String value produced by concatenating R and sep.
// d. Let R be a String value produced by concatenating S and next.
r = jsString(globalObject, r, separator, next);
RETURN_IF_EXCEPTION(scope, { });
}
// 10. Return R.
return r;
}
JSC_DEFINE_HOST_FUNCTION(arrayProtoFuncJoin, (JSGlobalObject* globalObject, CallFrame* callFrame))
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
// 1. Let O be ? ToObject(this value).
JSObject* thisObject = callFrame->thisValue().toThis(globalObject, ECMAMode::strict()).toObject(globalObject);
EXCEPTION_ASSERT(!!scope.exception() == !thisObject);
if (!thisObject) [[unlikely]]
return encodedJSValue();
StringRecursionChecker checker(globalObject, thisObject);
EXCEPTION_ASSERT(!scope.exception() || checker.earlyReturnValue());
if (JSValue earlyReturnValue = checker.earlyReturnValue())
return JSValue::encode(earlyReturnValue);
// 2. Let len be ? ToLength(? Get(O, "length")).
uint64_t length = toLength(globalObject, thisObject);
RETURN_IF_EXCEPTION(scope, encodedJSValue());
// 3. If separator is undefined, let separator be the single-element String ",".
JSValue separatorValue = callFrame->argument(0);
if (separatorValue.isUndefined()) {
const Latin1Character comma = ',';
if (length > std::numeric_limits<unsigned>::max() || !canUseFastArrayJoin(thisObject)) [[unlikely]] {
JSString* jsSeparator = jsSingleCharacterString(vm, comma);
RETURN_IF_EXCEPTION(scope, encodedJSValue());
RELEASE_AND_RETURN(scope, JSValue::encode(slowJoin(globalObject, thisObject, jsSeparator, length)));
}
unsigned unsignedLength = static_cast<unsigned>(length);
ASSERT(static_cast<double>(unsignedLength) == length);
RELEASE_AND_RETURN(scope, JSValue::encode(fastArrayJoin(globalObject, thisObject, span(comma), unsignedLength)));
}
// 4. Let sep be ? ToString(separator).
JSString* jsSeparator = separatorValue.toString(globalObject);
RETURN_IF_EXCEPTION(scope, encodedJSValue());
if (length > std::numeric_limits<unsigned>::max() || !canUseFastArrayJoin(thisObject)) [[unlikely]]
RELEASE_AND_RETURN(scope, JSValue::encode(slowJoin(globalObject, thisObject, jsSeparator, length)));
auto view = jsSeparator->view(globalObject);
RETURN_IF_EXCEPTION(scope, encodedJSValue());
RELEASE_AND_RETURN(scope, JSValue::encode(fastArrayJoin(globalObject, thisObject, view, length)));
}
inline EncodedJSValue createArrayIteratorObject(JSGlobalObject* globalObject, CallFrame* callFrame, IterationKind kind)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSObject* thisObject = callFrame->thisValue().toThis(globalObject, ECMAMode::strict()).toObject(globalObject);
EXCEPTION_ASSERT(!!scope.exception() == !thisObject);
UNUSED_PARAM(scope);
if (!thisObject) [[unlikely]]
return encodedJSValue();
return JSValue::encode(JSArrayIterator::create(vm, globalObject->arrayIteratorStructure(), thisObject, jsNumber(static_cast<unsigned>(kind))));
}
JSC_DEFINE_HOST_FUNCTION(arrayProtoFuncValues, (JSGlobalObject* globalObject, CallFrame* callFrame))
{
return createArrayIteratorObject(globalObject, callFrame, IterationKind::Values);
}
JSC_DEFINE_HOST_FUNCTION(arrayProtoFuncEntries, (JSGlobalObject* globalObject, CallFrame* callFrame))
{
return createArrayIteratorObject(globalObject, callFrame, IterationKind::Entries);
}
JSC_DEFINE_HOST_FUNCTION(arrayProtoFuncKeys, (JSGlobalObject* globalObject, CallFrame* callFrame))
{
return createArrayIteratorObject(globalObject, callFrame, IterationKind::Keys);
}
JSC_DEFINE_HOST_FUNCTION(arrayProtoFuncPop, (JSGlobalObject* globalObject, CallFrame* callFrame))
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSValue thisValue = callFrame->thisValue().toThis(globalObject, ECMAMode::strict());
if (isJSArray(thisValue)) [[likely]]
RELEASE_AND_RETURN(scope, JSValue::encode(asArray(thisValue)->pop(globalObject)));
JSObject* thisObj = thisValue.toObject(globalObject);
EXCEPTION_ASSERT(!!scope.exception() == !thisObj);
if (!thisObj) [[unlikely]]
return encodedJSValue();
uint64_t length = toLength(globalObject, thisObj);
RETURN_IF_EXCEPTION(scope, encodedJSValue());
if (length == 0) {
scope.release();
setLength(globalObject, vm, thisObj, length);
return JSValue::encode(jsUndefined());
}
static_assert(MAX_ARRAY_INDEX + 1 > MAX_ARRAY_INDEX);
uint64_t index = length - 1;
JSValue result = thisObj->get(globalObject, index);
RETURN_IF_EXCEPTION(scope, { });
bool success = thisObj->deleteProperty(globalObject, index);
RETURN_IF_EXCEPTION(scope, { });
if (!success) [[unlikely]] {
throwTypeError(globalObject, scope, UnableToDeletePropertyError);
return { };
}
scope.release();
setLength(globalObject, vm, thisObj, index);
return JSValue::encode(result);
}
JSC_DEFINE_HOST_FUNCTION(arrayProtoFuncPush, (JSGlobalObject* globalObject, CallFrame* callFrame))
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSValue thisValue = callFrame->thisValue().toThis(globalObject, ECMAMode::strict());
if (isJSArray(thisValue) && callFrame->argumentCount() == 1) [[likely]] {
JSArray* array = asArray(thisValue);
scope.release();
array->pushInline(globalObject, callFrame->uncheckedArgument(0));
return JSValue::encode(jsNumber(array->length()));
}
JSObject* thisObj = thisValue.toObject(globalObject);
EXCEPTION_ASSERT(!!scope.exception() == !thisObj);
if (!thisObj) [[unlikely]]
return encodedJSValue();
uint64_t length = toLength(globalObject, thisObj);
RETURN_IF_EXCEPTION(scope, encodedJSValue());
unsigned argCount = callFrame->argumentCount();
if (length + argCount > maxSafeIntegerAsUInt64()) [[unlikely]]
return throwVMTypeError(globalObject, scope, "push cannot produce an array of length larger than (2 ** 53) - 1"_s);
for (unsigned n = 0; n < argCount; n++) {
thisObj->putByIndexInline(globalObject, length + n, callFrame->uncheckedArgument(n), true);
RETURN_IF_EXCEPTION(scope, { });
}
uint64_t newLength = length + argCount;
scope.release();
setLength(globalObject, vm, thisObj, newLength);
return JSValue::encode(jsNumber(newLength));
}
JSC_DEFINE_HOST_FUNCTION(arrayProtoFuncReverse, (JSGlobalObject* globalObject, CallFrame* callFrame))
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSObject* thisObject = callFrame->thisValue().toThis(globalObject, ECMAMode::strict()).toObject(globalObject);
EXCEPTION_ASSERT(!!scope.exception() == !thisObject);
if (!thisObject) [[unlikely]]
return encodedJSValue();
uint64_t length = toLength(globalObject, thisObject);
RETURN_IF_EXCEPTION(scope, encodedJSValue());
thisObject->ensureWritable(vm);
switch (thisObject->indexingType()) {
case ALL_CONTIGUOUS_INDEXING_TYPES:
case ALL_INT32_INDEXING_TYPES: {
auto& butterfly = *thisObject->butterfly();
if (length > butterfly.publicLength())
break;
auto data = butterfly.contiguous().data();
if (containsHole(data, static_cast<uint32_t>(length)) && holesMustForwardToPrototype(thisObject))
break;
std::reverse(data, data + length);
if (!hasInt32(thisObject->indexingType()))
vm.writeBarrier(thisObject);
return JSValue::encode(thisObject);
}
case ALL_DOUBLE_INDEXING_TYPES: {
auto& butterfly = *thisObject->butterfly();
if (length > butterfly.publicLength())
break;
auto data = butterfly.contiguousDouble().data();
if (containsHole(data, static_cast<uint32_t>(length)) && holesMustForwardToPrototype(thisObject))
break;
std::reverse(data, data + length);
return JSValue::encode(thisObject);
}
case ALL_ARRAY_STORAGE_INDEXING_TYPES: {
auto& storage = *thisObject->butterfly()->arrayStorage();
if (length > storage.vectorLength())
break;
if (storage.hasHoles() && holesMustForwardToPrototype(thisObject))
break;
auto data = storage.vector().data();
std::reverse(data, data + length);
vm.writeBarrier(thisObject);
return JSValue::encode(thisObject);
}
}
uint64_t middle = length / 2;
for (uint64_t lower = 0; lower < middle; lower++) {
uint64_t upper = length - lower - 1;
bool lowerExists = thisObject->hasProperty(globalObject, lower);
RETURN_IF_EXCEPTION(scope, encodedJSValue());
JSValue lowerValue;
if (lowerExists) {
lowerValue = thisObject->get(globalObject, lower);
RETURN_IF_EXCEPTION(scope, encodedJSValue());
}
bool upperExists = thisObject->hasProperty(globalObject, upper);
RETURN_IF_EXCEPTION(scope, encodedJSValue());
JSValue upperValue;
if (upperExists) {
upperValue = thisObject->get(globalObject, upper);
RETURN_IF_EXCEPTION(scope, encodedJSValue());
}
if (!lowerExists && !upperExists) {
// Spec says to do nothing when neither lower nor upper exist.
continue;
}
if (upperExists) {
thisObject->putByIndexInline(globalObject, lower, upperValue, true);
RETURN_IF_EXCEPTION(scope, encodedJSValue());
} else {
bool success = thisObject->deleteProperty(globalObject, lower);
RETURN_IF_EXCEPTION(scope, encodedJSValue());
if (!success) [[unlikely]] {
throwTypeError(globalObject, scope, UnableToDeletePropertyError);
return encodedJSValue();
}
}
if (lowerExists) {
thisObject->putByIndexInline(globalObject, upper, lowerValue, true);
RETURN_IF_EXCEPTION(scope, encodedJSValue());
} else {
bool success = thisObject->deleteProperty(globalObject, upper);
RETURN_IF_EXCEPTION(scope, encodedJSValue());
if (!success) [[unlikely]] {
throwTypeError(globalObject, scope, UnableToDeletePropertyError);
return encodedJSValue();
}
}
}
return JSValue::encode(thisObject);
}
JSC_DEFINE_HOST_FUNCTION(arrayProtoFuncShift, (JSGlobalObject* globalObject, CallFrame* callFrame))
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSObject* thisObj = callFrame->thisValue().toThis(globalObject, ECMAMode::strict()).toObject(globalObject);
EXCEPTION_ASSERT(!!scope.exception() == !thisObj);
if (!thisObj) [[unlikely]]
return encodedJSValue();
uint64_t length = toLength(globalObject, thisObj);
RETURN_IF_EXCEPTION(scope, encodedJSValue());
if (length == 0) {
scope.release();
setLength(globalObject, vm, thisObj, length);
return JSValue::encode(jsUndefined());
}
JSValue result = thisObj->getIndex(globalObject, 0);
RETURN_IF_EXCEPTION(scope, encodedJSValue());
shift<JSArray::ShiftCountForShift>(globalObject, thisObj, 0, 1, 0, length);
RETURN_IF_EXCEPTION(scope, encodedJSValue());
scope.release();
setLength(globalObject, vm, thisObj, length - 1);
return JSValue::encode(result);
}
JSC_DEFINE_HOST_FUNCTION(arrayProtoFuncSlice, (JSGlobalObject* globalObject, CallFrame* callFrame))
{
// https://tc39.github.io/ecma262/#sec-array.prototype.slice
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSObject* thisObj = callFrame->thisValue().toThis(globalObject, ECMAMode::strict()).toObject(globalObject);
EXCEPTION_ASSERT(!!scope.exception() == !thisObj);
if (!thisObj) [[unlikely]]
return { };
uint64_t length = toLength(globalObject, thisObj);
RETURN_IF_EXCEPTION(scope, { });
uint64_t begin = argumentClampedIndexFromStartOrEnd<RelativeNegativeIndex::Yes>(globalObject, callFrame->argument(0), length);
RETURN_IF_EXCEPTION(scope, { });
uint64_t end = argumentClampedIndexFromStartOrEnd<RelativeNegativeIndex::Yes>(globalObject, callFrame->argument(1), length, length);
RETURN_IF_EXCEPTION(scope, { });
if (end < begin)
end = begin;
std::pair<SpeciesConstructResult, JSObject*> speciesResult = speciesConstructArray(globalObject, thisObj, end - begin);
// We can only get an exception if we call some user function.
EXCEPTION_ASSERT(!!scope.exception() == (speciesResult.first == SpeciesConstructResult::Exception));
if (speciesResult.first == SpeciesConstructResult::Exception) [[unlikely]]
return { };
if (speciesResult.first == SpeciesConstructResult::FastPath) [[likely]] {
JSArray* result = JSArray::fastSlice(globalObject, thisObj, begin, end - begin);
if (result) {
scope.assertNoExceptionExceptTermination();
return JSValue::encode(result);
}
RETURN_IF_EXCEPTION(scope, { });
}
JSObject* result;
if (speciesResult.first == SpeciesConstructResult::CreatedObject)
result = speciesResult.second;
else {
if (end - begin > std::numeric_limits<uint32_t>::max()) [[unlikely]] {
throwRangeError(globalObject, scope, LengthExceededTheMaximumArrayLengthError);
return encodedJSValue();
}
result = constructEmptyArray(globalObject, nullptr, static_cast<uint32_t>(end - begin));
RETURN_IF_EXCEPTION(scope, { });
}
// Document that we need to keep the source array alive until after anything
// that can GC (e.g. allocating the result array).
thisObj->use();
uint64_t n = 0;
for (uint64_t k = begin; k < end; k++, n++) {
JSValue v = getProperty(globalObject, thisObj, k);
RETURN_IF_EXCEPTION(scope, { });
if (v) {
result->putDirectIndex(globalObject, n, v, 0, PutDirectIndexShouldThrow);
RETURN_IF_EXCEPTION(scope, { });
}
}
scope.release();
setLength(globalObject, vm, result, n);
return JSValue::encode(result);
}
using SortJSValueVector = MarkedVector<JSValue, 64, RecordOverflow>;
using SortEntryVector = Vector<std::tuple<JSValue, String>>;
static ALWAYS_INLINE std::tuple<uint64_t, IndexingType, std::span<EncodedJSValue>> sortCompact(JSGlobalObject* globalObject, JSObject* thisObject, uint64_t length, SortJSValueVector& compactedRoot)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
uint64_t undefinedCount = 0;
if (isJSArray(thisObject) && !holesMustForwardToPrototype(thisObject)) [[likely]] {
IndexingType indexingType = thisObject->indexingType();
switch (indexingType) {
case ALL_INT32_INDEXING_TYPES: {
auto& butterfly = *thisObject->butterfly();
unsigned butterflyLength = butterfly.publicLength();
auto data = butterfly.contiguous().data();
unsigned count = 0;
compactedRoot.fill(vm, butterflyLength, [&](JSValue* buffer) {
for (unsigned i = 0; i < butterflyLength; ++i) {
if (JSValue value = data[i].get(); value) [[likely]]
buffer[count++] = value;
}
});
if (compactedRoot.hasOverflowed()) [[unlikely]] {
throwOutOfMemoryError(globalObject, scope);
return { };
}
return std::tuple { 0, ArrayWithInt32, std::span { compactedRoot.data(), count } };
}
case ALL_CONTIGUOUS_INDEXING_TYPES: {
auto& butterfly = *thisObject->butterfly();
unsigned butterflyLength = butterfly.publicLength();
auto data = butterfly.contiguous().data();
unsigned count = 0;
compactedRoot.fill(vm, butterflyLength, [&](JSValue* buffer) {
for (unsigned i = 0; i < butterflyLength; ++i) {
if (JSValue value = data[i].get(); value) [[likely]] {
if (!value.isUndefined()) [[likely]]
buffer[count++] = value;
else
++undefinedCount;
}
}
});
if (compactedRoot.hasOverflowed()) [[unlikely]] {
throwOutOfMemoryError(globalObject, scope);
return { };
}
return std::tuple { undefinedCount, ArrayWithContiguous, std::span { compactedRoot.data(), count } };
}
case ALL_DOUBLE_INDEXING_TYPES: {
auto& butterfly = *thisObject->butterfly();
unsigned butterflyLength = butterfly.publicLength();
auto data = butterfly.contiguousDouble().data();
unsigned count = 0;
compactedRoot.fill(vm, butterflyLength, [&](JSValue* buffer) {
for (unsigned i = 0; i < butterflyLength; ++i) {
double number = data[i];
if (!isHole(number)) [[likely]]
buffer[count++] = jsDoubleNumber(number);
}
});
if (compactedRoot.hasOverflowed()) [[unlikely]] {
throwOutOfMemoryError(globalObject, scope);
return { };
}
return std::tuple { 0, ArrayWithDouble, std::span { compactedRoot.data(), count } };
}
default:
break;
}
}
for (uint64_t index = 0; index < length; ++index) {
JSValue value = thisObject->getIfPropertyExists(globalObject, index);
RETURN_IF_EXCEPTION(scope, { });
if (value) {
if (value.isUndefined())
++undefinedCount;
else {
compactedRoot.append(value);
if (compactedRoot.hasOverflowed()) [[unlikely]] {
throwOutOfMemoryError(globalObject, scope);
return { };
}
}
}
}
return std::tuple { undefinedCount, ArrayWithContiguous, std::span { compactedRoot.data(), compactedRoot.size() } };
}
static unsigned sortBucketSort(std::span<EncodedJSValue> sorted, unsigned dst, SortEntryVector& bucket, unsigned depth)
{
if (bucket.size() < 32 || depth > 32) {
std::ranges::sort(bucket, WTF::codePointCompareLessThan, [](const auto& element) {
return std::get<1>(element);
});
for (auto& entry : bucket)
sorted[dst++] = JSValue::encode(std::get<0>(entry));
return dst;
}
StdMap<char16_t, SortEntryVector> buckets;
for (const auto& entry : bucket) {
if (std::get<1>(entry).length() == depth) {
sorted[dst++] = JSValue::encode(std::get<0>(entry));
continue;
}
char16_t character = std::get<1>(entry).characterAt(depth);
buckets.insert(std::pair { character, SortEntryVector { } }).first->second.append(entry);
}
for (auto& entries : buckets)
dst = sortBucketSort(sorted, dst, entries.second, depth + 1);
return dst;
}
static ALWAYS_INLINE std::span<EncodedJSValue> sortStableSort(JSGlobalObject* globalObject, std::span<EncodedJSValue> sorted, std::span<EncodedJSValue> compacted, JSObject* comparator)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
auto callData = JSC::getCallDataInline(comparator);
ASSERT(callData.type != CallData::Type::None);
if (callData.type == CallData::Type::JS) [[likely]] {
CachedCall cachedCall(globalObject, jsCast<JSFunction*>(comparator), 2);
RETURN_IF_EXCEPTION(scope, sorted);
RELEASE_AND_RETURN(scope, arrayStableSort(vm, compacted, sorted, [&](auto left, auto right) ALWAYS_INLINE_LAMBDA {
auto scope = DECLARE_THROW_SCOPE(vm);
JSValue jsResult = cachedCall.callWithArguments(globalObject, jsUndefined(), JSValue::decode(left), JSValue::decode(right));
RETURN_IF_EXCEPTION_WITH_TRAPS_DEFERRED(scope, false);
RELEASE_AND_RETURN(scope, coerceComparatorResultToBoolean(globalObject, jsResult));
}));
}
MarkedArgumentBuffer args;
RELEASE_AND_RETURN(scope, arrayStableSort(vm, compacted, sorted, [&](auto left, auto right) ALWAYS_INLINE_LAMBDA {
auto scope = DECLARE_THROW_SCOPE(vm);
args.clear();
args.append(JSValue::decode(left));
args.append(JSValue::decode(right));
if (args.hasOverflowed()) [[unlikely]] {
throwOutOfMemoryError(globalObject, scope);
return false;
}
JSValue jsResult = call(globalObject, comparator, callData, jsUndefined(), args);
RETURN_IF_EXCEPTION(scope, false);
RELEASE_AND_RETURN(scope, coerceComparatorResultToBoolean(globalObject, jsResult));
}));
}
static ALWAYS_INLINE void sortCommit(JSGlobalObject* globalObject, JSObject* thisObject, uint64_t length, IndexingType indexingType, std::span<const EncodedJSValue> sorted, uint64_t undefinedCount)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
unsigned index = 0;
bool appended = false;
if (isJSArray(thisObject)) [[likely]] {
appended = jsCast<JSArray*>(thisObject)->appendMemcpy(globalObject, vm, 0, indexingType, sorted);
RETURN_IF_EXCEPTION(scope, void());
}
if (!appended) [[unlikely]] {
for (EncodedJSValue encodedValue : sorted) {
JSValue value = JSValue::decode(encodedValue);
constexpr bool shouldThrow = true;
thisObject->putByIndexInline(globalObject, index++, value, shouldThrow);
RETURN_IF_EXCEPTION(scope, void());
}
} else {
index = sorted.size();
if (index == length) [[likely]]
return;
}
uint64_t index64 = index;
uint64_t undefinedMax = static_cast<uint64_t>(sorted.size()) + undefinedCount;
for (; index64 < undefinedMax; ++index64) {
constexpr bool shouldThrow = true;
thisObject->putByIndexInline(globalObject, index64, jsUndefined(), shouldThrow);
RETURN_IF_EXCEPTION(scope, void());
}
for (; index64 < length; ++index64) {
bool deleted = thisObject->deleteProperty(globalObject, index64);
RETURN_IF_EXCEPTION(scope, void());
if (!deleted) [[unlikely]] {
throwTypeError(globalObject, scope, UnableToDeletePropertyError);
return;
}
}
}
static ALWAYS_INLINE void sortImpl(JSGlobalObject* globalObject, JSObject* thisObject, uint64_t length, JSValue comparatorValue)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
// For compatibility with Firefox and Chrome, do nothing observable
// to the target array if it has 0 or 1 sortable properties.
if (length < 2)
return;
bool isStringSort = comparatorValue.isUndefined();
SortJSValueVector compactedRoot;
SortJSValueVector sortedRoot;