-
Notifications
You must be signed in to change notification settings - Fork 637
/
Array.cpp
3839 lines (3492 loc) · 131 KB
/
Array.cpp
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) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
//===----------------------------------------------------------------------===//
/// \file
/// ES5.1 15.4 Initialize the Array constructor.
//===----------------------------------------------------------------------===//
#include "JSLibInternal.h"
#include "hermes/ADT/SafeInt.h"
#include "hermes/VM/HandleRootOwner-inline.h"
#include "hermes/VM/JSLib/Sorting.h"
#include "hermes/VM/Operations.h"
#include "hermes/VM/StringBuilder.h"
#include "hermes/VM/StringRefUtils.h"
#include "hermes/VM/StringView.h"
#include "llvh/ADT/ScopeExit.h"
#pragma GCC diagnostic push
#ifdef HERMES_COMPILER_SUPPORTS_WSHORTEN_64_TO_32
#pragma GCC diagnostic ignored "-Wshorten-64-to-32"
#endif
namespace hermes {
namespace vm {
//===----------------------------------------------------------------------===//
/// Array.
Handle<JSObject> createArrayConstructor(Runtime &runtime) {
auto arrayPrototype = Handle<JSArray>::vmcast(&runtime.arrayPrototype);
// Array.prototype.xxx methods.
defineMethod(
runtime,
arrayPrototype,
Predefined::getSymbolID(Predefined::toString),
nullptr,
arrayPrototypeToString,
0);
defineMethod(
runtime,
arrayPrototype,
Predefined::getSymbolID(Predefined::toLocaleString),
nullptr,
arrayPrototypeToLocaleString,
0);
defineMethod(
runtime,
arrayPrototype,
Predefined::getSymbolID(Predefined::at),
nullptr,
arrayPrototypeAt,
1);
defineMethod(
runtime,
arrayPrototype,
Predefined::getSymbolID(Predefined::concat),
nullptr,
arrayPrototypeConcat,
1);
defineMethod(
runtime,
arrayPrototype,
Predefined::getSymbolID(Predefined::join),
nullptr,
arrayPrototypeJoin,
1);
defineMethod(
runtime,
arrayPrototype,
Predefined::getSymbolID(Predefined::push),
nullptr,
arrayPrototypePush,
1);
defineMethod(
runtime,
arrayPrototype,
Predefined::getSymbolID(Predefined::sort),
nullptr,
arrayPrototypeSort,
1);
defineMethod(
runtime,
arrayPrototype,
Predefined::getSymbolID(Predefined::forEach),
nullptr,
arrayPrototypeForEach,
1);
defineMethod(
runtime,
arrayPrototype,
Predefined::getSymbolID(Predefined::flat),
nullptr,
arrayPrototypeFlat,
0);
defineMethod(
runtime,
arrayPrototype,
Predefined::getSymbolID(Predefined::flatMap),
nullptr,
arrayPrototypeFlatMap,
1);
defineMethod(
runtime,
arrayPrototype,
Predefined::getSymbolID(Predefined::keys),
(void *)IterationKind::Key,
arrayPrototypeIterator,
0);
defineMethod(
runtime,
arrayPrototype,
Predefined::getSymbolID(Predefined::values),
(void *)IterationKind::Value,
arrayPrototypeIterator,
0);
defineMethod(
runtime,
arrayPrototype,
Predefined::getSymbolID(Predefined::entries),
(void *)IterationKind::Entry,
arrayPrototypeIterator,
0);
auto propValue = runtime.ignoreAllocationFailure(JSObject::getNamed_RJS(
arrayPrototype, runtime, Predefined::getSymbolID(Predefined::values)));
runtime.arrayPrototypeValues = std::move(propValue);
DefinePropertyFlags dpf = DefinePropertyFlags::getNewNonEnumerableFlags();
runtime.ignoreAllocationFailure(JSObject::defineOwnProperty(
arrayPrototype,
runtime,
Predefined::getSymbolID(Predefined::SymbolIterator),
dpf,
Handle<>(&runtime.arrayPrototypeValues)));
auto cons = defineSystemConstructor<JSArray>(
runtime,
Predefined::getSymbolID(Predefined::Array),
arrayConstructor,
arrayPrototype,
1,
CellKind::JSArrayKind);
defineMethod(
runtime,
cons,
Predefined::getSymbolID(Predefined::isArray),
nullptr,
arrayIsArray,
1);
defineMethod(
runtime,
arrayPrototype,
Predefined::getSymbolID(Predefined::slice),
nullptr,
arrayPrototypeSlice,
2);
defineMethod(
runtime,
arrayPrototype,
Predefined::getSymbolID(Predefined::splice),
nullptr,
arrayPrototypeSplice,
2);
defineMethod(
runtime,
arrayPrototype,
Predefined::getSymbolID(Predefined::copyWithin),
nullptr,
arrayPrototypeCopyWithin,
2);
defineMethod(
runtime,
arrayPrototype,
Predefined::getSymbolID(Predefined::pop),
nullptr,
arrayPrototypePop,
0);
defineMethod(
runtime,
arrayPrototype,
Predefined::getSymbolID(Predefined::shift),
nullptr,
arrayPrototypeShift,
0);
defineMethod(
runtime,
arrayPrototype,
Predefined::getSymbolID(Predefined::unshift),
nullptr,
arrayPrototypeUnshift,
1);
defineMethod(
runtime,
arrayPrototype,
Predefined::getSymbolID(Predefined::indexOf),
nullptr,
arrayPrototypeIndexOf,
1);
defineMethod(
runtime,
arrayPrototype,
Predefined::getSymbolID(Predefined::lastIndexOf),
nullptr,
arrayPrototypeLastIndexOf,
1);
defineMethod(
runtime,
arrayPrototype,
Predefined::getSymbolID(Predefined::every),
nullptr,
arrayPrototypeEvery,
1);
defineMethod(
runtime,
arrayPrototype,
Predefined::getSymbolID(Predefined::some),
nullptr,
arrayPrototypeSome,
1);
defineMethod(
runtime,
arrayPrototype,
Predefined::getSymbolID(Predefined::map),
nullptr,
arrayPrototypeMap,
1);
defineMethod(
runtime,
arrayPrototype,
Predefined::getSymbolID(Predefined::filter),
nullptr,
arrayPrototypeFilter,
1);
defineMethod(
runtime,
arrayPrototype,
Predefined::getSymbolID(Predefined::fill),
nullptr,
arrayPrototypeFill,
1);
defineMethod(
runtime,
arrayPrototype,
Predefined::getSymbolID(Predefined::find),
nullptr,
arrayPrototypeFind,
1);
defineMethod(
runtime,
arrayPrototype,
Predefined::getSymbolID(Predefined::findIndex),
// Pass a non-null pointer here to indicate we're finding the index.
(void *)true,
arrayPrototypeFind,
1);
defineMethod(
runtime,
arrayPrototype,
Predefined::getSymbolID(Predefined::findLast),
nullptr,
arrayPrototypeFindLast,
1);
defineMethod(
runtime,
arrayPrototype,
Predefined::getSymbolID(Predefined::findLastIndex),
// Pass a non-null pointer here to indicate we're finding the index.
(void *)true,
arrayPrototypeFindLast,
1);
defineMethod(
runtime,
arrayPrototype,
Predefined::getSymbolID(Predefined::reduce),
nullptr,
arrayPrototypeReduce,
1);
defineMethod(
runtime,
arrayPrototype,
Predefined::getSymbolID(Predefined::reduceRight),
nullptr,
arrayPrototypeReduceRight,
1);
defineMethod(
runtime,
arrayPrototype,
Predefined::getSymbolID(Predefined::reverse),
nullptr,
arrayPrototypeReverse,
0);
defineMethod(
runtime,
arrayPrototype,
Predefined::getSymbolID(Predefined::includes),
nullptr,
arrayPrototypeIncludes,
1);
defineMethod(
runtime,
cons,
Predefined::getSymbolID(Predefined::of),
nullptr,
arrayOf,
0);
defineMethod(
runtime,
cons,
Predefined::getSymbolID(Predefined::from),
nullptr,
arrayFrom,
1);
return cons;
}
CallResult<HermesValue>
arrayConstructor(void *, Runtime &runtime, NativeArgs args) {
MutableHandle<JSArray> selfHandle{runtime};
// If constructor, use the allocated object, otherwise allocate a new one.
// Everything else is the same after that.
if (args.isConstructorCall())
selfHandle = vmcast<JSArray>(args.getThisArg());
else {
auto arrRes = JSArray::create(runtime, 0, 0);
if (LLVM_UNLIKELY(arrRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
selfHandle = arrRes->get();
}
// Possibility 1: new Array(number)
if (args.getArgCount() == 1 && args.getArg(0).isNumber()) {
double number = args.getArg(0).getNumber();
uint32_t len = truncateToUInt32(number);
if (len != number) {
return runtime.raiseRangeError("invalid array length");
}
auto st = JSArray::setLengthProperty(selfHandle, runtime, len);
(void)st;
assert(
st != ExecutionStatus::EXCEPTION && *st &&
"Cannot set length of a new array");
return selfHandle.getHermesValue();
}
// Possibility 2: new Array(elements...)
uint32_t len = args.getArgCount();
// Resize the array.
auto st = JSArray::setLengthProperty(selfHandle, runtime, len);
(void)st;
assert(
st != ExecutionStatus::EXCEPTION && *st &&
"Cannot set length of a new array");
// Initialize the elements.
uint32_t index = 0;
GCScopeMarkerRAII marker(runtime);
for (Handle<> arg : args.handles()) {
JSArray::setElementAt(selfHandle, runtime, index++, arg);
marker.flush();
}
return selfHandle.getHermesValue();
}
CallResult<HermesValue>
arrayIsArray(void *, Runtime &runtime, NativeArgs args) {
CallResult<bool> res = isArray(runtime, dyn_vmcast<JSObject>(args.getArg(0)));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
return HermesValue::encodeBoolValue(*res);
}
/// ES5.1 15.4.4.5.
CallResult<HermesValue>
arrayPrototypeToString(void *, Runtime &runtime, NativeArgs args) {
auto objRes = toObject(runtime, args.getThisHandle());
if (LLVM_UNLIKELY(objRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
auto array = runtime.makeHandle<JSObject>(objRes.getValue());
auto propRes = JSObject::getNamed_RJS(
array, runtime, Predefined::getSymbolID(Predefined::join));
if (LLVM_UNLIKELY(propRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
auto func =
Handle<Callable>::dyn_vmcast(runtime.makeHandle(std::move(*propRes)));
if (!func) {
// If not callable, set func to be Object.prototype.toString.
return directObjectPrototypeToString(runtime, array);
}
return Callable::executeCall0(func, runtime, array).toCallResultHermesValue();
}
CallResult<HermesValue>
arrayPrototypeToLocaleString(void *, Runtime &runtime, NativeArgs args) {
GCScope gcScope{runtime};
auto objRes = toObject(runtime, args.getThisHandle());
if (LLVM_UNLIKELY(objRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
auto array = runtime.makeHandle<JSObject>(objRes.getValue());
auto emptyString = runtime.getPredefinedStringHandle(Predefined::emptyString);
if (runtime.insertVisitedObject(*array))
return emptyString.getHermesValue();
auto cycleScope =
llvh::make_scope_exit([&] { runtime.removeVisitedObject(*array); });
auto propRes = JSObject::getNamed_RJS(
array, runtime, Predefined::getSymbolID(Predefined::length));
if (LLVM_UNLIKELY(propRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
auto intRes = toUInt32_RJS(runtime, runtime.makeHandle(std::move(*propRes)));
if (LLVM_UNLIKELY(intRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
uint32_t len = intRes->getNumber();
// TODO: Get a list-separator String for the host environment's locale.
// Use a comma as a separator for now, as JSC does.
const char16_t separator = u',';
// Final size of the result string. Initialize to account for the separators.
SafeUInt32 size(len - 1);
if (len == 0) {
return emptyString.getHermesValue();
}
// Array to store each of the strings of the elements.
auto arrRes = JSArray::create(runtime, len, len);
if (LLVM_UNLIKELY(arrRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
auto strings = *arrRes;
// Index into the array.
MutableHandle<> i{runtime, HermesValue::encodeTrustedNumberValue(0)};
auto marker = gcScope.createMarker();
while (i->getNumber() < len) {
gcScope.flushToMarker(marker);
if (LLVM_UNLIKELY(
(propRes = JSObject::getComputed_RJS(array, runtime, i)) ==
ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
auto E = runtime.makeHandle(std::move(*propRes));
if (E->isUndefined() || E->isNull()) {
// Empty string for undefined or null element. No need to add to size.
JSArray::setElementAt(strings, runtime, i->getNumber(), emptyString);
} else {
if (LLVM_UNLIKELY(
(objRes = toObject(runtime, E)) == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
auto elementObj = runtime.makeHandle<JSObject>(objRes.getValue());
// Retrieve the toLocaleString function.
if (LLVM_UNLIKELY(
(propRes = JSObject::getNamed_RJS(
elementObj,
runtime,
Predefined::getSymbolID(Predefined::toLocaleString))) ==
ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
if (auto func = Handle<Callable>::dyn_vmcast(
runtime.makeHandle(std::move(*propRes)))) {
// If ECMA 402 is implemented, it provides a superseding
// definition of Array.prototype.toLocaleString. The only
// difference between these two definitions is that in ECMA
// 402, two arguments (locales and options), if provided, are
// passed on from this function to the element's
// "toLocaleString" method.
auto callRes =
#ifdef HERMES_ENABLE_INTL
Callable::executeCall2(
func, runtime, elementObj, args.getArg(0), args.getArg(1));
#else
Callable::executeCall0(func, runtime, elementObj);
#endif
if (LLVM_UNLIKELY(callRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
auto strRes =
toString_RJS(runtime, runtime.makeHandle(std::move(*callRes)));
if (LLVM_UNLIKELY(strRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
auto elementStr = runtime.makeHandle(std::move(*strRes));
uint32_t strLength = elementStr->getStringLength();
// Throw RangeError on overflow.
size.add(strLength);
if (LLVM_UNLIKELY(size.isOverflowed())) {
return runtime.raiseRangeError(
"resulting string length exceeds limit");
}
JSArray::setElementAt(strings, runtime, i->getNumber(), elementStr);
} else {
return runtime.raiseTypeError("toLocaleString() not callable");
}
}
i = HermesValue::encodeTrustedNumberValue(i->getNumber() + 1);
}
// Create and then populate the result string.
auto builder = StringBuilder::createStringBuilder(runtime, size);
if (builder == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
MutableHandle<StringPrimitive> element{runtime};
element = strings->at(runtime, 0).getString(runtime);
builder->appendStringPrim(element);
for (uint32_t j = 1; j < len; ++j) {
// Every element after the first needs a separator before it.
builder->appendCharacter(separator);
element = strings->at(runtime, j).getString(runtime);
builder->appendStringPrim(element);
}
return HermesValue::encodeStringValue(*builder->getStringPrimitive());
}
// 23.1.3.1
CallResult<HermesValue>
arrayPrototypeAt(void *, Runtime &runtime, NativeArgs args) {
GCScope gcScope(runtime);
// 1. Let O be ? ToObject(this value).
auto objRes = toObject(runtime, args.getThisHandle());
if (LLVM_UNLIKELY(objRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
auto O = runtime.makeHandle<JSObject>(objRes.getValue());
// 2. Let len be ? LengthOfArrayLike(O).
Handle<JSArray> jsArr = Handle<JSArray>::dyn_vmcast(O);
uint32_t len = 0;
if (LLVM_LIKELY(jsArr)) {
// Fast path for getting the length.
len = JSArray::getLength(jsArr.get(), runtime);
} else {
// Slow path
CallResult<PseudoHandle<>> propRes = JSObject::getNamed_RJS(
O, runtime, Predefined::getSymbolID(Predefined::length));
if (LLVM_UNLIKELY(propRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
auto lenRes = toLength(runtime, runtime.makeHandle(std::move(*propRes)));
if (LLVM_UNLIKELY(lenRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
len = lenRes->getNumber();
}
// 3. Let relativeIndex be ? ToIntegerOrInfinity(index).
auto idx = args.getArgHandle(0);
auto relativeIndexRes = toIntegerOrInfinity(runtime, idx);
if (relativeIndexRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
const double relativeIndex = relativeIndexRes->getNumber();
double k;
// 4. If relativeIndex ≥ 0, then
if (relativeIndex >= 0) {
// a. Let k be relativeIndex.
k = relativeIndex;
} else {
// 5. Else,
// a. Let k be len + relativeIndex.
k = len + relativeIndex;
}
// 6. If k < 0 or k ≥ len, return undefined.
if (k < 0 || k >= len) {
return HermesValue::encodeUndefinedValue();
}
// 7. Return ? Get(O, ! ToString(𝔽(k))).
if (LLVM_LIKELY(jsArr)) {
const SmallHermesValue elm = jsArr->at(runtime, k);
if (elm.isEmpty()) {
return HermesValue::encodeUndefinedValue();
} else {
return elm.unboxToHV(runtime);
}
}
CallResult<PseudoHandle<>> propRes = JSObject::getComputed_RJS(
O, runtime, runtime.makeHandle(HermesValue::encodeTrustedNumberValue(k)));
if (LLVM_UNLIKELY(propRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
return propRes->getHermesValue();
}
CallResult<HermesValue>
arrayPrototypeConcat(void *, Runtime &runtime, NativeArgs args) {
GCScope gcScope(runtime);
auto objRes = toObject(runtime, args.getThisHandle());
if (LLVM_UNLIKELY(objRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
auto O = runtime.makeHandle<JSObject>(objRes.getValue());
// Need a signed type here to account for uint32 and -1.
int64_t argCount = args.getArgCount();
// Precompute the final size of the array so it can be preallocated.
// Note this is necessarily an estimate because an accessor on one array
// may change the length of subsequent arrays.
SafeUInt32 finalSizeEstimate{0};
if (JSArray *arr = dyn_vmcast<JSArray>(O.get())) {
finalSizeEstimate.add(JSArray::getLength(arr, runtime));
} else {
finalSizeEstimate.add(1);
}
for (int64_t i = 0; i < argCount; ++i) {
if (JSArray *arr = dyn_vmcast<JSArray>(args.getArg(i))) {
finalSizeEstimate.add(JSArray::getLength(arr, runtime));
} else {
finalSizeEstimate.add(1);
}
}
if (finalSizeEstimate.isOverflowed()) {
return runtime.raiseTypeError("Array.prototype.concat result out of space");
}
// Resultant array.
auto arrRes =
JSArray::create(runtime, *finalSizeEstimate, *finalSizeEstimate);
if (LLVM_UNLIKELY(arrRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
auto A = *arrRes;
// Index to insert into A.
uint64_t n = 0;
// Temporary handle for an object.
MutableHandle<JSObject> objHandle{runtime};
// Temporary handle for an array.
MutableHandle<JSArray> arrHandle{runtime};
// Index to read from in the array that's being concatenated.
MutableHandle<> kHandle{runtime};
// Index to put into the resultant array.
MutableHandle<> nHandle{runtime};
// Temporary handle to use when holding intermediate elements.
MutableHandle<> tmpHandle{runtime};
// Used to find the object in the prototype chain that has index as property.
MutableHandle<JSObject> propObj{runtime};
MutableHandle<SymbolID> tmpPropNameStorage{runtime};
auto marker = gcScope.createMarker();
ComputedPropertyDescriptor desc;
// Loop first through the "this" value and then through the arguments.
// If i == -1, use the "this" value, else use the ith argument.
tmpHandle = O.getHermesValue();
for (int64_t i = -1; i < argCount; ++i, tmpHandle = args.getArg(i)) {
CallResult<bool> spreadable = isConcatSpreadable(runtime, tmpHandle);
if (LLVM_UNLIKELY(spreadable == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
if (*spreadable) {
// 7.d. If spreadable is true, then
objHandle = vmcast<JSObject>(*tmpHandle);
arrHandle = dyn_vmcast<JSArray>(*tmpHandle);
uint64_t len;
if (LLVM_LIKELY(arrHandle)) {
// Fast path: E is an array.
len = JSArray::getLength(*arrHandle, runtime);
} else {
CallResult<PseudoHandle<>> propRes = JSObject::getNamed_RJS(
objHandle, runtime, Predefined::getSymbolID(Predefined::length));
if (LLVM_UNLIKELY(propRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
tmpHandle = std::move(*propRes);
auto lengthRes = toLength(runtime, tmpHandle);
if (LLVM_UNLIKELY(lengthRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
len = lengthRes->getNumberAs<uint64_t>();
}
// 5.c.iii. If n + len > 2^53 - 1, throw a TypeError exception
if (LLVM_UNLIKELY(n + len > ((uint64_t)1 << 53) - 1)) {
return runtime.raiseTypeError(
"Array.prototype.concat result out of space");
}
// We know we are going to set elements in the range [n, n+len),
// regardless of any changes to 'arrHandle' (see ES5.1 15.4.4.4). Ensure
// we have capacity.
if (LLVM_UNLIKELY(n + len > A->getEndIndex()) &&
LLVM_LIKELY(n + len < UINT32_MAX)) {
// Only set the endIndex if it's going to be a valid length.
if (LLVM_UNLIKELY(
A->setStorageEndIndex(A, runtime, n + len) ==
ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
}
// Note that we must increase n every iteration even if nothing was
// appended to the result array.
// 5.c.iv. Repeat, while k < len
for (uint64_t k = 0; k < len; ++k, ++n) {
SmallHermesValue subElement = LLVM_LIKELY(arrHandle)
? arrHandle->at(runtime, k)
: SmallHermesValue::encodeEmptyValue();
if (LLVM_LIKELY(!subElement.isEmpty()) &&
LLVM_LIKELY(n < A->getEndIndex())) {
// Fast path: quickly set element without making any extra calls.
// Cast is safe because A->getEndIndex must be in uint32_t range.
JSArray::unsafeSetExistingElementAt(
A.get(), runtime, static_cast<uint32_t>(n), subElement);
} else {
// Slow path fallback if there's an empty slot in arr.
// We have to use getComputedPrimitiveDescriptor because the property
// may exist anywhere in the prototype chain.
kHandle = HermesValue::encodeTrustedNumberValue(k);
JSObject::getComputedPrimitiveDescriptor(
objHandle, runtime, kHandle, propObj, tmpPropNameStorage, desc);
CallResult<PseudoHandle<>> propRes =
JSObject::getComputedPropertyValue_RJS(
objHandle,
runtime,
propObj,
tmpPropNameStorage,
desc,
kHandle);
if (LLVM_UNLIKELY(propRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
if (LLVM_LIKELY(!(*propRes)->isEmpty())) {
tmpHandle = std::move(*propRes);
nHandle = HermesValue::encodeTrustedNumberValue(n);
if (LLVM_UNLIKELY(
JSArray::defineOwnComputedPrimitive(
A,
runtime,
nHandle,
DefinePropertyFlags::getDefaultNewPropertyFlags(),
tmpHandle) == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
}
gcScope.flushToMarker(marker);
}
}
gcScope.flushToMarker(marker);
} else {
// 5.d.i. NOTE: E is added as a single item rather than spread.
// 5.d.ii. If n >= 2**53 - 1, throw a TypeError exception.
if (LLVM_UNLIKELY(n >= ((uint64_t)1 << 53) - 1)) {
return runtime.raiseTypeError(
"Array.prototype.concat result out of space");
}
// Otherwise, just put the value into the next slot.
if (LLVM_LIKELY(n < UINT32_MAX)) {
JSArray::setElementAt(A, runtime, n, tmpHandle);
} else {
nHandle = HermesValue::encodeTrustedNumberValue(n);
auto cr = valueToSymbolID(runtime, nHandle);
if (LLVM_UNLIKELY(cr == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
if (LLVM_UNLIKELY(
JSArray::defineOwnProperty(
A,
runtime,
**cr,
DefinePropertyFlags::getDefaultNewPropertyFlags(),
tmpHandle) == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
}
gcScope.flushToMarker(marker);
++n;
}
}
// Update the array's length. We never expect this to fail since we just
// created the array.
if (n > UINT32_MAX) {
return runtime.raiseRangeError("invalid array length");
}
auto res = JSArray::setLengthProperty(A, runtime, static_cast<uint32_t>(n));
assert(
res == ExecutionStatus::RETURNED &&
"Setting length of new array should never fail");
(void)res;
return A.getHermesValue();
}
/// ES5.1 15.4.4.5.
CallResult<HermesValue>
arrayPrototypeJoin(void *, Runtime &runtime, NativeArgs args) {
GCScope gcScope(runtime);
auto objRes = toObject(runtime, args.getThisHandle());
if (LLVM_UNLIKELY(objRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
auto O = runtime.makeHandle<JSObject>(objRes.getValue());
auto emptyString = runtime.getPredefinedStringHandle(Predefined::emptyString);
if (runtime.insertVisitedObject(*O))
return emptyString.getHermesValue();
auto cycleScope =
llvh::make_scope_exit([&] { runtime.removeVisitedObject(*O); });
auto propRes = JSObject::getNamed_RJS(
O, runtime, Predefined::getSymbolID(Predefined::length));
if (LLVM_UNLIKELY(propRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
auto intRes = toLengthU64(runtime, runtime.makeHandle(std::move(*propRes)));
if (LLVM_UNLIKELY(intRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
uint64_t len = *intRes;
// Use comma for separator if the first argument is undefined.
auto separator = args.getArg(0).isUndefined()
? runtime.makeHandle(HermesValue::encodeStringValue(
runtime.getPredefinedString(Predefined::comma)))
: args.getArgHandle(0);
auto strRes = toString_RJS(runtime, separator);
if (LLVM_UNLIKELY(strRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
auto sep = runtime.makeHandle(std::move(*strRes));
if (len == 0) {
return HermesValue::encodeStringValue(
runtime.getPredefinedString(Predefined::emptyString));
}
// Track the size of the resultant string. Use a 64-bit value to detect
// overflow.
SafeUInt32 size;
// Storage for the strings for each element.
if (LLVM_UNLIKELY(len > JSArray::StorageType::maxElements())) {
return runtime.raiseRangeError("Out of memory for array elements.");
}
auto arrRes = JSArray::create(runtime, len, 0);
if (LLVM_UNLIKELY(arrRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
auto strings = *arrRes;
// Call toString on all the elements of the array.
for (MutableHandle<> i{runtime, HermesValue::encodeTrustedNumberValue(0)};
i->getNumber() < len;
i = HermesValue::encodeTrustedNumberValue(i->getNumber() + 1)) {
// Add the size of the separator, except the first time.
if (i->getNumberAs<uint32_t>())
size.add(sep->getStringLength());
GCScope gcScope2(runtime);
if (LLVM_UNLIKELY(
(propRes = JSObject::getComputed_RJS(O, runtime, i)) ==
ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
auto elem = runtime.makeHandle(std::move(*propRes));
if (elem->isUndefined() || elem->isNull()) {
JSArray::setElementAt(strings, runtime, i->getNumber(), emptyString);
} else {
// Otherwise, call toString_RJS() and push the result, incrementing size.
auto strRes = toString_RJS(runtime, elem);
if (LLVM_UNLIKELY(strRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
auto S = runtime.makeHandle(std::move(*strRes));
size.add(S->getStringLength());
JSArray::setElementAt(strings, runtime, i->getNumber(), S);
}
// Check for string overflow on every iteration to create the illusion that
// we are appending to the string. Also, prevent uint32_t overflow.
if (size.isOverflowed()) {
return runtime.raiseRangeError("String is too long");
}
}
// Allocate the complete result.
auto builder = StringBuilder::createStringBuilder(runtime, size);
if (builder == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
MutableHandle<StringPrimitive> element{runtime};
element = strings->at(runtime, 0).getString(runtime);
builder->appendStringPrim(element);
for (size_t i = 1; i < len; ++i) {
builder->appendStringPrim(sep);
element = strings->at(runtime, i).getString(runtime);
builder->appendStringPrim(element);
}
return HermesValue::encodeStringValue(*builder->getStringPrimitive());
}
/// ES9.0 22.1.3.18.
CallResult<HermesValue>
arrayPrototypePush(void *, Runtime &runtime, NativeArgs args) {
GCScope gcScope(runtime);
// 1. Let O be ? ToObject(this value).
auto objRes = toObject(runtime, args.getThisHandle());
if (LLVM_UNLIKELY(objRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
auto O = runtime.makeHandle<JSObject>(objRes.getValue());
MutableHandle<> len{runtime};
// 2. Let len be ? ToLength(? Get(O, "length")).
Handle<JSArray> arr = Handle<JSArray>::dyn_vmcast(O);
if (LLVM_LIKELY(arr)) {
// Fast path for getting the length.
len = HermesValue::encodeTrustedNumberValue(
JSArray::getLength(arr.get(), runtime));
} else {
// Slow path, used when pushing onto non-array objects.
auto propRes = JSObject::getNamed_RJS(
O, runtime, Predefined::getSymbolID(Predefined::length));
if (LLVM_UNLIKELY(propRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
auto lenRes = toLength(runtime, runtime.makeHandle(std::move(*propRes)));
if (LLVM_UNLIKELY(lenRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
len = lenRes.getValue();
}
// 3. Let items be a List whose elements are, in left to right order, the
// arguments that were passed to this function invocation.
// 4. Let argCount be the number of elements in items.
uint32_t argCount = args.getArgCount();
// 5. If len + argCount > 2**53-1, throw a TypeError exception.
if (len->getNumber() + (double)argCount > std::pow(2.0, 53) - 1) {
return runtime.raiseTypeError("Array length exceeded in push()");
}
auto marker = gcScope.createMarker();
// 6. Repeat, while items is not empty
for (auto arg : args.handles()) {
// a. Remove the first element from items and let E be the value of the
// element.
// b. Perform ? Set(O, ! ToString(len), E, true).
// NOTE: If the prototype has an index-like non-writable property at
// index n, we have to fail to push.
// If the prototype has an index-like accessor at index n,
// then we have to attempt to call the setter.
// Must call putComputed because the array prototype could have values for
// keys that haven't been inserted into O yet.
if (LLVM_UNLIKELY(
JSObject::putComputed_RJS(
O, runtime, len, arg, PropOpFlags().plusThrowOnError()) ==
ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
gcScope.flushToMarker(marker);
// c. Let len be len+1.
len = HermesValue::encodeTrustedNumberValue(len->getNumber() + 1);
}
// 7. Perform ? Set(O, "length", len, true).
if (LLVM_UNLIKELY(