-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathbuiltins-array.cc
1518 lines (1358 loc) · 55.9 KB
/
builtins-array.cc
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 2016 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/base/logging.h"
#include "src/builtins/builtins-utils-inl.h"
#include "src/builtins/builtins.h"
#include "src/codegen/code-factory.h"
#include "src/common/assert-scope.h"
#include "src/debug/debug.h"
#include "src/execution/isolate.h"
#include "src/execution/protectors-inl.h"
#include "src/handles/global-handles.h"
#include "src/logging/counters.h"
#include "src/objects/contexts.h"
#include "src/objects/elements-inl.h"
#include "src/objects/hash-table-inl.h"
#include "src/objects/js-array-inl.h"
#include "src/objects/lookup.h"
#include "src/objects/objects-inl.h"
#include "src/objects/prototype.h"
#include "src/objects/smi.h"
namespace v8 {
namespace internal {
namespace {
inline bool IsJSArrayFastElementMovingAllowed(Isolate* isolate,
JSArray receiver) {
return JSObject::PrototypeHasNoElements(isolate, receiver);
}
inline bool HasSimpleElements(JSObject current) {
return !current.map().IsCustomElementsReceiverMap() &&
!current.GetElementsAccessor()->HasAccessors(current);
}
inline bool HasOnlySimpleReceiverElements(Isolate* isolate, JSObject receiver) {
// Check that we have no accessors on the receiver's elements.
if (!HasSimpleElements(receiver)) return false;
return JSObject::PrototypeHasNoElements(isolate, receiver);
}
// inline bool HasOnlySimpleElements(Isolate* isolate, JSReceiver receiver) {
// DisallowGarbageCollection no_gc;
// PrototypeIterator iter(isolate, receiver, kStartAtReceiver);
// for (; !iter.IsAtEnd(); iter.Advance()) {
// if (iter.GetCurrent().IsJSProxy()) return false;
// JSObject current = iter.GetCurrent<JSObject>();
// if (!HasSimpleElements(current)) return false;
// }
// return true;
// }
// This method may transition the elements kind of the JSArray once, to make
// sure that all elements provided as arguments in the specified range can be
// added without further elements kinds transitions.
void MatchArrayElementsKindToArguments(Isolate* isolate, Handle<JSArray> array,
BuiltinArguments* args,
int first_arg_index, int num_arguments) {
int args_length = args->length();
if (first_arg_index >= args_length) return;
ElementsKind origin_kind = array->GetElementsKind();
// We do not need to transition for PACKED/HOLEY_ELEMENTS.
if (IsObjectElementsKind(origin_kind)) return;
ElementsKind target_kind = origin_kind;
{
DisallowGarbageCollection no_gc;
int last_arg_index = std::min(first_arg_index + num_arguments, args_length);
for (int i = first_arg_index; i < last_arg_index; i++) {
Object arg = (*args)[i];
if (arg.IsHeapObject()) {
if (arg.IsHeapNumber()) {
target_kind = PACKED_DOUBLE_ELEMENTS;
} else {
target_kind = PACKED_ELEMENTS;
break;
}
}
}
}
if (target_kind != origin_kind) {
// Use a short-lived HandleScope to avoid creating several copies of the
// elements handle which would cause issues when left-trimming later-on.
HandleScope scope(isolate);
JSObject::TransitionElementsKind(array, target_kind);
}
}
// Returns |false| if not applicable.
// TODO(szuend): Refactor this function because it is getting hard to
// understand what each call-site actually checks.
V8_WARN_UNUSED_RESULT
inline bool EnsureJSArrayWithWritableFastElements(Isolate* isolate,
Handle<Object> receiver,
BuiltinArguments* args,
int first_arg_index,
int num_arguments) {
if (!receiver->IsJSArray()) return false;
Handle<JSArray> array = Handle<JSArray>::cast(receiver);
ElementsKind origin_kind = array->GetElementsKind();
if (IsDictionaryElementsKind(origin_kind)) return false;
if (!array->map().is_extensible()) return false;
if (args == nullptr) return true;
// If there may be elements accessors in the prototype chain, the fast path
// cannot be used if there arguments to add to the array.
if (!IsJSArrayFastElementMovingAllowed(isolate, *array)) return false;
// Adding elements to the array prototype would break code that makes sure
// it has no elements. Handle that elsewhere.
if (isolate->IsAnyInitialArrayPrototype(*array)) return false;
// Need to ensure that the arguments passed in args can be contained in
// the array.
MatchArrayElementsKindToArguments(isolate, array, args, first_arg_index,
num_arguments);
return true;
}
// If |index| is Undefined, returns init_if_undefined.
// If |index| is negative, returns length + index.
// If |index| is positive, returns index.
// Returned value is guaranteed to be in the interval of [0, length].
V8_WARN_UNUSED_RESULT Maybe<double> GetRelativeIndex(Isolate* isolate,
double length,
Handle<Object> index,
double init_if_undefined) {
double relative_index = init_if_undefined;
if (!index->IsUndefined()) {
Handle<Object> relative_index_obj;
ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, relative_index_obj,
Object::ToInteger(isolate, index),
Nothing<double>());
relative_index = relative_index_obj->Number();
}
if (relative_index < 0) {
return Just(std::max(length + relative_index, 0.0));
}
return Just(std::min(relative_index, length));
}
// Returns "length", has "fast-path" for JSArrays.
V8_WARN_UNUSED_RESULT Maybe<double> GetLengthProperty(
Isolate* isolate, Handle<JSReceiver> receiver) {
if (receiver->IsJSArray()) {
Handle<JSArray> array = Handle<JSArray>::cast(receiver);
double length = array->length().Number();
DCHECK(0 <= length && length <= kMaxSafeInteger);
return Just(length);
}
Handle<Object> raw_length_number;
ASSIGN_RETURN_ON_EXCEPTION_VALUE(
isolate, raw_length_number,
Object::GetLengthFromArrayLike(isolate, receiver), Nothing<double>());
return Just(raw_length_number->Number());
}
// Set "length" property, has "fast-path" for JSArrays.
// Returns Nothing if something went wrong.
V8_WARN_UNUSED_RESULT MaybeHandle<Object> SetLengthProperty(
Isolate* isolate, Handle<JSReceiver> receiver, double length) {
if (receiver->IsJSArray()) {
Handle<JSArray> array = Handle<JSArray>::cast(receiver);
if (!JSArray::HasReadOnlyLength(array)) {
DCHECK_LE(length, kMaxUInt32);
JSArray::SetLength(array, static_cast<uint32_t>(length));
return receiver;
}
}
return Object::SetProperty(
isolate, receiver, isolate->factory()->length_string(),
isolate->factory()->NewNumber(length), StoreOrigin::kMaybeKeyed,
Just(ShouldThrow::kThrowOnError));
}
V8_WARN_UNUSED_RESULT Object GenericArrayFill(Isolate* isolate,
Handle<JSReceiver> receiver,
Handle<Object> value,
double start, double end) {
// 7. Repeat, while k < final.
while (start < end) {
// a. Let Pk be ! ToString(k).
Handle<String> index = isolate->factory()->NumberToString(
isolate->factory()->NewNumber(start));
// b. Perform ? Set(O, Pk, value, true).
RETURN_FAILURE_ON_EXCEPTION(isolate, Object::SetPropertyOrElement(
isolate, receiver, index, value,
Just(ShouldThrow::kThrowOnError)));
// c. Increase k by 1.
++start;
}
// 8. Return O.
return *receiver;
}
V8_WARN_UNUSED_RESULT bool TryFastArrayFill(
Isolate* isolate, BuiltinArguments* args, Handle<JSReceiver> receiver,
Handle<Object> value, double start_index, double end_index) {
// If indices are too large, use generic path since they are stored as
// properties, not in the element backing store.
if (end_index > kMaxUInt32) return false;
if (!receiver->IsJSObject()) return false;
if (!EnsureJSArrayWithWritableFastElements(isolate, receiver, args, 1, 1)) {
return false;
}
Handle<JSArray> array = Handle<JSArray>::cast(receiver);
// If no argument was provided, we fill the array with 'undefined'.
// EnsureJSArrayWith... does not handle that case so we do it here.
// TODO(szuend): Pass target elements kind to EnsureJSArrayWith... when
// it gets refactored.
if (args->length() == 1 && array->GetElementsKind() != PACKED_ELEMENTS) {
// Use a short-lived HandleScope to avoid creating several copies of the
// elements handle which would cause issues when left-trimming later-on.
HandleScope scope(isolate);
JSObject::TransitionElementsKind(array, PACKED_ELEMENTS);
}
DCHECK_LE(start_index, kMaxUInt32);
DCHECK_LE(end_index, kMaxUInt32);
uint32_t start, end;
CHECK(DoubleToUint32IfEqualToSelf(start_index, &start));
CHECK(DoubleToUint32IfEqualToSelf(end_index, &end));
ElementsAccessor* accessor = array->GetElementsAccessor();
accessor->Fill(array, value, start, end);
return true;
}
} // namespace
BUILTIN(ArrayPrototypeFill) {
HandleScope scope(isolate);
if (isolate->debug_execution_mode() == DebugInfo::kSideEffects) {
if (!isolate->debug()->PerformSideEffectCheckForObject(args.receiver())) {
return ReadOnlyRoots(isolate).exception();
}
}
// 1. Let O be ? ToObject(this value).
Handle<JSReceiver> receiver;
ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
isolate, receiver, Object::ToObject(isolate, args.receiver()));
// 2. Let len be ? ToLength(? Get(O, "length")).
double length;
MAYBE_ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
isolate, length, GetLengthProperty(isolate, receiver));
// 3. Let relativeStart be ? ToInteger(start).
// 4. If relativeStart < 0, let k be max((len + relativeStart), 0);
// else let k be min(relativeStart, len).
Handle<Object> start = args.atOrUndefined(isolate, 2);
double start_index;
MAYBE_ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
isolate, start_index, GetRelativeIndex(isolate, length, start, 0));
// 5. If end is undefined, let relativeEnd be len;
// else let relativeEnd be ? ToInteger(end).
// 6. If relativeEnd < 0, let final be max((len + relativeEnd), 0);
// else let final be min(relativeEnd, len).
Handle<Object> end = args.atOrUndefined(isolate, 3);
double end_index;
MAYBE_ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
isolate, end_index, GetRelativeIndex(isolate, length, end, length));
if (start_index >= end_index) return *receiver;
// Ensure indexes are within array bounds
DCHECK_LE(0, start_index);
DCHECK_LE(start_index, end_index);
DCHECK_LE(end_index, length);
Handle<Object> value = args.atOrUndefined(isolate, 1);
if (TryFastArrayFill(isolate, &args, receiver, value, start_index,
end_index)) {
return *receiver;
}
return GenericArrayFill(isolate, receiver, value, start_index, end_index);
}
namespace {
V8_WARN_UNUSED_RESULT Object GenericArrayPush(Isolate* isolate,
BuiltinArguments* args) {
// 1. Let O be ? ToObject(this value).
Handle<JSReceiver> receiver;
ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
isolate, receiver, Object::ToObject(isolate, args->receiver()));
// 2. Let len be ? ToLength(? Get(O, "length")).
Handle<Object> raw_length_number;
ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
isolate, raw_length_number,
Object::GetLengthFromArrayLike(isolate, receiver));
// 3. Let args be a List whose elements are, in left to right order,
// the arguments that were passed to this function invocation.
// 4. Let arg_count be the number of elements in args.
int arg_count = args->length() - 1;
// 5. If len + arg_count > 2^53-1, throw a TypeError exception.
double length = raw_length_number->Number();
if (arg_count > kMaxSafeInteger - length) {
THROW_NEW_ERROR_RETURN_FAILURE(
isolate, NewTypeError(MessageTemplate::kPushPastSafeLength,
isolate->factory()->NewNumberFromInt(arg_count),
raw_length_number));
}
// 6. Repeat, while args is not empty.
for (int i = 0; i < arg_count; ++i) {
// a. Remove the first element from args and let E be the value of the
// element.
Handle<Object> element = args->at(i + 1);
// b. Perform ? Set(O, ! ToString(len), E, true).
if (length <= static_cast<double>(JSArray::kMaxArrayIndex)) {
RETURN_FAILURE_ON_EXCEPTION(
isolate, Object::SetElement(isolate, receiver, length, element,
ShouldThrow::kThrowOnError));
} else {
LookupIterator::Key key(isolate, length);
LookupIterator it(isolate, receiver, key);
MAYBE_RETURN(Object::SetProperty(&it, element, StoreOrigin::kMaybeKeyed,
Just(ShouldThrow::kThrowOnError)),
ReadOnlyRoots(isolate).exception());
}
// c. Let len be len+1.
++length;
}
// 7. Perform ? Set(O, "length", len, true).
Handle<Object> final_length = isolate->factory()->NewNumber(length);
RETURN_FAILURE_ON_EXCEPTION(
isolate, Object::SetProperty(isolate, receiver,
isolate->factory()->length_string(),
final_length, StoreOrigin::kMaybeKeyed,
Just(ShouldThrow::kThrowOnError)));
// 8. Return len.
return *final_length;
}
} // namespace
BUILTIN(ArrayPush) {
HandleScope scope(isolate);
Handle<Object> receiver = args.receiver();
if (!EnsureJSArrayWithWritableFastElements(isolate, receiver, &args, 1,
args.length() - 1)) {
return GenericArrayPush(isolate, &args);
}
// Fast Elements Path
int to_add = args.length() - 1;
Handle<JSArray> array = Handle<JSArray>::cast(receiver);
uint32_t len = static_cast<uint32_t>(array->length().Number());
if (to_add == 0) return *isolate->factory()->NewNumberFromUint(len);
// Currently fixed arrays cannot grow too big, so we should never hit this.
DCHECK_LE(to_add, Smi::kMaxValue - Smi::ToInt(array->length()));
if (JSArray::HasReadOnlyLength(array)) {
return GenericArrayPush(isolate, &args);
}
ElementsAccessor* accessor = array->GetElementsAccessor();
uint32_t new_length = accessor->Push(array, &args, to_add);
return *isolate->factory()->NewNumberFromUint((new_length));
}
namespace {
V8_WARN_UNUSED_RESULT Object GenericArrayPop(Isolate* isolate,
BuiltinArguments* args) {
// 1. Let O be ? ToObject(this value).
Handle<JSReceiver> receiver;
ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
isolate, receiver, Object::ToObject(isolate, args->receiver()));
// 2. Let len be ? ToLength(? Get(O, "length")).
Handle<Object> raw_length_number;
ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
isolate, raw_length_number,
Object::GetLengthFromArrayLike(isolate, receiver));
double length = raw_length_number->Number();
// 3. If len is zero, then.
if (length == 0) {
// a. Perform ? Set(O, "length", 0, true).
RETURN_FAILURE_ON_EXCEPTION(
isolate, Object::SetProperty(isolate, receiver,
isolate->factory()->length_string(),
Handle<Smi>(Smi::zero(), isolate),
StoreOrigin::kMaybeKeyed,
Just(ShouldThrow::kThrowOnError)));
// b. Return undefined.
return ReadOnlyRoots(isolate).undefined_value();
}
// 4. Else len > 0.
// a. Let new_len be len-1.
Handle<Object> new_length = isolate->factory()->NewNumber(length - 1);
// b. Let index be ! ToString(newLen).
Handle<String> index = isolate->factory()->NumberToString(new_length);
// c. Let element be ? Get(O, index).
Handle<Object> element;
ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
isolate, element, Object::GetPropertyOrElement(isolate, receiver, index));
// d. Perform ? DeletePropertyOrThrow(O, index).
MAYBE_RETURN(JSReceiver::DeletePropertyOrElement(receiver, index,
LanguageMode::kStrict),
ReadOnlyRoots(isolate).exception());
// e. Perform ? Set(O, "length", newLen, true).
RETURN_FAILURE_ON_EXCEPTION(
isolate, Object::SetProperty(isolate, receiver,
isolate->factory()->length_string(),
new_length, StoreOrigin::kMaybeKeyed,
Just(ShouldThrow::kThrowOnError)));
// f. Return element.
return *element;
}
} // namespace
BUILTIN(ArrayPop) {
HandleScope scope(isolate);
Handle<Object> receiver = args.receiver();
if (!EnsureJSArrayWithWritableFastElements(isolate, receiver, nullptr, 0,
0)) {
return GenericArrayPop(isolate, &args);
}
Handle<JSArray> array = Handle<JSArray>::cast(receiver);
uint32_t len = static_cast<uint32_t>(array->length().Number());
if (JSArray::HasReadOnlyLength(array)) {
return GenericArrayPop(isolate, &args);
}
if (len == 0) return ReadOnlyRoots(isolate).undefined_value();
Handle<Object> result;
if (IsJSArrayFastElementMovingAllowed(isolate, JSArray::cast(*receiver))) {
// Fast Elements Path
result = array->GetElementsAccessor()->Pop(array);
} else {
// Use Slow Lookup otherwise
uint32_t new_length = len - 1;
ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
isolate, result, JSReceiver::GetElement(isolate, array, new_length));
// The length could have become read-only during the last GetElement() call,
// so check again.
if (JSArray::HasReadOnlyLength(array)) {
THROW_NEW_ERROR_RETURN_FAILURE(
isolate, NewTypeError(MessageTemplate::kStrictReadOnlyProperty,
isolate->factory()->length_string(),
Object::TypeOf(isolate, array), array));
}
JSArray::SetLength(array, new_length);
}
return *result;
}
namespace {
// Returns true, iff we can use ElementsAccessor for shifting.
V8_WARN_UNUSED_RESULT bool CanUseFastArrayShift(Isolate* isolate,
Handle<JSReceiver> receiver) {
if (!EnsureJSArrayWithWritableFastElements(isolate, receiver, nullptr, 0,
0) ||
!IsJSArrayFastElementMovingAllowed(isolate, JSArray::cast(*receiver))) {
return false;
}
Handle<JSArray> array = Handle<JSArray>::cast(receiver);
return !JSArray::HasReadOnlyLength(array);
}
V8_WARN_UNUSED_RESULT Object GenericArrayShift(Isolate* isolate,
Handle<JSReceiver> receiver,
double length) {
// 4. Let first be ? Get(O, "0").
Handle<Object> first;
ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, first,
Object::GetElement(isolate, receiver, 0));
// 5. Let k be 1.
double k = 1;
// 6. Repeat, while k < len.
while (k < length) {
// a. Let from be ! ToString(k).
Handle<String> from =
isolate->factory()->NumberToString(isolate->factory()->NewNumber(k));
// b. Let to be ! ToString(k-1).
Handle<String> to = isolate->factory()->NumberToString(
isolate->factory()->NewNumber(k - 1));
// c. Let fromPresent be ? HasProperty(O, from).
bool from_present;
MAYBE_ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
isolate, from_present, JSReceiver::HasProperty(receiver, from));
// d. If fromPresent is true, then.
if (from_present) {
// i. Let fromVal be ? Get(O, from).
Handle<Object> from_val;
ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
isolate, from_val,
Object::GetPropertyOrElement(isolate, receiver, from));
// ii. Perform ? Set(O, to, fromVal, true).
RETURN_FAILURE_ON_EXCEPTION(
isolate,
Object::SetPropertyOrElement(isolate, receiver, to, from_val,
Just(ShouldThrow::kThrowOnError)));
} else { // e. Else fromPresent is false,
// i. Perform ? DeletePropertyOrThrow(O, to).
MAYBE_RETURN(JSReceiver::DeletePropertyOrElement(receiver, to,
LanguageMode::kStrict),
ReadOnlyRoots(isolate).exception());
}
// f. Increase k by 1.
++k;
}
// 7. Perform ? DeletePropertyOrThrow(O, ! ToString(len-1)).
Handle<String> new_length = isolate->factory()->NumberToString(
isolate->factory()->NewNumber(length - 1));
MAYBE_RETURN(JSReceiver::DeletePropertyOrElement(receiver, new_length,
LanguageMode::kStrict),
ReadOnlyRoots(isolate).exception());
// 8. Perform ? Set(O, "length", len-1, true).
RETURN_FAILURE_ON_EXCEPTION(isolate,
SetLengthProperty(isolate, receiver, length - 1));
// 9. Return first.
return *first;
}
} // namespace
BUILTIN(ArrayShift) {
HandleScope scope(isolate);
// 1. Let O be ? ToObject(this value).
Handle<JSReceiver> receiver;
ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
isolate, receiver, Object::ToObject(isolate, args.receiver()));
// 2. Let len be ? ToLength(? Get(O, "length")).
double length;
MAYBE_ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
isolate, length, GetLengthProperty(isolate, receiver));
// 3. If len is zero, then.
if (length == 0) {
// a. Perform ? Set(O, "length", 0, true).
RETURN_FAILURE_ON_EXCEPTION(isolate,
SetLengthProperty(isolate, receiver, length));
// b. Return undefined.
return ReadOnlyRoots(isolate).undefined_value();
}
if (CanUseFastArrayShift(isolate, receiver)) {
Handle<JSArray> array = Handle<JSArray>::cast(receiver);
return *array->GetElementsAccessor()->Shift(array);
}
return GenericArrayShift(isolate, receiver, length);
}
BUILTIN(ArrayUnshift) {
HandleScope scope(isolate);
DCHECK(args.receiver()->IsJSArray());
Handle<JSArray> array = Handle<JSArray>::cast(args.receiver());
// These are checked in the Torque builtin.
DCHECK(array->map().is_extensible());
DCHECK(!IsDictionaryElementsKind(array->GetElementsKind()));
DCHECK(IsJSArrayFastElementMovingAllowed(isolate, *array));
DCHECK(!isolate->IsAnyInitialArrayPrototype(*array));
MatchArrayElementsKindToArguments(isolate, array, &args, 1,
args.length() - 1);
int to_add = args.length() - 1;
if (to_add == 0) return array->length();
// Currently fixed arrays cannot grow too big, so we should never hit this.
DCHECK_LE(to_add, Smi::kMaxValue - Smi::ToInt(array->length()));
DCHECK(!JSArray::HasReadOnlyLength(array));
ElementsAccessor* accessor = array->GetElementsAccessor();
int new_length = accessor->Unshift(array, &args, to_add);
return Smi::FromInt(new_length);
}
// Array Concat -------------------------------------------------------------
namespace {
/**
* A simple visitor visits every element of Array's.
* The backend storage can be a fixed array for fast elements case,
* or a dictionary for sparse array. Since Dictionary is a subtype
* of FixedArray, the class can be used by both fast and slow cases.
* The second parameter of the constructor, fast_elements, specifies
* whether the storage is a FixedArray or Dictionary.
*
* An index limit is used to deal with the situation that a result array
* length overflows 32-bit non-negative integer.
*/
class ArrayConcatVisitor {
public:
ArrayConcatVisitor(Isolate* isolate, Handle<HeapObject> storage,
bool fast_elements)
: isolate_(isolate),
storage_(isolate->global_handles()->Create(*storage)),
index_offset_(0u),
bit_field_(FastElementsField::encode(fast_elements) |
ExceedsLimitField::encode(false) |
IsFixedArrayField::encode(storage->IsFixedArray(isolate)) |
HasSimpleElementsField::encode(
storage->IsFixedArray(isolate) ||
// Don't take fast path for storages that might have
// side effects when storing to them.
(!storage->map(isolate).IsCustomElementsReceiverMap() &&
!storage->IsJSTypedArray(isolate)))) {
DCHECK_IMPLIES(this->fast_elements(), is_fixed_array());
}
~ArrayConcatVisitor() { clear_storage(); }
V8_WARN_UNUSED_RESULT bool visit(uint32_t i, Handle<Object> elm) {
uint32_t index = index_offset_ + i;
if (i >= JSObject::kMaxElementCount - index_offset_) {
set_exceeds_array_limit(true);
// Exception hasn't been thrown at this point. Return true to
// break out, and caller will throw. !visit would imply that
// there is already a pending exception.
return true;
}
if (!is_fixed_array()) {
LookupIterator it(isolate_, storage_, index, LookupIterator::OWN);
MAYBE_RETURN(
JSReceiver::CreateDataProperty(&it, elm, Just(kThrowOnError)), false);
return true;
}
if (fast_elements()) {
if (index < static_cast<uint32_t>(storage_fixed_array()->length())) {
storage_fixed_array()->set(index, *elm);
return true;
}
// Our initial estimate of length was foiled, possibly by
// getters on the arrays increasing the length of later arrays
// during iteration.
// This shouldn't happen in anything but pathological cases.
SetDictionaryMode();
// Fall-through to dictionary mode.
}
DCHECK(!fast_elements());
Handle<NumberDictionary> dict(NumberDictionary::cast(*storage_), isolate_);
// The object holding this backing store has just been allocated, so
// it cannot yet be used as a prototype.
Handle<JSObject> not_a_prototype_holder;
Handle<NumberDictionary> result = NumberDictionary::Set(
isolate_, dict, index, elm, not_a_prototype_holder);
if (!result.is_identical_to(dict)) {
// Dictionary needed to grow.
clear_storage();
set_storage(*result);
}
return true;
}
uint32_t index_offset() const { return index_offset_; }
void increase_index_offset(uint32_t delta) {
if (JSObject::kMaxElementCount - index_offset_ < delta) {
index_offset_ = JSObject::kMaxElementCount;
} else {
index_offset_ += delta;
}
// If the initial length estimate was off (see special case in visit()),
// but the array blowing the limit didn't contain elements beyond the
// provided-for index range, go to dictionary mode now.
if (fast_elements() &&
index_offset_ >
static_cast<uint32_t>(FixedArrayBase::cast(*storage_).length())) {
SetDictionaryMode();
}
}
bool exceeds_array_limit() const {
return ExceedsLimitField::decode(bit_field_);
}
Handle<JSArray> ToArray() {
DCHECK(is_fixed_array());
Handle<JSArray> array = isolate_->factory()->NewJSArray(0);
Handle<Object> length =
isolate_->factory()->NewNumber(static_cast<double>(index_offset_));
Handle<Map> map = JSObject::GetElementsTransitionMap(
array, fast_elements() ? HOLEY_ELEMENTS : DICTIONARY_ELEMENTS);
array->set_length(*length);
array->set_elements(*storage_fixed_array());
array->synchronized_set_map(*map);
return array;
}
V8_WARN_UNUSED_RESULT MaybeHandle<JSReceiver> ToJSReceiver() {
DCHECK(!is_fixed_array());
Handle<JSReceiver> result = Handle<JSReceiver>::cast(storage_);
Handle<Object> length =
isolate_->factory()->NewNumber(static_cast<double>(index_offset_));
RETURN_ON_EXCEPTION(
isolate_,
Object::SetProperty(
isolate_, result, isolate_->factory()->length_string(), length,
StoreOrigin::kMaybeKeyed, Just(ShouldThrow::kThrowOnError)),
JSReceiver);
return result;
}
bool has_simple_elements() const {
return HasSimpleElementsField::decode(bit_field_);
}
private:
// Convert storage to dictionary mode.
void SetDictionaryMode() {
DCHECK(fast_elements() && is_fixed_array());
Handle<FixedArray> current_storage = storage_fixed_array();
Handle<NumberDictionary> slow_storage(
NumberDictionary::New(isolate_, current_storage->length()));
uint32_t current_length = static_cast<uint32_t>(current_storage->length());
FOR_WITH_HANDLE_SCOPE(
isolate_, uint32_t, i = 0, i, i < current_length, i++, {
Handle<Object> element(current_storage->get(i), isolate_);
if (!element->IsTheHole(isolate_)) {
// The object holding this backing store has just been allocated, so
// it cannot yet be used as a prototype.
Handle<JSObject> not_a_prototype_holder;
Handle<NumberDictionary> new_storage = NumberDictionary::Set(
isolate_, slow_storage, i, element, not_a_prototype_holder);
if (!new_storage.is_identical_to(slow_storage)) {
slow_storage = loop_scope.CloseAndEscape(new_storage);
}
}
});
clear_storage();
set_storage(*slow_storage);
set_fast_elements(false);
}
inline void clear_storage() { GlobalHandles::Destroy(storage_.location()); }
inline void set_storage(FixedArray storage) {
DCHECK(is_fixed_array());
DCHECK(has_simple_elements());
storage_ = isolate_->global_handles()->Create(storage);
}
using FastElementsField = base::BitField<bool, 0, 1>;
using ExceedsLimitField = base::BitField<bool, 1, 1>;
using IsFixedArrayField = base::BitField<bool, 2, 1>;
using HasSimpleElementsField = base::BitField<bool, 3, 1>;
bool fast_elements() const { return FastElementsField::decode(bit_field_); }
void set_fast_elements(bool fast) {
bit_field_ = FastElementsField::update(bit_field_, fast);
}
void set_exceeds_array_limit(bool exceeds) {
bit_field_ = ExceedsLimitField::update(bit_field_, exceeds);
}
bool is_fixed_array() const { return IsFixedArrayField::decode(bit_field_); }
Handle<FixedArray> storage_fixed_array() {
DCHECK(is_fixed_array());
DCHECK(has_simple_elements());
return Handle<FixedArray>::cast(storage_);
}
Isolate* isolate_;
Handle<Object> storage_; // Always a global handle.
// Index after last seen index. Always less than or equal to
// JSObject::kMaxElementCount.
uint32_t index_offset_;
uint32_t bit_field_;
};
uint32_t EstimateElementCount(Isolate* isolate, Handle<JSArray> array) {
DisallowGarbageCollection no_gc;
uint32_t length = static_cast<uint32_t>(array->length().Number());
int element_count = 0;
switch (array->GetElementsKind()) {
case PACKED_SMI_ELEMENTS:
case HOLEY_SMI_ELEMENTS:
case PACKED_ELEMENTS:
case PACKED_FROZEN_ELEMENTS:
case PACKED_SEALED_ELEMENTS:
case PACKED_NONEXTENSIBLE_ELEMENTS:
case HOLEY_FROZEN_ELEMENTS:
case HOLEY_SEALED_ELEMENTS:
case HOLEY_NONEXTENSIBLE_ELEMENTS:
case HOLEY_ELEMENTS: {
// Fast elements can't have lengths that are not representable by
// a 32-bit signed integer.
DCHECK_GE(static_cast<int32_t>(FixedArray::kMaxLength), 0);
int fast_length = static_cast<int>(length);
FixedArray elements = FixedArray::cast(array->elements());
for (int i = 0; i < fast_length; i++) {
if (!elements.get(i).IsTheHole(isolate)) element_count++;
}
break;
}
case PACKED_DOUBLE_ELEMENTS:
case HOLEY_DOUBLE_ELEMENTS: {
// Fast elements can't have lengths that are not representable by
// a 32-bit signed integer.
DCHECK_GE(static_cast<int32_t>(FixedDoubleArray::kMaxLength), 0);
int fast_length = static_cast<int>(length);
if (array->elements().IsFixedArray()) {
DCHECK_EQ(FixedArray::cast(array->elements()).length(), 0);
break;
}
FixedDoubleArray elements = FixedDoubleArray::cast(array->elements());
for (int i = 0; i < fast_length; i++) {
if (!elements.is_the_hole(i)) element_count++;
}
break;
}
case DICTIONARY_ELEMENTS: {
NumberDictionary dictionary = NumberDictionary::cast(array->elements());
ReadOnlyRoots roots(isolate);
for (InternalIndex i : dictionary.IterateEntries()) {
Object key = dictionary.KeyAt(i);
if (dictionary.IsKey(roots, key)) {
element_count++;
}
}
break;
}
#define TYPED_ARRAY_CASE(Type, type, TYPE, ctype) case TYPE##_ELEMENTS:
TYPED_ARRAYS(TYPED_ARRAY_CASE)
#undef TYPED_ARRAY_CASE
// External arrays are always dense.
return length;
case NO_ELEMENTS:
return 0;
case FAST_SLOPPY_ARGUMENTS_ELEMENTS:
case SLOW_SLOPPY_ARGUMENTS_ELEMENTS:
case FAST_STRING_WRAPPER_ELEMENTS:
case SLOW_STRING_WRAPPER_ELEMENTS:
UNREACHABLE();
}
// As an estimate, we assume that the prototype doesn't contain any
// inherited elements.
return element_count;
}
void CollectElementIndices(Isolate* isolate, Handle<JSObject> object,
uint32_t range, std::vector<uint32_t>* indices) {
ElementsKind kind = object->GetElementsKind();
switch (kind) {
case PACKED_SMI_ELEMENTS:
case PACKED_ELEMENTS:
case PACKED_FROZEN_ELEMENTS:
case PACKED_SEALED_ELEMENTS:
case PACKED_NONEXTENSIBLE_ELEMENTS:
case HOLEY_SMI_ELEMENTS:
case HOLEY_FROZEN_ELEMENTS:
case HOLEY_SEALED_ELEMENTS:
case HOLEY_NONEXTENSIBLE_ELEMENTS:
case HOLEY_ELEMENTS: {
DisallowGarbageCollection no_gc;
FixedArray elements = FixedArray::cast(object->elements());
uint32_t length = static_cast<uint32_t>(elements.length());
if (range < length) length = range;
for (uint32_t i = 0; i < length; i++) {
if (!elements.get(i).IsTheHole(isolate)) {
indices->push_back(i);
}
}
break;
}
case HOLEY_DOUBLE_ELEMENTS:
case PACKED_DOUBLE_ELEMENTS: {
if (object->elements().IsFixedArray()) {
DCHECK_EQ(object->elements().length(), 0);
break;
}
Handle<FixedDoubleArray> elements(
FixedDoubleArray::cast(object->elements()), isolate);
uint32_t length = static_cast<uint32_t>(elements->length());
if (range < length) length = range;
for (uint32_t i = 0; i < length; i++) {
if (!elements->is_the_hole(i)) {
indices->push_back(i);
}
}
break;
}
case DICTIONARY_ELEMENTS: {
DisallowGarbageCollection no_gc;
NumberDictionary dict = NumberDictionary::cast(object->elements());
uint32_t capacity = dict.Capacity();
ReadOnlyRoots roots(isolate);
FOR_WITH_HANDLE_SCOPE(isolate, uint32_t, j = 0, j, j < capacity, j++, {
Object k = dict.KeyAt(InternalIndex(j));
if (!dict.IsKey(roots, k)) continue;
DCHECK(k.IsNumber());
uint32_t index = static_cast<uint32_t>(k.Number());
if (index < range) {
indices->push_back(index);
}
});
break;
}
#define TYPED_ARRAY_CASE(Type, type, TYPE, ctype) case TYPE##_ELEMENTS:
TYPED_ARRAYS(TYPED_ARRAY_CASE)
#undef TYPED_ARRAY_CASE
{
size_t length = Handle<JSTypedArray>::cast(object)->length();
if (range <= length) {
length = range;
// We will add all indices, so we might as well clear it first
// and avoid duplicates.
indices->clear();
}
// {range} puts a cap on {length}.
DCHECK_LE(length, std::numeric_limits<uint32_t>::max());
for (uint32_t i = 0; i < length; i++) {
indices->push_back(i);
}
if (length == range) return; // All indices accounted for already.
break;
}
case FAST_SLOPPY_ARGUMENTS_ELEMENTS:
case SLOW_SLOPPY_ARGUMENTS_ELEMENTS: {
DisallowGarbageCollection no_gc;
DisableGCMole no_gc_mole;
FixedArrayBase elements = object->elements();
JSObject raw_object = *object;
ElementsAccessor* accessor = object->GetElementsAccessor();
for (uint32_t i = 0; i < range; i++) {
if (accessor->HasElement(raw_object, i, elements)) {
indices->push_back(i);
}
}
break;
}
case FAST_STRING_WRAPPER_ELEMENTS:
case SLOW_STRING_WRAPPER_ELEMENTS: {
DCHECK(object->IsJSPrimitiveWrapper());
Handle<JSPrimitiveWrapper> js_value =
Handle<JSPrimitiveWrapper>::cast(object);
DCHECK(js_value->value().IsString());
Handle<String> string(String::cast(js_value->value()), isolate);
uint32_t length = static_cast<uint32_t>(string->length());
uint32_t i = 0;
uint32_t limit = std::min(length, range);
for (; i < limit; i++) {
indices->push_back(i);
}
ElementsAccessor* accessor = object->GetElementsAccessor();