/
TypedArray.cpp
1906 lines (1793 loc) · 64.5 KB
/
TypedArray.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) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*/
//===----------------------------------------------------------------------===//
/// \file
/// ES7 22.2 TypedArray
//===----------------------------------------------------------------------===//
#include "JSLibInternal.h"
#include "Sorting.h"
#include "hermes/VM/JSArrayBuffer.h"
#include "hermes/VM/JSTypedArray.h"
#include "hermes/VM/Operations.h"
#include "hermes/VM/StringBuilder.h"
#include "hermes/VM/StringView.h"
namespace hermes {
namespace vm {
namespace {
/// @name Abstract Operations and Helper functions
/// @{
/// ES7 22.2.2.1.1 IterableToArrayLike
CallResult<HermesValue> iterableToArrayLike(Runtime *runtime, Handle<> items) {
// NOTE: this is a very basic function for now because iterators do not
// yet exist in Hermes. When they do, update this function.
return toObject(runtime, items);
}
/// Given a numeric \p value and \p length, returns either length + value if
/// value is negative, or value if it is positive.
/// The returned value is always in the range [0, length].
template <typename T>
T convertNegativeBoundsRelativeToLength(T value, T length) {
// To avoid casting.
T zero = 0;
return value < 0 ? std::max(length + value, zero) : std::min(value, length);
}
/// ES7 22.2.4.6
CallResult<Handle<JSTypedArrayBase>> typedArrayCreate(
Runtime *runtime,
Handle<Callable> constructor,
HermesValue length) {
auto callRes = Callable::executeConstruct1(
constructor, runtime, runtime->makeHandle(length));
if (callRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
auto retval = *callRes;
if (!vmisa<JSTypedArrayBase>(retval)) {
return runtime->raiseTypeError(
"The constructor needs to construct a TypedArray");
}
auto newTypedArray = Handle<JSTypedArrayBase>::vmcast(runtime, retval);
// If `argumentList` is a single number, then
if (LLVM_LIKELY(length.isNumber())) {
// If the value of newTypedArray's [[ArrayLength]] internal slot <
// argumentList[0], throw a TypeError exception.
if (LLVM_UNLIKELY(
newTypedArray->getLength() <
length.getNumberAs<JSTypedArrayBase::size_type>())) {
return runtime->raiseTypeError(
"TypedArray constructor created an array that was too small");
}
}
return newTypedArray;
}
/// @name %JSTypedArray%
/// @{
// ES 2018 22.2.1.2
template <typename T, CellKind C>
CallResult<HermesValue> typedArrayConstructorFromLength(
Runtime *runtime,
Handle<JSTypedArray<T, C>> self,
Handle<> length) {
auto resIndex = toIndex(runtime, length);
if (resIndex == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
if (JSTypedArray<T, C>::createBuffer(
runtime, self, resIndex.getValue().getNumberAs<std::size_t>()) ==
ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
return self.getHermesValue();
}
// ES6 22.2.1.3
template <typename T, CellKind C>
CallResult<HermesValue> typedArrayConstructorFromTypedArray(
Runtime *runtime,
Handle<JSTypedArray<T, C>> self,
Handle<JSTypedArrayBase> other) {
if (JSTypedArray<T, C>::createBuffer(runtime, self, other->getLength()) ==
ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
if (JSTypedArrayBase::setToCopyOfTypedArray(
runtime, self, 0, other, 0, other->getLength()) ==
ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
return self.getHermesValue();
}
// ES6 22.2.1.5
template <typename T, CellKind C>
CallResult<HermesValue> typedArrayConstructorFromArrayBuffer(
Runtime *runtime,
Handle<JSTypedArray<T, C>> self,
Handle<JSArrayBuffer> buffer,
Handle<> byteOffset,
Handle<> length) {
// This differs from step 7 of the spec, which requires `ToInteger` instead
// of `ToIndex`; however, we have to bound offset to be fittable into a
// 64-bit integer to avoid overflow or loss of precision
auto res = toIndex(runtime, byteOffset);
if (res == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
uint64_t offset = res->getNumberAs<uint64_t>();
if (offset % sizeof(T) != 0) {
return runtime->raiseRangeError(
"new TypedArray(buffer, [byteOffset], "
"[length]): if byteOffset is specified, it "
"must be evenly divisible by the element size");
}
auto bufferByteLength = buffer->size();
uint64_t newByteLength = 0;
if (length->isUndefined()) {
if (bufferByteLength % sizeof(T) != 0) {
return runtime->raiseRangeError(
"new TypedArray(buffer, [byteOffset], "
"[length]): buffer's size must be evenly "
"divisible by the element size");
}
if (bufferByteLength < offset) {
return runtime->raiseRangeError(
"new TypedArray(buffer, [byteOffset], "
"[length]): byteOffset must be less than "
"buffer.byteLength");
}
newByteLength = bufferByteLength - offset;
} else {
auto res2 = toLength(runtime, length);
if (res2 == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
uint64_t newLength = res2->getNumberAs<uint64_t>();
newByteLength = newLength * sizeof(T);
if (offset + newByteLength > bufferByteLength) {
return runtime->raiseRangeError(
"new TypedArray(buffer, [byteOffset], [length]): byteOffset + "
"length * elementSize must be less than buffer.byteLength");
}
}
JSTypedArrayBase::setBuffer(
runtime, *self, *buffer, offset, newByteLength, sizeof(T));
return self.getHermesValue();
}
// ES7 22.2.4.4
template <typename T, CellKind C>
CallResult<HermesValue> typedArrayConstructorFromObject(
Runtime *runtime,
Handle<JSTypedArray<T, C>> self,
Handle<> obj) {
// Steps 1 & 2 already covered by caller.
// 5. Let arrayLike be ? IterableToArrayLike(object).
auto objRes = iterableToArrayLike(runtime, obj);
if (objRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
auto arrayLike = runtime->makeHandle<JSObject>(objRes.getValue());
// 6. Let len be ? ToLength(? Get(arrayLike, "length")).
auto propRes = JSObject::getNamed_RJS(
arrayLike, runtime, Predefined::getSymbolID(Predefined::length));
if (propRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
auto intRes = toLength(runtime, runtime->makeHandle(*propRes));
if (intRes == ExecutionStatus::EXCEPTION)
return ExecutionStatus::EXCEPTION;
uint64_t len = intRes->getNumberAs<uint64_t>();
// 4. Let O be ? AllocateTypedArray(constructorName, NewTarget,
// "%TypedArrayPrototype%").
// 7. Perform ? AllocateTypedArrayBuffer(O, len).
if (JSTypedArray<T, C>::createBuffer(runtime, self, len) ==
ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
GCScope scope(runtime);
// 8. Let k be 0.
MutableHandle<HermesValue> i(runtime, HermesValue::encodeNumberValue(0));
auto marker = scope.createMarker();
// 9. Repeat, while k < len.
for (; i->getNumberAs<uint64_t>() < len;
i = HermesValue::encodeNumberValue(i->getNumberAs<uint64_t>() + 1)) {
// a. Let Pk be ! ToString(k).
// b. Let kValue be ? Get(arrayLike, Pk).
// c. Perform ? Set(O, Pk, kValue, true).
if ((propRes = JSObject::getComputed_RJS(arrayLike, runtime, i)) ==
ExecutionStatus::EXCEPTION ||
JSTypedArray<T, C>::putComputed_RJS(
self, runtime, i, runtime->makeHandle(*propRes)) ==
ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
scope.flushToMarker(marker);
// d. Increase k by 1.
}
// 10. Return O.
return self.getHermesValue();
}
/// Implements the loop for map and filter. Template parameter \p MapOrFilter
/// should be true for map, and false for filter.
template <bool MapOrFilter>
CallResult<HermesValue> mapFilterLoop(
Runtime *runtime,
Handle<JSTypedArrayBase> self,
Handle<Callable> callbackfn,
Handle<> thisArg,
Handle<JSArray> values,
JSTypedArrayBase::size_type insert,
JSTypedArrayBase::size_type len) {
MutableHandle<> storage(runtime);
GCScopeMarkerRAII marker{runtime};
for (JSTypedArrayBase::size_type i = 0; i < len; ++i) {
if (!self->attached(runtime)) {
// If the callback detached this TypedArray, raise a TypeError and don't
// continue.
return runtime->raiseTypeError("Detached the TypedArray in the callback");
}
auto val = JSObject::getOwnIndexed(*self, runtime, i);
auto callRes = Callable::executeCall3(
callbackfn,
runtime,
thisArg,
val,
HermesValue::encodeNumberValue(i),
self.getHermesValue());
if (callRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
if (MapOrFilter) {
// Map adds the result of the callback onto the array.
storage = *callRes;
JSArray::setElementAt(values, runtime, insert++, storage);
} else if (toBoolean(*callRes)) {
storage = val;
JSArray::setElementAt(values, runtime, insert++, storage);
}
marker.flush();
}
return HermesValue::encodeNumberValue(insert);
}
/// This is the sort model for use with TypedArray.prototype.sort.
/// template param \p WithCompareFn should be true if the compare function is
/// a valid callback to call, and false if it is null or undefined.
template <bool WithCompareFn>
class TypedArraySortModel : public SortModel {
protected:
/// Runtime to sort in.
Runtime *runtime_;
/// Scope to allocate handles in, gets destroyed with this.
GCScope gcScope_;
/// JS comparison function, return -1 for less, 0 for equal, 1 for greater.
/// If null, then use the built in < operator.
Handle<Callable> compareFn_;
/// Object to sort.
Handle<JSTypedArrayBase> self_;
MutableHandle<HermesValue> aHandle_;
MutableHandle<HermesValue> bHandle_;
/// Marker created after initializing all fields so handles allocated later
/// can be flushed.
GCScope::Marker gcMarker_;
public:
TypedArraySortModel(
Runtime *runtime,
Handle<JSTypedArrayBase> obj,
Handle<Callable> compareFn)
: runtime_(runtime),
gcScope_(runtime),
compareFn_(compareFn),
self_(obj),
aHandle_(runtime),
bHandle_(runtime),
gcMarker_(gcScope_.createMarker()) {}
// Swap elements at indices a and b.
virtual ExecutionStatus swap(uint32_t a, uint32_t b) override {
aHandle_ = JSObject::getOwnIndexed(*self_, runtime_, a);
bHandle_ = JSObject::getOwnIndexed(*self_, runtime_, b);
if (JSObject::setOwnIndexed(self_, runtime_, a, bHandle_) ==
ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
if (JSObject::setOwnIndexed(self_, runtime_, b, aHandle_) ==
ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
return ExecutionStatus::RETURNED;
}
// Compare elements at index a and at index b.
virtual CallResult<bool> less(uint32_t a, uint32_t b) override {
GCScopeMarkerRAII gcMarker{gcScope_, gcMarker_};
HermesValue aVal = JSObject::getOwnIndexed(*self_, runtime_, a);
HermesValue bVal = JSObject::getOwnIndexed(*self_, runtime_, b);
if (!WithCompareFn) {
return aVal.getNumber() < bVal.getNumber();
}
assert(compareFn_ && "Cannot use this version if the compareFn is null");
// ES7 22.2.3.26 2a.
// Let v be toNumber_RJS(Call(comparefn, undefined, x, y)).
auto callRes = Callable::executeCall2(
compareFn_, runtime_, runtime_->getUndefinedValue(), aVal, bVal);
if (callRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
auto intRes = toNumber_RJS(runtime_, runtime_->makeHandle(*callRes));
if (intRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// ES7 22.2.3.26 2b.
// If IsDetachedBuffer(buffer) is true, throw a TypeError exception.
if (LLVM_UNLIKELY(!self_->attached(runtime_))) {
return runtime_->raiseTypeError("Callback to sort() detached the array");
}
return intRes->getNumber() < 0;
}
};
// ES7 22.2.3.23.1
CallResult<HermesValue> typedArrayPrototypeSetObject(
Runtime *runtime,
Handle<JSTypedArrayBase> self,
Handle<> obj,
double offset) {
double targetLength = self->getLength();
auto objRes = toObject(runtime, obj);
if (objRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
auto src = runtime->makeHandle<JSObject>(objRes.getValue());
auto propRes = JSObject::getNamed_RJS(
src, runtime, Predefined::getSymbolID(Predefined::length));
if (propRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
auto intRes = toLength(runtime, runtime->makeHandle(*propRes));
if (intRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
uint64_t srcLength = intRes->getNumberAs<uint64_t>();
if (srcLength + offset > targetLength) {
return runtime->raiseRangeError(
"The sum of the length of the given object "
"and the offset cannot be greater than the length "
"of this TypedArray");
}
// Read everything from the other array and write it into self starting from
// offset.
GCScope scope(runtime);
MutableHandle<> k(runtime, HermesValue::encodeNumberValue(0));
auto marker = scope.createMarker();
for (; k->getNumberAs<uint64_t>() < srcLength;
k = HermesValue::encodeNumberValue(k->getNumberAs<uint64_t>() + 1)) {
if ((propRes = JSObject::getComputed_RJS(src, runtime, k)) ==
ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
auto kValue = runtime->makeHandle(*propRes);
if (JSObject::setOwnIndexed(self, runtime, offset++, kValue) ==
ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
scope.flushToMarker(marker);
}
return HermesValue::encodeUndefinedValue();
}
// ES7 22.2.3.23.2
CallResult<HermesValue> typedArrayPrototypeSetTypedArray(
Runtime *runtime,
Handle<JSTypedArrayBase> self,
Handle<JSTypedArrayBase> src,
double offset) {
if (!src->attached(runtime)) {
return runtime->raiseTypeError(
"The src TypedArray must be attached in order to use set()");
}
const JSTypedArrayBase::size_type srcLength = src->getLength();
if (static_cast<double>(srcLength) + offset > self->getLength()) {
return runtime->raiseRangeError(
"The sum of the length of the given TypedArray "
"and the offset cannot be greater than the length "
"of this TypedArray");
}
// Since `src` is immutable, put the rest of the function into a continuation
// to be called with a different `src` parameter.
if (self->getBuffer(runtime)->getDataBlock() !=
src->getBuffer(runtime)->getDataBlock()) {
if (JSTypedArrayBase::setToCopyOfTypedArray(
runtime, self, offset, src, 0, srcLength) ==
ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
return HermesValue::encodeUndefinedValue();
}
// 23. If SameValue(srcBuffer, targetBuffer) is true, then
// a. Let srcBuffer be ? CloneArrayBuffer(targetBuffer, srcByteOffset,
// %ArrayBuffer%).
// If the two arrays have overlapping storage, make a copy of the source
// array.
// TODO: This could be implemented via a directional copy which either
// copies forwards or backwards depending on how the regions overlap.
auto possibleTA = JSTypedArrayBase::allocate(src, runtime, srcLength);
if (possibleTA == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
auto newSrc = possibleTA.getValue();
if (JSTypedArrayBase::setToCopyOfBuffer(
runtime,
newSrc,
0,
runtime->makeHandle(src->getBuffer(runtime)),
src->getByteOffset(),
src->getByteLength()) == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// Now copy from newSrc into self.
if (JSTypedArrayBase::setToCopyOfTypedArray(
runtime, self, offset, newSrc, 0, srcLength) ==
ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
return HermesValue::encodeUndefinedValue();
}
/// @}
} // namespace
/// @}
/// @name TypedArrayBase
/// @{
CallResult<HermesValue>
typedArrayBaseConstructor(void *, Runtime *runtime, NativeArgs) {
return runtime->raiseTypeError(
"TypedArray is abstract, it cannot be constructed");
}
/// @}
template <typename T, CellKind C>
CallResult<HermesValue>
typedArrayConstructor(void *, Runtime *runtime, NativeArgs args) {
// 1. If NewTarget is undefined, throw a TypeError exception.
if (!args.isConstructorCall()) {
return runtime->raiseTypeError(
"JSTypedArray() called in function context instead of constructor");
}
auto self = args.vmcastThis<JSTypedArray<T, C>>();
if (args.getArgCount() == 0) {
// ES6 22.2.1.1
if (JSTypedArray<T, C>::createBuffer(runtime, self, 0) ==
ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
return self.getHermesValue();
}
auto firstArg = args.getArgHandle(runtime, 0);
if (!firstArg->isObject()) {
return typedArrayConstructorFromLength<T, C>(runtime, self, firstArg);
}
if (auto otherTA = Handle<JSTypedArrayBase>::dyn_vmcast(runtime, firstArg)) {
return typedArrayConstructorFromTypedArray<T, C>(runtime, self, otherTA);
}
if (auto buffer = Handle<JSArrayBuffer>::dyn_vmcast(runtime, firstArg)) {
return typedArrayConstructorFromArrayBuffer<T, C>(
runtime,
self,
buffer,
args.getArgHandle(runtime, 1),
args.getArgHandle(runtime, 2));
}
return typedArrayConstructorFromObject<T, C>(runtime, self, firstArg);
}
/// ES7 22.2.2.1
CallResult<HermesValue>
typedArrayFrom(void *, Runtime *runtime, NativeArgs args) {
auto source = args.getArgHandle(runtime, 0);
// 1. Let C be the this value.
if (!isConstructor(runtime, args.getThisArg())) {
// 2. If IsConstructor(C) is false, throw a TypeError exception.
return runtime->raiseTypeError(
"Cannot invoke when the this is not a constructor");
}
auto C = Handle<Callable>::vmcast(runtime, args.getThisArg());
// 3. If mapfn was supplied and mapfn is not undefined, then
auto mapfn =
Handle<Callable>::dyn_vmcast(runtime, args.getArgHandle(runtime, 1));
if (!mapfn) {
// a. If IsCallable(mapfn) is false, throw a TypeError exception.
if (args.getArgCount() >= 2 && !vmisa<Callable>(args.getArg(1))) {
return runtime->raiseTypeError(
"Second argument to TypedArray.from must be callable");
}
// b. Let mapping be true
}
// 4. Else, let mapping be false. (mapfn can act as a bool for mapping).
// 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
auto T = args.getArgCount() >= 3 ? args.getArgHandle(runtime, 2)
: runtime->getUndefinedValue();
// 6. Let arrayLike be ? IterableToArrayLike(source).
auto objRes = iterableToArrayLike(runtime, source);
if (objRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
auto arrayLike = runtime->makeHandle<JSObject>(objRes.getValue());
// 7. Let len be ? ToLength(? Get(arrayLike, "length")).
auto propRes = JSObject::getNamed_RJS(
arrayLike, runtime, Predefined::getSymbolID(Predefined::length));
if (propRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
auto intRes = toLength(runtime, runtime->makeHandle(*propRes));
if (intRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
auto len = intRes.getValue();
// 8. Let targetObj be ? TypedArrayCreate(C, len).
auto targetObj = typedArrayCreate(runtime, C, len);
if (targetObj == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// 9. Let k be 0.
MutableHandle<> k(runtime, HermesValue::encodeNumberValue(0));
// 10. Repeat, while k < len.
for (; k->getNumberAs<uint64_t>() < len.getNumberAs<uint64_t>();
k = HermesValue::encodeNumberValue(k->getNumberAs<uint64_t>() + 1)) {
GCScopeMarkerRAII marker{runtime};
// a - b. Get the value of the property at k.
if ((propRes = JSObject::getComputed_RJS(arrayLike, runtime, k)) ==
ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// c. If mapping is true, then
if (mapfn) {
// i. Let mappedValue be ? Call(mapfn, T, [kValue, k]).
auto callRes = Callable::executeCall2(
mapfn, runtime, T, *propRes, k.getHermesValue());
if (callRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
propRes = callRes;
}
// NOTE: The returned value is either the same as the getComputed call, or
// the call to the mapfn, so either way it is the correct value.
// d. Else, let mappedValue be kValue (already done by initializer).
auto mappedValue = runtime->makeHandle(*propRes);
// e. Perform ? Set(targetObj, Pk, mappedValue, true).
if (JSObject::putComputed_RJS(*targetObj, runtime, k, mappedValue) ==
ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// f. Increase k by 1. (In the loop increment).
}
// 11. Return targetObj.
return targetObj->getHermesValue();
}
/// ES7 22.2.2.2
CallResult<HermesValue>
typedArrayOf(void *, Runtime *runtime, NativeArgs args) {
// 1. Let len be the actual number of arguments passed to this function.
auto len = args.getArgCount();
// 2. Let items be the List of arguments passed to this function. (args is
// items).
// 3. Let C be the this value.
if (!isConstructor(runtime, args.getThisArg())) {
// 4. If IsConstructor(C) is false, throw a TypeError exception.
return runtime->raiseTypeError(
"Cannot invoke %TypedArray%.of when %TypedArray% is not a constructor "
"function");
}
auto C = Handle<Callable>::vmcast(args.getThisHandle());
// 5. Let newObj be ? TypedArrayCreate(C, len).
auto newObj =
typedArrayCreate(runtime, C, HermesValue::encodeNumberValue(len));
if (newObj == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// 6. Let k be 0.
MutableHandle<> k(runtime, HermesValue::encodeNumberValue(0));
GCScope scope(runtime);
auto marker = scope.createMarker();
// 7. Repeat, while k < len.
for (; k->getNumberAs<uint64_t>() < len;
k = HermesValue::encodeNumberValue(k->getNumberAs<uint64_t>() + 1)) {
// a. Let kValue be items[k].
auto kValue = args.getArg(k->getNumberAs<uint64_t>());
// b. Let Pk be ! ToString(k).
// c. Perform ? Set(newObj, Pk, kValue, true).
if (JSObject::putComputed_RJS(
*newObj, runtime, k, runtime->makeHandle(kValue)) ==
ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// d. Increase k by 1. (In the loop increment).
scope.flushToMarker(marker);
}
// Return newObj.
return newObj->getHermesValue();
}
/// @}
/// @name %JSTypedArray%.prototype
/// @{
/// ES6 22.2.3.1
CallResult<HermesValue>
typedArrayPrototypeBuffer(void *, Runtime *runtime, NativeArgs args) {
if (JSTypedArrayBase::validateTypedArray(
runtime, args.getThisHandle(), false) == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
auto self = args.vmcastThis<JSTypedArrayBase>();
return HermesValue::encodeObjectValue(self->getBuffer(runtime));
}
CallResult<HermesValue>
typedArrayPrototypeByteLength(void *, Runtime *runtime, NativeArgs args) {
if (JSTypedArrayBase::validateTypedArray(
runtime, args.getThisHandle(), false) == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
auto self = args.vmcastThis<JSTypedArrayBase>();
return HermesValue::encodeNumberValue(self->getByteLength());
}
/// ES6 22.2.3.3
CallResult<HermesValue>
typedArrayPrototypeByteOffset(void *, Runtime *runtime, NativeArgs args) {
if (JSTypedArrayBase::validateTypedArray(
runtime, args.getThisHandle(), false) == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
auto self = args.vmcastThis<JSTypedArrayBase>();
return HermesValue::encodeNumberValue(
self->attached(runtime) && self->getLength() != 0 ? self->getByteOffset()
: 0);
}
/// ES6 22.2.3.5
CallResult<HermesValue>
typedArrayPrototypeCopyWithin(void *, Runtime *runtime, NativeArgs args) {
if (JSTypedArrayBase::validateTypedArray(
runtime, args.getThisHandle(), true) == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
GCScope gcScope{runtime};
auto O = args.vmcastThis<JSTypedArrayBase>();
// The this object’s [[ArrayLength]] internal slot is accessed in place of
// performing a [[Get]] of "length".
double len = O->getLength();
// 5. Let relativeTarget be ToInteger(target).
// 6. ReturnIfAbrupt(relativeTarget).
auto relativeTargetRes = toInteger(runtime, args.getArgHandle(runtime, 0));
if (LLVM_UNLIKELY(relativeTargetRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
double relativeTarget = relativeTargetRes->getNumber();
// 7. If relativeTarget < 0, let to be max((len + relativeTarget),0); else let
// to be min(relativeTarget, len).
double to = relativeTarget < 0 ? std::max((len + relativeTarget), (double)0)
: std::min(relativeTarget, len);
// 8. Let relativeStart be ToInteger(start).
// 9. ReturnIfAbrupt(relativeStart).
auto relativeStartRes = toInteger(runtime, args.getArgHandle(runtime, 1));
if (LLVM_UNLIKELY(relativeStartRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
double relativeStart = relativeStartRes->getNumber();
// 10. If relativeStart < 0, let from be max((len + relativeStart),0); else
// let from be min(relativeStart, len).
double from = relativeStart < 0 ? std::max((len + relativeStart), (double)0)
: std::min(relativeStart, len);
// 11. If end is undefined, let relativeEnd be len; else let relativeEnd be
// ToInteger(end).
// 12. ReturnIfAbrupt(relativeEnd).
double relativeEnd;
if (args.getArg(2).isUndefined()) {
relativeEnd = len;
} else {
auto relativeEndRes = toInteger(runtime, args.getArgHandle(runtime, 2));
if (LLVM_UNLIKELY(relativeEndRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
relativeEnd = relativeEndRes->getNumber();
}
// 13. If relativeEnd < 0, let final be max((len + relativeEnd),0); else let
// final be min(relativeEnd, len).
double fin = relativeEnd < 0 ? std::max((len + relativeEnd), (double)0)
: std::min(relativeEnd, len);
// 14. Let count be min(final-from, len-to).
double count = std::min(fin - from, len - to);
int direction;
if (from < to && to < from + count) {
// 15. If from<to and to<from+count
// a. Let direction be -1.
direction = -1;
// b. Let from be from + count -1.
from = from + count - 1;
// c. Let to be to + count -1.
to = to + count - 1;
} else {
// 16. Else,
// a. Let direction = 1.
direction = 1;
}
// Need to case on the TypedArray type to avoid encoding using HermesValues.
// We need to preserve the bit-level encoding of values, and HermesValues
// destroy information, e.g. which NaN is being used.
#define TYPED_ARRAY(name, type) \
case CellKind::name##ArrayKind: { \
auto *arr = vmcast<JSTypedArray<type, CellKind::name##ArrayKind>>(*O); \
if (!arr->attached(runtime)) { \
return runtime->raiseTypeError( \
"Underlying ArrayBuffer detached after calling copyWithin"); \
} \
while (count > 0) { \
arr->at(runtime, to) = arr->at(runtime, from); \
from += direction; \
to += direction; \
--count; \
} \
break; \
}
switch (O->getKind()) {
#include "hermes/VM/TypedArrays.def"
default:
llvm_unreachable("Invalid TypedArray after ValidateTypedArray call");
}
return O.getHermesValue();
}
// ES6 22.2.3.7 and 22.2.3.25 (also see Array.prototype.every/some)
CallResult<HermesValue>
typedArrayPrototypeEverySome(void *ctx, Runtime *runtime, NativeArgs args) {
// NOTE: this was implemented as separate from Array.prototype.every to take
// advantage of the known contiguous memory region.
GCScope gcScope(runtime);
auto every = static_cast<bool>(ctx);
if (JSTypedArrayBase::validateTypedArray(runtime, args.getThisHandle()) ==
ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
auto self = args.vmcastThis<JSTypedArrayBase>();
auto callbackfn = args.dyncastArg<Callable>(runtime, 0);
if (!callbackfn) {
return runtime->raiseTypeError("callbackfn must be a Callable");
}
auto thisArg = args.getArgHandle(runtime, 1);
// Run the callback over every element.
auto marker = gcScope.createMarker();
for (JSTypedArrayBase::size_type i = 0; i < self->getLength(); ++i) {
auto callRes = Callable::executeCall3(
callbackfn,
runtime,
thisArg,
JSObject::getOwnIndexed(*self, runtime, i),
HermesValue::encodeNumberValue(i),
self.getHermesValue());
if (callRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
gcScope.flushToMarker(marker);
auto testResult = toBoolean(*callRes);
if (every && !testResult) {
return HermesValue::encodeBoolValue(false);
} else if (!every && testResult) {
return HermesValue::encodeBoolValue(true);
}
}
// If we're looking for every, then we finished without returning true.
// If we're looking for some, then we finished without returning false.
return HermesValue::encodeBoolValue(every);
}
// ES6 22.2.3.8
CallResult<HermesValue>
typedArrayPrototypeFill(void *, Runtime *runtime, NativeArgs args) {
if (JSTypedArrayBase::validateTypedArray(runtime, args.getThisHandle()) ==
ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
auto self = args.vmcastThis<JSTypedArrayBase>();
const double len = self->getLength();
auto res = toNumber_RJS(runtime, args.getArgHandle(runtime, 0));
if (res == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
auto value = runtime->makeHandle(res.getValue());
res = toInteger(runtime, args.getArgHandle(runtime, 1));
if (res == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
const double relativeStart = res->getNumber();
auto end = args.getArgHandle(runtime, 2);
if (!end->isUndefined()) {
res = toInteger(runtime, end);
if (res == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
}
const double relativeEnd = end->isUndefined() ? len : res->getNumber();
// At this point it is safe to convert to integers because the values will be
// in the range [0, len], and len is an integer.
const int64_t k = convertNegativeBoundsRelativeToLength(relativeStart, len);
const int64_t last = convertNegativeBoundsRelativeToLength(relativeEnd, len);
// 9. If IsDetachedBuffer(O.[[ViewedArrayBuffer]]) is true, throw a TypeError
// exception.
if (!self->attached(runtime)) {
return runtime->raiseTypeError("Cannot fill a detached TypedArray");
}
if (k >= last) {
// Early return to avoid the case of zero requested fill space.
return self.getHermesValue();
}
if (JSObject::setOwnIndexed(self, runtime, k, value) ==
ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
auto elementSize = self->getByteWidth();
uint8_t *begin = self->begin(runtime);
// Fill with the same raw bytes as the first one.
switch (elementSize) {
case 1:
std::fill(begin + k, begin + last, *(begin + k));
break;
case 2: {
auto *src = reinterpret_cast<uint16_t *>(begin);
std::fill(src + k, src + last, *(src + k));
break;
}
case 4: {
auto *src = reinterpret_cast<uint32_t *>(begin);
std::fill(src + k, src + last, *(src + k));
break;
}
case 8: {
auto *src = reinterpret_cast<uint64_t *>(begin);
std::fill(src + k, src + last, *(src + k));
break;
}
default:
llvm_unreachable("No element that is that wide");
break;
}
return self.getHermesValue();
}
CallResult<HermesValue>
typedArrayPrototypeFind(void *ctx, Runtime *runtime, NativeArgs args) {
bool index = static_cast<bool>(ctx);
if (JSTypedArrayBase::validateTypedArray(runtime, args.getThisHandle()) ==
ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
auto self = args.vmcastThis<JSTypedArrayBase>();
auto len = self->getLength();
auto callbackfn = args.dyncastArg<Callable>(runtime, 0);
if (!callbackfn) {
return runtime->raiseTypeError("callbackfn must be a Callable");
}
auto thisArg = args.getArgHandle(runtime, 1);
GCScope gcScope(runtime);
auto marker = gcScope.createMarker();
for (JSTypedArrayBase::size_type i = 0; i < len; ++i) {
auto val = JSObject::getOwnIndexed(*self, runtime, i);
auto idx = HermesValue::encodeNumberValue(i);
auto callRes = Callable::executeCall3(
callbackfn, runtime, thisArg, val, idx, self.getHermesValue());
if (callRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
if (toBoolean(*callRes)) {
// Found one, return it.
return index ? idx : val;
}
gcScope.flushToMarker(marker);
}
return index ? HermesValue::encodeNumberValue(-1)
: HermesValue::encodeUndefinedValue();
}
CallResult<HermesValue>
typedArrayPrototypeForEach(void *, Runtime *runtime, NativeArgs args) {
if (JSTypedArrayBase::validateTypedArray(runtime, args.getThisHandle()) ==
ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
auto self = args.vmcastThis<JSTypedArrayBase>();
auto len = self->getLength();
auto callbackfn = args.dyncastArg<Callable>(runtime, 0);
if (!callbackfn) {
return runtime->raiseTypeError("callbackfn must be a Callable");
}
auto thisArg = args.getArgHandle(runtime, 1);
GCScope gcScope(runtime);
auto marker = gcScope.createMarker();
for (JSTypedArrayBase::size_type i = 0; i < len; ++i) {
// The callback function can detach the TypedArray.
if (!self->attached(runtime)) {
return runtime->raiseTypeError(
"Detached the ArrayBuffer in the callback");
}
HermesValue val = JSObject::getOwnIndexed(*self, runtime, i);
if (Callable::executeCall3(
callbackfn,
runtime,
thisArg,
val,
HermesValue::encodeNumberValue(i),
self.getHermesValue()) == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
gcScope.flushToMarker(marker);
}
return HermesValue::encodeUndefinedValue();
}
enum class IndexOfMode { includes, indexOf, lastIndexOf };
CallResult<HermesValue>
typedArrayPrototypeIndexOf(void *ctx, Runtime *runtime, NativeArgs args) {
const auto indexOfMode = *reinterpret_cast<const IndexOfMode *>(&ctx);
// indexOfMode stores Whether this call is "includes", "indexOf", or
// "lastIndexOf".
auto ret = [indexOfMode](bool x = false, double y = -1) {
switch (indexOfMode) {
case IndexOfMode::includes:
return HermesValue::encodeBoolValue(x);
default:
return HermesValue::encodeNumberValue(y);
}
};
if (JSTypedArrayBase::validateTypedArray(runtime, args.getThisHandle()) ==
ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
auto self = args.vmcastThis<JSTypedArrayBase>();
double len = self->getLength();
if (len == 0) {
return ret();
}
auto searchElement = args.getArg(0);
if (!searchElement.isNumber()) {
// If it's not a number, nothing will match.
return ret();
}
double fromIndex = 0;
if (args.getArgCount() < 2) {
// Zero default for forward, end default for backward.