quickjs-pure 0.11.0

Embeddable JavaScript engine written in pure Rust (QuickJS-compatible)
Documentation
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
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
//! The standard library, asserted against fixed expectations.
//!
//! Every expected string was taken from the reference implementation
//! (`qjs -e …`). The file is organised by the object the behaviour belongs to, and
//! states the rules that are easy to get subtly wrong rather than restating the
//! happy path.

fn eval(source: &str) -> String {
    let rt = quickjs::Runtime::new();
    let mut ctx = quickjs::Context::new(&rt);
    match ctx.eval(source) {
        Ok(_) => ctx.output().to_string(),
        Err(error) => panic!(
            "{source:?} failed: {error}\noutput so far:\n{}",
            ctx.output()
        ),
    }
}

fn value(source: &str) -> String {
    let rt = quickjs::Runtime::new();
    let mut ctx = quickjs::Context::new(&rt);
    match ctx.eval(source) {
        Ok(value) => value.to_js_string(),
        Err(error) => panic!("{source:?} failed: {error}"),
    }
}

fn throws(source: &str) -> String {
    let rt = quickjs::Runtime::new();
    let mut ctx = quickjs::Context::new(&rt);
    match ctx.eval(source) {
        Ok(_) => panic!("{source:?} should have thrown"),
        Err(error) => error.to_string(),
    }
}

// ---------------------------------------------------------------------------
// Object
// ---------------------------------------------------------------------------

#[test]
fn object_keys_order_integers_first() {
    // The specification's order: integer-like keys ascending, then the rest in
    // insertion order. `for-in` and `Object.keys` share it.
    assert_eq!(
        eval("print(Object.keys({b:1,2:1,1:1}))"),
        "[ \"1\", \"2\", \"b\" ]\n"
    );
    assert_eq!(eval("print(Object.keys({z:1,a:2}))"), "[ \"z\", \"a\" ]\n");
    assert_eq!(eval("print(Object.keys([7,8]))"), "[ \"0\", \"1\" ]\n");
}

#[test]
fn object_tostring_uses_the_tag_not_the_class_field() {
    assert_eq!(
        eval("print(Object.prototype.toString.call([]))"),
        "[object Array]\n"
    );
    assert_eq!(
        eval(
            "print(Object.prototype.toString.call(null), Object.prototype.toString.call(undefined))"
        ),
        "[object Null] [object Undefined]\n"
    );
    assert_eq!(eval("print(String({}))"), "[object Object]\n");
}

#[test]
fn object_is_differs_from_strict_equals_only_on_nan_and_zero() {
    assert_eq!(
        eval("print(Object.is(1,1), Object.is(NaN,NaN), Object.is(0,-0), 0 === -0, NaN === NaN)"),
        "true true false true false\n"
    );
}

#[test]
fn define_property_defaults_every_attribute_to_false() {
    // A descriptor that omits `writable`/`enumerable`/`configurable` gets `false` for
    // each, which is why `defineProperty` can create an invisible property.
    assert_eq!(
        eval("var o={}; Object.defineProperty(o,'x',{value:1}); print(o.x, Object.keys(o).length)"),
        "1 0\n"
    );
    assert_eq!(
        eval(
            "var o={}; Object.defineProperty(o,'x',{value:1,enumerable:true}); print(Object.keys(o))"
        ),
        "[ \"x\" ]\n"
    );
}

#[test]
fn freeze_and_seal_differ_and_are_observable() {
    assert_eq!(
        eval("var o={a:1}; Object.freeze(o); print(Object.isFrozen(o), Object.isSealed(o))"),
        "true true\n"
    );
    assert_eq!(
        eval("var o={a:1}; Object.seal(o); print(Object.isFrozen(o), Object.isSealed(o))"),
        "false true\n"
    );
    assert_eq!(
        eval("var o={a:1}; Object.preventExtensions(o); o.b=2; print(o.b)"),
        "undefined\n"
    );
}

#[test]
fn a_frozen_array_refuses_writes() {
    // The write is silent in sloppy mode and a `TypeError` in strict mode, which is
    // the one place an assignment differs by mode.
    assert_eq!(
        eval("var a=[1,2]; Object.freeze(a); a[0]=9; print(a[0])"),
        "1\n"
    );
    assert_eq!(
        eval("'use strict'; var a=[1,2]; Object.freeze(a); try{a[0]=9}catch(e){print(e.name)}"),
        "TypeError\n"
    );
    // `sort` writes every element back, so it throws rather than returning quietly.
    assert_eq!(
        eval("try{Object.freeze([2,1]).sort()}catch(e){print(e.name)}"),
        "TypeError\n"
    );
}

/// The boundaries of the `put_array_el` fast path.
///
/// The fast path is one store instead of `propkey` (integer → string → parsed back) plus
/// a generic property write. Every test here is a store it must *refuse*, because the
/// answer depends on something only the slow path may look at — and refusing after the
/// operands are popped is how a stack got emptied silently.
#[test]
fn an_array_element_store_is_fast_but_not_too_fast() {
    // A hole filled in the dense prefix: fast, and `length` must not move.
    assert_eq!(
        eval("var a=new Array(3); a[1]='m'; print(a.length, a[1])"),
        "3 m
"
    );
    // Filling from the front is the shape the fast path exists for.
    assert_eq!(
        eval("var a=new Array(4); for(var i=0;i<4;i++)a[i]=i; print(a)"),
        "[ 0, 1, 2, 3 ]
"
    );
    // Past the length grows the array, which the fast path leaves to the slow path.
    assert_eq!(
        eval("var a=[]; a[5]=1; print(a.length, a)"),
        "6 [ 5: 1 ]
"
    );
    // A non-integer key is a property, not an element.
    assert_eq!(
        eval("var a=[]; a['x']=1; print(a.length, a.x)"),
        "0 1
"
    );

    // `preventExtensions` and `seal` both make a growing store a strict-mode `TypeError`.
    // The fast path must not swallow that: reporting `false` after popping the operands
    // left the slow path with an empty stack and no exception at all.
    assert_eq!(
        eval(
            "'use strict'; var b=[1,,3]; Object.preventExtensions(b); try{b[3]=9}catch(e){print(e.name)} print(b.length)"
        ),
        "TypeError\n3\n"
    );
    assert_eq!(
        eval(
            "'use strict'; var s=[1,,3]; Object.seal(s); try{s[5]=1}catch(e){print(e.name)} print(s.length)"
        ),
        "TypeError\n3\n"
    );
    // A typed array's elements are a window onto a buffer, not an element vector.
    assert_eq!(
        eval("var u=new Uint8Array(2); u[5]=1; print(u[5], u.length)"),
        "undefined 2
"
    );
}

/// `x++` on a loop counter, in every shape the fused arm has to handle or refuse.
///
/// The arm reads the slot in place and overwrites it in place — one borrow instead of
/// `get_loc` plus `put_loc`'s two, which was 32% of an empty `for (j = 0; j < n; j++)`.
/// It only does that for an *uncaptured* slot, so the cases below are the ones that have
/// to keep working: a captured counter goes back to the slow path, and a float or an
/// `i32` overflow leaves `Int` entirely.
#[test]
fn a_fused_increment_keeps_every_case_the_slow_path_handles() {
    // A captured counter: the closure must see the increments.
    assert_eq!(
        eval(
            "function o(){var i=0;var f=function(){return i};for(i=0;i<5;i++){}return [i,f()]} print(o())"
        ),
        "[ 5, 5 ]\n"
    );
    assert_eq!(
        eval(
            "function g(){var n=0;var get=function(){return n};for(var k=0;k<10;k++){n++}return [n,get()]} print(g())"
        ),
        "[ 10, 10 ]\n"
    );
    // `2147483647 + 1` leaves `Int` for `Float`, which is the arm's other branch.
    assert_eq!(
        eval("function b(){var x=2147483646;for(var k=0;k<3;k++){x++}return x} print(b())"),
        "2147483649\n"
    );
    // A float counter is not an `Int`, so the arm refuses and the slow path adds 1.0.
    assert_eq!(
        eval("var t=0.5; for(var k=0;k<3;k++){t++} print(t)"),
        "3.5\n"
    );
    // A string counter is `ToNumber` + `toString`, not `+ 1`.
    assert_eq!(
        eval("var s='1'; for(var k=0;k<2;k++){s++} print(typeof s, s)"),
        "number 3\n"
    );
}

/// The atom table is turned into property keys once, when the code is compiled.
///
/// `get_field x` needs `x` as a `PropertyKey`. Building it per read ran
/// `Wtf8::from_rc_str`, which allocates a fresh `Rc<[u8]>` and copies the bytes — a
/// `malloc` on every property read, 5.3% of `property:monomorphic`. The keys now live
/// beside the decoded instructions, so a read clones an `Rc` instead.
///
/// These are the cases that share that path and must keep their answers: plain fields,
/// integer atoms (a canonical index is *not* a string in the atom table), a key with an
/// unpaired surrogate, a prototype lookup, and the two ways a cached answer goes stale.
#[test]
fn an_atom_becomes_the_same_property_key_every_time() {
    assert_eq!(eval("var o={x:1,y:2}; print(o.x, o.y)"), "1 2\n");
    // `Atom::Index` holds the number, so its key has to be the decimal string.
    assert_eq!(
        eval("var n={}; n[0]='zero'; n[7]='seven'; print(n[0], n[7])"),
        "zero seven\n"
    );
    // A key with an unpaired surrogate is one property, not two that collide.
    assert_eq!(
        eval("var s={}; s['\\uD800']=1; print(s['\\uD800'], Object.keys(s).length)"),
        "1 1\n"
    );
    assert_eq!(
        eval("function P(){} P.prototype.z=9; print(new P().z)"),
        "9\n"
    );
    // Writing a property the cache already saw must not serve the old value.
    assert_eq!(eval("var c={v:1}; print(c.v); c.v=5; print(c.v)"), "1\n5\n");
    // Nor must adding one.
    assert_eq!(
        eval("var d={v:1}; print(d.v); d.w=2; print(d.v, d.w)"),
        "1\n1 2\n"
    );
}

/// `arguments` and `...rest` after the passed-value copy stopped being unconditional.
///
/// A frame used to copy every passed value into a second buffer, on every call, so that
/// `arguments` could see the ones `truncate` drops from the parameter slots. Now it
/// copies only when more were passed than the function declares — the rest of the time
/// `arguments` is a slice of the parameter slots. Everything below is a case where the
/// two buffers used to differ, or where the count matters rather than the values.
#[test]
fn arguments_sees_exactly_what_the_caller_passed() {
    // More than declared, fewer than declared, and none: the three counts.
    assert_eq!(
        eval("function a(){return arguments.length} print(a(1,2,3), a(), a(undefined))"),
        "3 0 1\n"
    );
    // A declared parameter does not fill `arguments` in.
    assert_eq!(
        eval("function b(x){return [arguments.length, x]} print(b(1), b(1,2,3), b())"),
        "[ 1, 1 ] [ 3, 1 ] [ 0, undefined ]\n"
    );
    // `...rest` slices from the passed values, not from the parameter slots.
    assert_eq!(
        eval("function c(...r){return r} print(c(1,2,3), c(), c(undefined))"),
        "[ 1, 2, 3 ] [  ] [ undefined ]\n"
    );
    // Indexing past the declared parameters.
    assert_eq!(
        eval("function d(x,y){return arguments[1]} print(d(1,2,3), d(1))"),
        "2 undefined\n"
    );
    // An extra argument that happens to equal the first: `arguments[0]` must be the
    // parameter's value, and both must still be the *same* value after a write.
    assert_eq!(
        eval("function e(x){return [x, arguments[0]]} print(e(9), e(9,8))"),
        "[ 9, 9 ] [ 9, 9 ]\n"
    );
}

// ---------------------------------------------------------------------------
// Array
// ---------------------------------------------------------------------------

#[test]
fn array_length_is_derived_and_holes_are_real() {
    assert_eq!(
        eval("var a=[1,2,3]; a.length=2; print(a, a.length)"),
        "[ 1, 2 ] 2\n"
    );
    // Growing leaves holes, which `forEach` skips and the printer reports.
    assert_eq!(eval("var a=[1]; a[3]=4; print(a)"), "[ 0: 1, 3: 4 ]\n");
    assert_eq!(
        eval("var n=0; [1,,3].forEach(function(){n++}); print(n)"),
        "2\n"
    );
    assert_eq!(eval("print([1,,3].length, [1,,3][1])"), "3 undefined\n");
}

#[test]
fn array_sort_defaults_to_string_order() {
    // The surprising part of the spec: without a comparator, elements compare as
    // strings, so `10` sorts before `9`.
    assert_eq!(eval("print([10,9,1].sort())"), "[ 1, 10, 9 ]\n");
    assert_eq!(
        eval("print([10,9,1].sort(function(a,b){return a-b}))"),
        "[ 1, 9, 10 ]\n"
    );
}

#[test]
fn array_iteration_methods_pass_the_receiver() {
    assert_eq!(
        eval("print([1,2,3].map(function(x){return x*2}))"),
        "[ 2, 4, 6 ]\n"
    );
    assert_eq!(
        eval("print([1,2,3].filter(function(x){return x>1}))"),
        "[ 2, 3 ]\n"
    );
    assert_eq!(
        eval("print([1,2,3].reduce(function(a,b){return a+b}))"),
        "6\n"
    );
    assert_eq!(
        eval("print([1,2,3].reduce(function(a,b){return a+b}, 10))"),
        "16\n"
    );
}

