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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: set ts=8 sts=2 et sw=2 tw=80:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/* JavaScript iterators. */
#include "vm/Iteration.h"
#include "mozilla/ArrayUtils.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/Likely.h"
#include "mozilla/Maybe.h"
#include "mozilla/MemoryReporting.h"
#include "mozilla/PodOperations.h"
#include <algorithm>
#include <new>
#include "jsapi.h"
#include "jstypes.h"
#include "builtin/Array.h"
#include "builtin/SelfHostingDefines.h"
#include "ds/Sort.h"
#include "gc/GCContext.h"
#include "js/ForOfIterator.h" // JS::ForOfIterator
#include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
#include "js/PropertySpec.h"
#include "util/DifferentialTesting.h"
#include "util/Poison.h"
#include "vm/GlobalObject.h"
#include "vm/Interpreter.h"
#include "vm/JSContext.h"
#include "vm/JSObject.h"
#include "vm/NativeObject.h" // js::PlainObject
#include "vm/Shape.h"
#include "vm/StringType.h"
#include "vm/TypedArrayObject.h"
#include "vm/WellKnownAtom.h" // js_*_str
#ifdef ENABLE_RECORD_TUPLE
# include "builtin/RecordObject.h"
# include "builtin/TupleObject.h"
#endif
#include "vm/NativeObject-inl.h"
#include "vm/PlainObject-inl.h" // js::PlainObject::createWithTemplate
using namespace js;
using mozilla::ArrayEqual;
using mozilla::DebugOnly;
using mozilla::Maybe;
using mozilla::PodCopy;
using RootedPropertyIteratorObject = Rooted<PropertyIteratorObject*>;
static const gc::AllocKind ITERATOR_FINALIZE_KIND =
gc::AllocKind::OBJECT2_BACKGROUND;
// Beware! This function may have to trace incompletely-initialized
// |NativeIterator| allocations if the |IdToString| in that constructor recurs
// into this code.
void NativeIterator::trace(JSTracer* trc) {
TraceNullableEdge(trc, &objectBeingIterated_, "objectBeingIterated_");
TraceNullableEdge(trc, &iterObj_, "iterObj");
// The limits below are correct at every instant of |NativeIterator|
// initialization, with the end-pointer incremented as each new shape is
// created, so they're safe to use here.
std::for_each(shapesBegin(), shapesEnd(), [trc](GCPtr<Shape*>& shape) {
TraceEdge(trc, &shape, "iterator_shape");
});
// But as properties must be created *before* shapes, |propertiesBegin()|
// that depends on |shapesEnd()| having its final value can't safely be
// used. Until this is fully initialized, use |propertyCursor_| instead,
// which points at the start of properties even in partially initialized
// |NativeIterator|s. (|propertiesEnd()| is safe at all times with respect
// to the properly-chosen beginning.)
//
// Note that we must trace all properties (not just those not yet visited,
// or just visited, due to |NativeIterator::previousPropertyWas|) for
// |NativeIterator|s to be reusable.
GCPtr<JSLinearString*>* begin =
MOZ_LIKELY(isInitialized()) ? propertiesBegin() : propertyCursor_;
std::for_each(begin, propertiesEnd(), [trc](GCPtr<JSLinearString*>& prop) {
// Properties begin life non-null and never *become*
// null. (Deletion-suppression will shift trailing
// properties over a deleted property in the properties
// array, but it doesn't null them out.)
TraceEdge(trc, &prop, "prop");
});
}
using PropertyKeySet = GCHashSet<PropertyKey, DefaultHasher<PropertyKey>>;
template <bool CheckForDuplicates>
static inline bool Enumerate(JSContext* cx, HandleObject pobj, jsid id,
bool enumerable, unsigned flags,
MutableHandle<PropertyKeySet> visited,
MutableHandleIdVector props) {
if (CheckForDuplicates) {
// If we've already seen this, we definitely won't add it.
PropertyKeySet::AddPtr p = visited.lookupForAdd(id);
if (MOZ_UNLIKELY(!!p)) {
return true;
}
// It's not necessary to add properties to the hash set at the end of
// the prototype chain, but custom enumeration behaviors might return
// duplicated properties, so always add in such cases.
if (pobj->is<ProxyObject>() || pobj->staticPrototype() ||
pobj->getClass()->getNewEnumerate()) {
if (!visited.add(p, id)) {
return false;
}
}
}
if (!enumerable && !(flags & JSITER_HIDDEN)) {
return true;
}
// Symbol-keyed properties and nonenumerable properties are skipped unless
// the caller specifically asks for them. A caller can also filter out
// non-symbols by asking for JSITER_SYMBOLSONLY. PrivateName symbols are
// skipped unless JSITER_PRIVATE is passed.
if (id.isSymbol()) {
if (!(flags & JSITER_SYMBOLS)) {
return true;
}
if (!(flags & JSITER_PRIVATE) && id.isPrivateName()) {
return true;
}
} else {
if ((flags & JSITER_SYMBOLSONLY)) {
return true;
}
}
return props.append(id);
}
static bool EnumerateExtraProperties(JSContext* cx, HandleObject obj,
unsigned flags,
MutableHandle<PropertyKeySet> visited,
MutableHandleIdVector props) {
MOZ_ASSERT(obj->getClass()->getNewEnumerate());
RootedIdVector properties(cx);
bool enumerableOnly = !(flags & JSITER_HIDDEN);
if (!obj->getClass()->getNewEnumerate()(cx, obj, &properties,
enumerableOnly)) {
return false;
}
RootedId id(cx);
for (size_t n = 0; n < properties.length(); n++) {
id = properties[n];
// The enumerate hook does not indicate whether the properties
// it returns are enumerable or not. Since we already passed
// `enumerableOnly` to the hook to filter out non-enumerable
// properties, it doesn't really matter what we pass here.
bool enumerable = true;
if (!Enumerate<true>(cx, obj, id, enumerable, flags, visited, props)) {
return false;
}
}
return true;
}
static bool SortComparatorIntegerIds(jsid a, jsid b, bool* lessOrEqualp) {
uint32_t indexA, indexB;
MOZ_ALWAYS_TRUE(IdIsIndex(a, &indexA));
MOZ_ALWAYS_TRUE(IdIsIndex(b, &indexB));
*lessOrEqualp = (indexA <= indexB);
return true;
}
template <bool CheckForDuplicates>
static bool EnumerateNativeProperties(JSContext* cx, Handle<NativeObject*> pobj,
unsigned flags,
MutableHandle<PropertyKeySet> visited,
MutableHandleIdVector props) {
// We don't need to iterate over the shape's properties if we're only
// interested in enumerable properties and the object is known to have no
// enumerable properties.
//
// Don't optimize if CheckForDuplicates is true, because non-enumerable
// properties still have to participate in duplicate-property checking.
const bool iterShapeProperties = CheckForDuplicates ||
(flags & JSITER_HIDDEN) ||
pobj->hasEnumerableProperty();
bool enumerateSymbols;
if (flags & JSITER_SYMBOLSONLY) {
if (!iterShapeProperties) {
return true;
}
enumerateSymbols = true;
} else {
// Collect any dense elements from this object.
size_t firstElemIndex = props.length();
size_t initlen = pobj->getDenseInitializedLength();
const Value* vp = pobj->getDenseElements();
bool hasHoles = false;
for (size_t i = 0; i < initlen; ++i, ++vp) {
if (vp->isMagic(JS_ELEMENTS_HOLE)) {
hasHoles = true;
} else {
// Dense arrays never get so large that i would not fit into an
// integer id.
if (!Enumerate<CheckForDuplicates>(cx, pobj, PropertyKey::Int(i),
/* enumerable = */ true, flags,
visited, props)) {
return false;
}
}
}
// Collect any typed array or shared typed array elements from this
// object.
if (pobj->is<TypedArrayObject>()) {
size_t len = pobj->as<TypedArrayObject>().length();
// Fail early if the typed array is enormous, because this will be very
// slow and will likely report OOM. This also means we don't need to
// handle indices greater than PropertyKey::IntMax in the loop below.
static_assert(PropertyKey::IntMax == INT32_MAX);
if (len > INT32_MAX) {
ReportOutOfMemory(cx);
return false;
}
for (size_t i = 0; i < len; i++) {
if (!Enumerate<CheckForDuplicates>(cx, pobj, PropertyKey::Int(i),
/* enumerable = */ true, flags,
visited, props)) {
return false;
}
}
}
#ifdef ENABLE_RECORD_TUPLE
else {
Rooted<RecordType*> rec(cx);
if (RecordObject::maybeUnbox(pobj, &rec)) {
Rooted<ArrayObject*> keys(cx, rec->keys());
for (size_t i = 0; i < keys->length(); i++) {
JSAtom* key = &keys->getDenseElement(i).toString()->asAtom();
PropertyKey id = AtomToId(key);
if (!Enumerate<CheckForDuplicates>(cx, pobj, id,
/* enumerable = */ true, flags,
visited, props)) {
return false;
}
}
return true;
} else {
mozilla::Maybe<TupleType&> tup = TupleObject::maybeUnbox(pobj);
if (tup) {
uint32_t len = tup->length();
for (size_t i = 0; i < len; i++) {
// We expect tuple indices not to get so large that `i` won't
// fit into an `int32_t`.
MOZ_ASSERT(PropertyKey::fitsInInt(i));
PropertyKey id = PropertyKey::Int(i);
if (!Enumerate<CheckForDuplicates>(cx, pobj, id,
/* enumerable = */ true, flags,
visited, props)) {
return false;
}
}
return true;
}
}
}
#endif
// The code below enumerates shape properties (including sparse elements) so
// if we can ignore those we're done.
if (!iterShapeProperties) {
return true;
}
// Collect any sparse elements from this object.
bool isIndexed = pobj->isIndexed();
if (isIndexed) {
// If the dense elements didn't have holes, we don't need to include
// them in the sort.
if (!hasHoles) {
firstElemIndex = props.length();
}
for (ShapePropertyIter<NoGC> iter(pobj->shape()); !iter.done(); iter++) {
jsid id = iter->key();
uint32_t dummy;
if (IdIsIndex(id, &dummy)) {
if (!Enumerate<CheckForDuplicates>(cx, pobj, id, iter->enumerable(),
flags, visited, props)) {
return false;
}
}
}
MOZ_ASSERT(firstElemIndex <= props.length());
jsid* ids = props.begin() + firstElemIndex;
size_t n = props.length() - firstElemIndex;
RootedIdVector tmp(cx);
if (!tmp.resize(n)) {
return false;
}
PodCopy(tmp.begin(), ids, n);
if (!MergeSort(ids, n, tmp.begin(), SortComparatorIntegerIds)) {
return false;
}
}
size_t initialLength = props.length();
/* Collect all unique property names from this object's shape. */
bool symbolsFound = false;
for (ShapePropertyIter<NoGC> iter(pobj->shape()); !iter.done(); iter++) {
jsid id = iter->key();
if (id.isSymbol()) {
symbolsFound = true;
continue;
}
uint32_t dummy;
if (isIndexed && IdIsIndex(id, &dummy)) {
continue;
}
if (!Enumerate<CheckForDuplicates>(cx, pobj, id, iter->enumerable(),
flags, visited, props)) {
return false;
}
}
std::reverse(props.begin() + initialLength, props.end());
enumerateSymbols = symbolsFound && (flags & JSITER_SYMBOLS);
}
if (enumerateSymbols) {
MOZ_ASSERT(iterShapeProperties);
// Do a second pass to collect symbols. ES6 draft rev 25 (2014 May 22)
// 9.1.12 requires that all symbols appear after all strings in the
// result.
size_t initialLength = props.length();
for (ShapePropertyIter<NoGC> iter(pobj->shape()); !iter.done(); iter++) {
jsid id = iter->key();
if (id.isSymbol()) {
if (!Enumerate<CheckForDuplicates>(cx, pobj, id, iter->enumerable(),
flags, visited, props)) {
return false;
}
}
}
std::reverse(props.begin() + initialLength, props.end());
}
return true;
}
static bool EnumerateNativeProperties(JSContext* cx, Handle<NativeObject*> pobj,
unsigned flags,
MutableHandle<PropertyKeySet> visited,
MutableHandleIdVector props,
bool checkForDuplicates) {
if (checkForDuplicates) {
return EnumerateNativeProperties<true>(cx, pobj, flags, visited, props);
}
return EnumerateNativeProperties<false>(cx, pobj, flags, visited, props);
}
template <bool CheckForDuplicates>
static bool EnumerateProxyProperties(JSContext* cx, HandleObject pobj,
unsigned flags,
MutableHandle<PropertyKeySet> visited,
MutableHandleIdVector props) {
MOZ_ASSERT(pobj->is<ProxyObject>());
RootedIdVector proxyProps(cx);
if (flags & JSITER_HIDDEN || flags & JSITER_SYMBOLS) {
// This gets all property keys, both strings and symbols. The call to
// Enumerate in the loop below will filter out unwanted keys, per the
// flags.
if (!Proxy::ownPropertyKeys(cx, pobj, &proxyProps)) {
return false;
}
Rooted<mozilla::Maybe<PropertyDescriptor>> desc(cx);
for (size_t n = 0, len = proxyProps.length(); n < len; n++) {
bool enumerable = false;
// We need to filter, if the caller just wants enumerable symbols.
if (!(flags & JSITER_HIDDEN)) {
if (!Proxy::getOwnPropertyDescriptor(cx, pobj, proxyProps[n], &desc)) {
return false;
}
enumerable = desc.isSome() && desc->enumerable();
}
if (!Enumerate<CheckForDuplicates>(cx, pobj, proxyProps[n], enumerable,
flags, visited, props)) {
return false;
}
}
return true;
}
// Returns enumerable property names (no symbols).
if (!Proxy::getOwnEnumerablePropertyKeys(cx, pobj, &proxyProps)) {
return false;
}
for (size_t n = 0, len = proxyProps.length(); n < len; n++) {
if (!Enumerate<CheckForDuplicates>(cx, pobj, proxyProps[n], true, flags,
visited, props)) {
return false;
}
}
return true;
}
#ifdef DEBUG
struct SortComparatorIds {
JSContext* const cx;
explicit SortComparatorIds(JSContext* cx) : cx(cx) {}
bool operator()(jsid aArg, jsid bArg, bool* lessOrEqualp) {
RootedId a(cx, aArg);
RootedId b(cx, bArg);
// Pick an arbitrary order on jsids that is as stable as possible
// across executions.
if (a == b) {
*lessOrEqualp = true;
return true;
}
enum class KeyType { Void, Int, String, Symbol };
auto keyType = [](PropertyKey key) {
if (key.isString()) {
return KeyType::String;
}
if (key.isInt()) {
return KeyType::Int;
}
if (key.isSymbol()) {
return KeyType::Symbol;
}
MOZ_ASSERT(key.isVoid());
return KeyType::Void;
};
if (keyType(a) != keyType(b)) {
*lessOrEqualp = (keyType(a) <= keyType(b));
return true;
}
if (a.isInt()) {
*lessOrEqualp = (a.toInt() <= b.toInt());
return true;
}
RootedString astr(cx), bstr(cx);
if (a.isSymbol()) {
MOZ_ASSERT(b.isSymbol());
JS::SymbolCode ca = a.toSymbol()->code();
JS::SymbolCode cb = b.toSymbol()->code();
if (ca != cb) {
*lessOrEqualp = uint32_t(ca) <= uint32_t(cb);
return true;
}
MOZ_ASSERT(ca == JS::SymbolCode::PrivateNameSymbol ||
ca == JS::SymbolCode::InSymbolRegistry ||
ca == JS::SymbolCode::UniqueSymbol);
astr = a.toSymbol()->description();
bstr = b.toSymbol()->description();
if (!astr || !bstr) {
*lessOrEqualp = !astr;
return true;
}
// Fall through to string comparison on the descriptions. The sort
// order is nondeterministic if two different unique symbols have
// the same description.
} else {
astr = IdToString(cx, a);
if (!astr) {
return false;
}
bstr = IdToString(cx, b);
if (!bstr) {
return false;
}
}
int32_t result;
if (!CompareStrings(cx, astr, bstr, &result)) {
return false;
}
*lessOrEqualp = (result <= 0);
return true;
}
};
#endif /* DEBUG */
static void AssertNoEnumerableProperties(NativeObject* obj) {
#ifdef DEBUG
// Verify the object has no enumerable properties if the HasEnumerable
// ObjectFlag is not set.
MOZ_ASSERT(!obj->hasEnumerableProperty());
static constexpr size_t MaxPropsToCheck = 5;
size_t count = 0;
for (ShapePropertyIter<NoGC> iter(obj->shape()); !iter.done(); iter++) {
MOZ_ASSERT(!iter->enumerable());
if (++count > MaxPropsToCheck) {
break;
}
}
#endif // DEBUG
}
// Typed arrays and classes with an enumerate hook can have extra properties not
// included in the shape's property map or the object's dense elements.
static bool ClassCanHaveExtraEnumeratedProperties(const JSClass* clasp) {
return IsTypedArrayClass(clasp) || clasp->getNewEnumerate() ||
clasp->getEnumerate();
}
static bool ProtoMayHaveEnumerableProperties(JSObject* obj) {
if (!obj->is<NativeObject>()) {
return true;
}
JSObject* proto = obj->as<NativeObject>().staticPrototype();
while (proto) {
if (!proto->is<NativeObject>()) {
return true;
}
NativeObject* nproto = &proto->as<NativeObject>();
if (nproto->hasEnumerableProperty() ||
nproto->getDenseInitializedLength() > 0 ||
ClassCanHaveExtraEnumeratedProperties(nproto->getClass())) {
return true;
}
AssertNoEnumerableProperties(nproto);
proto = nproto->staticPrototype();
}
return false;
}
static bool Snapshot(JSContext* cx, HandleObject pobj_, unsigned flags,
MutableHandleIdVector props) {
Rooted<PropertyKeySet> visited(cx, PropertyKeySet(cx));
RootedObject pobj(cx, pobj_);
// If we're only interested in enumerable properties and the proto chain has
// no enumerable properties (the common case), we can optimize this to ignore
// the proto chain. This also lets us take advantage of the no-duplicate-check
// optimization below.
if (!(flags & JSITER_HIDDEN) && !(flags & JSITER_OWNONLY) &&
!ProtoMayHaveEnumerableProperties(pobj)) {
flags |= JSITER_OWNONLY;
}
// Don't check for duplicates if we're only interested in own properties.
// This does the right thing for most objects: native objects don't have
// duplicate property ids and we allow the [[OwnPropertyKeys]] proxy trap to
// return duplicates.
//
// The only special case is when the object has a newEnumerate hook: it
// can return duplicate properties and we have to filter them. This is
// handled below.
bool checkForDuplicates = !(flags & JSITER_OWNONLY);
do {
if (pobj->getClass()->getNewEnumerate()) {
if (!EnumerateExtraProperties(cx, pobj, flags, &visited, props)) {
return false;
}
if (pobj->is<NativeObject>()) {
if (!EnumerateNativeProperties(cx, pobj.as<NativeObject>(), flags,
&visited, props, true)) {
return false;
}
}
} else if (pobj->is<NativeObject>()) {
// Give the object a chance to resolve all lazy properties
if (JSEnumerateOp enumerate = pobj->getClass()->getEnumerate()) {
if (!enumerate(cx, pobj.as<NativeObject>())) {
return false;
}
}
if (!EnumerateNativeProperties(cx, pobj.as<NativeObject>(), flags,
&visited, props, checkForDuplicates)) {
return false;
}
} else if (pobj->is<ProxyObject>()) {
if (checkForDuplicates) {
if (!EnumerateProxyProperties<true>(cx, pobj, flags, &visited, props)) {
return false;
}
} else {
if (!EnumerateProxyProperties<false>(cx, pobj, flags, &visited,
props)) {
return false;
}
}
} else {
MOZ_CRASH("non-native objects must have an enumerate op");
}
if (flags & JSITER_OWNONLY) {
break;
}
if (!GetPrototype(cx, pobj, &pobj)) {
return false;
}
// The [[Prototype]] chain might be cyclic.
if (!CheckForInterrupt(cx)) {
return false;
}
} while (pobj != nullptr);
#ifdef DEBUG
if (js::SupportDifferentialTesting()) {
/*
* In some cases the enumeration order for an object depends on the
* execution mode (interpreter vs. JIT), especially for native objects
* with a class enumerate hook (where resolving a property changes the
* resulting enumeration order). These aren't really bugs, but the
* differences can change the generated output and confuse correctness
* fuzzers, so we sort the ids if such a fuzzer is running.
*
* We don't do this in the general case because (a) doing so is slow,
* and (b) it also breaks the web, which expects enumeration order to
* follow the order in which properties are added, in certain cases.
* Since ECMA does not specify an enumeration order for objects, both
* behaviors are technically correct to do.
*/
jsid* ids = props.begin();
size_t n = props.length();
RootedIdVector tmp(cx);
if (!tmp.resize(n)) {
return false;
}
PodCopy(tmp.begin(), ids, n);
if (!MergeSort(ids, n, tmp.begin(), SortComparatorIds(cx))) {
return false;
}
}
#endif
return true;
}
JS_PUBLIC_API bool js::GetPropertyKeys(JSContext* cx, HandleObject obj,
unsigned flags,
MutableHandleIdVector props) {
return Snapshot(cx, obj,
flags & (JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS |
JSITER_SYMBOLSONLY | JSITER_PRIVATE),
props);
}
static inline void RegisterEnumerator(JSContext* cx, NativeIterator* ni) {
MOZ_ASSERT(ni->objectBeingIterated());
// Register non-escaping native enumerators (for-in) with the current
// context.
ni->link(cx->compartment()->enumeratorsAddr());
MOZ_ASSERT(!ni->isActive());
ni->markActive();
}
static PropertyIteratorObject* NewPropertyIteratorObject(JSContext* cx) {
const JSClass* clasp = &PropertyIteratorObject::class_;
Rooted<SharedShape*> shape(
cx,
SharedShape::getInitialShape(cx, clasp, cx->realm(), TaggedProto(nullptr),
ITERATOR_FINALIZE_KIND));
if (!shape) {
return nullptr;
}
JSObject* obj = NativeObject::create(
cx, ITERATOR_FINALIZE_KIND, GetInitialHeap(GenericObject, clasp), shape);
if (!obj) {
return nullptr;
}
PropertyIteratorObject* res = &obj->as<PropertyIteratorObject>();
// CodeGenerator::visitIteratorStartO assumes the iterator object is not
// inside the nursery when deciding whether a barrier is necessary.
MOZ_ASSERT(!js::gc::IsInsideNursery(res));
return res;
}
static inline size_t NumTrailingWords(size_t propertyCount, size_t shapeCount) {
static_assert(sizeof(GCPtr<JSLinearString*>) == sizeof(uintptr_t));
static_assert(sizeof(GCPtr<Shape*>) == sizeof(uintptr_t));
return propertyCount + shapeCount;
}
static inline size_t AllocationSize(size_t propertyCount, size_t shapeCount) {
return sizeof(NativeIterator) +
(NumTrailingWords(propertyCount, shapeCount) * sizeof(uintptr_t));
}
static PropertyIteratorObject* CreatePropertyIterator(
JSContext* cx, Handle<JSObject*> objBeingIterated, HandleIdVector props,
uint32_t numShapes, HashNumber shapesHash) {
if (props.length() > NativeIterator::PropCountLimit) {
ReportAllocationOverflow(cx);
return nullptr;
}
Rooted<PropertyIteratorObject*> propIter(cx, NewPropertyIteratorObject(cx));
if (!propIter) {
return nullptr;
}
void* mem = cx->pod_malloc_with_extra<NativeIterator, uintptr_t>(
NumTrailingWords(props.length(), numShapes));
if (!mem) {
return nullptr;
}
// This also registers |ni| with |propIter|.
bool hadError = false;
new (mem) NativeIterator(cx, propIter, objBeingIterated, props, numShapes,
shapesHash, &hadError);
if (hadError) {
return nullptr;
}
return propIter;
}
static HashNumber HashIteratorShape(Shape* shape) {
return DefaultHasher<Shape*>::hash(shape);
}
/**
* Initialize a fresh NativeIterator.
*
* This definition is a bit tricky: some parts of initializing are fallible, so
* as we initialize, we must carefully keep this in GC-safe state (see
* NativeIterator::trace).
*/
NativeIterator::NativeIterator(JSContext* cx,
Handle<PropertyIteratorObject*> propIter,
Handle<JSObject*> objBeingIterated,
HandleIdVector props, uint32_t numShapes,
HashNumber shapesHash, bool* hadError)
: objectBeingIterated_(objBeingIterated),
iterObj_(propIter),
// NativeIterator initially acts (before full initialization) as if it
// contains no shapes...
shapesEnd_(shapesBegin()),
// ...and no properties.
propertyCursor_(
reinterpret_cast<GCPtr<JSLinearString*>*>(shapesBegin() + numShapes)),
propertiesEnd_(propertyCursor_),
shapesHash_(shapesHash),
flagsAndCount_(
initialFlagsAndCount(props.length())) // note: no Flags::Initialized
{
// If there are shapes, the object and all objects on its prototype chain must
// be native objects. See CanCompareIterableObjectToCache.
MOZ_ASSERT_IF(numShapes > 0,
objBeingIterated && objBeingIterated->is<NativeObject>());
MOZ_ASSERT(!*hadError);
// NOTE: This must be done first thing: The caller can't free `this` on error
// because it has GCPtr fields whose barriers have already fired; the
// store buffer has pointers to them. Only the GC can free `this` (via
// PropertyIteratorObject::finalize).
propIter->initNativeIterator(this);
// The GC asserts on finalization that `this->allocationSize()` matches the
// `nbytes` passed to `AddCellMemory`. So once these lines run, we must make
// `this->allocationSize()` correct. That means infallibly initializing the
// shapes. It's OK for the constructor to fail after that.
size_t nbytes = AllocationSize(props.length(), numShapes);
AddCellMemory(propIter, nbytes, MemoryUse::NativeIterator);
if (numShapes > 0) {
// Construct shapes into the shapes array. Also recompute the shapesHash,
// which incorporates Shape* addresses that could have changed during a GC
// triggered in (among other places) |IdToString| above.
JSObject* pobj = objBeingIterated;
#ifdef DEBUG
uint32_t i = 0;
#endif
HashNumber shapesHash = 0;
do {
MOZ_ASSERT(pobj->is<NativeObject>());
Shape* shape = pobj->shape();
new (shapesEnd_) GCPtr<Shape*>(shape);
shapesEnd_++;
#ifdef DEBUG
i++;
#endif
shapesHash = mozilla::AddToHash(shapesHash, HashIteratorShape(shape));
// The one caller of this method that passes |numShapes > 0|, does
// so only if the entire chain consists of cacheable objects (that
// necessarily have static prototypes).
pobj = pobj->staticPrototype();
} while (pobj);
shapesHash_ = shapesHash;
MOZ_ASSERT(i == numShapes);
}
MOZ_ASSERT(static_cast<void*>(shapesEnd_) == propertyCursor_);
for (size_t i = 0, len = props.length(); i < len; i++) {
JSLinearString* str = IdToString(cx, props[i]);
if (!str) {
*hadError = true;
return;
}
new (propertiesEnd_) GCPtr<JSLinearString*>(str);
propertiesEnd_++;
}
markInitialized();
MOZ_ASSERT(!*hadError);
}
inline size_t NativeIterator::allocationSize() const {
size_t numShapes = shapesEnd() - shapesBegin();
return AllocationSize(initialPropertyCount(), numShapes);
}
/* static */
bool IteratorHashPolicy::match(PropertyIteratorObject* obj,
const Lookup& lookup) {
NativeIterator* ni = obj->getNativeIterator();
if (ni->shapesHash() != lookup.shapesHash ||
ni->shapeCount() != lookup.numShapes) {
return false;
}
return ArrayEqual(reinterpret_cast<Shape**>(ni->shapesBegin()), lookup.shapes,
ni->shapeCount());
}
static inline bool CanCompareIterableObjectToCache(JSObject* obj) {
if (obj->is<NativeObject>()) {
return obj->as<NativeObject>().getDenseInitializedLength() == 0;
}
return false;
}
static bool CanStoreInIteratorCache(JSObject* obj) {
do {
MOZ_ASSERT(obj->as<NativeObject>().getDenseInitializedLength() == 0);
// Typed arrays have indexed properties not captured by the Shape guard.
// Enumerate hooks may add extra properties.
if (MOZ_UNLIKELY(ClassCanHaveExtraEnumeratedProperties(obj->getClass()))) {
return false;
}
obj = obj->staticPrototype();
} while (obj);
return true;
}
static MOZ_ALWAYS_INLINE PropertyIteratorObject* LookupInIteratorCache(
JSContext* cx, JSObject* obj, uint32_t* numShapes) {
MOZ_ASSERT(*numShapes == 0);
if (obj->shape()->cache().isIterator() &&
CanCompareIterableObjectToCache(obj)) {
PropertyIteratorObject* iterobj = obj->shape()->cache().toIterator();
NativeIterator* ni = iterobj->getNativeIterator();
MOZ_ASSERT(*ni->shapesBegin() == obj->shape());
if (!ni->isReusable()) {
return nullptr;
}
// Verify shapes of proto chain.
JSObject* pobj = obj;
for (GCPtr<Shape*>* s = ni->shapesBegin() + 1; s != ni->shapesEnd(); s++) {
Shape* shape = *s;
pobj = pobj->staticPrototype();
if (pobj->shape() != shape) {
return nullptr;
}
if (!CanCompareIterableObjectToCache(pobj)) {
return nullptr;
}
}
MOZ_ASSERT(CanStoreInIteratorCache(obj));
return iterobj;
}
Vector<Shape*, 8> shapes(cx);
HashNumber shapesHash = 0;
JSObject* pobj = obj;
do {
if (!CanCompareIterableObjectToCache(pobj)) {
return nullptr;
}
MOZ_ASSERT(pobj->is<NativeObject>());
Shape* shape = pobj->shape();
shapesHash = mozilla::AddToHash(shapesHash, HashIteratorShape(shape));
if (MOZ_UNLIKELY(!shapes.append(shape))) {
cx->recoverFromOutOfMemory();
return nullptr;
}
pobj = pobj->staticPrototype();
} while (pobj);
MOZ_ASSERT(!shapes.empty());
*numShapes = shapes.length();
IteratorHashPolicy::Lookup lookup(shapes.begin(), shapes.length(),
shapesHash);
auto p = ObjectRealm::get(obj).iteratorCache.lookup(lookup);
if (!p) {
return nullptr;
}
PropertyIteratorObject* iterobj = *p;
MOZ_ASSERT(iterobj->compartment() == cx->compartment());
NativeIterator* ni = iterobj->getNativeIterator();
if (!ni->isReusable()) {
return nullptr;
}
return iterobj;
}
[[nodiscard]] static bool StoreInIteratorCache(
JSContext* cx, JSObject* obj, PropertyIteratorObject* iterobj) {
MOZ_ASSERT(CanStoreInIteratorCache(obj));
NativeIterator* ni = iterobj->getNativeIterator();
MOZ_ASSERT(ni->shapeCount() > 0);
obj->shape()->maybeCacheIterator(cx, iterobj);
IteratorHashPolicy::Lookup lookup(
reinterpret_cast<Shape**>(ni->shapesBegin()), ni->shapeCount(),
ni->shapesHash());
ObjectRealm::IteratorCache& cache = ObjectRealm::get(obj).iteratorCache;
bool ok;
auto p = cache.lookupForAdd(lookup);
if (MOZ_LIKELY(!p)) {
ok = cache.add(p, iterobj);
} else {
// If we weren't able to use an existing cached iterator, just
// replace it.
cache.remove(p);
ok = cache.relookupOrAdd(p, lookup, iterobj);
}
if (!ok) {
ReportOutOfMemory(cx);
return false;
}
return true;
}
bool js::EnumerateProperties(JSContext* cx, HandleObject obj,
MutableHandleIdVector props) {
MOZ_ASSERT(props.empty());
if (MOZ_UNLIKELY(obj->is<ProxyObject>())) {
return Proxy::enumerate(cx, obj, props);
}
return Snapshot(cx, obj, 0, props);
}
JSObject* js::GetIterator(JSContext* cx, HandleObject obj) {
MOZ_ASSERT(!obj->is<PropertyIteratorObject>());
MOZ_ASSERT(cx->compartment() == obj->compartment(),
"We may end up allocating shapes in the wrong zone!");
uint32_t numShapes = 0;
if (PropertyIteratorObject* iterobj =
LookupInIteratorCache(cx, obj, &numShapes)) {
NativeIterator* ni = iterobj->getNativeIterator();
ni->initObjectBeingIterated(*obj);
RegisterEnumerator(cx, ni);
return iterobj;
}
if (numShapes > 0 && !CanStoreInIteratorCache(obj)) {
numShapes = 0;
}
RootedIdVector keys(cx);
if (!EnumerateProperties(cx, obj, &keys)) {
return nullptr;
}
// If the object has dense elements, mark the dense elements as
// maybe-in-iteration.
//
// The iterator is a snapshot so if indexed properties are added after this
// point we don't need to do anything. However, the object might have sparse
// elements now that can be densified later. To account for this, we set the
// maybe-in-iteration flag also in NativeObject::maybeDensifySparseElements.
//
// In debug builds, AssertDenseElementsNotIterated is used to check the flag
// is set correctly.
if (obj->is<NativeObject>() &&
obj->as<NativeObject>().getDenseInitializedLength() > 0) {
obj->as<NativeObject>().markDenseElementsMaybeInIteration();
}
PropertyIteratorObject* iterobj =
CreatePropertyIterator(cx, obj, keys, numShapes, 0);
if (!iterobj) {
return nullptr;
}
RegisterEnumerator(cx, iterobj->getNativeIterator());
cx->check(iterobj);
#ifdef DEBUG
if (obj->is<NativeObject>()) {
if (PrototypeMayHaveIndexedProperties(&obj->as<NativeObject>())) {
iterobj->getNativeIterator()->setMaybeHasIndexedPropertiesFromProto();
}
}
#endif
// Cache the iterator object.
if (numShapes > 0) {
if (!StoreInIteratorCache(cx, obj, iterobj)) {
return nullptr;
}
}
return iterobj;
}
PropertyIteratorObject* js::LookupInIteratorCache(JSContext* cx,
HandleObject obj) {
uint32_t numShapes = 0;
return LookupInIteratorCache(cx, obj, &numShapes);
}
// ES 2017 draft 7.4.7.
PlainObject* js::CreateIterResultObject(JSContext* cx, HandleValue value,
bool done) {
// Step 1 (implicit).
// Step 2.
Rooted<PlainObject*> templateObject(
cx, GlobalObject::getOrCreateIterResultTemplateObject(cx));
if (!templateObject) {
return nullptr;
}
PlainObject* resultObj = PlainObject::createWithTemplate(cx, templateObject);
if (!resultObj) {
return nullptr;
}
// Step 3.
resultObj->setSlot(GlobalObject::IterResultObjectValueSlot, value);
// Step 4.
resultObj->setSlot(GlobalObject::IterResultObjectDoneSlot,
done ? TrueHandleValue : FalseHandleValue);
// Step 5.
return resultObj;
}
PlainObject* GlobalObject::getOrCreateIterResultTemplateObject(JSContext* cx) {
HeapPtr<PlainObject*>& obj = cx->global()->data().iterResultTemplate;
if (obj) {
return obj;
}
PlainObject* templateObj =
createIterResultTemplateObject(cx, WithObjectPrototype::Yes);
obj.init(templateObj);
return obj;
}
/* static */
PlainObject* GlobalObject::getOrCreateIterResultWithoutPrototypeTemplateObject(
JSContext* cx) {
HeapPtr<PlainObject*>& obj =
cx->global()->data().iterResultWithoutPrototypeTemplate;
if (obj) {
return obj;
}
PlainObject* templateObj =
createIterResultTemplateObject(cx, WithObjectPrototype::No);
obj.init(templateObj);
return obj;
}
/* static */
PlainObject* GlobalObject::createIterResultTemplateObject(
JSContext* cx, WithObjectPrototype withProto) {
// Create template plain object
Rooted<PlainObject*> templateObject(
cx, withProto == WithObjectPrototype::Yes
? NewPlainObject(cx, TenuredObject)
: NewPlainObjectWithProto(cx, nullptr));
if (!templateObject) {
return nullptr;
}
// Set dummy `value` property
if (!NativeDefineDataProperty(cx, templateObject, cx->names().value,
UndefinedHandleValue, JSPROP_ENUMERATE)) {
return nullptr;
}
// Set dummy `done` property
if (!NativeDefineDataProperty(cx, templateObject, cx->names().done,
TrueHandleValue, JSPROP_ENUMERATE)) {
return nullptr;
}
#ifdef DEBUG
// Make sure that the properties are in the right slots.
ShapePropertyIter<NoGC> iter(templateObject->shape());
MOZ_ASSERT(iter->slot() == GlobalObject::IterResultObjectDoneSlot &&
iter->key() == NameToId(cx->names().done));
iter++;
MOZ_ASSERT(iter->slot() == GlobalObject::IterResultObjectValueSlot &&
iter->key() == NameToId(cx->names().value));
#endif
return templateObject;
}
/*** Iterator objects *******************************************************/
size_t PropertyIteratorObject::sizeOfMisc(
mozilla::MallocSizeOf mallocSizeOf) const {
return mallocSizeOf(getNativeIterator());
}
void PropertyIteratorObject::trace(JSTracer* trc, JSObject* obj) {
if (NativeIterator* ni =
obj->as<PropertyIteratorObject>().getNativeIterator()) {
ni->trace(trc);
}
}
void PropertyIteratorObject::finalize(JS::GCContext* gcx, JSObject* obj) {
if (NativeIterator* ni =
obj->as<PropertyIteratorObject>().getNativeIterator()) {
gcx->free_(obj, ni, ni->allocationSize(), MemoryUse::NativeIterator);
}
}
const JSClassOps PropertyIteratorObject::classOps_ = {
nullptr, // addProperty
nullptr, // delProperty
nullptr, // enumerate
nullptr, // newEnumerate
nullptr, // resolve
nullptr, // mayResolve
finalize, // finalize
nullptr, // call
nullptr, // construct
trace, // trace
};
const JSClass PropertyIteratorObject::class_ = {
"Iterator",
JSCLASS_HAS_RESERVED_SLOTS(SlotCount) | JSCLASS_BACKGROUND_FINALIZE,
&PropertyIteratorObject::classOps_};
static const JSClass ArrayIteratorPrototypeClass = {"Array Iterator", 0};
enum {
ArrayIteratorSlotIteratedObject,
ArrayIteratorSlotNextIndex,
ArrayIteratorSlotItemKind,
ArrayIteratorSlotCount
};
const JSClass ArrayIteratorObject::class_ = {
"Array Iterator", JSCLASS_HAS_RESERVED_SLOTS(ArrayIteratorSlotCount)};
ArrayIteratorObject* js::NewArrayIteratorTemplate(JSContext* cx) {
RootedObject proto(
cx, GlobalObject::getOrCreateArrayIteratorPrototype(cx, cx->global()));
if (!proto) {
return nullptr;
}
return NewTenuredObjectWithGivenProto<ArrayIteratorObject>(cx, proto);
}
ArrayIteratorObject* js::NewArrayIterator(JSContext* cx) {
RootedObject proto(
cx, GlobalObject::getOrCreateArrayIteratorPrototype(cx, cx->global()));
if (!proto) {
return nullptr;
}
return NewObjectWithGivenProto<ArrayIteratorObject>(cx, proto);
}
static const JSFunctionSpec array_iterator_methods[] = {
JS_SELF_HOSTED_FN("next", "ArrayIteratorNext", 0, 0), JS_FS_END};
static const JSClass StringIteratorPrototypeClass = {"String Iterator", 0};
enum {
StringIteratorSlotIteratedObject,
StringIteratorSlotNextIndex,
StringIteratorSlotCount
};
const JSClass StringIteratorObject::class_ = {
"String Iterator", JSCLASS_HAS_RESERVED_SLOTS(StringIteratorSlotCount)};
static const JSFunctionSpec string_iterator_methods[] = {
JS_SELF_HOSTED_FN("next", "StringIteratorNext", 0, 0), JS_FS_END};
StringIteratorObject* js::NewStringIteratorTemplate(JSContext* cx) {
RootedObject proto(
cx, GlobalObject::getOrCreateStringIteratorPrototype(cx, cx->global()));
if (!proto) {
return nullptr;
}
return NewTenuredObjectWithGivenProto<StringIteratorObject>(cx, proto);
}
StringIteratorObject* js::NewStringIterator(JSContext* cx) {
RootedObject proto(
cx, GlobalObject::getOrCreateStringIteratorPrototype(cx, cx->global()));
if (!proto) {
return nullptr;
}
return NewObjectWithGivenProto<StringIteratorObject>(cx, proto);
}
static const JSClass RegExpStringIteratorPrototypeClass = {
"RegExp String Iterator", 0};
enum {
// The regular expression used for iteration. May hold the original RegExp
// object when it is reused instead of a new RegExp object.
RegExpStringIteratorSlotRegExp,
// The String value being iterated upon.
RegExpStringIteratorSlotString,
// The source string of the original RegExp object. Used to validate we can
// reuse the original RegExp object for matching.
RegExpStringIteratorSlotSource,
// The flags of the original RegExp object.
RegExpStringIteratorSlotFlags,
// When non-negative, this slot holds the current lastIndex position when
// reusing the original RegExp object for matching. When set to |-1|, the
// iterator has finished. When set to any other negative value, the
// iterator is not yet exhausted and we're not on the fast path and we're
// not reusing the input RegExp object.
RegExpStringIteratorSlotLastIndex,
RegExpStringIteratorSlotCount
};
static_assert(RegExpStringIteratorSlotRegExp ==
REGEXP_STRING_ITERATOR_REGEXP_SLOT,
"RegExpStringIteratorSlotRegExp must match self-hosting define "
"for regexp slot.");
static_assert(RegExpStringIteratorSlotString ==
REGEXP_STRING_ITERATOR_STRING_SLOT,
"RegExpStringIteratorSlotString must match self-hosting define "
"for string slot.");
static_assert(RegExpStringIteratorSlotSource ==
REGEXP_STRING_ITERATOR_SOURCE_SLOT,
"RegExpStringIteratorSlotString must match self-hosting define "
"for source slot.");
static_assert(RegExpStringIteratorSlotFlags ==
REGEXP_STRING_ITERATOR_FLAGS_SLOT,
"RegExpStringIteratorSlotFlags must match self-hosting define "
"for flags slot.");
static_assert(RegExpStringIteratorSlotLastIndex ==
REGEXP_STRING_ITERATOR_LASTINDEX_SLOT,
"RegExpStringIteratorSlotLastIndex must match self-hosting "
"define for lastIndex slot.");
const JSClass RegExpStringIteratorObject::class_ = {
"RegExp String Iterator",
JSCLASS_HAS_RESERVED_SLOTS(RegExpStringIteratorSlotCount)};
static const JSFunctionSpec regexp_string_iterator_methods[] = {
JS_SELF_HOSTED_FN("next", "RegExpStringIteratorNext", 0, 0),
JS_FS_END};
RegExpStringIteratorObject* js::NewRegExpStringIteratorTemplate(JSContext* cx) {
RootedObject proto(cx, GlobalObject::getOrCreateRegExpStringIteratorPrototype(
cx, cx->global()));
if (!proto) {
return nullptr;
}
return NewTenuredObjectWithGivenProto<RegExpStringIteratorObject>(cx, proto);
}
RegExpStringIteratorObject* js::NewRegExpStringIterator(JSContext* cx) {
RootedObject proto(cx, GlobalObject::getOrCreateRegExpStringIteratorPrototype(
cx, cx->global()));
if (!proto) {
return nullptr;
}
return NewObjectWithGivenProto<RegExpStringIteratorObject>(cx, proto);
}
// static
PropertyIteratorObject* GlobalObject::getOrCreateEmptyIterator(JSContext* cx) {
if (!cx->global()->data().emptyIterator) {
RootedIdVector props(cx); // Empty
PropertyIteratorObject* iter =
CreatePropertyIterator(cx, nullptr, props, 0, 0);
if (!iter) {
return nullptr;
}
iter->getNativeIterator()->markEmptyIteratorSingleton();
cx->global()->data().emptyIterator.init(iter);
}
return cx->global()->data().emptyIterator;
}
JSObject* js::ValueToIterator(JSContext* cx, HandleValue vp) {
RootedObject obj(cx);
if (vp.isObject()) {
/* Common case. */
obj = &vp.toObject();
} else if (vp.isNullOrUndefined()) {
/*
* Enumerating over null and undefined gives an empty enumerator, so
* that |for (var p in <null or undefined>) <loop>;| never executes
* <loop>, per ES5 12.6.4.
*/
return GlobalObject::getOrCreateEmptyIterator(cx);
} else {
obj = ToObject(cx, vp);
if (!obj) {
return nullptr;
}
}
return GetIterator(cx, obj);
}
void js::CloseIterator(JSObject* obj) {
if (!obj->is<PropertyIteratorObject>()) {
return;
}
// Remove iterator from the active list, which is a stack. The shared iterator
// used for for-in with null/undefined is immutable and unlinked.
NativeIterator* ni = obj->as<PropertyIteratorObject>().getNativeIterator();
if (ni->isEmptyIteratorSingleton()) {
return;
}
ni->unlink();
MOZ_ASSERT(ni->isActive());
ni->markInactive();
ni->clearObjectBeingIterated();
// Reset the enumerator; it may still be in the cached iterators for
// this thread and can be reused.
ni->resetPropertyCursorForReuse();
}
bool js::IteratorCloseForException(JSContext* cx, HandleObject obj) {
MOZ_ASSERT(cx->isExceptionPending());
bool isClosingGenerator = cx->isClosingGenerator();
JS::AutoSaveExceptionState savedExc(cx);
// Implements IteratorClose (ES 7.4.6) for exception unwinding. See
// also the bytecode generated by BytecodeEmitter::emitIteratorClose.
// Step 3.
//
// Get the "return" method.
RootedValue returnMethod(cx);
if (!GetProperty(cx, obj, obj, cx->names().return_, &returnMethod)) {
return false;
}
// Step 4.
//
// Do nothing if "return" is null or undefined. Throw a TypeError if the
// method is not IsCallable.
if (returnMethod.isNullOrUndefined()) {
return true;
}
if (!IsCallable(returnMethod)) {
return ReportIsNotFunction(cx, returnMethod);
}
// Step 5, 6, 8.
//
// Call "return" if it is not null or undefined.
RootedValue rval(cx);
bool ok = Call(cx, returnMethod, obj, &rval);
if (isClosingGenerator) {
// Closing an iterator is implemented as an exception, but in spec
// terms it is a Completion value with [[Type]] return. In this case
// we *do* care if the call threw and if it returned an object.
if (!ok) {
return false;
}
if (!rval.isObject()) {
return ThrowCheckIsObject(cx, CheckIsObjectKind::IteratorReturn);
}
} else {
// We don't care if the call threw or that it returned an Object, as
// Step 6 says if IteratorClose is being called during a throw, the
// original throw has primacy.
savedExc.restore();
}
return true;
}
void js::UnwindIteratorForUncatchableException(JSObject* obj) {
if (obj->is<PropertyIteratorObject>()) {
NativeIterator* ni = obj->as<PropertyIteratorObject>().getNativeIterator();
if (ni->isEmptyIteratorSingleton()) {
return;
}
ni->unlink();
}
}
static bool SuppressDeletedProperty(JSContext* cx, NativeIterator* ni,
HandleObject obj,
Handle<JSLinearString*> str) {
if (ni->objectBeingIterated() != obj) {
return true;
}
// Optimization for the following common case:
//
// for (var p in o) {
// delete o[p];
// }
//
// Note that usually both strings will be atoms so we only check for pointer
// equality here.
if (ni->previousPropertyWas(str)) {
return true;
}
while (true) {
bool restart = false;
// Check whether id is still to come.
GCPtr<JSLinearString*>* const cursor = ni->nextProperty();
GCPtr<JSLinearString*>* const end = ni->propertiesEnd();
for (GCPtr<JSLinearString*>* idp = cursor; idp < end; ++idp) {
// Common case: both strings are atoms.
if ((*idp)->isAtom() && str->isAtom()) {
if (*idp != str) {
continue;
}
} else {
if (!EqualStrings(*idp, str)) {
continue;
}
}
// Check whether another property along the prototype chain became
// visible as a result of this deletion.
RootedObject proto(cx);
if (!GetPrototype(cx, obj, &proto)) {
return false;
}
if (proto) {
RootedId id(cx);
RootedValue idv(cx, StringValue(*idp));
if (!PrimitiveValueToId<CanGC>(cx, idv, &id)) {
return false;
}
Rooted<mozilla::Maybe<PropertyDescriptor>> desc(cx);
RootedObject holder(cx);
if (!GetPropertyDescriptor(cx, proto, id, &desc, &holder)) {
return false;
}
if (desc.isSome() && desc->enumerable()) {
continue;
}
}
// If GetPropertyDescriptor above removed a property from ni, start
// over.
if (end != ni->propertiesEnd() || cursor != ni->nextProperty()) {
restart = true;
break;
}
// No property along the prototype chain stepped in to take the
// property's place, so go ahead and delete id from the list.
// If it is the next property to be enumerated, just skip it.
if (idp == cursor) {
ni->incCursor();
} else {
for (GCPtr<JSLinearString*>* p = idp; p + 1 != end; p++) {
*p = *(p + 1);
}
ni->trimLastProperty();
}
ni->markHasUnvisitedPropertyDeletion();
return true;
}
if (!restart) {
return true;
}
}
}
/*
* Suppress enumeration of deleted properties. This function must be called
* when a property is deleted and there might be active enumerators.
*
* We maintain a list of active non-escaping for-in enumerators. To suppress
* a property, we check whether each active enumerator contains the (obj, id)
* pair and has not yet enumerated |id|. If so, and |id| is the next property,
* we simply advance the cursor. Otherwise, we delete |id| from the list.
*
* We do not suppress enumeration of a property deleted along an object's
* prototype chain. Only direct deletions on the object are handled.
*/
static bool SuppressDeletedPropertyHelper(JSContext* cx, HandleObject obj,
Handle<JSLinearString*> str) {
NativeIteratorListIter iter(cx->compartment()->enumeratorsAddr());
while (!iter.done()) {
NativeIterator* ni = iter.next();
if (!SuppressDeletedProperty(cx, ni, obj, str)) {
return false;
}
}
return true;
}
bool js::SuppressDeletedProperty(JSContext* cx, HandleObject obj, jsid id) {
if (MOZ_LIKELY(!cx->compartment()->objectMaybeInIteration(obj))) {
return true;
}
if (id.isSymbol()) {
return true;
}
Rooted<JSLinearString*> str(cx, IdToString(cx, id));
if (!str) {
return false;
}
return SuppressDeletedPropertyHelper(cx, obj, str);
}
bool js::SuppressDeletedElement(JSContext* cx, HandleObject obj,
uint32_t index) {
if (MOZ_LIKELY(!cx->compartment()->objectMaybeInIteration(obj))) {
return true;
}
RootedId id(cx);
if (!IndexToId(cx, index, &id)) {
return false;
}
Rooted<JSLinearString*> str(cx, IdToString(cx, id));
if (!str) {
return false;
}
return SuppressDeletedPropertyHelper(cx, obj, str);
}
#ifdef DEBUG
void js::AssertDenseElementsNotIterated(NativeObject* obj) {
// Search for active iterators for |obj| and assert they don't contain any
// property keys that are dense elements. This is used to check correctness
// of the MAYBE_IN_ITERATION flag on ObjectElements.
//
// Ignore iterators that may contain indexed properties from objects on the
// prototype chain, as that can result in false positives. See bug 1656744.
// Limit the number of properties we check to avoid slowing down debug builds
// too much.
static constexpr uint32_t MaxPropsToCheck = 10;
uint32_t propsChecked = 0;
NativeIteratorListIter iter(obj->compartment()->enumeratorsAddr());
while (!iter.done()) {
NativeIterator* ni = iter.next();
if (ni->objectBeingIterated() == obj &&
!ni->maybeHasIndexedPropertiesFromProto()) {
for (GCPtr<JSLinearString*>* idp = ni->nextProperty();
idp < ni->propertiesEnd(); ++idp) {
uint32_t index;
if (idp->get()->isIndex(&index)) {
MOZ_ASSERT(!obj->containsDenseElement(index));
}
if (++propsChecked > MaxPropsToCheck) {
return;
}
}
}
}
}
#endif
static const JSFunctionSpec iterator_methods[] = {
JS_SELF_HOSTED_SYM_FN(iterator, "IteratorIdentity", 0, 0), JS_FS_END};
static const JSFunctionSpec iterator_static_methods[] = {
JS_SELF_HOSTED_FN("from", "IteratorFrom", 1, 0), JS_FS_END};
// These methods are only attached to Iterator.prototype when the
// Iterator Helpers feature is enabled.
static const JSFunctionSpec iterator_methods_with_helpers[] = {
JS_SELF_HOSTED_FN("map", "IteratorMap", 1, 0),
JS_SELF_HOSTED_FN("filter", "IteratorFilter", 1, 0),
JS_SELF_HOSTED_FN("take", "IteratorTake", 1, 0),
JS_SELF_HOSTED_FN("drop", "IteratorDrop", 1, 0),
JS_SELF_HOSTED_FN("asIndexedPairs", "IteratorAsIndexedPairs", 0, 0),
JS_SELF_HOSTED_FN("flatMap", "IteratorFlatMap", 1, 0),
JS_SELF_HOSTED_FN("reduce", "IteratorReduce", 1, 0),
JS_SELF_HOSTED_FN("toArray", "IteratorToArray", 0, 0),
JS_SELF_HOSTED_FN("forEach", "IteratorForEach", 1, 0),
JS_SELF_HOSTED_FN("some", "IteratorSome", 1, 0),
JS_SELF_HOSTED_FN("every", "IteratorEvery", 1, 0),
JS_SELF_HOSTED_FN("find", "IteratorFind", 1, 0),
JS_SELF_HOSTED_SYM_FN(iterator, "IteratorIdentity", 0, 0),
JS_FS_END};
/* static */
bool GlobalObject::initIteratorProto(JSContext* cx,
Handle<GlobalObject*> global) {
if (global->hasBuiltinProto(ProtoKind::IteratorProto)) {
return true;
}
RootedObject proto(
cx, GlobalObject::createBlankPrototype<PlainObject>(cx, global));
if (!proto) {
return false;
}
// %IteratorPrototype%.map.[[Prototype]] is %Generator% and
// %Generator%.prototype.[[Prototype]] is %IteratorPrototype%.
// Populate the slot early, to prevent runaway mutual recursion.
global->initBuiltinProto(ProtoKind::IteratorProto, proto);
if (!DefinePropertiesAndFunctions(cx, proto, nullptr, iterator_methods)) {
// In this case, we leave a partially initialized object in the
// slot. There's no obvious way to do better, since this object may already
// be in the prototype chain of %GeneratorPrototype%.
return false;
}
return true;
}
/* static */
template <GlobalObject::ProtoKind Kind, const JSClass* ProtoClass,
const JSFunctionSpec* Methods>
bool GlobalObject::initObjectIteratorProto(JSContext* cx,
Handle<GlobalObject*> global,
Handle<JSAtom*> tag) {
if (global->hasBuiltinProto(Kind)) {
return true;
}
RootedObject iteratorProto(
cx, GlobalObject::getOrCreateIteratorPrototype(cx, global));
if (!iteratorProto) {
return false;
}
RootedObject proto(cx, GlobalObject::createBlankPrototypeInheriting(
cx, ProtoClass, iteratorProto));
if (!proto || !DefinePropertiesAndFunctions(cx, proto, nullptr, Methods) ||
(tag && !DefineToStringTag(cx, proto, tag))) {
return false;
}
global->initBuiltinProto(Kind, proto);
return true;
}
/* static */
NativeObject* GlobalObject::getOrCreateArrayIteratorPrototype(
JSContext* cx, Handle<GlobalObject*> global) {
return MaybeNativeObject(getOrCreateBuiltinProto(
cx, global, ProtoKind::ArrayIteratorProto,
cx->names().ArrayIterator.toHandle(),
initObjectIteratorProto<ProtoKind::ArrayIteratorProto,
&ArrayIteratorPrototypeClass,
array_iterator_methods>));
}
/* static */
JSObject* GlobalObject::getOrCreateStringIteratorPrototype(
JSContext* cx, Handle<GlobalObject*> global) {
return getOrCreateBuiltinProto(
cx, global, ProtoKind::StringIteratorProto,
cx->names().StringIterator.toHandle(),
initObjectIteratorProto<ProtoKind::StringIteratorProto,
&StringIteratorPrototypeClass,
string_iterator_methods>);
}
/* static */
JSObject* GlobalObject::getOrCreateRegExpStringIteratorPrototype(
JSContext* cx, Handle<GlobalObject*> global) {
return getOrCreateBuiltinProto(
cx, global, ProtoKind::RegExpStringIteratorProto,
cx->names().RegExpStringIterator.toHandle(),
initObjectIteratorProto<ProtoKind::RegExpStringIteratorProto,
&RegExpStringIteratorPrototypeClass,
regexp_string_iterator_methods>);
}
// Iterator Helper Proposal 2.1.3.1 Iterator()
// https://tc39.es/proposal-iterator-helpers/#sec-iterator as of revision
// ed6e15a
static bool IteratorConstructor(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
// Step 1.
if (!ThrowIfNotConstructing(cx, args, js_Iterator_str)) {
return false;
}
// Throw TypeError if NewTarget is the active function object, preventing the
// Iterator constructor from being used directly.
if (args.callee() == args.newTarget().toObject()) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_BOGUS_CONSTRUCTOR, js_Iterator_str);
return false;
}
// Step 2.
RootedObject proto(cx);
if (!GetPrototypeFromBuiltinConstructor(cx, args, JSProto_Iterator, &proto)) {
return false;
}
JSObject* obj = NewObjectWithClassProto<IteratorObject>(cx, proto);
if (!obj) {
return false;
}
args.rval().setObject(*obj);
return true;
}
static const ClassSpec IteratorObjectClassSpec = {
GenericCreateConstructor<IteratorConstructor, 0, gc::AllocKind::FUNCTION>,
GenericCreatePrototype<IteratorObject>,
iterator_static_methods,
nullptr,
iterator_methods_with_helpers,
nullptr,
nullptr,
};
const JSClass IteratorObject::class_ = {
js_Iterator_str,
JSCLASS_HAS_CACHED_PROTO(JSProto_Iterator),
JS_NULL_CLASS_OPS,
&IteratorObjectClassSpec,
};
const JSClass IteratorObject::protoClass_ = {
"Iterator.prototype",
JSCLASS_HAS_CACHED_PROTO(JSProto_Iterator),
JS_NULL_CLASS_OPS,
&IteratorObjectClassSpec,
};
// Set up WrapForValidIteratorObject class and its prototype.
static const JSFunctionSpec wrap_for_valid_iterator_methods[] = {
JS_SELF_HOSTED_FN("next", "WrapForValidIteratorNext", 1, 0),
JS_SELF_HOSTED_FN("return", "WrapForValidIteratorReturn", 1, 0),
JS_SELF_HOSTED_FN("throw", "WrapForValidIteratorThrow", 1, 0),
JS_FS_END,
};
static const JSClass WrapForValidIteratorPrototypeClass = {
"Wrap For Valid Iterator", 0};
const JSClass WrapForValidIteratorObject::class_ = {
"Wrap For Valid Iterator",
JSCLASS_HAS_RESERVED_SLOTS(WrapForValidIteratorObject::SlotCount),
};
/* static */
NativeObject* GlobalObject::getOrCreateWrapForValidIteratorPrototype(
JSContext* cx, Handle<GlobalObject*> global) {
return MaybeNativeObject(getOrCreateBuiltinProto(
cx, global, ProtoKind::WrapForValidIteratorProto,
Handle<JSAtom*>(nullptr),
initObjectIteratorProto<ProtoKind::WrapForValidIteratorProto,
&WrapForValidIteratorPrototypeClass,
wrap_for_valid_iterator_methods>));
}
WrapForValidIteratorObject* js::NewWrapForValidIterator(JSContext* cx) {
RootedObject proto(cx, GlobalObject::getOrCreateWrapForValidIteratorPrototype(
cx, cx->global()));
if (!proto) {
return nullptr;
}
return NewObjectWithGivenProto<WrapForValidIteratorObject>(cx, proto);
}
// Common iterator object returned by Iterator Helper methods.
static const JSFunctionSpec iterator_helper_methods[] = {
JS_SELF_HOSTED_FN("next", "IteratorHelperNext", 1, 0),
JS_SELF_HOSTED_FN("return", "IteratorHelperReturn", 1, 0),
JS_SELF_HOSTED_FN("throw", "IteratorHelperThrow", 1, 0), JS_FS_END};
static const JSClass IteratorHelperPrototypeClass = {"Iterator Helper", 0};
const JSClass IteratorHelperObject::class_ = {
"Iterator Helper",
JSCLASS_HAS_RESERVED_SLOTS(IteratorHelperObject::SlotCount),
};
/* static */
NativeObject* GlobalObject::getOrCreateIteratorHelperPrototype(
JSContext* cx, Handle<GlobalObject*> global) {
return MaybeNativeObject(getOrCreateBuiltinProto(
cx, global, ProtoKind::IteratorHelperProto, Handle<JSAtom*>(nullptr),
initObjectIteratorProto<ProtoKind::IteratorHelperProto,
&IteratorHelperPrototypeClass,
iterator_helper_methods>));
}
IteratorHelperObject* js::NewIteratorHelper(JSContext* cx) {
RootedObject proto(
cx, GlobalObject::getOrCreateIteratorHelperPrototype(cx, cx->global()));
if (!proto) {
return nullptr;
}
return NewObjectWithGivenProto<IteratorHelperObject>(cx, proto);
}
bool js::IterableToArray(JSContext* cx, HandleValue iterable,
MutableHandle<ArrayObject*> array) {
JS::ForOfIterator iterator(cx);
if (!iterator.init(iterable, JS::ForOfIterator::ThrowOnNonIterable)) {
return false;
}
array.set(NewDenseEmptyArray(cx));
if (!array) {
return false;
}
RootedValue nextValue(cx);
while (true) {
bool done;
if (!iterator.next(&nextValue, &done)) {
return false;
}
if (done) {
break;
}
if (!NewbornArrayPush(cx, array, nextValue)) {
return false;
}
}
return true;
}
|