#[test]
fn an_array_method_works_on_any_array_like() {
    // The methods are generic in the spec, including a string receiver — whose
    // indices are read-only, which is why the mutating ones throw.
    assert_eq!(
        eval(r#"print(Array.prototype.join.call("abc"))"#),
        "a,b,c\n"
    );
    assert_eq!(
        eval(r#"print(Array.prototype.slice.call("abc",1))"#),
        "[ \"b\", \"c\" ]\n"
    );
    assert_eq!(
        eval(r#"try{Array.prototype.sort.call("aa")}catch(e){print(e.name)}"#),
        "TypeError\n"
    );
}

#[test]
fn array_iterators_are_lazy() {
    // A huge `length` must not be materialised: the loop only takes six steps.
    assert_eq!(
        eval(
            "var n=0; for (var k of Array.prototype.keys.call({length: 2**32+1})) { if (++n>5) break } print(n)"
        ),
        "6\n"
    );
    assert_eq!(eval("for (var x of [10,20].values()) print(x)"), "10\n20\n");
    assert_eq!(
        eval(r#"for (var e of ["a"].entries()) print(e)"#),
        "[ 0, \"a\" ]\n"
    );
}

// ---------------------------------------------------------------------------
// String
// ---------------------------------------------------------------------------

#[test]
fn string_index_family_treats_negatives_as_absent() {
    assert_eq!(
        eval(r#"print("a".charAt(-1) === "", "abc".charAt(1))"#),
        "true b\n"
    );
    assert_eq!(
        eval(r#"print("abc".charCodeAt(-1), "abc".charCodeAt(9))"#),
        "NaN NaN\n"
    );
    assert_eq!(eval(r#"print("abc".codePointAt(-1))"#), "undefined\n");
    // `indexOf` clamps a negative start to zero instead of counting from the end.
    assert_eq!(
        eval(r#"print("aaa".indexOf("a",-1), "aaa".lastIndexOf("a",-Infinity))"#),
        "0 0\n"
    );
}

#[test]
fn string_slicing_family_disagrees_on_negatives() {
    assert_eq!(eval(r#"print("abcdef".slice(-2))"#), "ef\n");
    assert_eq!(eval(r#"print("abcdef".substring(-2))"#), "abcdef\n");
    assert_eq!(eval(r#"print("abcdef".substr(-2))"#), "ef\n");
    // `substring` swaps its arguments; `slice` does not.
    assert_eq!(
        eval(r#"print("abcdef".substring(4,1), "abcdef".slice(4,1))"#),
        "bcd \n"
    );
}

#[test]
fn strings_count_utf16_code_units() {
    assert_eq!(eval(r#"print("😀".length)"#), "2\n");
    // A surrogate pair written as two escapes is the same string as the character.
    assert_eq!(eval(r#"print("\ud83d\ude00" === "😀")"#), "true\n");
    assert_eq!(
        eval(r#"print("\u{dbff}\u{dfff}" === "\u{10ffff}")"#),
        "true\n"
    );
    assert_eq!(
        eval(r#"print("😀".codePointAt(0), "😀".charCodeAt(0))"#),
        "128512 55357\n"
    );
}

#[test]
fn string_search_and_case() {
    assert_eq!(
        eval(r#"print("AbC".toLowerCase(), "abc".toUpperCase())"#),
        "abc ABC\n"
    );
    assert_eq!(eval(r#"print(" a ".trim() === "a")"#), "true\n");
    assert_eq!(
        eval(r#"print("ab".repeat(3), "5".padStart(3,"0"))"#),
        "ababab 005\n"
    );
    assert_eq!(eval(r#"print("a,b".split(","))"#), "[ \"a\", \"b\" ]\n");
    assert_eq!(eval(r#"print("abc".replace("b","X"))"#), "aXc\n");
}

// ---------------------------------------------------------------------------
// Number and Math
// ---------------------------------------------------------------------------

#[test]
fn number_formatting_rounds_halves_away_from_zero() {
    // Rust's formatter rounds halves to even, so these would be `2e+1` and `1.12`.
    assert_eq!(
        eval("print((25).toExponential(0), (-25).toExponential(0))"),
        "3e+1 -3e+1\n"
    );
    assert_eq!(
        eval("print((1.125).toFixed(2), (0.5).toFixed(0))"),
        "1.13 1\n"
    );
    assert_eq!(
        eval("print((25).toPrecision(1), (25).toPrecision(2))"),
        "3e+1 25\n"
    );
}

#[test]
fn number_to_string_in_other_radixes() {
    assert_eq!(
        eval("print((255).toString(16), (0.5).toString(2))"),
        "ff 0.1\n"
    );
    assert_eq!(eval("print((-255).toString(16))"), "-ff\n");
}

#[test]
fn number_to_string_radix_is_the_shortest_that_reads_back() {
    // Taken from the reference. Each of these is one digit short or one digit
    // misrounded by any conversion that decides "close enough" in floating point:
    // the error of the multiply-and-subtract loop compounds before the remainder
    // drops under half an ulp.
    assert_eq!(eval("print((1.3).toString(7))"), "1.2046204620462046205\n");
    assert_eq!(eval("print((1.3).toString(35))"), "1.ahhhhhhhhhm\n");
    assert_eq!(
        eval("print((1 - 2**-53).toString(12))"),
        "0.bbbbbbbbbbbbbba\n"
    );
    // Rounding up to `radix^digits` carries into an extra digit, which has to move the
    // radix point rather than print a trailing zero: `1/3` in radix 3 is `0.1`.
    assert_eq!(eval("print((1/3).toString(3))"), "0.1\n");
    // The smallest subnormal is exactly `2^-1074`; its magnitude underflows to zero
    // when rebuilt as `mantissa * 2^exponent`, which used to send the digit count
    // search off the end of the integer range.
    assert_eq!(eval("print((5e-324).toString(16).length)"), "271\n");
}

#[test]
fn math_round_and_sign_keep_negative_zero() {
    assert_eq!(eval("print(Math.round(-0.5), Math.round(0.5))"), "-0 1\n");
    assert_eq!(eval("print(1/Math.round(-0.4))"), "-Infinity\n");
    assert_eq!(eval("print(Math.min(0,-0), Math.max(0,-0))"), "-0 0\n");
    assert_eq!(eval("print(Math.min(1,NaN), Math.max(1,NaN))"), "NaN NaN\n");
    assert_eq!(
        eval("print(Math.floor(-0.5), Math.ceil(-0.5), Math.trunc(-0.5))"),
        "-1 -0 -0\n"
    );
}

#[test]
fn math_sum_precise_rounds_once() {
    // A compensated accumulator still rounds `1 + 2^-53` back to `1`; only an exact
    // sum rounded once produces the extra ulp.
    assert_eq!(
        eval("print(Math.sumPrecise([1, Number.EPSILON/2, Number.MIN_VALUE]))"),
        "1.0000000000000002\n"
    );
    assert_eq!(
        eval("print(Math.sumPrecise([]), Math.sumPrecise([0.1,0.2]))"),
        "-0 0.30000000000000004\n"
    );
}

#[test]
fn parse_int_stops_at_the_first_invalid_digit() {
    assert_eq!(
        eval("print(parseInt('12px'), parseInt('0x10'), parseInt('  42  '))"),
        "12 16 42\n"
    );
    assert_eq!(
        eval("print(parseInt('11',2), parseInt('z'), parseInt('10',1))"),
        "3 NaN NaN\n"
    );
    assert_eq!(
        eval("print(parseFloat('1.5x'), parseFloat('x'))"),
        "1.5 NaN\n"
    );
}

// ---------------------------------------------------------------------------
// JSON
// ---------------------------------------------------------------------------

#[test]
fn json_stringify_matches_the_reference_text() {
    assert_eq!(
        eval("print(JSON.stringify({a:1}))"),
        r#"{"a":1}"#.to_string() + "\n"
    );
    assert_eq!(eval("print(JSON.stringify([1,2]))"), "[1,2]\n");
    // A hole or `undefined` in an array becomes `null`; in an object it is omitted.
    assert_eq!(
        eval("print(JSON.stringify([undefined,null]))"),
        "[null,null]\n"
    );
    assert_eq!(
        eval("print(JSON.stringify({a:undefined,b:1}))"),
        r#"{"b":1}"#.to_string() + "\n"
    );
    assert_eq!(eval("print(JSON.stringify(undefined))"), "undefined\n");
    // `NaN` and the infinities serialise as `null`.
    assert_eq!(
        eval("print(JSON.stringify([NaN,Infinity]))"),
        "[null,null]\n"
    );
}

#[test]
fn json_stringify_indents_with_the_given_string() {
    assert_eq!(
        eval("print(JSON.stringify({a:1,b:[2]}, null, 2))"),
        "{\n  \"a\": 1,\n  \"b\": [\n    2\n  ]\n}\n"
    );
}

#[test]
fn json_parse_round_trips_and_rejects_garbage() {
    assert_eq!(eval(r#"print(JSON.parse('{"a":[1,2]}').a[1])"#), "2\n");
    assert_eq!(eval(r#"print(JSON.parse('"x"'))"#), "x\n");
    assert!(throws(r#"JSON.parse('{')"#).contains("SyntaxError"));
}

#[test]
fn json_stringify_honours_the_replacer() {
    // The array form filters by key, and only for strings and numbers.
    assert_eq!(
        eval(r#"print(JSON.stringify({a:1,b:2}, ["a"]))"#),
        r#"{"a":1}"#.to_string() + "\n"
    );
    // A nested object only keeps keys that are in the list too.
    assert_eq!(
        eval(r#"print(JSON.stringify({a:{b:1,c:2}}, ["a","b"]))"#),
        r#"{"a":{"b":1}}"#.to_string() + "\n"
    );
    // The function form may drop a key by answering `undefined`.
    assert_eq!(
        eval("print(JSON.stringify({a:1,b:2}, function(k,v){return k==='b'?undefined:v}))"),
        r#"{"a":1}"#.to_string() + "\n"
    );
    // Its `this` is the holder, so a sibling is readable.
    assert_eq!(
        eval("print(JSON.stringify({a:1}, function(k,v){return k===''?v:this.a}))"),
        r#"{"a":1}"#.to_string() + "\n"
    );
}

#[test]
fn json_parse_honours_the_reviver() {
    assert_eq!(
        eval("print(JSON.parse('{\"a\":1}', function(k,v){return typeof v==='number'?v*2:v}).a)"),
        "2\n"
    );
    // Answering `undefined` deletes the property.
    assert_eq!(
        eval(
            "print(JSON.stringify(JSON.parse('{\"a\":1,\"b\":2}', \
             function(k,v){return k==='a'?undefined:v})))"
        ),
        r#"{"b":2}"#.to_string() + "\n"
    );
}

#[test]
fn json_rejects_a_raw_control_character_in_a_string() {
    // The grammar requires the escape form; a literal tab is not valid JSON. The source
    // passed to `eval` here has a real backslash-t inside the JSON text, which the *JSON*
    // parser then evaluates -- so the first call has a raw tab and the second an escape.
    assert!(throws("JSON.parse('\"a\tb\"')").contains("SyntaxError"));
    // The escaped form decodes to three characters: `a`, the tab, `b`.
    assert_eq!(eval("print(JSON.parse('\"a\\\\tb\"').length)"), "3\n");
}

#[test]
fn sort_keeps_holes_at_the_end() {
    // A hole is not `undefined`: it sorts after every present element, and the comparator
    // is never called for it.
    assert_eq!(
        eval("var x=new Array(2); x[1]=1; x.sort(function(a,b){return a-b}); print(0 in x, x[0])"),
        "true 1\n"
    );
    assert_eq!(
        eval("var y=[3,,1]; y.sort(); print(JSON.stringify(y), 2 in y)"),
        "[1,3,null] false\n"
    );
}

// ---------------------------------------------------------------------------
// Function and Reflect
// ---------------------------------------------------------------------------

#[test]
fn bind_carries_this_and_leading_arguments() {
    assert_eq!(
        eval("function f(a,b){return [this,a,b]} var g=f.bind(1,2); print(g(3).join(','))"),
        "1,2,3\n"
    );
    assert_eq!(
        eval("function f(a,b){return a+b} print(f.bind(null,1)(2))"),
        "3\n"
    );
    assert_eq!(
        eval("function f(a,b){} print(f.bind(null,1).length)"),
        "1\n"
    );
    assert_eq!(eval("function f(){} print(f.bind(null).name)"), "bound f\n");
    assert_eq!(
        eval("print(typeof (function(){}).bind(null))"),
        "function\n"
    );
}

#[test]
fn apply_and_call_differ_on_their_argument_list() {
    // `Function.prototype.apply` accepts `undefined` as an empty list;
    // `Reflect.apply` requires one.
    assert_eq!(
        eval("print((function(){return 1}).apply(null, undefined))"),
        "1\n"
    );
    assert_eq!(
        eval("try{Reflect.apply(function(){return 1}, null, undefined)}catch(e){print(e.name)}"),
        "TypeError\n"
    );
    assert_eq!(
        eval("print((function(a,b){return a+b}).call(null,1,2))"),
        "3\n"
    );
}

#[test]
fn sloppy_mode_boxes_a_primitive_receiver() {
    assert_eq!(
        eval("function f(){return typeof this} print(f.call(1))"),
        "object\n"
    );
    assert_eq!(
        eval("'use strict'; function f(){return typeof this} print(f.call(1))"),
        "number\n"
    );
}

// ---------------------------------------------------------------------------
// Builtins as a whole
// ---------------------------------------------------------------------------

#[test]
fn arguments_reports_what_was_passed() {
    assert_eq!(
        eval("function f(){return arguments.length} print(f(1,2,3), f())"),
        "3 0\n"
    );
    // A declared parameter count does not change what `arguments` holds.
    assert_eq!(
        eval("function f(a){return arguments.length} print(f(1,2))"),
        "2\n"
    );
    assert_eq!(
        eval("function f(){return arguments[1]} print(f(7,8))"),
        "8\n"
    );
}

#[test]
fn method_names_are_not_enumerable() {
    // Otherwise `for (k in [])` would list a hundred built-ins and `JSON.stringify`
    // would serialise them.
    assert_eq!(eval("var n=0; for (var k in []) n++; print(n)"), "0\n");
    assert_eq!(eval("var n=0; for (var k in {a:1}) n++; print(n)"), "1\n");
}

#[test]
fn a_script_can_use_the_whole_library_together() {
    let source = r#"
        var data = [{n: "a", v: 3}, {n: "b", v: 1}, {n: "c", v: 2}];
        var sorted = data.slice().sort(function (x, y) { return x.v - y.v });
        var names = sorted.map(function (o) { return o.n });
        print(names.join("-"));
        print(JSON.stringify(sorted.map(function (o) { return o.v })));
        print(Math.max.apply(null, sorted.map(function (o) { return o.v })));
    "#;
    assert_eq!(eval(source), "b-c-a\n[1,2,3]\n3\n");
}

#[test]
fn an_uncaught_error_names_its_class() {
    assert_eq!(
        eval("try{null.x}catch(e){print(e instanceof TypeError, e.name)}"),
        "true TypeError\n"
    );
    assert_eq!(
        eval("try{throw new RangeError('bad')}catch(e){print(e.name, e.message)}"),
        "RangeError bad\n"
    );
    assert_eq!(
        value("try{null.x}catch(e){e.toString()}"),
        "TypeError: cannot read property 'x' of null"
    );
}

// ---------------------------------------------------------------------------
// Language semantics that the builtins exposed
// ---------------------------------------------------------------------------

#[test]
fn block_scoped_bindings_do_not_leak_or_shadow() {
    // A `let` belongs to its block. Regressing this made `{ let x }` shadow the
    // outer `x` for the rest of the function, which is worse than not supporting
    // blocks at all: the program kept running with the wrong answer.
    assert_eq!(eval("var x=1; { let x=2; } print(x)"), "1\n");
    assert_eq!(eval("{ let y=2; } print(typeof y)"), "undefined\n");
    assert_eq!(eval("let z=1; { let z=2; } print(z)"), "1\n");
    assert_eq!(
        eval("for (let i=0;i<1;i++){} print(typeof i)"),
        "undefined\n"
    );
    assert_eq!(
        eval("{ let s=1; { let s=2; print(s) } print(s) }"),
        "2\n1\n"
    );
    // …and an inner block still sees the outer binding shadowed by its own.
    assert_eq!(eval("var x=1; { let x=2; print(x) } print(x)"), "2\n1\n");
    assert_eq!(
        eval("function f(){ { let a=1 } return typeof a } print(f())"),
        "undefined\n"
    );
}

#[test]
fn const_is_read_only_after_initialisation() {
    assert_eq!(
        eval("try{ const c=1; c=2 }catch(e){print(e.name, e.message)}"),
        "TypeError 'c' is read-only\n"
    );
    // A closure writing it is caught too, which needs the realm to remember the
    // declaration: the closure's own entry does not carry the `const` flag.
    assert_eq!(
        eval("const c=1; var f=function(){c=2}; try{f()}catch(e){print(e.name)}"),
        "TypeError\n"
    );
    // The initialiser itself must go through, and so must mutating the value.
    assert_eq!(eval("const o={}; o.x=1; print(o.x)"), "1\n");
}

#[test]
fn var_globals_are_properties_of_the_global_object() {
    // The observable half of the split between `var` (on the global object) and
    // `let` (in the global lexical environment, invisible there).
    assert_eq!(eval("var v=1; print(globalThis.v)"), "1\n");
    assert_eq!(eval("var v=1; globalThis.v=3; print(v)"), "3\n");
    assert_eq!(
        eval("let n=2; print(globalThis.n, 'n' in globalThis)"),
        "undefined false\n"
    );
    // Writable and enumerable, but not configurable.
    assert_eq!(eval("var v=1; print(delete globalThis.v, v)"), "false 1\n");
    // Hoisted: it exists, holding `undefined`, before its initialiser runs.
    assert_eq!(eval("print(v); var v=1"), "undefined\n");
    assert_eq!(
        eval("function f(){} print(typeof globalThis.f)"),
        "function\n"
    );
    // An implicit global is the one that *is* configurable.
    assert_eq!(eval("x=1; print(x, delete globalThis.x)"), "1 true\n");
}

#[test]
fn delete_removes_properties_and_leaves_holes() {
    assert_eq!(
        eval("var o={a:1}; print(delete o.a, o.a)"),
        "true undefined\n"
    );
    // An array index becomes a hole: the length stays and `in` starts answering false.
    assert_eq!(
        eval("var a=[1,2,3]; delete a[1]; print(a.length, 1 in a, a[1])"),
        "3 false undefined\n"
    );
    // A non-configurable property refuses and says so.
    assert_eq!(
        eval("var o={}; Object.defineProperty(o,'x',{value:1}); print(delete o.x)"),
        "false\n"
    );
    // Deleting a binding always fails; nothing to do at run time.
    assert_eq!(
        eval("function f(x){return delete x} print(f(1))"),
        "false\n"
    );
}

#[test]
fn loose_equality_converts_objects_but_not_object_to_object() {
    assert_eq!(
        eval("print([]=='', [1]=='1', [1,2]=='1,2')"),
        "true true true\n"
    );
    assert_eq!(
        eval("var a={},b={}; print(a===b, a==b, a==a)"),
        "false false true\n"
    );
    assert_eq!(
        eval("print(null==undefined, null===undefined)"),
        "true false\n"
    );
    assert_eq!(eval("print([0]==false, '0'==false)"), "true true\n");
}

#[test]
fn unsigned_shift_produces_a_non_negative_number() {
    // `>>>` is the unsigned shift, so its result can exceed `i32::MAX` and must not
    // be squeezed back into a negative int.
    assert_eq!(
        eval("print(1<<31, (1<<31)>>>0)"),
        "-2147483648 2147483648\n"
    );
    assert_eq!(eval("print(-1>>>0, -1>>0)"), "4294967295 -1\n");
    assert_eq!(eval("print(7>>>1, 0xdeadbeef>>>0)"), "3 3735928559\n");
}

#[test]
fn spread_appends_whatever_the_iterable_yields() {
    assert_eq!(eval(r#"print([..."ab"])"#), "[ \"a\", \"b\" ]\n");
    assert_eq!(eval("print([0,...[1,2],3])"), "[ 0, 1, 2, 3 ]\n");
    assert_eq!(eval("print([...[]].length)"), "0\n");
    // A hole is yielded as `undefined`, so the spread fills it in for real.
    assert_eq!(eval("print([...[1,,3]])"), "[ 1, undefined, 3 ]\n");
}

#[test]
fn named_function_expressions_bind_their_own_name() {
    assert_eq!(
        eval("var f=function g(){return typeof g}; print(f(), typeof g)"),
        "function undefined\n"
    );
    // Recursion through the self-binding works even when the outer name is rebound.
    assert_eq!(
        eval("print((function f(n){return n<2?1:n*f(n-1)})(5))"),
        "120\n"
    );
    assert_eq!(
        eval("var f=function g(){return g===f}; print(f())"),
        "true\n"
    );
}

#[test]
fn array_constructor_validates_its_length_argument() {
    assert_eq!(
        eval("try{new Array(-1)}catch(e){print(e.name)}"),
        "RangeError\n"
    );
    assert_eq!(
        eval("try{new Array(1.5)}catch(e){print(e.name)}"),
        "RangeError\n"
    );
    assert_eq!(eval("print(Array(3).length, Array(3,4).length)"), "3 2\n");
    assert_eq!(eval("print(2 in new Array(3))"), "false\n");
}

#[test]
fn string_conversion_runs_to_primitive() {
    assert_eq!(
        eval(r#"print(String({toString:function(){return "T"}}))"#),
        "T\n"
    );
    assert_eq!(eval(r#"print(String(new Error("m")))"#), "Error: m\n");
}

#[test]
fn a_for_let_loop_binds_freshly_each_iteration() {
    // `let` in a `for` head creates a new binding per iteration, so a closure made in
    // the body captures that iteration's value. Sharing one binding — which is what
    // happens with `var` — gives the final value everywhere.
    assert_eq!(
        eval(
            "var a=[];for(let i=0;i<3;i++)a.push(function(){return i});print(a[0](),a[1](),a[2]())"
        ),
        "0 1 2\n"
    );
    assert_eq!(
        eval(
            "var a=[];for(var i=0;i<3;i++)a.push(function(){return i});print(a[0](),a[1](),a[2]())"
        ),
        "3 3 3\n"
    );
    // A block-scoped binding is frozen when its block ends, so a closure made inside
    // keeps the value it had then.
    assert_eq!(
        eval("var f; { let x=1; f=function(){return x} } print(f())"),
        "1\n"
    );
    // A loop variable that no closure captures needs no per-iteration cell at all.
    assert_eq!(eval("var n=0;for(let i=0;i<3;i++)n++;print(n)"), "3\n");
}

// ---------------------------------------------------------------------------
// Date
// ---------------------------------------------------------------------------

#[test]
fn date_parses_both_grammars() {
    // ISO form, then the lenient one the reference also accepts.
    assert_eq!(value("Date.parse('1970-01-01T00:30:00Z')"), "1800000");
    assert_eq!(value("Date.parse('1970-01-01T00:30:00+00:30')"), "0");
    // An explicit zone wins over the local one, whatever this machine's zone is.
    assert_eq!(value("Date.parse('Jan 1 1970 00:30:00 UTC')"), "1800000");
    // Out-of-range fields are not repaired.
    assert_eq!(value("Date.parse('1970-13-01')"), "NaN");
    assert_eq!(value("Date.parse('1970-01-01T24:00:01Z')"), "NaN");
    // The fractional part is truncated to milliseconds, not rounded.
    assert_eq!(
        value("new Date('2020-01-01T01:01:01.9999Z').toISOString()"),
        "2020-01-01T01:01:01.999Z"
    );
}

#[test]
fn date_make_time_keeps_the_specified_operation_order() {
    // test262's fp-evaluation-order case: the products in `MakeTime` may not be
    // fused or reordered, or these two answers change.
    assert_eq!(
        value("Date.UTC(1970, 0, 1, 80063993375, 29, 1, -288230376151711740)"),
        "29312"
    );
    assert_eq!(
        value("Date.UTC(1970, 0, 213503982336, 0, 0, 0, -18446744073709552000)"),
        "34447360"
    );
}

#[test]
fn date_local_and_utc_halves_agree_at_the_epoch() {
    // Whatever this machine's zone is, breaking a time into local fields and putting
    // those fields back through the local-time constructor must return the same
    // instant. This is the round trip the two halves have to agree on.
    assert_eq!(
        eval(
            "var d = new Date(0)\n\
              var e = new Date(d.getFullYear(), d.getMonth(), d.getDate(),\n\
                               d.getHours(), d.getMinutes(), d.getSeconds(),\n\
                               d.getMilliseconds())\n\
              print(e.getTime() === d.getTime())"
        ),
        "true\n"
    );
    // The UTC half is zone-independent.
    assert_eq!(
        value("new Date(0).toISOString()"),
        "1970-01-01T00:00:00.000Z"
    );
}

#[test]
fn date_printing_and_serialisation() {
    assert_eq!(
        value("String(new Date(0).toISOString())"),
        "1970-01-01T00:00:00.000Z"
    );
    // `print` shows a Date as its ISO string, the way the reference's value printer
    // does, and `JSON.stringify` goes through `toJSON`.
    assert_eq!(eval("print(new Date(0))"), "1970-01-01T00:00:00.000Z\n");
    assert_eq!(
        value("JSON.stringify({d: new Date(0)})"),
        "{\"d\":\"1970-01-01T00:00:00.000Z\"}"
    );
    // An invalid Date prints as an object and serialises to `null`, because
    // `toJSON` answers `null` for a non-finite time value.
    assert_eq!(value("new Date(NaN).toJSON()"), "null");
    assert_eq!(value("new Date(NaN).toString()"), "Invalid Date");
    assert_eq!(
        throws("new Date(NaN).toISOString()"),
        "RangeError: Date value is NaN\n    at toISOString (native)\n    \
         at <eval> (<input>:1:26)"
    );
}

#[test]
fn date_is_tagged_and_its_default_hint_is_json_safe() {
    assert_eq!(
        value("Object.prototype.toString.call(new Date(0))"),
        "[object Date]"
    );
    assert_eq!(
        value("Object.prototype.toString.call(new Error('x'))"),
        "[object Error]"
    );
    // The default hint converts a Date to a *string*, so `"" + d` is not the number.
    assert_eq!(
        value("'' + new Date(0).toISOString()"),
        "1970-01-01T00:00:00.000Z"
    );
    assert_eq!(value("typeof ('' + new Date(0))"), "string");
    // A Date method on a non-Date is a TypeError, not a silent coercion.
    assert_eq!(
        throws("Date.prototype.getTime.call({})"),
        "TypeError: not a Date object\n    \
         at getTime (native)\n    at call (native)\n    at <eval> (<input>:1:28)"
    );
}

/// A native frame's name is read from the function **object** when the trace is built.
///
/// It used to be read on every native call and stored in the frame, which cost a
/// `own_property("name")` plus a `String` allocation per `values.push(i)` — worth about
/// 5% of that benchmark for a trace that is almost never built. Reading it late is also
/// what the reference does, and the two differ observably: renaming the function changes
/// the name that later traces report.
#[test]
fn a_native_frame_reports_the_name_it_has_now() {
    assert_eq!(
        throws("[1].map(1)"),
        "TypeError: callback is not a function\n    at map (native)\n    at <eval> (<input>:1:8)"
    );
    // Renaming the shared builtin changes what the trace says, which a name captured at
    // call time could not do.
    assert_eq!(
        throws("Object.defineProperty(Array.prototype.map, 'name', {value: 'zzz'}); [1].map(1)"),
        "TypeError: callback is not a function\n    at zzz (native)\n    at <eval> (<input>:1:76)"
    );
}

// ---------------------------------------------------------------------------
// Spread calls and eval
// ---------------------------------------------------------------------------

#[test]
fn spread_arguments_reach_the_callee() {
    assert_eq!(
        eval("function g(a,b){print(a+b)} var v=[1,2]; g(...v)"),
        "3\n"
    );
    // Mixed forms build one argument array, in order.
    assert_eq!(
        eval("function g(){print([].slice.call(arguments).join())} g(0,...[1,2],3)"),
        "0,1,2,3\n"
    );
    // A method keeps its receiver, which is what `apply` has to carry through.
    assert_eq!(
        eval("var o={n:7,f:function(a){print(this.n+a)}}; o.f(...[1])"),
        "8\n"
    );
    // `new` with spread still constructs and still sets the prototype.
    assert_eq!(
        eval("function C(a,b){this.s=a+b} var c=new C(...[3,4]); print(c.s, c instanceof C)"),
        "7 true\n"
    );
}

#[test]
fn update_expressions_work_on_members_and_elements() {
    // `o.x++` has to read the receiver twice, so it compiles to a `get_field2` /
    // `post_inc` / `perm3` / `put_field` sequence; a prefix one swaps `perm3` for
    // `insert2`. Both forms must write back *and* leave the right result behind.
    assert_eq!(
        eval("var o={x:1}; print(o.x++, o.x, ++o.x, o.x--, o.x)"),
        "1 2 3 3 2\n"
    );
    // A computed element keeps the key alive as well, which is the `perm4` /
    // `insert3` shape.
    assert_eq!(
        eval("var a=[5],i=0; print(a[i]++, a[0], ++a[i], --a[i])"),
        "5 6 7 6\n"
    );
    // The receiver of a deep chain is evaluated once, and only the last link is read
    // with the form that keeps it.
    assert_eq!(
        eval("var o={a:{b:2}}; print(o.a.b++, o.a.b, ++o.a.b)"),
        "2 3 4\n"
    );
}

#[test]
fn eval_sees_the_calling_scope() {
    // `this` and `arguments` come from the callee, not from global scope. Strict
    // mode is needed for `this` to stay the primitive: a sloppy function boxes it.
    assert_eq!(
        eval("'use strict'; function f(b){return eval(b)} print(f.call(1,'this'))"),
        "1\n"
    );
    assert_eq!(
        eval("function f(b){return eval(b)} print(f('arguments.length', 1))"),
        "2\n"
    );
    // A local of the calling function is readable *and* writable.
    assert_eq!(
        eval("function f(){var x=1,y=2; eval('x = x + y'); return x} print(f())"),
        "3\n"
    );
    // The scope chain is followed outwards, not just the immediate caller.
    assert_eq!(
        eval(
            "function inner(){return eval('a')}\n\
              function outer(){var a=5; return inner()}\n\
              print(outer())"
        ),
        "5\n"
    );
    // A strict eval's `var` does not leak into the global object.
    assert_eq!(
        eval("'use strict'; eval('var leaked = 1'); print(typeof leaked)"),
        "undefined\n"
    );
    // An *assignment* to an undeclared name is still a ReferenceError in strict mode;
    // only a declaration creates a binding of the eval's own.
    assert_eq!(
        throws("'use strict'; eval('undeclared_thing = 1')"),
        // The name is quoted, as `JS_ThrowReferenceError(ctx, "'%s' is not defined")` does.
        "ReferenceError: 'undeclared_thing' is not defined\n    \
         at <eval> (<input>:1:1)\n    at <eval> (<input>:1:19)"
    );
    // A *sloppy* eval has no variable environment of its own, so its `var` lands in
    // the caller's — for a top-level eval, the global object. The split is on
    // strictness alone, not on being called from a function.
    assert_eq!(
        eval("eval('var sloppy = 1'); print(typeof sloppy)"),
        "number\n"
    );
    // A sloppy assignment to a non-writable global is a silent no-op; strict mode
    // reports the same refusal as a TypeError.
    assert_eq!(
        eval(
            "(1, eval)('var ro = 1');\n\
             Object.defineProperty(globalThis, 'ro', { writable: false });\n\
             ro = 2;\n\
             print(ro)"
        ),
        "1\n"
    );
    assert_eq!(
        throws(
            "'use strict'; (1, eval)('var ro = 1');\n\
             Object.defineProperty(globalThis, 'ro', { writable: false });\n\
             ro = 2;"
        ),
        "TypeError: 'ro' is read-only\n    at <eval> (<input>:3:1)"
    );
}

// ---------------------------------------------------------------------------
// The wrapper constructors
// ---------------------------------------------------------------------------

#[test]
fn new_number_string_boolean_store_their_primitive() {
    // `new Number(1)` is a wrapper object, so every `ToPrimitive` step on it runs
    // the prototype's `valueOf`, which reads the primitive the constructor stored
    // on the receiver. Without that store the whole boxed family throws.
    assert_eq!(eval("print(new Number(1) == 1)"), "true\n");
    assert_eq!(eval("print(new String('ab') == 'ab')"), "true\n");
    assert_eq!(eval("print(new Boolean(true) == true)"), "true\n");
    // Called as a plain function there is no receiver to store into, and the
    // primitive comes back unwrapped.
    assert_eq!(
        eval("print(new Number(1) + 1, Number(5), String(new String('x')))"),
        "2 5 x\n"
    );
}

// ---------------------------------------------------------------------------
// Destructuring
// ---------------------------------------------------------------------------

/// Every expectation here was read off the reference implementation.
#[test]
fn array_patterns_drain_an_iterator() {
    assert_eq!(eval("var [a,b]=[1,2]; print(a,b)"), "1 2\n");
    // A hole skips a value rather than binding it.
    assert_eq!(eval("var [x,,y]=[1,2,3]; print(x,y)"), "1 3\n");
    // A rest element collects what is left, into a real array.
    assert_eq!(
        eval("var [x,,y,...z]=[1,2,3,4]; print(x,y,JSON.stringify(z))"),
        "1 3 [4]\n"
    );
    assert_eq!(
        eval("var [...all]=[1,2]; print(JSON.stringify(all))"),
        "[1,2]\n"
    );
    // Patterns nest, and any iterable works — a string is one.
    assert_eq!(eval("var [[p],[q]]=[[7],[8]]; print(p,q)"), "7 8\n");
    assert_eq!(eval("var [p,q]='ab'; print(p,q)"), "a b\n");
    // A default fills in only `undefined`, never `null`.
    assert_eq!(eval("var [a=1,b=2]=[5]; print(a,b)"), "5 2\n");
    assert_eq!(eval("var [a=1]=[null]; print(a)"), "null\n");
}

#[test]
fn object_patterns_box_their_source() {
    assert_eq!(eval("var {c,d:e=5}={c:3}; print(c,e)"), "3 5\n");
    // A default may itself be a template, and it is evaluated lazily.
    assert_eq!(
        eval("var a='Bar'; var {b=`${a+`a${a}`}baz`}={}; print(b)"),
        "BaraBarbaz\n"
    );
    // A rest element gets the properties the literal part did not take.
    assert_eq!(
        eval("var {a,...r}={a:1,b:2}; print(a,JSON.stringify(r))"),
        "1 {\"b\":2}\n"
    );
    // `ToObject` is what makes a null source a TypeError rather than a silent miss.
    assert_eq!(
        eval("try{var {} = null}catch(e){print(e.name)}"),
        "TypeError\n"
    );
    assert_eq!(eval("var {} = {}; print('ok')"), "ok\n");
}

#[test]
fn destructuring_assignments_keep_the_right_hand_side() {
    // The assigned value is the expression's value, and a member target is legal here
    // even though it is not in a declaration.
    assert_eq!(eval("var o={}; [o.x,o.y]=[5,6]; print(o.x,o.y)"), "5 6\n");
    assert_eq!(
        eval("var a,b; var r=[a,b]=[1,2]; print(JSON.stringify(r),a,b)"),
        "[1,2] 1 2\n"
    );
    assert_eq!(eval("var o={}; var k='z'; [o[k]]=[7]; print(o.z)"), "7\n");
    assert_eq!(eval("var a,b; ({a,b}={a:3,b:4}); print(a,b)"), "3 4\n");
}

#[test]
fn pattern_parameters_bind_locals_and_count_towards_length() {
    assert_eq!(
        eval("function f({b},[c]){return b+c} print(f({b:1},[2]))"),
        "3\n"
    );
    assert_eq!(
        eval("function f(a=1,...r){return a+r.length} print(f(undefined,2,3))"),
        "3\n"
    );
    // `.length` is the arity before the first default or rest parameter, so a
    // destructuring parameter counts as one and a defaulted one ends the count.
    assert_eq!(eval("print((([a,b]) => {}).length)"), "1\n");
    assert_eq!(eval("print(((c,[a,b]=1,d)=>{}).length)"), "1\n");
    assert_eq!(
        eval("print(((a,b=1,c)=>{}).length, ((...r)=>{}).length)"),
        "1 0\n"
    );
}

#[test]
fn a_tagged_template_passes_the_call_site_object() {
    assert_eq!(eval("print(String.raw `a${1}b`)"), "a1b\n");
    // `raw` is the source text, so an escape is not expanded.
    assert_eq!(eval("print(String.raw `x\\ty`)"), "x\\ty\n");
    // The tag receives the cooked chunks and the substitutions, and a member tag keeps
    // its receiver as `this`.
    assert_eq!(
        eval("function t(s,...v){return s[0]+'|'+s.raw[0]+'|'+v.join()} print(t`x\\ty${2}z`)"),
        "x\ty|x\\ty|2\n"
    );
    assert_eq!(
        eval("var o={n:5,m(s){return this.n+s[0]}}; print(o.m`!`)"),
        "5!\n"
    );
}

// ---------------------------------------------------------------------------
// with
// ---------------------------------------------------------------------------

#[test]
fn with_puts_an_object_in_front_of_every_scope() {
    // The object shadows a global and a local alike: the Object Environment Record sits
    // between the block and the function's own bindings.
    assert_eq!(eval("var o={x:1},x=2; with(o){print(x)}"), "1\n");
    assert_eq!(
        eval("function f(){var x=2; with({x:1}) return x} print(f())"),
        "1\n"
    );
    // A store writes through to the object that supplied the name.
    assert_eq!(eval("var o={x:1},x=2; with(o){x=5} print(x,o.x)"), "2 5\n");
    // Nested blocks resolve innermost first.
    assert_eq!(
        eval("var o1={x:1},o2={y:2}; with(o1){with(o2){print(x,y)}}"),
        "1 2\n"
    );
    // A name the object does not have falls through to the ordinary lookup.
    assert_eq!(
        eval("var o={x:1}; with(o){print(typeof nope)}"),
        "undefined\n"
    );
    // A function created inside the block keeps seeing the object, because the boxed
    // object is a captured local.
    assert_eq!(
        eval("var f; with({z:1}){f=function(){return z}} print(f())"),
        "1\n"
    );
}

#[test]
fn eval_inside_with_sees_the_object() {
    assert_eq!(eval("var o={x:'o1'}; with(o){print(eval('x'))}"), "o1\n");
    // A write through an `eval` reaches the object too.
    assert_eq!(
        eval("var o={x:'o1'}; with(o){eval('x=7')} print(o.x)"),
        "7\n"
    );
    // The innermost object wins, and a name it lacks comes from the enclosing one.
    assert_eq!(
        eval("var o1={x:'a',y:'b'},o2={x:'c'}; with(o1){with(o2){print(eval('x'),eval('y'))}}"),
        "c b\n"
    );
}

// ---------------------------------------------------------------------------
// Arrows inherit `this`, `arguments` and `new.target`
// ---------------------------------------------------------------------------

#[test]
fn an_arrow_reads_the_enclosing_functions_bindings() {
    // An arrow has no `this` of its own, so the enclosing function materialises its
    // receiver into a local and the arrow captures it.
    assert_eq!(
        eval("'use strict'; function f(){return (()=>this)()} print(f.call('t'))"),
        "t\n"
    );
    assert_eq!(
        eval("var o={m(){return (()=>this)()}}; print(o.m()===o)"),
        "true\n"
    );
    // Two levels deep is still the outermost function's receiver.
    assert_eq!(
        eval("'use strict'; function f(){return (()=>()=>this)()()} print(f.call('x'))"),
        "x\n"
    );
    // The same holds for `arguments`, which is likewise the enclosing function's.
    assert_eq!(
        eval("function f(){return (()=>arguments.length)()} print(f(1,2))"),
        "2\n"
    );
    // `new.target` is lexical too, and `undefined` for an ordinary call.
    assert_eq!(
        eval("function f(){return new.target} print(f(), new f()===f)"),
        "undefined true\n"
    );
    assert_eq!(
        eval("function f(){return (()=>new.target)()} print(new f()===f)"),
        "true\n"
    );
}

#[test]
fn eval_inherits_the_callers_this_and_new_target() {
    // A direct eval runs in the caller's function context, so both are visible even
    // though the eval'd source is a bare script.
    assert_eq!(
        eval("'use strict'; function f(){return eval('this')} print(f.call('v'))"),
        "v\n"
    );
    assert_eq!(
        eval("function f(){return eval('new.target')} print(new f()===f)"),
        "true\n"
    );
    // Through an arrow the lookup skips the arrow's own frame, which has neither.
    assert_eq!(
        eval("'use strict'; function f(){return (()=>eval('this'))()} print(f.call('v'))"),
        "v\n"
    );
    assert_eq!(
        eval("'use strict'; function f(){return (()=>eval('new.target'))()} print(new f()===f)"),
        "true\n"
    );
}

// ---------------------------------------------------------------------------
// Classes
// ---------------------------------------------------------------------------

#[test]
fn class_members_land_on_the_right_object() {
    // Methods and accessors go on the prototype, `static` ones on the constructor —
    // and none of them is enumerable, which is the whole difference from an object
    // literal.
    assert_eq!(eval("class A{m(){return 1}} print(new A().m())"), "1\n");
    assert_eq!(eval("class A{static s(){return 2}} print(A.s())"), "2\n");
    assert_eq!(eval("class A{get g(){return 3}} print(new A().g)"), "3\n");
    assert_eq!(
        eval("class A{m(){}} print(Object.keys(A.prototype).length)"),
        "0\n"
    );
    // `static` is a legal method *name* as well as a modifier.
    assert_eq!(
        eval(
            "class P{get=()=>'123'; static(){return 42}} var p=new P(); print(p.get(),p.static())"
        ),
        "123 42\n"
    );
    // A class constructor may not be called without `new`.
    assert_eq!(
        eval("class A{} try{A()}catch(e){print(e.name)}"),
        "TypeError\n"
    );
}

#[test]
fn a_class_binds_its_own_name_inside_the_body() {
    assert_eq!(
        eval("var E1=class E{static F(){return E}}; print(E1===E1.F())"),
        "true\n"
    );
    assert_eq!(
        eval("class A{static m(){return A}} print(A.m()===A)"),
        "true\n"
    );
    // The static field initialiser sees the class too — and inside a *function*, where the
    // binding is a closure variable rather than a local.
    assert_eq!(
        eval("class S{static x=42;static y=S.x;static z=this.x} print(S.x,S.y,S.z)"),
        "42 42 42\n"
    );
    assert_eq!(
        eval("function f(){class S{static x=42;static y=S.x} return S.y} print(f())"),
        "42\n"
    );
}

#[test]
fn extends_inherits_both_chains() {
    assert_eq!(
        eval("class A{f(){return 1}} class B extends A{} print(new B().f())"),
        "1\n"
    );
    // The instance must be a `new.target` instance, so a derived constructor's `super()`
    // has to build an object of the *subclass* prototype.
    assert_eq!(
        eval("class A{constructor(){this.v=1}} class B extends A{} print(new B().v)"),
        "1\n"
    );
    assert_eq!(
        eval(
            "class A{constructor(){this.v=1}} class B extends A{} class C extends B{} print(new C().v)"
        ),
        "1\n"
    );
    // `new` on a bound function constructs its target, so the instance is a target one.
    assert_eq!(
        eval(
            "function C(a){this.x=a} var g=C.bind(null,1); var r=new g(); print(r.x, r instanceof C)"
        ),
        "1 true\n"
    );
}

#[test]
fn super_reads_writes_and_calls_through_the_home_object() {
    assert_eq!(
        eval("class A{f(){return 1}} class B extends A{h(){return super.f()}} print(new B().h())"),
        "1\n"
    );
    assert_eq!(
        eval(
            "class A{static F(){return -1}} class B extends A{static H(){return super['F']()}} print(B.H())"
        ),
        "-1\n"
    );
    // A getter found on the parent prototype runs with the *instance* as `this`.
    assert_eq!(
        eval(
            "class A{get g(){return this.v}} class B extends A{constructor(){super();this.v=9} h(){return super.g}} print(new B().h())"
        ),
        "9\n"
    );
    // `delete super.x` is refused rather than deleting the parent's property.
    assert_eq!(
        eval("var a={f(){delete super.a}}; try{a.f()}catch(e){print(e.name)}"),
        "ReferenceError\n"
    );
}

#[test]
fn a_short_circuited_optional_chain_is_still_a_receiver() {
    // `(a?.b)()` keeps `a` as `this`, and a short-circuited one calls `undefined` so the
    // call throws instead of silently yielding `undefined`.
    assert_eq!(
        eval("var a={b(){return this._b},_b:{c:42}}; print((a?.b)().c, (a?.['b'])().c)"),
        "42 42\n"
    );
    assert_eq!(
        eval("var z=null; try{(z?.b)()}catch(e){print(e.name)}"),
        "TypeError\n"
    );
    // `delete` on a skipped chain answers `true`: there was nothing to delete.
    assert_eq!(
        eval("var a={b:{c:2}},z=null; print(delete z?.b.c, delete a?.b.c, JSON.stringify(a))"),
        "true true {\"b\":{}}\n"
    );
}

// ---------------------------------------------------------------------------
// Generators
// ---------------------------------------------------------------------------

#[test]
fn a_generator_pauses_and_resumes_its_frame() {
    // The body does not run until the first `next()`, and the value passed to `next`
    // becomes the value of the `yield` expression.
    assert_eq!(
        eval(
            "function* g(){yield 1} var it=g(); print(JSON.stringify(it.next()),JSON.stringify(it.next()))"
        ),
        "{\"value\":1,\"done\":false} {\"done\":true}\n"
    );
    assert_eq!(
        eval(
            "function* g(){var x=yield 1; yield x*2} var it=g(); it.next(); print(JSON.stringify(it.next(5)))"
        ),
        "{\"value\":10,\"done\":false}\n"
    );
    // A `return` leaves the frame's locals and operand stack intact across the pause.
    assert_eq!(
        eval(
            "function* g(){var a=1; yield a; a=2; yield a} var it=g(); it.next(); print(JSON.stringify(it.next()))"
        ),
        "{\"value\":2,\"done\":false}\n"
    );
    // `return(v)` finishes the generator with that value, even before it started.
    assert_eq!(
        eval("function* g(){yield 1} var it=g(); print(JSON.stringify(it.return(9)))"),
        "{\"value\":9,\"done\":true}\n"
    );
    assert_eq!(
        eval("function* g(){} var it=g(); print(JSON.stringify(it.return(5)))"),
        "{\"value\":5,\"done\":true}\n"
    );
    // `throw(e)` is delivered at the `yield`, so the body's own `try` catches it.
    assert_eq!(
        eval(
            "function* g(){try{yield 1}catch(e){yield 'caught:'+e}} var it=g(); it.next(); print(JSON.stringify(it.throw('boom')))"
        ),
        "{\"value\":\"caught:boom\",\"done\":false}\n"
    );
}

#[test]
fn yield_star_forwards_the_inner_iterator() {
    assert_eq!(
        eval(
            "function* o(){yield* [2,3]} var it=o(); print(JSON.stringify(it.next()),JSON.stringify(it.next()),JSON.stringify(it.next()))"
        ),
        "{\"value\":2,\"done\":false} {\"value\":3,\"done\":false} {\"done\":true}\n"
    );
    // The delegate's return value becomes the value of the `yield*` expression.
    assert_eq!(
        eval(
            "function* i(){yield 1; return 'end'} function* o(){var r=yield* i(); yield r} var it=o(); print(JSON.stringify(it.next())); print(JSON.stringify(it.next())); print(JSON.stringify(it.next()))"
        ),
        "{\"value\":1,\"done\":false}\n{\"value\":\"end\",\"done\":false}\n{\"done\":true}\n"
    );
}

#[test]
fn a_generator_is_iterable_and_not_a_constructor() {
    // `for (… of …)` and the array spread both drive it through `next`.
    assert_eq!(
        eval(
            "function* g(){yield 1; yield 2} var t=[]; for (var x of g()) t.push(x); print(t.join())"
        ),
        "1,2\n"
    );
    assert_eq!(
        eval("function* g(){yield 1; yield 2} print([...g()].join())"),
        "1,2\n"
    );
    // A pattern drains it, and a `return` value is not a yielded element.
    assert_eq!(
        eval("function* g(){return 0} var [x]=g(); print(x)"),
        "undefined\n"
    );
    // A generator function has no `[[Construct]]`.
    assert_eq!(
        eval("function* G(){} try{new G()}catch(e){print(e.name, e.message)}"),
        "TypeError G is not a constructor\n"
    );
}

// ---------------------------------------------------------------------------
// Symbols
// ---------------------------------------------------------------------------

#[test]
fn a_symbol_is_a_unique_key_that_is_not_a_string() {
    // Identity, not description: two symbols with the same text are two different keys.
    assert_eq!(
        eval("print(Symbol()===Symbol(), Symbol.for('k')===Symbol.for('k'))"),
        "false true\n"
    );
    // A symbol key and a string key coexist on one object and are invisible to each
    // other. `Object.keys` and `JSON.stringify` skip the symbol; only
    // `getOwnPropertySymbols` and `Reflect.ownKeys` report it.
    assert_eq!(
        eval(
            "var o={}; var s=Symbol('a'); o[s]=1; o.a=2; print(o[s], o.a, Object.keys(o).length, Object.getOwnPropertySymbols(o).length, JSON.stringify(o), s in o)"
        ),
        "1 2 1 1 {\"a\":2} true\n"
    );
    assert_eq!(
        eval("print(Reflect.ownKeys({a:1,[Symbol('s')]:2}).map(String).join())"),
        "a,Symbol(s)\n"
    );
}

#[test]
fn symbol_converts_to_a_string_only_on_request() {
    assert_eq!(
        eval(
            "print(typeof Symbol(), String(Symbol('x')), Symbol().description, Object.prototype.toString.call(Symbol()))"
        ),
        "symbol Symbol(x) undefined [object Symbol]\n"
    );
    // `ToString` of a symbol is a TypeError, in concatenation and in a template alike.
    assert_eq!(
        eval("try{''+Symbol()}catch(e){print(e.name)}"),
        "TypeError\n"
    );
    assert_eq!(
        eval("try{print(`${Symbol()}`)}catch(e){print(e.name)}"),
        "TypeError\n"
    );
    // `new Symbol()` has no `[[Construct]]`.
    assert_eq!(
        eval("try{new Symbol()}catch(e){print(e.name, e.message)}"),
        "TypeError Symbol is not a constructor\n"
    );
}

#[test]
fn well_known_symbols_drive_the_protocols() {
    // `Symbol.toStringTag` overrides the class name in `Object.prototype.toString`.
    assert_eq!(
        eval("var o={[Symbol.toStringTag]:'M'}; print(Object.prototype.toString.call(o))"),
        "[object M]\n"
    );
    // `Symbol.toPrimitive` takes over conversion, and is handed the hint.
    assert_eq!(
        eval("var o={[Symbol.toPrimitive](h){return h}}; print(`${o}`)"),
        "string\n"
    );
    // `Symbol.iterator` makes any object iterable — no special case in the engine.
    assert_eq!(
        eval(
            "var o={[Symbol.iterator](){var i=0;return{next:()=>({value:i++,done:i>2})}}}; print([...o].join())"
        ),
        "0,1\n"
    );
    // The built-in types advertise iteration through the same symbol, so a script can
    // drive them by hand.
    assert_eq!(
        eval(
            "var it=[1,2][Symbol.iterator](); print(JSON.stringify(it.next()), JSON.stringify(it.next()), JSON.stringify(it.next()))"
        ),
        "{\"value\":1,\"done\":false} {\"value\":2,\"done\":false} {\"done\":true}\n"
    );
    assert_eq!(
        eval("print([...'ab'].join(), typeof Symbol.iterator)"),
        "a,b symbol\n"
    );
}

#[test]
fn eval_hands_its_scope_to_the_closures_it_builds() {
    // A closure created by `eval` outlives the eval, so it has to keep reading the
    // caller's binding — and each iteration of `for (let i …)` is a *different*
    // binding, because the loop variable is copied per iteration.
    assert_eq!(
        eval(
            "var tab=[]; for(let i=0;i<3;i++) eval('tab.push(function(){return i})');\n\
             print(tab[0](), tab[1](), tab[2]())"
        ),
        "0 1 2\n"
    );
    // The eval may sit in a nested function, in which case the binding it captures
    // belongs to that function's *caller*.
    assert_eq!(
        eval(
            "var tab=[];\n\
             for(let i=0;i<3;i++){ let f=function(){ eval('tab.push(function(){return i})') }; f() }\n\
             print(tab[0](), tab[1](), tab[2]())"
        ),
        "0 1 2\n"
    );
    // Two loops in a row use the same name, so name lookup alone cannot tell them
    // apart: the compiler records which slot each call site means.
    assert_eq!(
        eval(
            "var a=[], b=[];\n\
             for(let i=0;i<3;i++) eval('a.push(function(){return i})');\n\
             for(let i=0;i<3;i++) eval('b.push(function(){return i})');\n\
             print(a.map(f=>f()).join(), b.map(f=>f()).join())"
        ),
        "0,1,2 0,1,2\n"
    );
}

#[test]
fn eval_respects_a_read_only_binding() {
    // A local `const` is as read-only through `eval` as it is directly.
    assert_eq!(
        eval(
            "function f(){const a=1; try{eval('a = 2'); print('no throw')}catch(e){print(e.name)}} f()"
        ),
        "TypeError\n"
    );
    // The name of a named function expression is read-only too, but only strict mode
    // reports the attempt — a sloppy store is silently dropped, the same as a direct one.
    assert_eq!(
        eval("var f=function n(){eval('n = 1'); return n}; print(f()===f)"),
        "true\n"
    );
    assert_eq!(
        eval(
            "var f=function n(){'use strict'; eval('n = 1')}; try{f(); print('no throw')}catch(e){print(e.name)}"
        ),
        "TypeError\n"
    );
    // …and the same holds when the assignment goes through a nested arrow, which
    // reaches the binding via a closure entry rather than a local slot.
    assert_eq!(
        eval("var f=function n(){ (()=>{n=1})(); return n }; print(f()===f)"),
        "true\n"
    );
    assert_eq!(
        eval(
            "var f=function n(){ 'use strict'; (()=>{n=1})() }; try{f(); print('no throw')}catch(e){print(e.name)}"
        ),
        "TypeError\n"
    );
}

#[test]
fn parameter_expressions_get_their_own_variable_environment() {
    // A default expression makes the parameter list a scope of its own: the body's `var a`
    // is a different binding, so the closure still sees the parameter.
    assert_eq!(
        eval(
            "var f = function f(a = 1, p = () => a) { var a = 2; return [a, p()] };\n\
             print(f().join())"
        ),
        "2,1\n"
    );
    // A destructured parameter behaves the same way.
    assert_eq!(
        eval(
            "var g = ({x} = {x: 7}, p = () => x) => { var x = 9; return [x, p()] }; print(g().join())"
        ),
        "9,7\n"
    );
    // …and so does a body that leaves the parameter alone.
    assert_eq!(
        eval("var g = ({x} = {x: 7}, p = () => x) => [x, p()]; print(g().join())"),
        "7,7\n"
    );
    // `arguments` exists twice as well, and the parameter list's copy is the one its
    // closures see: the arrow returns `f`'s arguments, not its own call's.
    assert_eq!(
        eval("var f = function f(a, b = () => arguments) { return b()[0] }; print(f(9))"),
        "9\n"
    );
    // A parameter list does not see the body's `var`s, so this `c` is the global one.
    assert_eq!(
        eval(
            "var c = 'global';\n\
             var f = (a = 1, p = () => c) => { var c = 2; return [c, p()] };\n\
             print(f().join())"
        ),
        "2,global\n"
    );
}

#[test]
fn eval_in_a_parameter_list_belongs_to_the_caller() {
    // A `var` a sloppy eval declares goes into the caller's variable environment, not onto
    // the global object — and a direct eval inside a parameter list puts it in the
    // parameter environment, which its closures and the body both see.
    assert_eq!(
        eval(
            "var c = 'global';\n\
             var f = function f(a = eval('var c = 1')) { return c };\n\
             print(f(), c)"
        ),
        "1 global\n"
    );
    // A closure born in the parameter list sees it…
    assert_eq!(
        eval(
            "var c = 'global';\n\
             var f = (a = eval('var c = 1'), p = () => c) => { var c = 2; return [c, p()] };\n\
             print(f().join(), c)"
        ),
        "2,1 global\n"
    );
    // …including when the variable shadows an enclosing function's own binding.
    assert_eq!(
        eval(
            "function t() {\n\
                 var c = 'outer';\n\
                 function f(a = eval('var c = 1'), p = () => c) { return [p(), c] }\n\
                 return [f().join(), c]\n\
             }\n\
             print(t().join(' '))"
        ),
        "1,1 outer\n"
    );
    // An *indirect* eval has no caller scope at all, so its `var` is a global.
    assert_eq!(
        eval(
            "function t() { (1, eval)('var indirect = 1') }\n\
             t(); print(typeof indirect)"
        ),
        "number\n"
    );
}

#[test]
fn eval_inherits_the_callers_super() {
    // An eval'd body is not a method, but it runs inside one: `super.x` resolves against
    // the caller's `[[HomeObject]]`, which is what `special_object 4` already walks to.
    assert_eq!(
        eval(
            "var o1 = { x: 1 };\n\
             var o2 = { f() { return eval('super.x') } };\n\
             o2.__proto__ = o1;\n\
             print(o2.f())"
        ),
        "1\n"
    );
    // The receiver is still `this`, so a `super` method call gets the right one.
    assert_eq!(
        eval(
            "var o1 = { f() { return this } };\n\
             var o2 = { f() { return (() => eval('super.f()'))() } };\n\
             o2.__proto__ = o1;\n\
             print(o2.f() === o2)"
        ),
        "true\n"
    );
    // Outside a method there is no home object, so `super.x` stays a syntax error, and the
    // position is the `.` — the reference consumes `super` before it checks.
    assert_eq!(
        throws("eval('super.x')"),
        // Bare message, with the position on the stack rather than in it.
        "SyntaxError: 'super' is only valid in a method\n    \
         at <input>:1:6\n    at <eval> (<input>:1:5)"
    );
}

#[test]
fn object_prototype_has_a_proto_accessor() {
    // `__proto__` is an ordinary accessor on `Object.prototype`, not a magic property of
    // every object — scripts read and write it constantly.
    assert_eq!(
        eval(
            "var o = {}; o.__proto__ = { x: 1 }; print(o.x, Object.getPrototypeOf(o) === o.__proto__)"
        ),
        "1 true\n"
    );
    assert_eq!(
        eval("var o = Object.create(null); print(o.__proto__ === undefined)"),
        "true\n"
    );
    // A primitive receiver is boxed, so it reports its wrapper's prototype.
    assert_eq!(eval("print((1).__proto__ === Number.prototype)"), "true\n");
    // A cycle is refused rather than creating an infinite chain.
    assert_eq!(
        eval(
            "var a = {}, b = {}; a.__proto__ = b; b.__proto__ = a; print(Object.getPrototypeOf(b) === a)"
        ),
        "false\n"
    );
}

#[test]
fn regexp_literals_and_exec_match_the_reference() {
    // A literal is compiled by the `regexp` opcode, not by a call to the constructor.
    assert_eq!(eval("print(/ab+c/i.source, /ab+c/i.flags)"), "ab+c i\n");
    // `exec` reports the whole match, the groups, and where it found them.
    assert_eq!(
        eval(
            "var m = /(\\d+)-(\\d+)/.exec('x 12-34 y');\n\
             print([m[0], m[1], m[2], m.index, m.input].join(' '))"
        ),
        "12-34 12 34 2 x 12-34 y\n"
    );
    // A group that did not participate is `undefined`, not an empty string.
    assert_eq!(
        eval("print(/a(b)?c/.exec('ac')[1] === undefined)"),
        "true\n"
    );
    // `lastIndex` advances for `g` and resets when the match fails.
    assert_eq!(
        eval(
            "var r = /o/g;\n\
             print([r.test('foo'), r.lastIndex, r.test('foo'), r.lastIndex, r.test('foo'), r.lastIndex].join() )"
        ),
        "true,2,true,3,false,0\n"
    );
    // A quantified group takes its captures from the *last* iteration.
    assert_eq!(
        eval("print(/(z)((a+)?(b+)?(c))*/.exec('zaacbbbcac').join('|'))"),
        "zaacbbbcac|z|ac|a||c\n"
    );
}

#[test]
fn string_methods_dispatch_to_the_regexp_symbol_methods() {
    // `replace`, `split`, `search` and `match` reach the pattern through
    // `Symbol.replace` and friends, so a `RegExp` decides what they mean.
    assert_eq!(eval("print('a1b2c3'.replace(/\\d/g, '#'))"), "a#b#c#\n");
    assert_eq!(
        eval("print('a1b2c3'.replace(/(\\d)/g, '[$1]'))"),
        "a[1]b[2]c[3]\n"
    );
    assert_eq!(
        eval("print('a1b2'.replace(/\\d/g, function (m) { return '<' + m + '>' }))"),
        "a<1>b<2>\n"
    );
    assert_eq!(eval("print('a,b;c'.split(/[,;]/).join('|'))"), "a|b|c\n");
    assert_eq!(eval("print('abcabc'.search(/b/))"), "1\n");
    assert_eq!(eval("print('xabcx'.match(/b/).index)"), "2\n");
    assert_eq!(eval("print('aXbXc'.match(/X/g).join('-'))"), "X-X\n");
    // A dollar in the replacement template refers to a group, and `$&` to the match.
    assert_eq!(eval("print('ab'.replace(/b/, '[$&]'))"), "a[b]\n");
    assert_eq!(eval("print('ab'.replace(/b/, '$1'))"), "a$1\n");
}

#[test]
fn regexp_flags_change_meaning() {
    assert_eq!(eval("print(/^b/m.test('a\\nb'))"), "true\n");
    assert_eq!(eval("print(/a.c/s.test('a\\nc'))"), "true\n");
    assert_eq!(eval("print(/abc/i.test('AbC'))"), "true\n");
    // `y` refuses to search forward from `lastIndex`.
    assert_eq!(
        eval("var r = /b/y; r.lastIndex = 0; print(r.test('abc'))"),
        "false\n"
    );
    // An invalid pattern or flag is a SyntaxError, as it is in the reference.
    assert_eq!(
        throws("new RegExp('a', 'bad')"),
        "SyntaxError: invalid regular expression flags\n    at RegExp (native)\n    \
         at <eval> (<input>:1:11)"
    );
    assert_eq!(
        throws("new RegExp('(')"),
        "SyntaxError: expecting ')'\n    at RegExp (native)\n    at <eval> (<input>:1:11)"
    );
}

#[test]
fn using_disposes_in_reverse_order() {
    // The resources go out in reverse, and the body's own work happens first.
    assert_eq!(
        eval(
            "var log = [];\n\
             function f() {\n\
                 using a = { [Symbol.dispose]() { log.push('a') } };\n\
                 using b = { [Symbol.dispose]() { log.push('b') } };\n\
                 log.push('body');\n\
             }\n\
             f(); print(log.join())"
        ),
        "body,b,a\n"
    );
    // A `return` still disposes, because the region is a cleanup on every exit.
    assert_eq!(
        eval(
            "var log = [];\n\
             function f() { using a = { [Symbol.dispose]() { log.push('a') } }; return 7 }\n\
             print(f(), log.join())"
        ),
        "7 a\n"
    );
    // So does a `break` out of a loop inside the block.
    assert_eq!(
        eval(
            "var log = [];\n\
             function f() {\n\
                 using a = { [Symbol.dispose]() { log.push('a') } };\n\
                 for (;;) { log.push('loop'); break }\n\
                 log.push('after');\n\
             }\n\
             f(); print(log.join())"
        ),
        "loop,after,a\n"
    );
    // `null` and `undefined` are legal and dispose to nothing.
    assert_eq!(
        eval(
            "function f() { using a = null; using b = undefined; return 1 }\n\
             print(f())"
        ),
        "1\n"
    );
}

#[test]
fn using_validates_at_the_declaration() {
    // A value that is not an object, or has no `Symbol.dispose`, fails before the body runs.
    assert_eq!(
        eval(
            "var ran = false;\n\
             try { (function () { using x = {}; ran = true })() } catch (e) {}\n\
             print(ran)"
        ),
        "false\n"
    );
    assert_eq!(
        eval(
            "var name;\n\
             try { (function () { using x = 42 })() } catch (e) { name = e.constructor.name }\n\
             print(name)"
        ),
        "TypeError\n"
    );
    // A non-callable disposer is a `TypeError` too.
    assert_eq!(
        throws("(function () { using x = { [Symbol.dispose]: 1 } })()"),
        // The position is the `.` of `Symbol.dispose`, not the declaration: the reference
        // records a source position for a member access and for nothing else in this
        // body, so the `using_dispose` epilogue — which records none of its own — inherits
        // the last one written.
        "TypeError: dispose method is not a function\n    \
         at <anonymous> (<input>:1:35)\n    at <eval> (<input>:1:52)"
    );
    // The method is snapshotted once, at the declaration: replacing it afterwards does not
    // change what runs.
    assert_eq!(
        eval(
            "var reads = 0, disposed = 0, target = {};\n\
             Object.defineProperty(target, Symbol.dispose, {\n\
                 get() { reads++; return function () { disposed++ } }\n\
             });\n\
             (function () { using x = target })();\n\
             print(reads, disposed)"
        ),
        "1 1\n"
    );
}

#[test]
fn failed_disposals_chain_into_suppressed_errors() {
    // Each failure is wrapped around the one before it, newest outermost:
    // LIFO disposes c, then b, then a, so `a` ends up on the outside.
    assert_eq!(
        eval(
            "var caught;\n\
             try {\n\
                 (function () {\n\
                     using a = { [Symbol.dispose]() { throw new Error('a') } };\n\
                     using b = { [Symbol.dispose]() { throw new Error('b') } };\n\
                     using c = { [Symbol.dispose]() { throw new Error('c') } };\n\
                 })();\n\
             } catch (e) { caught = e }\n\
             print(caught instanceof SuppressedError, caught.error.message,\n\
                   caught.suppressed.error.message,\n\
                   caught.suppressed.suppressed.message)"
        ),
        "true a b c\n"
    );
    // A body that throws still disposes, and the disposal failure wins over the body's.
    assert_eq!(
        eval(
            "var caught;\n\
             try {\n\
                 (function () {\n\
                     using a = { [Symbol.dispose]() { throw new Error('dispose') } };\n\
                     throw new Error('body');\n\
                 })();\n\
             } catch (e) { caught = e }\n\
             print(caught instanceof SuppressedError, caught.error.message,\n\
                   caught.suppressed.message)"
        ),
        "true dispose body\n"
    );
    // Rewriting `SuppressedError.prototype.constructor` must not hijack the engine's own
    // wrapping: the aggregate is built from the prototype, not by calling the constructor.
    assert_eq!(
        eval(
            "var saved = SuppressedError.prototype.constructor, hijacked = false;\n\
             SuppressedError.prototype.constructor = function () { hijacked = true };\n\
             try {\n\
                 (function () {\n\
                     using a = { [Symbol.dispose]() { throw new Error('a') } };\n\
                     using b = { [Symbol.dispose]() { throw new Error('b') } };\n\
                 })();\n\
             } catch (e) {}\n\
             SuppressedError.prototype.constructor = saved;\n\
             print(hijacked)"
        ),
        "false\n"
    );
}

#[test]
fn for_of_using_disposes_each_iteration() {
    // The element is validated per iteration, so a bad one fails on its own turn.
    assert_eq!(
        eval(
            "var iters = 0, name;\n\
             try {\n\
                 (function () {\n\
                     for (using x of [{ [Symbol.dispose]() {} }, 42]) { iters++ }\n\
                 })();\n\
             } catch (e) { name = e.constructor.name }\n\
             print(iters, name)"
        ),
        "1 TypeError\n"
    );
    // …and a good run disposes after each iteration body, not at the end of the loop.
    assert_eq!(
        eval(
            "var log = [];\n\
             (function () {\n\
                 for (using x of [\n\
                     { tag: 'a', [Symbol.dispose]() { log.push(this.tag) } },\n\
                     { tag: 'b', [Symbol.dispose]() { log.push(this.tag) } },\n\
                 ]) { log.push('iter') }\n\
             })();\n\
             print(log.join())"
        ),
        "iter,a,iter,b\n"
    );
}

#[test]
fn disposable_stack_moves_through_the_intrinsic_prototype() {
    assert_eq!(
        eval(
            "var saved = DisposableStack, disposed = 0;\n\
             var ds = new saved();\n\
             ds.use({ [Symbol.dispose]() { disposed++ } });\n\
             DisposableStack = class Other {};\n\
             var moved = ds.move();\n\
             var same = Object.getPrototypeOf(moved) === saved.prototype;\n\
             moved.dispose();\n\
             DisposableStack = saved;\n\
             print(same, disposed, moved.disposed)"
        ),
        "true 1 true\n"
    );
    // `defer` takes a plain callback, `adopt` gives a resource a disposer.
    assert_eq!(
        eval(
            "var log = [];\n\
             var stack = new DisposableStack();\n\
             stack.defer(function () { log.push('deferred') });\n\
             stack.adopt({ n: 3 }, function (value) { log.push('adopted' + value.n) });\n\
             stack.dispose();\n\
             print(log.join())"
        ),
        "adopted3,deferred\n"
    );
    // A stack can itself be a `using` resource.
    assert_eq!(
        eval(
            "var log = [];\n\
             (function () {\n\
                 using stack = new DisposableStack();\n\
                 stack.use({ [Symbol.dispose]() { log.push('inner') } });\n\
                 log.push('body');\n\
             })();\n\
             print(log.join())"
        ),
        "body,inner\n"
    );
}

#[test]
fn boxed_primitives_report_their_own_tag() {
    // `Object(sym)` is a real wrapper: `valueOf` hands the symbol back and the object tags
    // as a Symbol rather than an Object.
    assert_eq!(
        eval(
            "var s = Symbol('aaa'); var b = Object(s);\n\
              print(b.valueOf() === s, b.toString(), typeof b, Object.prototype.toString.call(b))"
        ),
        "true Symbol(aaa) object [object Symbol]\n"
    );
    assert_eq!(
        eval(
            "print(Object.prototype.toString.call('x'),\n\
                   Object.prototype.toString.call(1),\n\
                   Object.prototype.toString.call(true),\n\
                   Object.prototype.toString.call({}))"
        ),
        "[object String] [object Number] [object Boolean] [object Object]\n"
    );
}

#[test]
fn generator_resumes_after_calling_a_function() {
    // A generator body that calls an ordinary function must survive the call: the callee's
    // `return` ends *its* frame, not the generator's. Getting this wrong is silent — the
    // generator reports the callee's value as its own result and marks itself done.
    assert_eq!(
        eval(
            "function *f() { var r = yield 1; return 3 }\n\
             function *g() { var r = yield 1; (function () {}()); return 3 }\n\
             function *h() { var r = yield 1; return r }\n\
             var a = f(); a.next(); var ra = a.next(9);\n\
             var b = g(); b.next(); var rb = b.next(9);\n\
             var c = h(); c.next(); var rc = c.next(9);\n\
             print(ra.value, ra.done, rb.value, rb.done, rc.value, rc.done)"
        ),
        "3 true 3 true 9 true\n"
    );
    // A throw from a called function still reaches the generator's own `catch`.
    assert_eq!(
        eval(
            "function boom() { throw new Error('boom') }\n\
             function *a() { try { yield 1; boom() } catch (e) { yield 'caught:' + e.message } }\n\
             var g = a(); g.next(); var v = g.next();\n\
             print(v.value, v.done)"
        ),
        "caught:boom false\n"
    );
}

#[test]
fn regexp_unicode_mode_and_case_folding() {
    // `u` tightens the grammar: `{`, `}` and `]` must be escaped, unlike Annex B, where
    // they are ordinary literals.
    for pattern in ["aaa]", "a}", "a{"] {
        assert!(
            throws(&format!("new RegExp({pattern:?}, 'u')")).starts_with("SyntaxError"),
            "{pattern} should be a SyntaxError under u"
        );
        assert_eq!(
            eval(&format!(
                "try {{ new RegExp({pattern:?}); print('ok') }} catch (e) {{ print(e.name) }}"
            )),
            "ok
",
            "{pattern} is a literal without u"
        );
    }
    // `\b` is backspace inside a class and a word boundary outside it.
    assert_eq!(
        eval("print(/[\\b]/.test('\\b'), /\\b/.test('a'))"),
        "true true\n"
    );
    // Property escapes, and the case folding that applies to them.
    assert_eq!(
        eval("print('aAbBcC#4'.replace(/\\p{Lower}/gu, 'X'))"),
        "XAXBXC#4\n"
    );
    assert_eq!(
        eval("print('aAbBcC#4'.replace(/\\p{Upper}/gui, 'X'))"),
        "XXXXXX#4\n"
    );
    // Negation applies to the *set*, then the character is canonicalised — so `\P{Lower}`
    // matches `a` under `i`, because `a` canonicalises to the `A` that is in the complement.
    assert_eq!(
        eval("print('aAbBcC#4'.replace(/\\P{Lower}/gui, 'X'))"),
        "XXXXXXXX\n"
    );
    // A case-insensitive range has to fold both sides, not only the input.
    assert_eq!(eval("print(/[A-Z]/i.test('a'))"), "true\n");
    // …without breaking a range whose bounds do not survive folding.
    assert_eq!(
        eval("print(/[A-_]/.test('a'), /[A-_]/.test('^'))"),
        "false true\n"
    );
}

#[test]
fn typed_arrays_are_views_onto_a_buffer() {
    // The whole point of the type: two views of one buffer see each other's writes.
    assert_eq!(
        eval(
            "var b = new ArrayBuffer(8); var u = new Uint8Array(b); var i = new Int32Array(b);\n\
              i[0] = -1; print(u.join(','))"
        ),
        "255,255,255,255,0,0,0,0\n"
    );
    // `subarray` shares storage; `slice` copies.
    assert_eq!(
        eval(
            "var a = new Uint8Array([1, 2, 3, 4]);\n\
              var s = a.subarray(1, 3); s[0] = 9;\n\
              var c = a.slice(1, 3); c[0] = 7;\n\
              print(a.join(','), s.join(','), c.join(','))"
        ),
        "1,9,3,4 9,3 7,3\n"
    );
    // `.set` reads its source before writing, so `a.set(a)` is a no-op rather than a smear.
    assert_eq!(
        eval(
            "var a = new Uint8Array([1, 2, 3, 4]); a.set([10, 11], 2); a.set(a.subarray(0, 2), 2);\n\
              print(a.join(','))"
        ),
        "1,2,1,2\n"
    );
}

#[test]
fn typed_array_stores_wrap_and_clamp() {
    // An integer element type wraps at its own width; `Int8Array` of `255` is `-1`, and
    // `Int32Array` of `2^32 - 1` is `-1` as well.
    assert_eq!(
        eval(
            "var a = new Int8Array(1); a[0] = 255; var b = new Int32Array(1);\n\
              b[0] = Math.pow(2, 32) - 1; print(a[0], b[0])"
        ),
        "-1 -1\n"
    );
    // `Uint8ClampedArray` clamps instead, and rounds half to *even*: `0.5` is `0`, `2.5` is
    // `2`, `1.5` is `2`.
    assert_eq!(
        eval(
            "var a = new Uint8ClampedArray(5);\n\
              a[0] = -100; a[1] = 1.5; a[2] = 0.5; a[3] = 1233.5; a[4] = NaN;\n\
              print(a.join(','))"
        ),
        "0,2,0,255,0\n"
    );
    // …and a float view round-trips through half precision.
    assert_eq!(
        eval("print(new Float16Array([1, 0.5, -2]).join(','))"),
        "1,0.5,-2\n"
    );
}

#[test]
fn typed_array_writes_convert_their_value_before_storing() {
    // The value conversion is `ToNumber`/`ToBigInt`, both of which are observable script.
    // Storing the raw `Value` made every object land as `NaN`, so a `valueOf` that returned
    // a number was silently ignored: `new Uint8Array([{valueOf(){return 5}}])` was `0`.
    assert_eq!(
        eval(
            "var a = new Uint8Array([{valueOf: function () { return 5; }}, '7', true]);\n\
              print(a.join(','))"
        ),
        "5,7,1\n"
    );
    // `a[i] = obj` takes the same path, so it has to convert too.
    assert_eq!(
        eval(
            "var b = new Float64Array(1); b[0] = {valueOf: function () { return 0.5; }};\n\
              print(b[0])"
        ),
        "0.5\n"
    );
    // A BigInt element type runs `ToBigInt` on each value, so a BigInt-returning `valueOf`
    // works and a String parses — but a Number is refused, and the two failures are
    // *different kinds*: `TypeError` for the Number, `SyntaxError` for a bad literal.
    assert_eq!(
        eval(
            "var c = new BigInt64Array([{valueOf: function () { return 3n; }}, '4', true]);\n\
              print(c.join(','))"
        ),
        "3,4,1\n"
    );
    assert!(throws("new BigInt64Array([1])").starts_with("TypeError"));
    assert_eq!(
        throws("new BigInt64Array(['nope'])"),
        "SyntaxError: invalid bigint literal\n    at BigInt64Array (native)\n    \
         at <eval> (<input>:1:18)"
    );
    // A Symbol has no number form at all, so both element families refuse it rather than
    // storing `NaN` or `0n`.
    assert!(throws("new Uint8Array([Symbol()])").starts_with("TypeError"));
    assert!(throws("new BigInt64Array([Symbol()])").starts_with("TypeError"));
}

#[test]
fn to_bigint_differs_from_the_bigint_constructor_on_a_number() {
    // §7.1.14 versus §21.2.1: `BigInt(1)` is `1n` but `ToBigInt(1)` is a `TypeError`.
    // Routing one through the other made `BigInt.asIntN(8, 1)` answer `1n` where the
    // reference throws — and it is the same substitution that made `new BigInt64Array([1])`
    // look legitimate.
    assert!(throws("BigInt.asIntN(8, 1)").starts_with("TypeError"));
    assert!(throws("BigInt.asUintN(8, 1)").starts_with("TypeError"));
    // A String parses, with the radix forms and none of the sign rules of a Number.
    assert_eq!(
        eval(
            "print(BigInt.asIntN(16, '255'), BigInt.asIntN(16, '0xff'),\n\
              BigInt.asIntN(16, true), BigInt.asIntN(16, ''))"
        ),
        "255n 255n 1n 0n\n"
    );
    // `StrNonDecimalIntegerLiteral` carries no sign, so these are `SyntaxError`s.
    for source in [
        "BigInt('-0x10')",
        "BigInt('+0x10')",
        "BigInt('- 1')",
        "BigInt(' +0x10 ')",
    ] {
        assert!(
            throws(source).starts_with("SyntaxError"),
            "{source} should be a SyntaxError"
        );
    }
    // An object is `ToPrimitive`d first, and `Symbol()` is not convertible at all. That
    // last one used to recurse forever: `to_primitive` hands a symbol straight back, so the
    // conversion re-entered itself on the same value until the process aborted.
    assert_eq!(
        eval("print(BigInt({valueOf: function () { return 12n; }}), BigInt(Object(5n)))"),
        "12n 5n\n"
    );
    assert!(throws("BigInt(Symbol())").starts_with("TypeError"));
    assert!(throws("BigInt.asIntN(8, Symbol())").starts_with("TypeError"));
}

#[test]
fn weak_collections_do_not_keep_their_keys_alive() {
    // The whole point of `WeakMap`: an entry keyed by an otherwise-unreachable object is
    // reclaimed with that object. Here that happens the instant the last strong handle goes,
    // because the engine frees on release rather than waiting for a collector.
    assert_eq!(
        eval(
            "var wm = new WeakMap();\n\
             var k = {};\n\
             wm.set(k, 'v');\n\
             print(wm.get(k), wm.has(k));\n\
             k = null;\n\
             print(wm.has({}), wm.get({}))"
        ),
        "v true\nfalse undefined\n"
    );
    // A `WeakSet` is the same machinery without a value slot.
    assert_eq!(
        eval(
            "var ws = new WeakSet(); var o = {};\n\
             ws.add(o); print(ws.has(o)); o = null; print(ws.has({}))"
        ),
        "true\nfalse\n"
    );
    // A key has to be an object or a symbol; a primitive is a `TypeError` from `set`/`add`
    // but merely `undefined`/`false` from the readers.
    assert!(throws("new WeakMap().set(1, 2)").starts_with("TypeError"));
    assert!(throws("new WeakSet().add('s')").starts_with("TypeError"));
    assert_eq!(
        eval("print(new WeakMap().get(1), new WeakMap().has(1), new WeakSet().delete(1))"),
        "undefined false false\n"
    );
    // A *registered* symbol cannot be held weakly (it never dies), but a plain one and a
    // well-known one can — the `symbols-as-weakmap-keys` rule.
    assert!(throws("new WeakMap().set(Symbol.for('k'), 1)").starts_with("TypeError"));
    assert_eq!(
        eval(
            "var wm2 = new WeakMap(); var sym = Symbol('a');\n\
             wm2.set(sym, 7); wm2.set(Symbol.hasInstance, 8);\n\
             print(wm2.get(sym), wm2.get(Symbol.hasInstance))"
        ),
        "7 8\n"
    );
}

#[test]
fn weak_ref_derefs_until_the_target_dies() {
    assert_eq!(
        eval(
            "var o = {}; var r = new WeakRef(o);\n\
             print(r.deref() === o);\n\
             o = null;\n\
             print(r.deref() === undefined)"
        ),
        "true\ntrue\n"
    );
    // A symbol is a valid target too; a primitive is not.
    assert_eq!(
        eval("var s = Symbol('t'); print(new WeakRef(s).deref() === s)"),
        "true\n"
    );
    assert!(throws("new WeakRef(1)").starts_with("TypeError"));
    assert!(throws("new WeakRef()").starts_with("TypeError"));
    // `WeakRef` is a constructor only: calling it without `new` is refused.
    assert!(throws("WeakRef({})").starts_with("TypeError"));
}

#[test]
fn finalization_registry_runs_its_callback_at_a_safe_point() {
    // The callback runs at a job boundary, not from inside a drop: the engine never runs
    // script while it is holding an internal borrow. A host can force the point with the
    // collector hook.
    assert_eq!(
        eval(
            "var seen = [];\n\
             var fr = new FinalizationRegistry(function (held) { seen.push(held); });\n\
             (function () { var target = {}; fr.register(target, 'held'); })();\n\
             print(seen.length);\n\
             __gc();\n\
             print(seen.length, seen[0])"
        ),
        "0\n1 held\n"
    );
    // `unregister` cancels by `SameValue` token, and the held value must not be the target
    // (it would be kept alive by the registry forever).
    assert_eq!(
        eval(
            "var fired = 0;\n\
             var fr2 = new FinalizationRegistry(function () { fired++; });\n\
             var token = {};\n\
             (function () { var t = {}; fr2.register(t, 1, token); })();\n\
             print(fr2.unregister(token));\n\
             __gc();\n\
             print(fired)"
        ),
        "true\n0\n"
    );
    assert!(throws("new FinalizationRegistry(1)").starts_with("TypeError"));
    assert_eq!(
        eval(
            "var t = {};\n\
             try { new FinalizationRegistry(function(){}).register(t, t) }\n\
             catch (e) { print(e.name) }"
        ),
        "TypeError\n"
    );
}

#[test]
fn typed_array_callbacks_receive_their_this_arg() {
    // The same root cause as the Array methods two rounds earlier: `call_typed` passed
    // `undefined` to `[[Call]]`, so `typedArray.map(f, thisArg)` dropped it. test262's
    // `map`/`filter`/`forEach`/`some`/`every`/`find`/`findIndex` callbackfn-this cases are
    // nothing but `assert(this === thisArg)`.
    //
    // Each method is checked on its own rather than through a shared counter: the
    // short-circuiting ones (`some`/`every`/`find`/`findIndex`) stop early by design, so a
    // single counter would measure the short-circuit as much as the `this` binding.
    assert_eq!(
        eval(
            "var t = { tag: 1 };\n\
             var a = new Uint8Array([1, 2, 3]);\n\
             function bound(f) { var ok = true; f(ok); return ok; }\n\
             var results = [\n\
               a.map(function (v) { return this === t ? v : -1; }, t).join(),\n\
               a.filter(function () { return this === t; }, t).length,\n\
               a.some(function () { return this === t; }, t),\n\
               a.every(function () { return this === t; }, t),\n\
               a.find(function () { return this === t; }, t),\n\
               a.findIndex(function () { return this === t; }, t)\n\
             ];\n\
             var seen = [];\n\
             a.forEach(function () { seen.push(this === t); }, t);\n\
             print(results.join('/'), seen.length, seen.every(Boolean))"
        ),
        "1,2,3/3/true/true/1/0 3 true\n"
    );
    // `reduce`/`reduceRight` are the exception and must stay one: their second argument is
    // the initial accumulator, so no `thisArg` is read — and in sloppy mode the callback's
    // `this` is therefore the global object, not `undefined`.
    assert_eq!(
        eval(
            "var a = new Uint8Array([1, 2]);\n\
             print(a.reduce(function (x, y) { return x + y; }, 10),\n\
                   a.reduceRight(function (x, y) { return x + y; }, 10),\n\
                   a.reduce(function (x, y) { return this === globalThis ? x + y : -1; }, 10))"
        ),
        "13 13 13\n"
    );
}

#[test]
fn set_methods_take_a_set_like_record_not_just_a_set() {
    // §24.2.3.13–.19 all take a `SetRecord`: any object with a numeric `size`, a `has`
    // method and a `keys` method. That is why they cannot be layered on
    // `Set.prototype.has` — the argument need not be a `Set` at all.
    assert_eq!(
        eval(
            "var a = new Set([1, 2, 3]);\n\
             var b = new Set([2, 3, 4]);\n\
             function sorted(set) { return set instanceof Set ? [...set].sort().join() : set; }\n\
             print(sorted(a.union(b)), sorted(a.intersection(b)),\n\
                   sorted(a.difference(b)), sorted(a.symmetricDifference(b)))"
        ),
        "1,2,3,4 2,3 1 1,4\n"
    );
    assert_eq!(
        eval(
            "var a = new Set([1, 2]);\n\
             var like = { size: 1, has: function (k) { return k === 9; },\n\
                          keys: function () { return [9][Symbol.iterator](); } };\n\
             print(a.isSubsetOf(new Set([1, 2, 3])), a.isSubsetOf(new Set([1])));\n\
             print(a.isSupersetOf(new Set([1])), a.isSupersetOf(new Set([1, 9])));\n\
             print(a.isDisjointFrom(new Set([9])), a.isDisjointFrom(new Set([1])));\n\
             print([...a.union(like)].sort().join())"
        ),
        "true false\ntrue false\ntrue false\n1,2,9\n"
    );
    // `GetSetRecord` validates all three members, and `size` has to be a number — even
    // for the methods that never call `keys`.
    assert!(throws("new Set().union({ has: function () {} })").starts_with("TypeError"));
    assert!(
        throws("new Set().union({ size: 'x', has: function () {}, keys: function () {} })")
            .starts_with("TypeError")
    );
    assert!(
        throws("new Set().difference({ size: 1, has: function () {}, keys: {} })")
            .starts_with("TypeError")
    );
    assert!(
        throws("new Set().isSubsetOf({ size: 1, has: function () {}, keys: undefined })")
            .starts_with("TypeError")
    );
}

#[test]
fn uri_and_escape_globals_follow_their_annex_b_rules() {
    // `encodeURI` keeps the URI's own delimiters; `encodeURIComponent` does not. This pair
    // is the whole difference between the two, and it was missing entirely.
    assert_eq!(
        eval("print(encodeURI('a b/c?d=e&f#g'), encodeURIComponent('a b/c?d=e&f#g'))"),
        "a%20b/c?d=e&f#g a%20b%2Fc%3Fd%3De%26f%23g\n"
    );
    // `decodeURI` puts a decoded reserved character back in its `%XX` form.
    assert_eq!(
        eval("print(decodeURI('%2F%20'), decodeURIComponent('%2F%20'))"),
        "%2F  / \n"
    );
    // `escape` works on *code units*, so `\u00FF` is one byte (`%FF`) while
    // `encodeURIComponent` would produce the UTF-8 pair. Anything wider is `%uXXXX`.
    assert_eq!(
        eval("print(escape('a b'), escape('\\u00ff'), escape('\\u4e2d'), escape('@*_+-./'))"),
        "a%20b %FF %u4E2D @*_+-./\n"
    );
    // `unescape` is the inverse and leaves a stray `%` alone rather than throwing.
    assert_eq!(
        eval(
            "print(unescape('a%20b'), unescape('%FF') === '\\u00ff',\n\
                   unescape('%u4E2D'), unescape('100%'))"
        ),
        "a b true 中 100%\n"
    );
    // A malformed escape is a `URIError` from the URI functions, but not from `unescape`.
    assert!(throws("decodeURIComponent('%')").starts_with("URIError"));
    assert!(throws("decodeURI('%zz')").starts_with("URIError"));
}

#[test]
fn aggregate_error_takes_an_iterable_and_a_cause() {
    assert_eq!(
        eval(
            "var e = new AggregateError([1, 2], 'msg');\n\
             print(e.name, e.message, e.errors.join(), e instanceof Error,\n\
                   e instanceof AggregateError, e.toString())"
        ),
        "AggregateError msg 1,2 true true AggregateError: msg\n"
    );
    // `errors` is an own, non-enumerable data property; `length` is 2 because the
    // constructor takes `(errors, message, options)`.
    assert_eq!(
        eval(
            "var e = new AggregateError([1]);\n\
             print(Object.getOwnPropertyDescriptor(e, 'errors').enumerable,\n\
                   AggregateError.length, AggregateError.name)"
        ),
        "false 2 AggregateError\n"
    );
    // `InstallErrorCause` tests `in`, so `{cause: undefined}` installs the property.
    assert_eq!(
        eval(
            "print(new AggregateError([], 'm', { cause: 7 }).cause,\n\
                   'cause' in new AggregateError([], 'm'),\n\
                   'cause' in new AggregateError([], 'm', { cause: undefined }))"
        ),
        "7 false true\n"
    );
    // A missing `errors` is a `TypeError` from `IteratorToList`, called without `new` too.
    assert!(throws("new AggregateError()").starts_with("TypeError"));
    assert_eq!(eval("print(AggregateError([1], 'm').message)"), "m\n");
}

#[test]
fn string_methods_coerce_their_receiver_but_to_string_does_not() {
    // §22.1: the methods run `RequireObjectCoercible` then `ToString`, so a non-string
    // receiver is converted. Only `toString`/`valueOf` run `thisStringValue`, a brand
    // check. Treating them all as brand checks made 116 test262 cases fail.
    assert_eq!(
        eval(
            "print(String.prototype.trim.call(123),\n\
                   String.prototype.toUpperCase.call(true),\n\
                   String.prototype.slice.call(123, 1),\n\
                   String.prototype.includes.call({ toString: function () { return 'ab'; } }, 'b'))"
        ),
        "123 TRUE 23 true\n"
    );
    // `null` and `undefined` are the one refusal: `RequireObjectCoercible` comes first.
    assert!(throws("String.prototype.trim.call(null)").starts_with("TypeError"));
    assert!(throws("String.prototype.trim.call(undefined)").starts_with("TypeError"));
    // A Symbol has no string form at all, so `ToString` refuses it too.
    assert!(throws("String.prototype.trim.call(Symbol())").starts_with("TypeError"));
    // …but the two brand-checking methods refuse everything that is not a string.
    assert!(throws("String.prototype.toString.call(123)").starts_with("TypeError"));
    assert!(throws("String.prototype.valueOf.call(123)").starts_with("TypeError"));
    assert!(throws("String.prototype.toString.call({})").starts_with("TypeError"));
    assert_eq!(
        eval("print(String.prototype.toString.call(new String('x')))"),
        "x\n"
    );
}

#[test]
fn string_split_converts_its_separator() {
    // `ToString(separator)`, so an object separator is observable — and a `toString` that
    // answers another object is a `TypeError` out of `ToPrimitive`. Leaving a non-string
    // separator alone made this "pass" for the wrong reason: the receiver refused first.
    assert_eq!(
        eval("print('a-b'.split({ toString: function () { return '-'; } }).join('|'))"),
        "a|b\n"
    );
    assert!(
        throws("'1'.split({ toString: function () { return /x/; } })").starts_with("TypeError")
    );
    // The default separator, and an empty one, keep their old shapes.
    assert_eq!(
        eval("print('abc'.split().length, ''.split().length, 'abc'.split('').join('|'))"),
        "1 0 a|b|c\n"
    );
}

#[test]
fn typed_array_reads_and_detachment() {
    // Out-of-range reads and writes are silently `undefined`/ignored, not errors.
    assert_eq!(
        eval("var a = new Uint8Array(2); a[5] = 1; print(String(a[5]), a.length)"),
        "undefined 2\n"
    );
    // `transfer()` detaches: the byte count drops to 0 and every index reads `undefined`,
    // which all the views of that buffer see at once.
    assert_eq!(
        eval(
            "var b = new ArrayBuffer(16); var a = new Uint8Array(b); a.fill(42);\n\
              var before = a[0]; b.transfer();\n\
              print(before, String(a[0]), a.length, b.byteLength)"
        ),
        "42 undefined 0 0\n"
    );
    // A misaligned or oversized window is a `RangeError`.
    assert_eq!(
        throws("new Uint32Array(new ArrayBuffer(16), 2, 1)"),
        "RangeError: invalid offset\n    at Uint32Array (native)\n    \
         at <eval> (<input>:1:16)"
    );
    assert_eq!(
        throws("new Uint32Array(new ArrayBuffer(4), 0, 2)"),
        "RangeError: invalid length\n    at Uint32Array (native)\n    \
         at <eval> (<input>:1:16)"
    );
    // One argument means "the rest of the buffer", so a missing length is not a `NaN` error.
    assert_eq!(
        eval("var b = new ArrayBuffer(16); print(new Uint8Array(b).length)"),
        "16\n"
    );
}

#[test]
fn strings_hold_unpaired_surrogates() {
    // The whole reason for the WTF-8 representation: `String.fromCharCode` takes a code
    // unit, and a unit with no partner is a legal string.
    assert_eq!(
        eval(
            "var s = String.fromCharCode(0xD800);\n\
              print(s.length, s.charCodeAt(0))"
        ),
        "1 55296\n"
    );
    // Building a run of units, which is what a script does when it assembles a string.
    assert_eq!(
        eval(
            "var s = ''; for (var i = 0; i < 5; i++) s += String.fromCharCode(0xD800 + i);\n\
              print(s.length, s.charCodeAt(0), s.charCodeAt(4), String(s.charCodeAt(9)))"
        ),
        "5 55296 55300 NaN\n"
    );
    // `length` and indexing count code *units*, so an astral character is two of them.
    assert_eq!(
        eval("print('\\u{1F600}'.length, String.fromCharCode(0xD800, 0xDC00).length)"),
        "2 2\n"
    );
    // `codePointAt` recombines a pair; `charCodeAt` does not.
    assert_eq!(
        eval(
            "var s = String.fromCharCode(0xD800, 0xDC00);\n\
              print(s.codePointAt(0), s.charCodeAt(0), s.charCodeAt(1))"
        ),
        "65536 55296 56320\n"
    );
}

#[test]
fn concatenation_keeps_the_encoding_canonical() {
    // A surrogate pair split across a `+` must produce the *same* string as the astral
    // character, or equality and property keys would disagree with the language.
    assert_eq!(
        eval("print(String.fromCharCode(0xD800) + String.fromCharCode(0xDC00) === '\\u{10000}')"),
        "true\n"
    );
    assert_eq!(
        eval("print((String.fromCharCode(0xD800) + String.fromCharCode(0xDC00)).length)"),
        "2\n"
    );
    // …and the same through `+=`, which is how a script usually builds one.
    assert_eq!(
        eval(
            "var s = ''; s += String.fromCharCode(0xD83D); s += String.fromCharCode(0xDE00);\n\
              print(s.length, s === '\\u{1F600}')"
        ),
        "2 true\n"
    );
    // Two unpaired surrogates that are *not* a pair stay two separate units.
    assert_eq!(
        eval("print((String.fromCharCode(0xD800) + String.fromCharCode(0xD800)).length)"),
        "2\n"
    );
}

#[test]
fn a_lone_surrogate_key_is_its_own_property() {
    // A key with an unpaired surrogate must not collide with the replacement character,
    // which is what a lossy conversion would do.
    assert_eq!(
        eval(
            "var o = {};\n\
              o[String.fromCharCode(0xD800)] = 1;\n\
              o[String.fromCharCode(0xFFFD)] = 2;\n\
              print(o[String.fromCharCode(0xD800)], o[String.fromCharCode(0xFFFD)],\n\
                    Object.keys(o).length)"
        ),
        "1 2 2\n"
    );
}

#[test]
fn indexing_a_long_string_stays_linear() {
    // `charCodeAt` in a loop must not re-decode from the start each time: it is the one
    // shape a script uses to walk a whole string, so the code units are cached on first
    // use. 60k units is enough that a quadratic implementation would take minutes.
    assert_eq!(
        eval(
            "var s = ''; for (var i = 0; i < 60000; i++) s += String.fromCharCode(i & 0xffff);\n\
              var bad = 0;\n\
              for (var i = 0; i < 60000; i++) if (s.charCodeAt(i) !== (i & 0xffff)) bad++;\n\
              print(s.length, bad)"
        ),
        "60000 0\n"
    );
}

#[test]
fn bigint_is_exact_at_any_width() {
    // The canonical representation is what makes a computed value equal to itself.
    assert_eq!(
        eval("print(2n ** 1000n === 2n ** 1000n, 2n ** 1000n - (2n ** 1000n - 1n))"),
        "true 1n\n"
    );
    assert_eq!(
        eval("print(1n + 2n, 10n - 3n, 6n * 7n, 7n / 2n, 7n % 2n, 1n << 128n)"),
        "3n 7n 42n 3n 1n 340282366920938463463374607431768211456n\n"
    );
    assert_eq!(eval("print(typeof 1n, -5n, ~0n)"), "bigint -5n -1n\n");
    // `>>` is arithmetic: `-1n >> 1n` is `-1n`, not `0n`.
    assert_eq!(
        eval("print(-1n >> 1n, -3n >> 1n, -1n & 3n, -1n | 3n)"),
        "-1n -2n 3n -1n\n"
    );
}

#[test]
fn bigint_and_number_never_mix_in_arithmetic() {
    // The trace is part of the expectation: `qjs` reports a pending exception with
    // `JS_PrintValue`, which for an error prints its stack.
    for (expression, column) in [("1n + 1", 4), ("1n * 2", 4), ("1 - 1n", 3)] {
        assert_eq!(
            throws(expression),
            format!(
                "TypeError: cannot convert bigint to number\n    at <eval> (<input>:1:{column})"
            ),
            "{expression}"
        );
    }
    // Relation is the exception: it compares the mathematical values, not rounded ones.
    assert_eq!(
        eval("print(-1n < 1n, 2n < 2.5, 3n > 2.5)"),
        "true true true\n"
    );
    // …and loose equality crosses the types while strict does not.
    assert_eq!(
        eval("print(1n == 1, 1n === 1, 1n == '1')"),
        "true false true\n"
    );
}

#[test]
fn bigint_conversion_is_exact_or_refuses() {
    assert_eq!(
        eval("print(BigInt(5), BigInt('123'), BigInt(true), BigInt('0x1f'))"),
        "5n 123n 1n 31n\n"
    );
    // `StringToBigInt` reads an empty literal as zero, while a lone sign stays a
    // `SyntaxError` — that pair is why the empty case cannot simply be "no digits".
    assert_eq!(
        eval("print(BigInt(''), BigInt('   '), BigInt('  123  '))"),
        "0n 0n 123n\n"
    );
    for source in ["BigInt('+')", "BigInt('-')", "BigInt('\\x00a')"] {
        assert!(
            throws(source).starts_with("SyntaxError"),
            "{source} should be a SyntaxError"
        );
    }
    // A fraction has no exact bigint form, so it is a `RangeError` rather than a truncation.
    assert!(throws("BigInt(1.5)").starts_with("RangeError"));
    // A bigint is a primitive, so there is no wrapper to construct — but `BigInt` *is*
    // constructible as far as `[[Construct]]` is concerned (the reference registers it with
    // `JS_CFUNC_constructor_or_func`), and the refusal happens inside the native function.
    // That is why the trace has an `at BigInt (native)` frame above the caller.
    assert_eq!(
        throws("new BigInt(1)"),
        "TypeError: BigInt is not a constructor\n    at BigInt (native)\n    \
         at <eval> (<input>:1:11)"
    );
    // The message names `new.target`, not the callee: a subclass constructed through
    // `super()` reports its own name. Its frame sits at the class body's closing `}`
    // because a class that writes no constructor still gets one, created at that token.
    assert_eq!(
        throws("class B extends BigInt {}; new B(1)"),
        "TypeError: B is not a constructor\n    at BigInt (native)\n    \
         at B (<input>:1:25)\n    at <eval> (<input>:1:33)"
    );
    assert_eq!(
        eval("print((255n).toString(16), BigInt.asIntN(8, 128n))"),
        "ff -128n\n"
    );
    // `Number()` of a bigint rounds to the nearest double, losing width past 53 bits.
    assert_eq!(
        eval("print(Number(1n), Number(0xffffffffffffffffn))"),
        "1 18446744073709552000\n"
    );
}

#[test]
fn bigint_obeys_the_number_rules_for_truth_and_equality() {
    // `0n` is falsy. Treating every bigint as truthy made `if (b & 1n)` branch
    // unconditionally, which silently corrupted bigint algorithms that test a bit —
    // `compute_pi` drifted from the 29th digit onwards.
    assert_eq!(
        eval("print(0n ? 'T' : 'F', 1n ? 'T' : 'F', !0n, Boolean(-1n))"),
        "F T true true\n"
    );
    // `++`/`--` keep a bigint a bigint. Routing them through `ToNumber` produced `NaN`,
    // so `for (i = 0n; i < n; i++)` ran exactly once.
    assert_eq!(
        eval("var i = 0n; print(i++, i, ++i, typeof i); var j = 3n; print(j--, j)"),
        "0n 1n 2n bigint\n3n 2n\n"
    );
    // Unary `+` asks for a *number*, which a bigint cannot become, so it is a `TypeError`
    // rather than the `NaN` it used to be.
    assert!(throws("+1n").starts_with("TypeError"));
    // Loose equality compares the exact integers, not two rounded doubles:
    // `100000000000000000001n` and `1e20` round to the same double but are not equal.
    // A boolean is `ToNumber`ed first, so `true == 1n` holds.
    assert_eq!(
        eval(
            "print(2 == 3n, 2 == 2n, '' == 0n, 2.5 == 2n, true == 1n, false == 0n,\n\
             100000000000000000000n == 1e20, 100000000000000000001n == 1e20, null == 0n)"
        ),
        "false true true false true true true false false\n"
    );
    // `+` concatenates before it ever considers the numeric types.
    assert_eq!(eval("print('a' + 1n, 1n + 'b')"), "a1 1b\n");
    assert!(throws("1n + 1").starts_with("TypeError"));
}

#[test]
fn map_keys_use_same_value_zero() {
    // `NaN` equals itself as a key, which `===` does not give.
    assert_eq!(
        eval("var m = new Map(); m.set(NaN, 'nan'); print(m.get(NaN), m.size)"),
        "nan 1\n"
    );
    // Numbers, strings and bigints are three different keys even when they look alike.
    assert_eq!(
        eval(
            "var m = new Map(); m.set(1, 'n'); m.set('1', 's'); m.set(1n, 'b');\n\
              print(m.size, m.get(1), m.get('1'), m.get(1n))"
        ),
        "3 n s b\n"
    );
    // Objects key by identity, never structurally.
    assert_eq!(
        eval(
            "var m = new Map(); var a = {}, b = {}; m.set(a, 'a');\n\
              print(m.get(a), m.get(b))"
        ),
        "a undefined\n"
    );
    // Insertion order is iteration order, and a re-set key keeps its position.
    assert_eq!(
        eval(
            "var m = new Map(); m.set(1, 'a'); m.set(2, 'b'); m.set(1, 'c');\n\
              var log = []; m.forEach(function (v, k) { log.push(k + ':' + v) });\n\
              print(m.size, log.join(','))"
        ),
        "2 1:c,2:b\n"
    );
}

#[test]
fn map_and_set_surface() {
    assert_eq!(
        eval(
            "var m = new Map([[1, 'a'], [2, 'b']]);\n\
              print(m.size, m.has(1), m.delete(1), m.has(1), m.size)"
        ),
        "2 true true false 1\n"
    );
    // A `Set` deduplicates and its entries repeat the value.
    assert_eq!(
        eval(
            "var s = new Set([1, 2, 2, 3]);\n\
              print(s.size, [...s.entries()].map(e => e.join('=')).join(','))"
        ),
        "3 1=1,2=2,3=3\n"
    );
    assert_eq!(
        eval(
            "print(Object.prototype.toString.call(new Map()),\n\
                    Object.prototype.toString.call(new Set()))"
        ),
        "[object Map] [object Set]\n"
    );
    assert_eq!(
        eval(
            "var s = new Set(['a']); var out = [];\n\
              s.forEach(function (v, k) { out.push(v === k) });\n\
              print(out.join(','))"
        ),
        "true\n"
    );
}

#[test]
fn regexp_character_class_set_algebra() {
    // `v` mode replaces the flat range list with a real set algebra: nested classes,
    // intersection and subtraction.
    assert_eq!(
        eval("print('aAbBcC'.replace(/[[a-c]&&B]/gvi, 'X'))"),
        "aAXXcC\n"
    );
    assert_eq!(
        eval("print('aAbBcC'.replace(/[[a-c]--B]/gvi, 'X'))"),
        "XXbBXX\n"
    );
    // `\q{…}` makes a set of *strings*: a member may be two characters long, so matching it
    // consumes two and the alternation is tried longest-first.
    assert_eq!(
        eval("print('abcAbC'.replace(/[\\q{BC|A}]/gvi, 'X'))"),
        "XXXX\n"
    );
    assert_eq!(
        eval("print('abcAbC'.replace(/[\\q{BC|A}--a]/gvi, 'X'))"),
        "aXAX\n"
    );
    // `&&` and `--` cannot be mixed at one level, and `-` must be escaped.
    assert!(throws("new RegExp('[[a-c]&&B--a]', 'v')").starts_with("SyntaxError"));
    // A range is still a range, but a lone `-` has to be escaped — that is what makes `--`
    // unambiguous as the subtraction operator.
    assert_eq!(eval("print(/[a-z]/v.test('m'))"), "true\n");
    assert!(throws("new RegExp('[-]', 'v')").starts_with("SyntaxError"));
    assert!(throws("new RegExp('[a-]', 'v')").starts_with("SyntaxError"));
}

#[test]
fn regexp_u_and_v_disagree_about_negated_properties() {
    // Under `i`, `u` negates per case variant — `a` canonicalises to the non-lowercase `A` —
    // while `v` case-closes the set first and only then complements it.
    assert_eq!(
        eval("print(/\\P{Lower}/ui.test('a'), /\\P{Lower}/vi.test('a'))"),
        "true false\n"
    );
    assert_eq!(
        eval(
            "print('aAbBcC#4'.replace(/\\P{Lower}/gui, 'X'), 'aAbBcC#4'.replace(/\\P{Lower}/gvi, 'X'))"
        ),
        "XXXXXXXX aAbBcCXX\n"
    );
    // …so the double negation `[^\P{Lower}]` means "lowercase letters" in `v`.
    assert_eq!(
        eval("print('aAbBcC#4'.replace(/[^\\P{Lower}]/gvi, 'X'))"),
        "XXXXXX#4\n"
    );
    // A property escape inside a class works in `u` as well.
    assert_eq!(
        eval("print(/[\\p{Lower}]/u.test('a'), /[\\p{Lower}]/u.test('A'))"),
        "true false\n"
    );
}

#[test]
fn regexp_code_point_escapes_and_code_unit_offsets() {
    // `\u{…}` is the strict-grammar spelling of a code point; without `u` it is the letter
    // `u` followed by a quantifier, which is the Annex B reading.
    assert_eq!(
        eval("print(/\\u{10000}/u.test('\\u{10000}'), /\\u{2}/.test('uu'))"),
        "true true\n"
    );
    assert_eq!(eval("print(/\\u{2}/.source)"), "\\u{2}\n");
    // `index`, `lastIndex` and the `d` flag's pairs all count UTF-16 code *units*, so an
    // astral match spans two.
    assert_eq!(
        eval("var m = /\\u{10000}/u.exec('a\\u{10000}'); print(m.index, m[0].length)"),
        "1 2\n"
    );
    assert_eq!(
        eval("var m = /\\u{10000}/vgd.exec('\\u{10000}_'); print(m.indices[0].join(','))"),
        "0,2\n"
    );
    // A `lastIndex` inside a surrogate pair belongs to the character containing it, which is
    // the same as rounding down to a code point boundary.
    assert_eq!(
        eval("var a = /(?:)/gu; a.lastIndex = 1; a.exec('\\u{1F600}'); print(a.lastIndex)"),
        "0\n"
    );
}

#[test]
fn a_sets_default_iterator_yields_values_not_entries() {
    // A `Map` iterates `[key, value]` pairs and a `Set` iterates its values. Wiring both
    // to `entries` made `[...new Set([3])]` produce `[[3, 3]]` — one pair — which reads
    // like a working iterator until you look at the elements.
    assert_eq!(
        eval(
            r#"
print([...new Set([3])].join());
print([...new Set([1,2,2,3])].join());
for (const v of new Set(["a"])) print("v:" + v);
print([...new Map([["k", 1]])].join("|"));
"#
        ),
        "3\n1,2,3\nv:a\nk,1\n"
    );
}

#[test]
fn array_from_reads_an_iterable_not_only_an_array_like() {
    // A `Map` and a `Set` have no `length`, so an array-like-only reader answered `[]`
    // for both — the wrong answer rather than an error.
    assert_eq!(
        eval(
            r#"
print(JSON.stringify(Array.from(new Set([1,2]))));
print(JSON.stringify(Array.from(new Map([[1,2]]))));
print(JSON.stringify(Array.from("ab")));
print(JSON.stringify(Array.from([1,2])));
print(JSON.stringify(Array.from({length: 2, 0: "x", 1: "y"})));
print(JSON.stringify(Array.from(new Set([1,2]), v => v * 10)));
"#
        ),
        "[1,2]\n[[1,2]]\n[\"a\",\"b\"]\n[1,2]\n[\"x\",\"y\"]\n[10,20]\n"
    );
}

#[test]
fn function_name_length_and_prototype_have_the_spec_attributes() {
    // Every one of these was `configurable: false` — derived from `writable`, a
    // derivation that is right for a built-in method and wrong for these three shapes.
    // Roughly five hundred conformance tests depended on it, spread over every built-in,
    // because `Object.assign`, `bind` and every `defineProperty(f, "length", …)` need to
    // be able to redefine them.
    let descriptor = |expr: &str| {
        value(&format!(
            r#"var d = Object.getOwnPropertyDescriptor({expr});
               d === undefined ? "absent" : [d.writable, d.enumerable, d.configurable].join(",")"#
        ))
    };
    // `{writable: false, enumerable: false, configurable: true}` for name and length.
    let pairs = [
        ("(function f(a){})", "name"),
        ("(function f(a){})", "length"),
        ("(function(){})", "name"),
        ("(()=>{})", "name"),
        ("(()=>{})", "length"),
        ("(class C{})", "name"),
        ("Object", "name"),
        ("Object", "length"),
        ("Array.prototype.map", "name"),
        ("Array.prototype.map", "length"),
        ("(function f(a){}).bind(null)", "name"),
        ("(function f(a){a}).bind(null)", "length"),
        (
            "Object.getOwnPropertyDescriptor({get x(){}}, 'x').get",
            "name",
        ),
    ];
    for (object, key) in pairs {
        assert_eq!(
            descriptor(&format!("{object}, \"{key}\"")),
            "false,false,true",
            "{object}.{key}"
        );
    }
    // An anonymous function's name is present and empty, not absent.
    assert_eq!(value("(function(){}).name"), "");
    assert_eq!(value("(()=>{}).name"), "");
    assert_eq!(value("(class {}).name"), "");
    // A user function's `prototype` is writable but *not* configurable, and a built-in
    // constructor's is neither.
    assert_eq!(
        descriptor("(function f(){}), \"prototype\""),
        "true,false,false"
    );
    assert_eq!(descriptor("Object, \"prototype\""), "false,false,false");
    assert_eq!(value("delete (function f(){}).prototype"), "false");
    // NamedEvaluation still names an anonymous class after its binding.
    assert_eq!(value("var x = class {}; x.name"), "x");
    assert_eq!(value("var x = class {}; typeof x"), "function");
}

#[test]
fn array_methods_are_generic_over_array_likes_and_read_the_receiver_lazily() {
    // Every line here was wrong: the receiver was copied up front (so the third callback
    // argument was an impostor and a callback that deleted an element still saw it),
    // holes were dropped from `map`'s result, a primitive receiver was not boxed, and an
    // absurd `length` looped instead of being refused.
    assert_eq!(
        eval(
            r#"
var o = {length: 2, 0: 1, 1: 2};
var same = null;
Array.prototype.map.call(o, function (v, i, x) { same = x; });
print(same === o);

var a = [1, 2];
print(JSON.stringify(a.map(function (v, i, x) { if (i === 0) x[1] = 99; return v; })));
print(JSON.stringify([1,,3].map(function (x) { return x; })));
print(1 in [1,,3].map(function (x) { return x; }));
print([1,,3].includes(undefined), [1,,3].indexOf(undefined));

Boolean.prototype[0] = true;
Boolean.prototype.length = 1;
print(Array.prototype.map.call(false, function (v, i, x) {
  return x instanceof Boolean;
})[0]);

print(JSON.stringify(Object.assign({}, "ab")));
print(typeof Object.assign(1, {a: 1}));

Array.prototype[1] = 9;
var visited = [];
[1,,3].forEach(function (v) { visited.push(v); });
print(JSON.stringify(visited));
delete Array.prototype[1];

try {
  Array.prototype.map.call({length: 4294967296}, function () {});
  print("no throw");
} catch (e) { print(e.name); }
"#
        ),
        concat!(
            "true\n",
            "[1,99]\n",
            "[1,null,3]\n",
            "false\n",
            "true -1\n",
            "true\n",
            "{\"0\":\"a\",\"1\":\"b\"}\n",
            "object\n",
            "[1,9,3]\n",
            "RangeError\n",
        )
    );
}

#[test]
fn define_property_follows_validate_and_apply() {
    // `Object.defineProperties` did not exist, so "undefined is not a function" was the
    // answer to everything — including the tests that assert a TypeError, which passed by
    // accident. With it in place the validation rules had to be real.
    assert_eq!(
        eval(
            r#"
function attempt(source) {
  try { return String(eval(source)); } catch (e) { return e.name; }
}
// An omitted attribute is kept, not defaulted to false.
print(attempt("var o={a:1}; Object.defineProperty(o,'a',{value:5});" +
              "JSON.stringify(Object.getOwnPropertyDescriptor(o,'a'))"));
// A non-configurable property cannot be redefined...
print(attempt("var o={}; Object.defineProperty(o,'p',{value:1});" +
              "Object.defineProperty(o,'p',{value:2})"));
// ...but redefining it with the same value is not a change, `NaN` included.
print(attempt("var o={}; Object.defineProperty(o,'n',{value:NaN});" +
              "Object.defineProperty(o,'n',{value:NaN}); 'ok'"));
// A descriptor cannot be both a data and an accessor property.
print(attempt("Object.defineProperty({},'x',{value:1,set:function(){}})"));
// A non-extensible target refuses a new property.
print(attempt("var o=Object.preventExtensions({}); Object.defineProperty(o,'p',{value:1})"));
// An array's `length` is exotic.
var a = [1, 2, 3];
Object.defineProperty(a, "length", {value: 1});
print(a.length, a[2]);
print(attempt("Object.defineProperty([],'length',{enumerable:true})"));
var b = [1, 2, 3];
Object.defineProperty(b, "length", {writable: false});
print(Object.getOwnPropertyDescriptor(b, "length").writable);
print(attempt("Object.defineProperty(b,'3',{value:'x'})"));
print(b.hasOwnProperty("3"));
"#
        ),
        concat!(
            "{\"value\":5,\"writable\":true,\"enumerable\":true,\"configurable\":true}\n",
            "TypeError\n",
            "ok\n",
            "TypeError\n",
            "TypeError\n",
            "1 undefined\n",
            "TypeError\n",
            "false\n",
            "TypeError\n",
            "false\n",
        )
    );
}

#[test]
fn typed_arrays_are_complete_enough_to_iterate_and_transform() {
    // Every one of these was `TypeError: undefined is not a function`: `%TypedArray%` and
    // its whole method family did not exist. `map`/`filter`/`slice` answer a *view of the
    // same type* rather than an array, and `map` over `BigInt64Array` must answer BigInts.
    assert_eq!(
        eval(
            r#"
print(new Int32Array([1,2,3]).map(function (x) { return x * 2; }).join(","));
print(new Int32Array([1,2,3]).map(function (x) { return x; }).constructor.name);
print(new Int32Array([1,2,3,4]).filter(function (x) { return x % 2 === 0; }).join(","));
print([...new Int32Array([1,2,3])].join(","));
print(JSON.stringify([...new Int32Array([9,8]).keys()]));
print(new Int32Array([10,9,1]).sort().join(","));
print(new Int32Array([1,2,3]).reduce(function (a, b) { return a + b; }));
print(new Int32Array([5,6,7]).at(-1), new Int32Array([5,6,7]).findLast(function (x) { return x > 5; }));

// A BigInt view reads and writes BigInts, refuses numbers, and wraps modulo 2^64.
print(typeof new BigInt64Array(1)[0]);
var wrapped = new BigUint64Array(1);
wrapped[0] = -1n;
print(wrapped[0]);
try { new BigInt64Array([1]); print("no throw"); } catch (e) { print(e.name); }
print(new BigInt64Array([1n,-2n]).sort().join(","));

// `%TypedArray%` is the shared parent of every view constructor.
var TA = Object.getPrototypeOf(Int8Array);
print(TA.name, Object.getOwnPropertyNames(TA).join(","));
print(Int8Array.from([1,2]).join(","), Int32Array.of(3,4).join(","));
try { TA(); print("no throw"); } catch (e) { print(e.name); }

// `Symbol.iterator` wins over `length` when constructing from a source.
var iterable = {};
iterable[Symbol.iterator] = function () {
  var i = 0;
  return { next: function () { return i < 2 ? { value: ++i, done: false } : { done: true }; } };
};
print(new Int32Array(iterable).join(","));

// A derived view that is too short is refused rather than written past its end.
var s = new Int8Array(2);
s.constructor = {};
s.constructor[Symbol.species] = function () { return new Int8Array(); };
try { s.map(function () { return 0; }); print("no throw"); } catch (e) { print(e.name); }

// A detached buffer makes every method throw.
var ab = new ArrayBuffer(8);
var detached = new Int32Array(ab);
ab.transfer();
try { detached.map(function () { return 0; }); print("no throw"); } catch (e) { print(e.name); }
"#
        ),
        concat!(
            "2,4,6\n",
            "Int32Array\n",
            "2,4\n",
            "1,2,3\n",
            "[0,1]\n",
            "1,9,10\n",
            "6\n",
            "7 7\n",
            "bigint\n",
            "18446744073709551615n\n",
            "TypeError\n",
            "-2,1\n",
            "TypedArray length,name,from,of,prototype\n",
            "1,2 3,4\n",
            "TypeError\n",
            "1,2\n",
            "TypeError\n",
            "TypeError\n",
        )
    );
}

#[test]
fn array_from_and_array_index_search_honour_their_arguments() {
    // `Array.from({length: 2})` was an *empty* array — a missing index was skipped instead
    // of contributing `undefined` — which quietly shortened every source a test built with
    // `Array.from({length: n}, …)`. And the typed-array searches ignored `fromIndex`
    // entirely, so a Symbol there returned cleanly instead of throwing.
    assert_eq!(
        eval(
            r#"
print(Array.from({length: 2}).length);
print(JSON.stringify(Array.from({length: 2, 0: "x"})));
print(JSON.stringify(Array.from([1], function () { return this.v; }, {v: 9})));
print(JSON.stringify(Array.from(new Set([1,2]))));

var a = new Int32Array([1,2,3,2,1]);
print(a.indexOf(2), a.indexOf(2, 2), a.indexOf(2, -2));
print(a.lastIndexOf(2), a.lastIndexOf(2, 2), a.lastIndexOf(2, -2));
print(a.includes(1, 2), a.includes(1, -1), a.includes(1, Infinity));
print(a.indexOf(1, Infinity), a.lastIndexOf(1, -Infinity));
try { a.includes(1, Symbol()); print("no throw"); } catch (e) { print(e.name); }
"#
        ),
        concat!(
            "2\n",
            "[\"x\",null]\n",
            "[9]\n",
            "[1,2]\n",
            "1 3 3\n",
            "3 1 3\n",
            "true true false\n",
            "-1 -1\n",
            "TypeError\n",
        )
    );
}

#[test]
fn array_callbacks_receive_their_this_arg_and_wrapped_strings_have_length() {
    // Two independent root causes behind one batch of failures:
    //
    // * Every callback-taking `Array.prototype` method passed `undefined` to `[[Call]]`
    //   instead of the second argument. Invisible in `arr.map(f)`, wrong in `arr.map(f, x)`
    //   — and 159 test262 files do nothing but `assert(this === thisArg)` inside one.
    //   `reduce`/`reduceRight` are the exception: their second argument is the initial
    //   accumulator, so they keep passing `undefined`.
    // * `new String(x)` filled only `_value`, never `length` or the index properties, so
    //   the box was an array-like of length 0. `ToObject` on a *primitive* had the right
    //   shape, so the two paths had drifted apart.
    assert_eq!(
        eval(
            r#"
var arg = {tag: "arg"};
var seen = [];
[1].forEach(function () { seen.push(this); }, arg);
[1].map(function () { seen.push(this); }, arg);
[1].filter(function () { seen.push(this); }, arg);
[1].some(function () { seen.push(this); }, arg);
[1].every(function () { seen.push(this); }, arg);
[1].find(function () { seen.push(this); }, arg);
[1].findIndex(function () { seen.push(this); }, arg);
[1].findLast(function () { seen.push(this); }, arg);
[1].findLastIndex(function () { seen.push(this); }, arg);
[1].flatMap(function () { seen.push(this); return []; }, arg);
print(seen.length, seen.every(function (value) { return value === arg; }));
// `reduce`'s second argument is the accumulator, not a `thisArg`, so the callback's
// `this` stays `undefined` — which sloppy mode then coerces to the global object.
print([1].reduce(function () { return this === this; }, 0, arg));

var boxed = new String("ab");
print(boxed.length, boxed[0], JSON.stringify(Object.keys(boxed)));
print(Array.prototype.every.call(boxed, function (v, i, o) {
  return o instanceof String && !(o[Symbol.iterator] === undefined);
}));
print(new String("\u{1D11E}").length);
"#
        ),
        concat!(
            "10 true\n",
            "true\n",
            "2 a [\"0\",\"1\"]\n",
            "true\n",
            "2\n",
        )
    );
}

#[test]
fn array_search_and_change_by_copy_follow_their_index_rules() {
    // `lastIndexOf` ignored `fromIndex` outright, so `[1,2,3].lastIndexOf(3, 1)` answered
    // `2` instead of `-1`; an explicit `undefined` is `ToIntegerOrInfinity(undefined)` = 0,
    // which is *not* the same as the argument being absent. The missing methods
    // (`copyWithin`, `with`, `toReversed`, `toSorted`, `toSpliced`) then had to write to
    // the receiver rather than a copy, and `copyWithin` turns a copied hole into a
    // *deleted* property.
    assert_eq!(
        eval(
            r#"
var target = {};
print([0, target, true].lastIndexOf(target, 1.5));
print([0, true, target].lastIndexOf(target, 1.5));
print([1, 2, 3].lastIndexOf(3, 1), [1, 2, 3].lastIndexOf(1, 2));
print([1, 2, 1].lastIndexOf(2, undefined), [1, 2, 1].lastIndexOf(1));
print([0, 1, 1].lastIndexOf(1, "1"), [0, 1, 1].lastIndexOf(1, "one"));

var holes = [0, 1, , , 1];
holes.copyWithin(0, 1, 4);
print(holes.length, holes[0], holes[4], holes.hasOwnProperty(1), holes.hasOwnProperty(2));

print([0, 1, 2, 3].copyWithin(1, undefined).join(","));
print(Array.prototype.copyWithin.call(true) instanceof Boolean);

print([0,,2,,4].with(2, 6).join("|"));
print([1, 2, 3].toReversed().join(","));
print([1, 2, 3].toSpliced(0, 1).join(","));
print([3,,1].toSorted().join("|"));
print([1, 2, 3].with(-1, 9).join(","));
try { [1, 2, 3].with(3, 9); } catch (e) { print(e.name); }
print([1,2,3].findLast(function (v) { return v < 3; }), [1,2,3].findLastIndex(function (v) { return v < 3; }));

print(Array.prototype[Symbol.unscopables].with, Array.prototype[Symbol.unscopables].at);
print(Object.getPrototypeOf(Array.prototype[Symbol.unscopables]));
"#
        ),
        concat!(
            "1\n",
            "-1\n",
            "-1 0\n",
            "-1 2\n",
            "1 -1\n",
            "5 1 1 false false\n",
            "0,0,1,2\n",
            "true\n",
            "0||6||4\n",
            "3,2,1\n",
            "2,3\n",
            "1|3|\n",
            "1,2,9\n",
            "RangeError\n",
            "2 1\n",
            "undefined true\n",
            "null\n",
        )
    );
}

#[test]
fn namespaced_builtins_carry_their_tostring_tag() {
    // `Object.prototype.toString.call(Math)` was `[object Object]`: none of `Math`, `JSON`
    // or `Reflect` had a `@@toStringTag`. That single omission is what a run of
    // `Array.prototype` tests check from *inside* a callback applied to `Math` and `JSON`,
    // so it showed up as a dozen `map`/`filter`/`every` failures with no array bug at all.
    // The tag is a *data* property — an accessor reports `writable: undefined` and fails
    // `verifyProperty`.
    assert_eq!(
        eval(
            r#"
print(Object.prototype.toString.call(Math), Object.prototype.toString.call(JSON));
print(Object.prototype.toString.call(Reflect));
print(Math[Symbol.toStringTag], typeof Math[Symbol.toStringTag]);
print(Object.getOwnPropertyDescriptor(Math, Symbol.toStringTag).writable);
Math.length = 1; Math[0] = 1;
print(JSON.stringify(Array.prototype.map.call(Math, function (v, i, o) {
  return Object.prototype.toString.call(o) === "[object Math]";
})));
"#
        ),
        concat!(
            "[object Math] [object JSON]\n",
            "[object Reflect]\n",
            "Math string\n",
            "false\n",
            "[true]\n",
        )
    );
}

#[test]
fn generator_return_and_throw_run_finally_blocks() {
    // `it.return()` is a `return` from the body's point of view, so every enclosing
    // `finally` has to run before the generator finishes. It emitted `return_async`
    // directly, which ended the generator and skipped the cleanup entirely — the thing
    // `for…of` and resource disposal rely on.
    assert_eq!(
        eval(
            r#"
function count(fn) { var n = 0; fn(function () { n++; }); return n; }

var a = count(function (bump) {
  var g = (function* () { try { yield 1; } finally { bump(); } })();
  g.next(); g.return();
});
var b = count(function (bump) {
  var g = (function* () { try { yield 1; yield 2; } finally { bump(); } })();
  g.next(); g.next(); g.next();          // runs to the end naturally
});
var c = count(function (bump) {
  var g = (function* () { try { yield 1; } catch (e) { bump(); } })();
  g.next(); g.throw(new Error("x"));
});
print(a, b, c);

// A tail call to a generator must not inherit the caller's frame: that made the first
// `yield` report "a generator body ran as an ordinary call".
function makeGenerator() { return (function* () { yield 7; })(); }
print(JSON.stringify(makeGenerator().next()));
"#
        ),
        concat!("1 1 1\n", "{\"value\":7,\"done\":false}\n"),
    );
}

#[test]
fn array_from_async_is_a_real_async_function() {
    // `fromAsync` is written in JavaScript and compiled at install time, because it is
    // specified as an *async* function: it must answer a promise even when `mapfn` is not
    // callable, and each mapped value is awaited exactly once per iteration.
    assert_eq!(
        eval(
            r#"
print(typeof Array.fromAsync, Array.fromAsync.length, Array.fromAsync.name);
print(Object.getPrototypeOf(Array.fromAsync) === Function.prototype);
print(Object.getOwnPropertyDescriptor(Array.fromAsync, "prototype") === undefined);

// Sequenced, not concurrent: several `fromAsync` calls interleave their microtasks, so
// the order they print in is a property of the queue rather than of the method.
(async function () {
  print("iterable", (await Array.fromAsync([1, 2, 3])).join());
  print("arraylike", (await Array.fromAsync({length: 2, 0: 4, 1: 5})).join());
  print("mapped", (await Array.fromAsync([1, 2], function (v) { return v * 10; })).join());

  try {
    await Array.fromAsync([], null);
    print("BUG: fulfilled");
  } catch (e) {
    print("bad mapfn", e.name);
  }

  // A thenable's `then` runs once per element.
  var awaited = 0;
  await Array.fromAsync([1, 2], function (v) {
    return { then: function (resolve) { awaited++; resolve(v); } };
  });
  print("awaited", awaited);

  // A rejecting thenable closes the source iterator, so its `finally` runs.
  var closed = false;
  function* source() {
    try { yield { then: function (_, reject) { reject(new Error("no")); } }; }
    finally { closed = true; }
  }
  try {
    await Array.fromAsync(source());
    print("BUG: fulfilled");
  } catch (e) {
    print("rejected", e.message, closed);
  }
})();
"#
        ),
        concat!(
            "function 1 fromAsync\n",
            "true\n",
            "true\n",
            "iterable 1,2,3\n",
            "arraylike 4,5\n",
            "mapped 10,20\n",
            "bad mapfn TypeError\n",
            "awaited 2\n",
            "rejected no true\n",
        )
    );
}

#[test]
fn internal_slots_are_invisible_and_wrappers_are_branded() {
    // The engine keeps `[[Value]]`, `[[Class]]` and `[[DateValue]]` in properties on the
    // object. As string keys they showed up in `Object.getOwnPropertyNames`, which is a
    // property the language does not define — and copying them (as
    // `Object.create(null, props)` does) hit an internal name that is not writable.
    assert_eq!(
        eval(
            r#"
print(Object.getOwnPropertyNames(new Error("t")).join());
print(Object.getOwnPropertyNames(new Number(1)).join(), "|");
print(Object.getOwnPropertyNames(new Date(0)).join(), "|");
print(Object.getOwnPropertyNames(new String("ab")).join());

// A brand check, not a coercion.
var boxed = new String("x");
boxed.valueOf = Boolean.prototype.valueOf;
try { boxed.valueOf(); print("BUG: no throw"); } catch (e) { print("string box", e.name); }
try { Number.prototype.valueOf.call(boxed); print("BUG: no throw"); } catch (e) {
  print("number brand", e.name);
}

// The three prototypes are wrappers of their own type holding the empty value.
print(Boolean.prototype.valueOf(), Number.prototype.valueOf(),
      JSON.stringify(String.prototype.valueOf()));

// `Function.prototype` is a function, so it has the two own data properties — which is
// what `delete f.length` falls through to.
print(Function.prototype.length, JSON.stringify(Function.prototype.name));
var f = function (a, b) {};
delete f.length;
print(f.length);
print([].constructor === Array, (function () {}).length);

// A Symbol argument to a numeric conversion raises `TypeError`, not a range complaint.
try { (1.5).toPrecision(Symbol()); } catch (e) { print("precision", e.name); }
try { (1).toString(Symbol()); } catch (e) { print("radix", e.name); }
print((1.5).toFixed(1), (255).toString(16));
"#
        ),
        concat!(
            "message,stack\n",
            " |\n",
            " |\n",
            "0,1,length\n",
            "string box TypeError\n",
            "number brand TypeError\n",
            "false 0 \"\"\n",
            "0 \"\"\n",
            "0\n",
            "true 0\n",
            "precision TypeError\n",
            "radix TypeError\n",
            "1.5 ff\n",
        )
    );
}

#[test]
fn array_length_and_index_beyond_i32_survive_the_trip_out() {
    // `Value::Int` is an `i32`, and an array's `length` may legitimately reach `2^32-1`,
    // so every place that cast was wrong: `Object.defineProperty(a, "length", …)` reported
    // `-1`, `a.length` reported `-1`, and — worst — an array *index* came back truncated,
    // so `a.indexOf(x)` at index `2^32-2` answered `-2`.
    //
    // The index half is only reachable through an array-like, because a real array stores a
    // dense `Vec<Value>` and an index that large would need 68 GB. That is a separate,
    // recorded limitation; what this pins down is the arithmetic on the way out.
    //
    // `findIndex` is deliberately absent: it scans forward from 0, so a length of `2^32` is
    // 4 billion `[[Get]]`s — spec-mandated, and the reason the conformance tests that care
    // about huge lengths all use `findLast`/`lastIndexOf`, which search downwards.
    assert_eq!(
        eval(
            r#"
var like = {length: 4294967296, 4294967294: "x", 4294967295: "y"};
print(like.length);
print(Array.prototype.lastIndexOf.call(like, "x", 4294967295));
print(Array.prototype.indexOf.call(like, "y", 4294967294));

var big = [];
big.length = 4294967295;
print(big.length, Object.getOwnPropertyDescriptor(big, "length").value);
print([1, 2, 3].length, [1, 2, 3].indexOf(2), [1, 2, 3].lastIndexOf(1));
"#
        ),
        concat!(
            "4294967296\n",
            "4294967294\n",
            "4294967295\n",
            "4294967295 4294967295\n",
            "3 1 0\n",
        )
    );
}

#[test]
fn data_view_reads_and_writes_bytes_at_any_offset() {
    // `DataView` did not exist at all — all 520 conformance cases were `ReferenceError`.
    // Its distinguishing feature against a typed array is that the width and byte offset are
    // named per access, so alignment never matters and endianness is per call.
    assert_eq!(
        eval(
            r#"
var ab = new ArrayBuffer(16);
var dv = new DataView(ab);
print(dv.byteOffset, dv.byteLength, dv.buffer === ab);
print(Object.prototype.toString.call(dv));

var partial = new DataView(ab, 4);
print(partial.byteOffset, partial.byteLength);
var sized = new DataView(ab, 4, 8);
print(sized.byteOffset, sized.byteLength);

// Big-endian by default, little-endian on request.
var order = new DataView(new ArrayBuffer(4));
order.setUint32(0, 0x01020304);
print([...new Uint8Array(order.buffer)].join(","));
order.setUint32(0, 0x01020304, true);
print([...new Uint8Array(order.buffer)].join(","));

var nums = new DataView(new ArrayBuffer(8));
nums.setInt16(0, -2);
print(nums.getInt16(0, true), nums.getInt16(0, false));
nums.setFloat64(0, Math.PI);
print(nums.getFloat64(0));
nums.setBigInt64(0, -1n);
print(String(nums.getBigInt64(0)), String(nums.getBigUint64(0)));

// Bounds are enforced per access, not per view.
var small = new DataView(new ArrayBuffer(2));
try { small.getInt32(0); print("no throw"); } catch (e) { print(e.name); }
try { new DataView(ab, 4, 100); print("no throw"); } catch (e) { print(e.name); }
try { new DataView(new ArrayBuffer(8), Symbol()); print("no throw"); } catch (e) { print(e.name); }
// A detached buffer makes reads throw but keeps the properties readable.
var gone = new DataView(new ArrayBuffer(8));
gone.buffer.transfer();
print(gone.byteLength);
try { gone.getInt8(0); print("no throw"); } catch (e) { print(e.name); }
"#
        ),
        concat!(
            "0 16 true\n",
            "[object DataView]\n",
            "4 12\n",
            "4 8\n",
            "1,2,3,4\n",
            "4,3,2,1\n",
            "-257 -2\n",
            "3.141592653589793\n",
            "-1 18446744073709551615\n",
            "RangeError\n",
            "RangeError\n",
            "TypeError\n",
            "0\n",
            "TypeError\n",
        )
    );
}

#[test]
fn reflect_construct_honours_new_target_and_native_constructors_order_their_checks() {
    // `Reflect.construct`'s third argument was dropped entirely, so `new.target.prototype`
    // never decided the prototype. Fixing that exposed the next layer: a native constructor
    // built its instance *before* validating its arguments, so `new Promise(nonCallable)`
    // and `new DataView(detached, …)` read a `prototype` getter they should not have
    // reached. Both halves are asserted here because each hid the other.
    assert_eq!(
        eval(
            r#"
function newTarget() {}
var proto = {};
newTarget.prototype = proto;

function C() {}
print(Object.getPrototypeOf(Reflect.construct(C, [], newTarget)) === proto);
print(Object.getPrototypeOf(Reflect.construct(C, [])) === C.prototype);
print(Object.getPrototypeOf(Reflect.construct(ArrayBuffer, [8], newTarget)) === proto);

// A `prototype` that is not an object falls back to the callee's own.
var bad = function () {};
bad.prototype = 1;
print(Object.getPrototypeOf(Reflect.construct(C, [], bad)) === C.prototype);

// A throwing `prototype` getter must not be reached when an argument is already invalid.
var angry = (function () {}).bind();
Object.defineProperty(angry, "prototype", {
  get: function () { throw new Error("prototype read too early"); },
});
try { Reflect.construct(Promise, [], angry); print("no throw"); }
catch (e) { print(e.name); }
"#
        ),
        "true\ntrue\ntrue\ntrue\nTypeError\n"
    );
}

#[test]
fn only_constructors_have_a_construct_method() {
    // §7.2.4 `IsConstructor`. Being callable is not the same property: an arrow function,
    // a generator, an async function, a class method and a plain object method are all
    // callable and none of them may be used with `new`. Deriving `[[Construct]]` from
    // `is_callable` made `new (Array.prototype.map)` build an object out of nothing.
    assert_eq!(
        eval(
            r#"
function isCtor(f) { try { Reflect.construct(function () {}, [], f); return true } catch (e) { return false } }
print(isCtor(Array.prototype.map), isCtor(Object.keys), isCtor(JSON.stringify), isCtor(Math.max));
print(isCtor(Object), isCtor(Array), isCtor(Map), isCtor(Error), isCtor(Proxy));
print(isCtor(1), isCtor({}), isCtor(null));
function plain() {}
print(isCtor(plain), isCtor(class {}), isCtor(() => 1), isCtor(function* () {}), isCtor(async function () {}));
var object = { method() {} };
class Klass { method() {} }
print(isCtor(object.method), isCtor(Klass.prototype.method), isCtor(Klass));
print(isCtor(plain.bind(null)), isCtor((() => 1).bind(null)));
print(isCtor(Symbol), isCtor(BigInt));
"#
        ),
        "false false false false\n\
         true true true true true\n\
         false false false\n\
         true true false false false\n\
         false false true\n\
         true false\n\
         true true\n"
    );
}

#[test]
fn new_on_a_non_constructor_names_it() {
    // The message matters: test262 asserts on the class, and users read the name.
    assert_eq!(
        eval(
            r#"
function kind(f) { try { f(); return "no throw" } catch (e) { return e.constructor.name + ": " + e.message } }
function named() {}
print(kind(() => new named()));
print(kind(() => new (() => 1)()));
print(kind(() => new (function* G() {})()));
print(kind(() => new (async function A() {})()));
print(kind(() => new Symbol()));
print(kind(() => new BigInt(1)));
print(kind(() => new named()));
"#
        ),
        "no throw\n\
         TypeError:  is not a constructor\n\
         TypeError: G is not a constructor\n\
         TypeError: A is not a constructor\n\
         TypeError: Symbol is not a constructor\n\
         TypeError: BigInt is not a constructor\n\
         no throw\n"
    );
}

#[test]
fn math_refuses_a_bigint_instead_of_answering_nan() {
    // `Value::to_number` is total and answers `NaN`, which is fine for the operators (they
    // check the bigint themselves) and wrong for every `ToNumber` caller: `Math.max(1n)`
    // is a `TypeError`, and answering `NaN` made it silently wrong for a whole milestone.
    assert_eq!(
        eval(
            r#"
function kind(f) { try { f(); return "no throw" } catch (e) { return e.constructor.name } }
print(kind(() => Math.max(1n)), kind(() => Math.min(1n)), kind(() => Math.abs(1n)));
print(kind(() => Math.sqrt(1n)), kind(() => Math.pow(1n, 2)), kind(() => Math.hypot(1n)));
print(kind(() => Math.sign(1n)), kind(() => Math.imul(1n, 2)), kind(() => Math.clz32(1n)));
print(kind(() => Math.fround(1n)), kind(() => Math.sumPrecise([1n])));
print(kind(() => Math.max(Symbol())));
print(Math.max(1, 2), Math.max(), 1 / Math.min(0, -0));
"#
        ),
        "TypeError TypeError TypeError\n\
         TypeError TypeError TypeError\n\
         TypeError TypeError TypeError\n\
         TypeError TypeError\n\
         TypeError\n\
         2 -Infinity -Infinity\n"
    );
}

#[test]
fn number_refuses_a_symbol_but_accepts_a_bigint() {
    // The one asymmetry in `ToNumber`: §21.1.1.1 makes `Number(1n)` return `1`, while
    // `Number(Symbol())` is a `TypeError` — so the BigInt special case cannot be dropped
    // in favour of `ToNumber`, and the Symbol case cannot be left to `to_number`'s `NaN`.
    assert_eq!(
        eval(
            r#"
function kind(f) { try { return String(f()) } catch (e) { return e.constructor.name } }
print(kind(() => Number(1n)), kind(() => Number()), kind(() => Number(true)));
print(kind(() => Number(Symbol())), kind(() => Number(Object(Symbol()))));
"#
        ),
        "1 0 1\nTypeError TypeError\n"
    );
}

#[test]
fn iterator_helpers_are_lazy_and_chainable() {
    // The defining property of the API: `take` on an infinite generator has to terminate,
    // which is only possible if nothing runs until `next` is called.
    assert_eq!(
        eval(
            r#"
function* naturals() { let i = 0; while (true) yield i++; }
print(JSON.stringify(naturals().take(3).toArray()));
print(JSON.stringify([1, 2, 3, 4].values().map(x => x * 2).filter(x => x > 4).toArray()));
print(JSON.stringify([1, 2, 3, 4, 5].values().drop(3).toArray()));
print(JSON.stringify([[1, 2], [3]].values().flatMap(x => x).toArray()));
print(JSON.stringify([1, 2, 3].values().reduce((a, b) => a + b, 10)));
print(JSON.stringify([1, 2, 3, 4].values().chunks(3).toArray()));
print(JSON.stringify([1, 2, 3, 4].values().windows(3).toArray()));
print(JSON.stringify([1, 2].values().join("-")), [1, 2].values().includes(2));
print(JSON.stringify([1, 2, 3].values().map((v, i) => i).toArray()));
"#
        ),
        "[0,1,2]\n[6,8]\n[4,5]\n[1,2,3]\n16\n[[1,2,3],[4]]\n[[1,2,3],[2,3,4]]\n\"1-2\" true\n[0,1,2]\n"
    );
}

#[test]
fn an_iterator_is_not_the_same_as_an_iterable() {
    // `Iterator` may be subclassed but not instantiated, `Iterator.from` returns an
    // existing iterator untouched, and a bare `{next}` counts as an iterator even without
    // `Symbol.iterator`. All three are easy to get backwards.
    assert_eq!(
        eval(
            r#"
function kind(f) { try { f(); return "no throw" } catch (e) { return e.constructor.name + ": " + e.message } }
class Sub extends Iterator {}
print(Object.getPrototypeOf(new Sub()) === Sub.prototype);
print(kind(() => new Iterator()));
print(kind(() => Iterator()));
const existing = [1].values();
print(Iterator.from(existing) === existing);
print(JSON.stringify(Iterator.from("ab").toArray()));
print(JSON.stringify(Iterator.from({ next() { return { done: true }; } }).toArray()));
print(kind(() => Iterator.from(1)));
print(JSON.stringify(Iterator.concat([1], [2]).toArray()));
print(JSON.stringify(Iterator.zip([[1, 2], [3, 4]]).toArray()));
print(JSON.stringify(Iterator.zip([[1, 2, 3], [4, 5]], { mode: "longest" }).toArray()));
print(JSON.stringify(Iterator.zipKeyed({ a: [1], b: [2] }).toArray()));
print(kind(() => Iterator.zip([[1, 2], [3]], { mode: "strict" }).toArray()));
"#
        ),
        "true\nTypeError: abstract class not constructable\nTypeError: constructor requires 'new'\n\
         true\n[\"a\",\"b\"]\n[]\nTypeError: not an object\n[1,2]\n[[1,3],[2,4]]\n\
         [[1,4],[2,5],[3,null]]\n[{\"a\":1,\"b\":2}]\n\
         TypeError: iterators have different lengths\n"
    );
}

#[test]
fn object_create_applies_its_properties_argument() {
    // `Object.create(proto, props)` used to drop `props` on the floor: the object came out
    // empty. Five test262 cases in the Iterator area alone build a null-prototype
    // properties bag that way.
    assert_eq!(
        eval(
            r#"
const o = Object.create(null, {
  a: { value: 1, enumerable: true },
  b: { get() { return 2; }, enumerable: true },
  c: { value: 3, enumerable: false },
});
print(Object.getPrototypeOf(o) === null);
print(Object.keys(o).join(","), Object.getOwnPropertyNames(o).join(","));
print(o.a, o.b);
const plain = Object.create(Object.prototype, { x: { value: 9 } });
print(plain.x, Object.getPrototypeOf(plain) === Object.prototype);
"#
        ),
        "true\na,b a,b,c\n1 2\n9 true\n"
    );
}

#[test]
fn define_property_keeps_an_accessor_whole() {
    // A descriptor that only names `enumerable` must leave an accessor an accessor: the
    // property used to be converted to a data property and its value blanked. And a
    // descriptor that names *one* half must keep the other.
    assert_eq!(
        eval(
            r#"
const o = {};
Object.defineProperty(o, "e", { get() { return "ve"; }, configurable: true });
Object.defineProperty(o, "e", { enumerable: true });
print(o.e, typeof Object.getOwnPropertyDescriptor(o, "e").get, o.propertyIsEnumerable("e"));

let stored = 1;
const p = {};
Object.defineProperty(p, "x", { get() { return stored; }, set(v) { stored = v; }, configurable: true });
Object.defineProperty(p, "x", { set(v) { stored = v * 10; } });
p.x = 3;
print(p.x);
"#
        ),
        "ve function true\n30\n"
    );
}

#[test]
fn a_property_name_is_only_set_on_a_function() {
    // `NamedEvaluation` applies to anonymous *functions*, never to whatever happens to sit
    // on the right-hand side. Renaming plain objects was how a `zipKeyed` result object
    // acquired an extra `name` property, and it happened through `Object.defineProperty`
    // too, which has no `NamedEvaluation` at all.
    assert_eq!(
        eval(
            r#"
const value = {};
Object.defineProperty({}, "value", { value });
print(value.name === undefined);
const other = {};
({ key: other });
print(other.name === undefined);
print(({ m: function () {} }).m.name, ({ n: class {} }).n.name, ({ p: () => 1 }).p.name);
"#
        ),
        "true\ntrue\nm n p\n"
    );
}

#[test]
fn reflect_keys_stay_symbols_and_propagate_errors() {
    // `Reflect.get`/`set`/`has` coerced the key with `ToString`, so every symbol key read
    // as `""` — which made a Proxy's `get` trap look like it returned `undefined`, because
    // `proxy_get` forwards through `Reflect.get`. `has` also ignored the prototype chain.
    assert_eq!(
        eval(
            r#"
const s = Symbol.iterator;
const o = { [s]: 1, a: 2 };
print(Reflect.get(o, s), Reflect.has(o, s), Reflect.has({}, "toString"));
Reflect.set(o, s, 7);
print(o[s]);
const p = new Proxy(o, { get: (t, k, r) => Reflect.get(t, k, r) });
print(typeof p[s]);
function kind(f) { try { f(); return "no throw" } catch (e) { return "threw" } }
const bad = { toString() { throw new Error("boom"); } };
print(kind(() => Reflect.get({}, bad)), kind(() => Reflect.set({}, bad, 1)), kind(() => Reflect.has({}, bad)));
"#
        ),
        "1 true true\n7\nnumber\nthrew threw threw\n"
    );
}

#[test]
fn object_ships_the_apis_scripts_reach_for() {
    // `hasOwn`, `getOwnPropertyDescriptors`, `groupBy` and the Annex B
    // `__defineGetter__` family were all absent — 94 test262 cases failed with
    // "undefined is not a function" before they existed.
    assert_eq!(
        eval(
            r#"
print(Object.hasOwn({a: 1}, "a"), Object.hasOwn({}, "toString"), Object.hasOwn("ab", "0"));
print(JSON.stringify(Object.getOwnPropertyDescriptors({a: 1}).a));
print(JSON.stringify(Object.groupBy([1, 2, 3, 4], x => (x % 2 ? "odd" : "even"))));
print(Object.getPrototypeOf(Object.groupBy([], () => 1)) === null);
print(Object.groupBy([1], () => "__proto__").__proto__[0]);

const o = {};
Object.prototype.__defineGetter__.call(o, "g", () => 7);
print(o.g, o.propertyIsEnumerable("g"));
print(typeof Object.prototype.__lookupGetter__.call(o, "g"));
print(String(Object.prototype.__lookupGetter__.call({a: 1}, "a")));
"#
        ),
        "true false true\n\
         {\"value\":1,\"writable\":true,\"enumerable\":true,\"configurable\":true}\n\
         {\"odd\":[1,3],\"even\":[2,4]}\n\
         true\n1\n7 true\nfunction\nundefined\n"
    );
}

#[test]
fn to_string_names_what_the_value_really_is() {
    // A function's tag names its kind, a BigInt is `[object BigInt]`, an arguments object
    // is `[object Arguments]`, and a proxy reports what it stands in for.
    assert_eq!(
        eval(
            r#"
function tag(v) { return Object.prototype.toString.call(v); }
print(tag(10n), tag(function () {}), tag(async function () {}));
print(tag(function* () {}), tag(async function* () {}));
print(tag(new Proxy(function* () {}, {})), tag(new Proxy(async function () {}, {})));
print(tag((function () { return arguments; })()));
print(tag(new Proxy([], {})), tag({}), tag([]));
print(JSON.stringify([...(function () { return arguments; })(1, 2)]));
"#
        ),
        "[object BigInt] [object Function] [object AsyncFunction]\n\
         [object GeneratorFunction] [object AsyncGeneratorFunction]\n\
         [object GeneratorFunction] [object AsyncFunction]\n\
         [object Arguments]\n\
         [object Array] [object Object] [object Array]\n\
         [1,2]\n"
    );
}

#[test]
fn from_entries_runs_the_iterator_protocol() {
    // It used to walk an array by index: a non-iterable answered `{}` instead of throwing,
    // a bad entry was skipped instead of refused, and the iterator was never closed.
    assert_eq!(
        eval(
            r#"
function kind(f) { try { f(); return "no throw" } catch (e) { return e.constructor.name } }
print(JSON.stringify(Object.fromEntries([["a", 1], ["b", 2]])));
print(JSON.stringify(Object.fromEntries(new Map([["a", 1]]))));
print(String(Object.fromEntries([["__proto__", 1]]).__proto__));
print(kind(() => Object.fromEntries(5)), kind(() => Object.fromEntries([1])));
let closed = false;
const iterable = {
  [Symbol.iterator]() { return this; },
  next() { return { value: 1, done: false }; },
  return() { closed = true; return {}; },
};
kind(() => Object.fromEntries(iterable));
print(closed);
"#
        ),
        "{\"a\":1,\"b\":2}\n{\"a\":1}\n1\nTypeError TypeError\ntrue\n"
    );
}

#[test]
fn an_array_length_goes_through_to_uint_32() {
    // `ArraySetLength` runs `ToUint32`, and an object yielding a fraction falls through to
    // `ToString`: `{toString: () => "2"}` is a valid length, `{valueOf: () => 2.5}` is not,
    // and `2**32` is a `RangeError` rather than a modulo.
    assert_eq!(
        eval(
            r#"
function kind(f) { try { return String(f()) } catch (e) { return e.constructor.name } }
function withLength(value) { const a = []; try { Object.defineProperty(a, "length", { value }); return a.length } catch (e) { return e.constructor.name } }
print(withLength({ toString: () => "2" }), withLength({ valueOf: () => 3 }));
print(kind(() => withLength({ valueOf: () => 2.5 })), kind(() => withLength(4294967296)));
print(kind(() => withLength(-1)), kind(() => withLength("abc")), withLength("5"));
const a = [0, 1, 2];
Object.defineProperty(a, "1", { configurable: false });
print(kind(() => Object.defineProperty(a, "length", { value: 0, writable: false })));
print(a.length, JSON.stringify(a));
"#
        ),
        "2 3\nRangeError RangeError\nRangeError RangeError 5\nTypeError\n2 [0,1]\n"
    );
}

#[test]
fn the_function_constructors_exist_and_build_their_kind() {
    // `%GeneratorFunction%` and friends are reachable through
    // `Object.getPrototypeOf(function*(){}).constructor`, and `new` on one really compiles
    // a function of that kind. Their `Symbol.toStringTag` lives on the prototype so that
    // `delete g.constructor.prototype[Symbol.toStringTag]` is observable.
    assert_eq!(
        eval(
            r#"
function tag(v) { return Object.prototype.toString.call(v); }
const G = Object.getPrototypeOf(function* () {}).constructor;
const made = new G("a", "yield a; return 1");
print(tag(made), made.name, made.length, JSON.stringify([...made(7)]));
print(G.name, G.length, function* () {} instanceof G);
const A = Object.getPrototypeOf(async function () {}).constructor;
const AG = Object.getPrototypeOf(async function* () {}).constructor;
print(A.name, A.length, tag(new A("return 1")));
print(AG.name, AG.length, tag(new AG("yield 1")));
print(tag(function* () {}));
delete G.prototype[Symbol.toStringTag];
print(tag(function* () {}));
"#
        ),
        "[object GeneratorFunction] anonymous 1 [7]\n\
         GeneratorFunction 1 true\n\
         AsyncFunction 1 [object AsyncFunction]\n\
         AsyncGeneratorFunction 1 [object AsyncGeneratorFunction]\n\
         [object GeneratorFunction]\n\
         [object Function]\n"
    );
}

/// `[[Set]]` refuses where it must, and refuses *silently* in sloppy code only.
///
/// Four clauses of §10.1.9.2, each one a case the engine used to answer differently from
/// the reference. The two that matter most are the inherited ones: an inherited read-only
/// **data** property must not be shadowed by a new own property, and an inherited
/// **accessor with no setter** must not be shadowed either. Both used to fall through to
/// `define_data_key` and create the shadow, which is a silent wrong answer to a legal
/// program — the write "succeeded" and the value the script read back was its own.
///
/// The accessor cases are also why the sloppy/strict split has to be exact: the same
/// refusal is a `TypeError` in strict code and a no-op in sloppy code.
#[test]
fn an_assignment_that_cannot_stick_refuses_the_way_the_spec_says() {
    // §10.1.9.2 step 3 — an accessor with no setter.
    assert_eq!(
        eval(
            "function t(f){ try { f(); return 'no throw' } catch (e) { return e.name } }\n\
             var own = {}; Object.defineProperty(own, 'q', { get: function () { return 4; } });\n\
             print(t(function () { (function () { 'use strict'; own.q = 9; })(); }));\n\
             own.q = 9;\n\
             print(own.q);"
        ),
        "TypeError\n4\n"
    );
    // §10.1.9.2 step 4 — an inherited non-writable data property is neither written nor
    // shadowed, in either mode.
    assert_eq!(
        eval(
            "function t(f){ try { f(); return 'no throw' } catch (e) { return e.name } }\n\
             var frozen = Object.freeze({ x: 1 });\n\
             print(t(function () { var a = Object.create(frozen);\n\
                 (function () { 'use strict'; a.x = 2; })(); }));\n\
             var b = Object.create(frozen); b.x = 2;\n\
             print(b.x, b.hasOwnProperty('x'));\n\
             var deep = Object.create(Object.create(frozen)); deep.x = 2;\n\
             print(deep.x, deep.hasOwnProperty('x'));"
        ),
        "TypeError\n1 false\n1 false\n"
    );
    // The same refusal through a class's own getter, which is the shape real code hits.
    assert_eq!(
        eval(
            "function t(f){ try { f(); return 'no throw' } catch (e) { return e.name } }\n\
             class K { get m() { return 1 } }\n\
             print(t(function () { var k = new K();\n\
                 (function () { 'use strict'; k.m = 9; })(); }));\n\
             var k2 = new K(); k2.m = 9;\n\
             print(k2.m, k2.hasOwnProperty('m'));"
        ),
        "TypeError\n1 false\n"
    );
    // An inherited *writable* property is shadowed, and an inherited setter runs.
    assert_eq!(
        eval(
            "var base = { y: 1 };\n\
             var c = Object.create(base); c.y = 5;\n\
             print(c.y, c.hasOwnProperty('y'), base.y);\n\
             var st = Object.create({ set w(v) { this._w = v * 3 } }); st.w = 2;\n\
             print(st._w);"
        ),
        "5 true 1\n6\n"
    );
}

/// An array index follows the same `[[Set]]` order as any other key: the prototype chain
/// is consulted **before** the element vector.
///
/// The element store used to run first, so a setter installed on `Array.prototype` for an
/// index was never called and the array kept an own element the reference never creates.
/// `arr[0] = 7` answered `arr[0] === 7` and `arr._s === undefined`; the reference answers
/// the opposite.
#[test]
fn an_array_index_consults_the_prototype_chain_before_the_element_vector() {
    assert_eq!(
        eval(
            "Object.defineProperty(Array.prototype, '0', {\n\
                 set: function (v) { this._s = v; },\n\
                 configurable: true,\n\
             });\n\
             var arr = []; arr[0] = 7;\n\
             print(arr._s, arr.hasOwnProperty('0'));\n\
             delete Array.prototype['0'];\n\
             var plain = []; plain[0] = 7;\n\
             print(plain[0], plain.length);"
        ),
        "7 false\n7 1\n"
    );
}