quickjs-pure 0.14.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
//! The object model: property tables, arrays, functions, and the prototype chain.
//!
//! QuickJS splits an object into a *shape* (the property names and their
//! attributes, shared between objects with the same layout) and a *property
//! vector* (the values). That split is a performance feature, not a semantic one,
//! and it only pays off once objects are created in bulk; this model keeps the
//! property table per object, in insertion order, and therefore reproduces the
//! ordering rules directly.
//!
//! Insertion order is load-bearing: `for (k in o)` and `Object.keys` iterate in the
//! order properties were defined, with integer-like keys first in ascending order.

use std::cell::RefCell;

use js_compile::bytecode::Function as CompiledFunction;
use js_gc::{Gc, Trace, Tracer, WeakGc};

use std::fmt;
use std::rc::Rc;

use crate::value::{Cell, JsSymbol, Value};

/// The bytes an `ArrayBuffer` owns, plus whether they have been detached.
///
/// `transfer()` moves the bytes to a new buffer and leaves this one empty and detached; a
/// view of a detached buffer reads `undefined` from every index.
pub struct BufferStorage {
    /// The bytes, in memory order.
    ///
    /// `bytes.len()` *is* the byte length: resizing is `Vec::resize`, which is what keeps the
    /// length, the capacity and the pointer from ever disagreeing.
    pub bytes: Vec<u8>,
    /// Whether `transfer()` has taken the bytes away.
    pub detached: bool,
    /// The most bytes this buffer may grow to, or `None` when it cannot grow at all.
    ///
    /// `Some(max)` is what `new ArrayBuffer(n, {maxByteLength: max})` asks for: `resizable`
    /// answers `true`, `maxByteLength` answers `max`, and `resize` may move the length
    /// anywhere up to it. A fixed-length buffer answers `false`/the byte length.
    pub max_byte_length: Option<usize>,
    /// A host's "release this block" callback, run when the storage dies.
    ///
    /// This is what lets the C API's `JS_NewArrayBuffer` honour its `free_func` contract: the
    /// header says the block is released when the buffer is collected, not when it is built,
    /// and a host that counts allocations sees the difference. The bytes themselves are
    /// *copied* — this engine's storage is a `Vec<u8>` and cannot alias a foreign pointer
    /// without a second representation of every typed-array operation — so the callback
    /// releases the host's original block while the storage keeps its own copy. Writes the
    /// host makes to its block after the call are therefore not visible to script, which is
    /// the one documented difference.
    pub release: Option<Box<dyn FnOnce()>>,
}

impl BufferStorage {
    /// Storage for a fixed-length buffer, which is what every caller but a resizable
    /// constructor wants.
    pub fn fixed(bytes: Vec<u8>) -> BufferStorage {
        BufferStorage {
            bytes,
            detached: false,
            max_byte_length: None,
            release: None,
        }
    }

    /// Storage for a fixed-length buffer whose origin block has to be released at collection.
    ///
    /// The C API's `JS_NewArrayBuffer(ctx, buf, len, free_func, opaque, …)`: the bytes are a
    /// copy, and `release` is the closure that calls `free_func(opaque, buf)` when this
    /// storage is dropped. Keeping the closure here rather than calling it at construction is
    /// the whole difference between honouring the header and approximating it.
    pub fn fixed_with_release(bytes: Vec<u8>, release: Box<dyn FnOnce()>) -> BufferStorage {
        BufferStorage {
            bytes,
            detached: false,
            max_byte_length: None,
            release: Some(release),
        }
    }

    /// Storage for a resizable buffer of `bytes` bytes that may grow to `max`.
    pub fn resizable(bytes: Vec<u8>, max: usize) -> BufferStorage {
        BufferStorage {
            bytes,
            detached: false,
            max_byte_length: Some(max),
            release: None,
        }
    }

    /// Whether `resize` can change this buffer's length.
    pub fn is_resizable(&self) -> bool {
        self.max_byte_length.is_some()
    }

    /// What `maxByteLength` reports: the ceiling for a resizable buffer, and the current
    /// length for a fixed one — which is what the getter's `IsDetachedBuffer`/`IsFixedLength`
    /// split in the spec amounts to once the length stops changing.
    pub fn max_byte_length(&self) -> usize {
        match self.max_byte_length {
            Some(max) => max,
            None => self.bytes.len(),
        }
    }
}

impl Drop for BufferStorage {
    fn drop(&mut self) {
        // The host's callback runs here rather than in the constructor: that is the contract
        // `JS_NewArrayBuffer`'s `free_func` states, and the difference is observable to a
        // host that counts how many blocks it owns at any moment.
        if let Some(release) = self.release.take() {
            release();
        }
    }
}

/// How long a view is, which for a resizable buffer is not a constant.
///
/// `new Uint8Array(resizableBuffer)` with no length argument is **length-tracking**
/// (§23.2.5.1 step 8: the length comes out `auto`): the view has no length of its own, it
/// has a rule for computing one from the buffer's *current* byte length. Growing the
/// buffer therefore grows the view, and shrinking it to nothing empties the view without
/// detaching anything. An explicit length — or a view of a fixed-length buffer — is the
/// other case, and its length stays put while the buffer may not fit it any more.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ViewLength {
    /// The length the view was created with, in its own units.
    Fixed(usize),
    /// Recomputed from the buffer's byte length on every access.
    Tracking,
}

impl ViewLength {
    /// The length as an integer, for the paths that know the view is in bounds.
    pub fn stored(self) -> usize {
        match self {
            ViewLength::Fixed(length) => length,
            // Only reachable for a view whose length was just computed; `geometry` is the
            // one place that knows what a tracking view currently measures.
            ViewLength::Tracking => 0,
        }
    }

    /// Whether the length follows the buffer rather than being fixed at construction.
    pub fn is_tracking(self) -> bool {
        matches!(self, ViewLength::Tracking)
    }
}

/// A view's geometry at this instant: its byte offset, its length in its own units, and
/// whether it is out of bounds.
///
/// This is the whole of §10.4.5.12 (`IsTypedArrayOutOfBounds`, `TypedArrayLength`,
/// `TypedArrayByteOffset`) shared between typed arrays and `DataView`, which differ only in
/// what one unit is. Nothing is cached on the view: the same view goes out of bounds when
/// its buffer shrinks and back in bounds when it grows again, and every read has to ask.
///
/// Out of bounds answers `(0, 0, true)` rather than the last good numbers, because that is
/// what the spec's accessors report — `ta.byteOffset` is `0`, not the offset it was built
/// with, once the buffer can no longer hold the view.
fn view_geometry(
    offset: usize,
    length: ViewLength,
    unit: usize,
    buffer_bytes: usize,
    detached: bool,
) -> (usize, usize, bool) {
    if detached {
        return (0, 0, true);
    }
    match length {
        // A tracking view only falls out of bounds when its *offset* alone is past the end;
        // otherwise a partial element is simply not an element.
        ViewLength::Tracking => {
            if offset > buffer_bytes {
                (0, 0, true)
            } else {
                (offset, (buffer_bytes - offset) / unit, false)
            }
        }
        ViewLength::Fixed(count) => {
            if offset.saturating_add(count.saturating_mul(unit)) > buffer_bytes {
                (0, 0, true)
            } else {
                (offset, count, false)
            }
        }
    }
}

impl JsObject {
    /// The storage of this object, when it is an `ArrayBuffer`.
    pub fn array_buffer_storage(&self) -> Option<Rc<RefCell<BufferStorage>>> {
        match &self.data.borrow().kind {
            ObjectKind::ArrayBuffer(storage) => Some(storage.clone()),
            _ => None,
        }
    }

    /// Make this object an `ArrayBuffer` owning `storage`.
    pub fn set_array_buffer(&self, storage: Rc<RefCell<BufferStorage>>) {
        self.data.borrow_mut().kind = ObjectKind::ArrayBuffer(storage);
    }

    /// The entries of this object, when it is a `Map` or a `Set`.
    pub fn collection_entries(&self) -> Option<Vec<(Value, Value)>> {
        match &self.data.borrow().kind {
            ObjectKind::Collection { entries, .. } => Some(entries.clone()),
            _ => None,
        }
    }

    /// Whether this object is a `Set` rather than a `Map`.
    pub fn collection_is_set(&self) -> Option<bool> {
        match &self.data.borrow().kind {
            ObjectKind::Collection { is_set, .. } => Some(*is_set),
            _ => None,
        }
    }

    /// Make this object a `Map` or `Set` holding `entries`.
    pub fn set_collection(&self, heap: &js_gc::Heap, entries: Vec<(Value, Value)>, is_set: bool) {
        let mut data = self.data.borrow_mut();
        let before = match &data.kind {
            ObjectKind::Collection { entries, .. } => entries.capacity(),
            _ => 0,
        };
        let after = entries.capacity();
        data.kind = ObjectKind::Collection { entries, is_set };
        charge_capacity::<(Value, Value)>(heap, before, after);
    }

    /// This object's weak entries, when it is a `WeakMap` or `WeakSet`.
    ///
    /// Expired handles are filtered out here rather than at the call site, so every reader
    /// sees the same live view of the map and a dead key can never be observed.
    pub fn weak_entries(&self) -> Option<Vec<(Value, Value)>> {
        match &self.data.borrow().kind {
            ObjectKind::WeakCollection { entries, .. } => Some(
                entries
                    .iter()
                    .filter_map(|(key, value)| key.upgrade().map(|key| (key, value.clone())))
                    .collect(),
            ),
            _ => None,
        }
    }

    /// Whether this object is a `WeakSet` rather than a `WeakMap`.
    pub fn weak_is_set(&self) -> Option<bool> {
        match &self.data.borrow().kind {
            ObjectKind::WeakCollection { is_set, .. } => Some(*is_set),
            _ => None,
        }
    }

    /// Make this object a `WeakMap` or `WeakSet`, replacing any entries it had.
    pub fn set_weak_collection(
        &self,
        heap: &js_gc::Heap,
        entries: Vec<(WeakKey, Value)>,
        is_set: bool,
    ) {
        let mut data = self.data.borrow_mut();
        let before = match &data.kind {
            ObjectKind::WeakCollection { entries, .. } => entries.capacity(),
            _ => 0,
        };
        let after = entries.capacity();
        data.kind = ObjectKind::WeakCollection { entries, is_set };
        charge_capacity::<(WeakKey, Value)>(heap, before, after);
    }

    /// Store one entry in a weak collection, replacing the value for a live equal key.
    ///
    /// The comparison is pointer identity: a weak key has to be an object, and two objects
    /// are the same key exactly when they are the same object. Expired entries are dropped
    /// on the way through, which keeps the vector from growing without bound in a program
    /// that churns keys.
    pub fn weak_set(&self, key: WeakKey, value: Value) {
        let mut data = self.data.borrow_mut();
        let ObjectKind::WeakCollection { entries, .. } = &mut data.kind else {
            return;
        };
        entries.retain(|(existing, _)| !existing.is_expired());
        for (existing, slot) in entries.iter_mut() {
            if existing.same(&key) {
                *slot = value;
                return;
            }
        }
        entries.push((key, value));
    }

    /// Remove `key` from a weak collection, answering whether it was there.
    pub fn weak_delete(&self, key: &Value) -> bool {
        let mut data = self.data.borrow_mut();
        let ObjectKind::WeakCollection { entries, .. } = &mut data.kind else {
            return false;
        };
        let before = entries.len();
        entries.retain(|(existing, _)| !existing.is_expired() && !existing.matches(key));
        entries.len() != before
    }

    /// The target of a `WeakRef`, when this object is one.
    pub fn weak_ref_target(&self) -> Option<WeakKey> {
        match &self.data.borrow().kind {
            ObjectKind::WeakRef { target } => Some(target.clone()),
            _ => None,
        }
    }

    /// Make this object a `WeakRef` to `target`.
    pub fn set_weak_ref(&self, target: WeakKey) {
        self.data.borrow_mut().kind = ObjectKind::WeakRef { target };
    }

    /// The registry state, when this object is a `FinalizationRegistry`.
    pub fn finalization_state(&self) -> Option<Box<FinalizationState>> {
        match &self.data.borrow().kind {
            ObjectKind::Finalization(state) => Some(Box::new(FinalizationState {
                registrations: state
                    .registrations
                    .iter()
                    .map(|registration| Registration {
                        target: registration.target.clone(),
                        held_value: registration.held_value.clone(),
                        token: registration.token.clone(),
                    })
                    .collect(),
                cleanup: state.cleanup.clone(),
            })),
            _ => None,
        }
    }

    /// Replace a registry's state.
    pub fn set_finalization_state(&self, state: FinalizationState) {
        self.data.borrow_mut().kind = ObjectKind::Finalization(Box::new(state));
    }

    /// `(buffer, element, offset, length)`, when this object is a typed-array view.
    ///
    /// The offset and length are **effective**: a view whose buffer has been resized out
    /// from under it answers `(0, 0)`, and a length-tracking view answers what the buffer
    /// measures now — see [`view_geometry`].
    pub fn typed_array_parts(
        &self,
    ) -> Option<(
        Gc<JsObject>,
        crate::builtins::typedarray::ElementType,
        usize,
        usize,
    )> {
        self.typed_array_geometry()
            .map(|(buffer, element, offset, length, _)| (buffer, element, offset, length))
    }

    /// As [`JsObject::typed_array_parts`], plus whether the view is out of bounds.
    ///
    /// The extra flag cannot be recovered from the length: an empty view that legitimately
    /// sits at the end of its buffer is in bounds and answers `0`, while a view that shrank
    /// away is out of bounds and *also* answers `0`. Every method that runs
    /// `ValidateTypedArray` has to tell them apart, since one is allowed to return and the
    /// other has to throw.
    pub fn typed_array_geometry(
        &self,
    ) -> Option<(
        Gc<JsObject>,
        crate::builtins::typedarray::ElementType,
        usize,
        usize,
        bool,
    )> {
        let (buffer, element, offset, length) = match &self.data.borrow().kind {
            ObjectKind::TypedArray {
                buffer,
                element,
                offset,
                length,
            } => (buffer.clone(), *element, *offset, *length),
            _ => return None,
        };
        let storage = buffer.array_buffer_storage()?;
        let storage = storage.borrow();
        let (offset, length, oob) = view_geometry(
            offset,
            length,
            element.size(),
            storage.bytes.len(),
            storage.detached,
        );
        Some((buffer, element, offset, length, oob))
    }

    /// The view's **stored** geometry: `(buffer, element, offset, length)` as it was built,
    /// with no collapse for an out-of-bounds buffer.
    ///
    /// Apart from [`JsObject::typed_array_geometry`], which reports what a script sees, this
    /// is what `subarray` needs: §23.2.3.30 computes `beginByteOffset` from
    /// `O.[[ByteOffset]]`, and that slot keeps its value when the buffer shrinks — so
    /// `oobView.subarray(1)` still starts at the original offset once the buffer grows back
    /// (`subarray/result-byteOffset-from-out-of-bounds`).
    pub fn typed_array_stored(
        &self,
    ) -> Option<(
        Gc<JsObject>,
        crate::builtins::typedarray::ElementType,
        usize,
        ViewLength,
    )> {
        match &self.data.borrow().kind {
            ObjectKind::TypedArray {
                buffer,
                element,
                offset,
                length,
            } => Some((buffer.clone(), *element, *offset, *length)),
            _ => None,
        }
    }

    /// Whether this view's length follows its buffer rather than being fixed.
    pub fn typed_array_tracks_length(&self) -> bool {
        matches!(
            &self.data.borrow().kind,
            ObjectKind::TypedArray {
                length: ViewLength::Tracking,
                ..
            }
        )
    }

    /// Whether this callable is a native function rather than compiled JavaScript.
    ///
    /// `construct` uses it to decide who builds the instance: a native constructor creates
    /// its own, after validating its arguments.
    pub fn is_native_function(&self) -> bool {
        matches!(
            &self.data.borrow().kind,
            ObjectKind::Function(Callable::Native { .. })
        )
    }

    /// Whether this native constructor builds its own instance, so `new` must not pass one.
    pub fn native_creates_own_instance(&self) -> bool {
        matches!(
            &self.data.borrow().kind,
            ObjectKind::Function(Callable::Native {
                own_instance: true,
                ..
            })
        )
    }

    /// Make this object a `DataView` over `buffer`.
    pub fn set_data_view(&self, buffer: Gc<JsObject>, offset: usize, length: ViewLength) {
        self.data.borrow_mut().kind = ObjectKind::DataView {
            buffer,
            offset,
            length,
        };
    }

    /// Whether this object has a `[[ViewedArrayBuffer]]` internal slot.
    ///
    /// Deliberately *not* `typed_array_parts().is_some() || data_view_parts().is_some()`
    /// written at each call site: `ArrayBuffer.isView` must answer `false` for a Proxy
    /// whose target is a view, because a Proxy has no such slot and `[[Get]]` is never
    /// reached. Keeping the predicate here means the "no proxy, no prototype" rule lives
    /// in one place.
    pub fn is_array_buffer_view(&self) -> bool {
        matches!(
            &self.data.borrow().kind,
            ObjectKind::TypedArray { .. } | ObjectKind::DataView { .. }
        )
    }

    /// The `(buffer, offset, length)` of a `DataView`, or `None` when this is not one.
    ///
    /// Like [`JsObject::typed_array_parts`], the offset and length are effective: a
    /// `DataView` whose buffer shrank under it answers `(0, 0)`.
    pub fn data_view_parts(&self) -> Option<(Gc<JsObject>, usize, usize)> {
        self.data_view_geometry()
            .map(|(buffer, offset, length, _)| (buffer, offset, length))
    }

    /// As [`JsObject::data_view_parts`], plus whether the view is out of bounds.
    pub fn data_view_geometry(&self) -> Option<(Gc<JsObject>, usize, usize, bool)> {
        let (buffer, offset, length) = match &self.data.borrow().kind {
            ObjectKind::DataView {
                buffer,
                offset,
                length,
            } => (buffer.clone(), *offset, *length),
            _ => return None,
        };
        let storage = buffer.array_buffer_storage()?;
        let storage = storage.borrow();
        // A `DataView`'s unit is the byte, so the typed-array rule applies unchanged.
        let (offset, length, oob) =
            view_geometry(offset, length, 1, storage.bytes.len(), storage.detached);
        Some((buffer, offset, length, oob))
    }

    /// Whether this `DataView`'s length follows its buffer.
    pub fn data_view_tracks_length(&self) -> bool {
        matches!(
            &self.data.borrow().kind,
            ObjectKind::DataView {
                length: ViewLength::Tracking,
                ..
            }
        )
    }

    /// Make this object a typed-array view of `length` elements.
    pub fn set_typed_array(
        &self,
        buffer: Gc<JsObject>,
        element: crate::builtins::typedarray::ElementType,
        offset: usize,
        length: ViewLength,
    ) {
        self.data.borrow_mut().kind = ObjectKind::TypedArray {
            buffer,
            element,
            offset,
            length,
        };
    }

    /// The element type, when this object is a typed-array view.
    pub fn typed_array_element_type(&self) -> Option<crate::builtins::typedarray::ElementType> {
        self.typed_array_parts().map(|(_, element, _, _)| element)
    }

    /// How many elements the view exposes, or `None` when this is not a view.
    ///
    /// A detached or resized-away buffer reports `0`: there is nothing to index. A
    /// length-tracking view reports what its buffer measures *now*, which is why this is
    /// computed rather than read.
    pub fn typed_array_length(&self) -> Option<usize> {
        self.typed_array_geometry()
            .map(|(_, _, _, length, _)| length)
    }

    /// Read one view element.
    ///
    /// Out-of-range and out-of-bounds reads are `undefined` rather than an error, which is
    /// what makes `a[999]`, `a[0]` after the buffer shrank, and every read of a detached
    /// view behave the way the language says.
    pub fn typed_array_element(&self, index: usize) -> Option<Value> {
        let (buffer, element, offset, length) = self.typed_array_parts()?;
        let storage = buffer.array_buffer_storage()?;
        let storage = storage.borrow();
        if storage.detached || index >= length {
            return Some(Value::Undefined);
        }
        // The buffer's own handle is where the heap comes from, so a BigInt element can be
        // allocated without every caller having to thread one through.
        Some(element.read(
            buffer.heap(),
            &storage.bytes,
            offset + index * element.size(),
        ))
    }

    /// Store one view element, applying the type's wrap or clamp.
    ///
    /// `Some(Ok(()))` stored, `Some(Err(()))` refused the *value* — a Number into a BigInt
    /// view, which the caller turns into a `TypeError` — and `None` when this is not a
    /// view at all or the index is out of range, which is a silent no-op.
    pub fn typed_array_set(&self, index: usize, value: Value) -> Option<Result<(), &'static str>> {
        let (buffer, element, offset, length) = self.typed_array_parts()?;
        if index >= length {
            return Some(Ok(()));
        }
        let storage = buffer.array_buffer_storage()?;
        let mut storage = storage.borrow_mut();
        if storage.detached {
            return Some(Ok(()));
        }
        let stored = element.write(&mut storage.bytes, offset + index * element.size(), &value);
        Some(stored)
    }
}

/// A property of an object.
#[derive(Clone, Default)]
pub struct Property {
    /// The value of a data property.
    pub value: Option<Value>,
    /// The getter of an accessor property.
    pub getter: Option<Value>,
    /// The setter of an accessor property.
    pub setter: Option<Value>,
    /// Whether the value can be replaced.
    pub writable: bool,
    /// Whether `for`/`Object.keys` sees the property.
    pub enumerable: bool,
    /// Whether the property can be deleted or redefined.
    pub configurable: bool,
}

impl Property {
    /// A writable, enumerable, configurable data property.
    ///
    /// This is what a plain assignment or an object literal creates, and the
    /// attributes only differ for built-ins and `Object.defineProperty`.
    pub fn data(value: Value) -> Property {
        Property {
            value: Some(value),
            writable: true,
            enumerable: true,
            configurable: true,
            ..Property::default()
        }
    }

    /// A data property with explicit attributes.
    ///
    /// `configurable` is derived from `writable`, because that derivation is right for the
    /// case this is overwhelmingly used for: a built-in method or constructor, which the
    /// spec gives `{writable: true, enumerable: false, configurable: true}`.
    ///
    /// It is *not* right for the two other shapes the spec uses on functions, and both were
    /// wrong here for a long time — `name`/`length` are `{writable: false, enumerable:
    /// false, configurable: true}`, and a function's `prototype` is `{writable: true,
    /// enumerable: false, configurable: false}`. Use [`Property::name_or_length`] and
    /// [`Property::prototype_of`] for those rather than spelling them out, so that the two
    /// exceptions to the rule stay in one place.
    pub fn with_attributes(value: Value, writable: bool, enumerable: bool) -> Property {
        Property {
            value: Some(value),
            writable,
            enumerable,
            configurable: writable,
            ..Property::default()
        }
    }

    /// A `name` or `length` property: writable and enumerable are false, configurable true.
    ///
    /// Every function has both, and the spec makes them configurable so that a definition
    /// can replace them (`Object.defineProperty(f, "length", {value: 0})`, and
    /// `Function.prototype.bind` renaming its result). With them non-configurable, those
    /// definitions throw and about five hundred conformance tests fail.
    pub fn name_or_length(value: Value) -> Property {
        Property {
            value: Some(value),
            writable: false,
            enumerable: false,
            configurable: true,
            ..Property::default()
        }
    }

    /// A function's `prototype`: not configurable, and writable only for user functions.
    ///
    /// A built-in constructor's `prototype` is read-only — assigning to `Object.prototype`
    /// must not stick — while a user function's is writable, since that is how
    /// `Ctor.prototype.method = f` sets up inheritance. Neither is configurable, so
    /// `delete Ctor.prototype` fails in both cases.
    pub fn prototype_of(value: Value, writable: bool) -> Property {
        Property {
            value: Some(value),
            writable,
            enumerable: false,
            configurable: false,
            ..Property::default()
        }
    }

    /// An accessor property.
    /// An accessor property with explicit `enumerable`/`configurable` flags, which is
    /// what `Symbol.prototype.description` needs: it is enumerable: false in the spec.
    pub fn accessor_with(
        getter: Option<Value>,
        setter: Option<Value>,
        enumerable: bool,
    ) -> Property {
        Property {
            getter,
            setter,
            enumerable,
            configurable: true,
            ..Property::default()
        }
    }

    /// An accessor property with the default `enumerable`/`configurable` flags.
    pub fn accessor(getter: Option<Value>, setter: Option<Value>) -> Property {
        Property {
            getter,
            setter,
            enumerable: true,
            configurable: true,
            ..Property::default()
        }
    }

    /// Whether this is an accessor rather than a data property.
    pub fn is_accessor(&self) -> bool {
        self.getter.is_some() || self.setter.is_some()
    }
}

impl Trace for Property {
    fn trace(&self, tracer: &mut Tracer) {
        self.value.trace(tracer);
        self.getter.trace(tracer);
        self.setter.trace(tracer);
    }
}

// ---------------------------------------------------------------------------
// Host classes
// ---------------------------------------------------------------------------

/// The id a host class is registered under: what `JS_NewClassID` hands out.
///
/// Zero means "no class" (`JS_INVALID_CLASS_ID`), which is why allocation starts at one:
/// `JS_GetOpaque(val, 0)` has to match nothing, or every object in the realm would answer
/// for a class that was never registered.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct ClassId(u32);

impl ClassId {
    /// The id that matches no object (`JS_INVALID_CLASS_ID`).
    pub const INVALID: ClassId = ClassId(0);

    /// The id as the integer the C API speaks.
    pub fn get(self) -> u32 {
        self.0
    }

    /// Whether this id could name a registered class.
    pub fn is_valid(self) -> bool {
        self.0 != ClassId::INVALID.0
    }

    /// Build one from the integer a host kept on its side.
    pub fn from_raw(raw: u32) -> ClassId {
        ClassId(raw)
    }
}

impl fmt::Display for ClassId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// A pointer the engine never dereferences.
///
/// This is the payload of `JS_SetOpaque`: the host owns whatever it points at, and the
/// engine's whole involvement is handing it back unchanged, showing it to `gc_mark`, and
/// passing it to the finalizer. Storing, copying and comparing a raw pointer are safe
/// operations in Rust — only the host's own code ever dereferences it — which is what lets
/// this live in `quickjs-pure` without the crate growing an `unsafe` block.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Opaque(*mut ());

impl Opaque {
    /// The "nothing is set" pointer: what `JS_GetOpaque` answers for a host object whose
    /// `JS_SetOpaque` never ran.
    pub const NULL: Opaque = Opaque(std::ptr::null_mut());

    /// Wrap a pointer the host owns.
    pub fn new(pointer: *mut ()) -> Opaque {
        Opaque(pointer)
    }

    /// The pointer back, for the host to dereference.
    pub fn as_ptr(self) -> *mut () {
        self.0
    }

    /// Whether nothing has been stored.
    pub fn is_null(self) -> bool {
        self.0.is_null()
    }
}

impl fmt::Debug for Opaque {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Opaque({:p})", self.0)
    }
}

/// The property behaviour a host class may override: the exotic half of `JSClassDef`.
///
/// Every method's default is "no opinion", so an implementation names only the traps it
/// actually wants and everything else keeps the ordinary algorithm. That is what makes
/// `point.c`'s class — which has no exotic methods at all — work with an empty impl.
///
/// The `Option` in each answer is the same two-level question `JSClassExoticMethods` asks:
///
/// * outer `None` — not my business, run the ordinary algorithm;
/// * outer `Some(None)` — this object has no such property;
/// * outer `Some(Some(x))` — here is the answer.
///
/// # Re-entrancy
///
/// A trap receives the interpreter and may call back into it, because a host property can
/// be a JavaScript getter or a function on another object. It must not re-enter the *same*
/// operation on the *same* object (`get_property` calling `interp.get_property(object, …)`
/// for the key it was asked about), which recurses until the stack ends. The C API has the
/// identical hazard.
pub trait Exotic: 'static {
    /// `[[GetOwnProperty]]` (`JSClassExoticMethods::get_own_property`).
    fn get_own_property(
        &self,
        _interp: &mut crate::interp::Interp<'_>,
        _object: &Gc<JsObject>,
        _key: &PropertyKey,
    ) -> crate::interp::JsResult<Option<Option<Property>>> {
        Ok(None)
    }

    /// `[[DefineOwnProperty]]` (`JSClassExoticMethods::define_own_property`).
    fn define_own_property(
        &self,
        _interp: &mut crate::interp::Interp<'_>,
        _object: &Gc<JsObject>,
        _key: &PropertyKey,
        _property: &Property,
    ) -> crate::interp::JsResult<Option<bool>> {
        Ok(None)
    }

    /// `[[HasProperty]]` (`JSClassExoticMethods::has_property`).
    fn has_property(
        &self,
        _interp: &mut crate::interp::Interp<'_>,
        _object: &Gc<JsObject>,
        _key: &PropertyKey,
    ) -> crate::interp::JsResult<Option<bool>> {
        Ok(None)
    }

    /// `[[Delete]]` (`JSClassExoticMethods::delete_property`).
    fn delete_property(
        &self,
        _interp: &mut crate::interp::Interp<'_>,
        _object: &Gc<JsObject>,
        _key: &PropertyKey,
    ) -> crate::interp::JsResult<Option<bool>> {
        Ok(None)
    }

    /// `[[Get]]` (`JSClassExoticMethods::get_property`).
    ///
    /// Answers the *value*, and does its own prototype walk if it wants one; returning
    /// `None` leaves the read to the ordinary algorithm.
    fn get_property(
        &self,
        _interp: &mut crate::interp::Interp<'_>,
        _object: &Gc<JsObject>,
        _key: &PropertyKey,
        _receiver: &Value,
    ) -> crate::interp::JsResult<Option<Value>> {
        Ok(None)
    }

    /// `[[Set]]` (`JSClassExoticMethods::set_property`).
    ///
    /// `Some(false)` is a refusal, which the caller turns into a `TypeError` in strict code
    /// and silence in sloppy code — exactly like a proxy's `set` trap.
    fn set_property(
        &self,
        _interp: &mut crate::interp::Interp<'_>,
        _object: &Gc<JsObject>,
        _key: &PropertyKey,
        _value: &Value,
        _receiver: &Value,
    ) -> crate::interp::JsResult<Option<bool>> {
        Ok(None)
    }

    /// `[[GetPrototypeOf]]` (`JSClassExoticMethods::get_prototype`).
    fn get_prototype(
        &self,
        _interp: &mut crate::interp::Interp<'_>,
        _object: &Gc<JsObject>,
    ) -> crate::interp::JsResult<Option<Option<Gc<JsObject>>>> {
        Ok(None)
    }

    /// `[[SetPrototypeOf]]` (`JSClassExoticMethods::set_prototype`).
    fn set_prototype(
        &self,
        _interp: &mut crate::interp::Interp<'_>,
        _object: &Gc<JsObject>,
        _proto: Option<Gc<JsObject>>,
    ) -> crate::interp::JsResult<Option<bool>> {
        Ok(None)
    }

    /// `[[IsExtensible]]` (`JSClassExoticMethods::is_extensible`).
    fn is_extensible(
        &self,
        _interp: &mut crate::interp::Interp<'_>,
        _object: &Gc<JsObject>,
    ) -> crate::interp::JsResult<Option<bool>> {
        Ok(None)
    }

    /// `[[PreventExtensions]]` (`JSClassExoticMethods::prevent_extensions`).
    fn prevent_extensions(
        &self,
        _interp: &mut crate::interp::Interp<'_>,
        _object: &Gc<JsObject>,
    ) -> crate::interp::JsResult<Option<bool>> {
        Ok(None)
    }
}

/// A host class's finalizer: `JSClassDef::finalizer`.
///
/// Receives the class id and the payload, and nothing else — no interpreter, no context —
/// because it runs from [`Drop`], at which point there may be neither.
pub type HostFinalizer = Box<dyn Fn(ClassId, Opaque)>;

/// A host class's `gc_mark` callback: `JSClassDef::gc_mark`.
pub type HostGcMark = Box<dyn Fn(Opaque, &mut Tracer)>;

/// What every instance of one host class shares: the engine's half of `JSClassDef`.
///
/// Shared by `Rc` with each instance rather than looked up in a table when needed, because
/// the finalizer runs from `Drop` — at which point there is no interpreter, and often no
/// `Context`, left to look anything up in.
pub struct ClassDef {
    /// The class name (`JSClassDef::class_name`). Used in diagnostics.
    ///
    /// It is deliberately *not* the `Object.prototype.toString` tag: the reference answers
    /// `[object Object]` for a host object named `Point`, and only names its own built-in
    /// class ids. Making this the tag would be a visible difference.
    pub name: String,
    /// Run once when an instance is released (`JSClassDef::finalizer`).
    ///
    /// Called from `Drop`, so it must not touch the object being destroyed and must not
    /// allocate JavaScript values — it is not given an interpreter, which is what makes
    /// both mistakes impossible rather than merely discouraged.
    pub finalizer: Option<HostFinalizer>,
    /// Report the JavaScript values an instance's opaque state points at
    /// (`JSClassDef::gc_mark`).
    ///
    /// An instance whose Rust state holds a [`Gc`] has to say so here. The collector cannot
    /// see inside an opaque pointer, so a hidden handle counts as a reference from *outside*
    /// the heap — which makes the object it holds look like a root, and every garbage cycle
    /// closed through it immortal. It is a leak rather than a use-after-free (an invisible
    /// reference is still a reference), but it is a leak a host class creates without
    /// noticing, which is why the C API makes the callback part of the class definition.
    ///
    /// The callback must only report edges: it runs from [`Trace::trace`], which the
    /// collector calls while it holds a snapshot of the heap.
    pub gc_mark: Option<HostGcMark>,
    /// Property behaviour (`JSClassDef::exotic`).
    pub exotic: Option<Rc<dyn Exotic>>,
}

impl ClassDef {
    /// A class with no behaviour beyond being its own class id.
    pub fn new(name: impl Into<String>) -> ClassDef {
        ClassDef {
            name: name.into(),
            finalizer: None,
            gc_mark: None,
            exotic: None,
        }
    }

    /// Attach the finalizer `JSClassDef::finalizer` would carry.
    pub fn with_finalizer(mut self, finalizer: impl Fn(ClassId, Opaque) + 'static) -> ClassDef {
        self.finalizer = Some(Box::new(finalizer));
        self
    }

    /// Attach the `gc_mark` callback.
    pub fn with_gc_mark(mut self, mark: impl Fn(Opaque, &mut Tracer) + 'static) -> ClassDef {
        self.gc_mark = Some(Box::new(mark));
        self
    }

    /// Attach the exotic methods.
    pub fn with_exotic(mut self, exotic: Rc<dyn Exotic>) -> ClassDef {
        self.exotic = Some(exotic);
        self
    }
}

impl fmt::Debug for ClassDef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ClassDef")
            .field("name", &self.name)
            .field("finalizer", &self.finalizer.is_some())
            .field("gc_mark", &self.gc_mark.is_some())
            .field("exotic", &self.exotic.is_some())
            .finish()
    }
}

/// One instance of a host class: the class id, the class, and the host's payload.
///
/// Boxed inside [`ObjectKind`] because every `ObjectKind` is stored inline in the object
/// header: an unboxed `Rc` plus a pointer plus an id would widen *every* object in the
/// realm to no purpose.
pub struct HostData {
    /// Which class this is an instance of.
    pub class_id: ClassId,
    /// The class's shared behaviour.
    pub class: Rc<ClassDef>,
    /// The host's payload. See [`Opaque`].
    pub opaque: Opaque,
}

impl Drop for HostData {
    /// The finalizer's one and only call site.
    ///
    /// `HostData` is owned by exactly one `ObjectKind`, which is owned by exactly one
    /// `ObjectData`, so this runs exactly once — when the last strong reference goes away
    /// or when the cycle collector reclaims an unreachable object, which is the same two
    /// moments the reference implementation runs `JSClassDef::finalizer`.
    fn drop(&mut self) {
        if let Some(finalizer) = &self.class.finalizer {
            finalizer(self.class_id, self.opaque);
        }
    }
}

impl Trace for HostData {
    fn trace(&self, tracer: &mut Tracer) {
        // Nothing in the opaque state is visible to the collector unless the class says
        // so: `gc_mark` is the host's declaration that its Rust state holds `Gc` handles.
        if let Some(mark) = &self.class.gc_mark {
            mark(self.opaque, tracer);
        }
    }
}

/// A host function: a native function plus the state it captured.
///
/// `NativeFn` is a bare `fn` pointer, so a builtin that needs state (an open-file table,
/// a timer queue, a sink to write to) has nowhere to put it. `HostFn` boxes the closure
/// instead, and [`Callable::Host`] keeps it on the function object.
///
/// # Why the closure must not capture a `Gc`
///
/// The collector finds live objects by walking the object graph through [`Trace`]. A
/// closure is opaque Rust, so nothing inside it is walked: a `Gc<JsObject>` captured here
/// would be invisible to the collector and could be freed while the closure still holds
/// it — a use-after-free.
///
/// Keep Rust-side state (file descriptors, timer ids, deadlines) in the closure, and keep
/// every JavaScript value somewhere the collector already scans: a property of a real JS
/// object, or a table hanging off [`Interp`]. `os.setTimeout(fn, ms)` stores `fn` in the
/// interpreter's timer table for exactly this reason.
///
/// [`Trace`]: js_gc::Trace
/// [`Interp`]: crate::interp::Interp
pub type HostFn = Box<
    dyn for<'i> FnMut(
        &mut crate::interp::Interp<'i>,
        Value,
        &[Value],
    ) -> crate::interp::JsResult<Value>,
>;

/// A native (Rust) function reachable from JavaScript.
///
/// It receives the interpreter so a builtin can allocate (which needs the heap),
/// call back into JavaScript (which needs the frame stack) and raise exceptions.
pub type NativeFn =
    fn(&mut crate::interp::Interp<'_>, Value, &[Value]) -> crate::interp::JsResult<Value>;

/// The body of a callable object.
pub enum Callable {
    /// A function compiled from JavaScript source.
    Bytecode {
        /// The bytecode and slot mapping.
        code: Gc<CompiledCode>,
        /// The captured environment.
        env: Gc<ClosureEnv>,
    },
    /// A function produced by `Function.prototype.bind`.
    ///
    /// This is a variant rather than a native function carrying the state in
    /// properties because the state is not observable: `bind` has to remember its
    /// target, `this` and leading arguments, and a native trampoline cannot capture
    /// them.
    Bound {
        /// The function being called.
        target: Value,
        /// The `this` every call uses.
        this: Value,
        /// Arguments prepended to every call's own.
        args: Vec<Value>,
    },
    /// A built-in implemented in Rust.
    ///
    /// The `name` and `length` a script observes are ordinary properties on the
    /// function object, not fields here: they are writable (`f.name = "x"` works)
    /// and would otherwise be two sources of truth.
    Native {
        /// The implementation.
        func: NativeFn,
        /// Whether this constructor builds its own instance instead of being handed one.
        ///
        /// The spec has a constructor validate its arguments *before*
        /// `OrdinaryCreateFromConstructor` reads `new.target.prototype`, and only the ones
        /// with real validation need to: `new Promise(nonCallable)` and `new DataView(…)`
        /// must refuse the argument before a throwing `prototype` getter can run. The rest
        /// keep the simpler shape where `new` has already made the object.
        own_instance: bool,
    },
    /// A host function: a native closure that carries its own state.
    ///
    /// Behind an `Rc<RefCell<…>>` because the closure has to be *called* with
    /// `&mut Interp`, and the call site would otherwise still be holding a borrow of this
    /// object's data — the closure itself may reach the same object. Cloning the `Rc` out
    /// and dropping the borrow first is what keeps that from panicking.
    Host {
        /// The body, with whatever it captured.
        func: std::rc::Rc<std::cell::RefCell<HostFn>>,
        /// Whether this constructor builds its own instance; see [`Callable::Native`].
        own_instance: bool,
    },
    /// The `revoke` function `Proxy.revocable` hands back.
    ///
    /// It is a variant rather than a `Native` with the slots in a property because a
    /// `NativeFn` is a plain function pointer: it cannot capture, and the slots are
    /// precisely what this function exists to hold. Keeping them here also means the
    /// collector sees them, so a proxy stays alive while only its `revoke` is reachable.
    Revoker(crate::object::ProxyRef),
    /// The `resolve` a `Promise` executor receives.
    ///
    /// Like [`Callable::Revoker`], this cannot be a plain `Native` with the state in a
    /// property: a `NativeFn` is a function pointer and cannot capture, and the promise
    /// it settles is exactly what it has to remember. Both are one-shot per §27.2.1.3.1 —
    /// the second call is a no-op rather than a second settlement.
    ///
    /// The promise object is held directly rather than the state behind its `Rc`, because
    /// settling has to run *that object's* reactions.
    PromiseResolve(Gc<JsObject>),
    /// The `reject` half of that pair.
    PromiseReject(Gc<JsObject>),
    /// The executor handed to a *user* promise constructor by `NewPromiseCapability(C)`.
    ///
    /// `Promise.all.call(MyPromise, …)` has to let `MyPromise` decide what a capability is,
    /// so the executor cannot be a Rust closure: it has to be a function object the script
    /// can call, and it records whatever `resolve`/`reject` it is given into `state` so the
    /// combinator can read them back after the constructor returns.
    CapabilityExecutor {
        /// The hidden object the pair is recorded on.
        state: Gc<JsObject>,
    },
    /// One of the two continuations an `await` parks on.
    ///
    /// Reached through the ordinary reaction machinery, which is why it has to be a
    /// callable object rather than a queue entry: `await x` is specified as
    /// `PerformPromiseThen(x, resume, rethrow)`.
    AwaitResume {
        /// The body to continue.
        coroutine: Gc<JsObject>,
        /// The promise the async function returned.
        promise: Gc<JsObject>,
        /// Whether this continuation delivers the value or raises the reason.
        kind: crate::interp::ResumeKind,
    },
    /// One element of `Promise.all`/`allSettled`/`any`/`race` settling.
    CombinatorSettle {
        /// The hidden object holding the results array, the remaining count and the
        /// combinator's own resolve/reject pair.
        state: Gc<JsObject>,
        /// Which element this callback belongs to.
        index: usize,
        /// Whether the element fulfilled or rejected.
        fulfilled: bool,
    },
    /// One leg of a `then` that answers through a *user* capability.
    ///
    /// `promise.then(f, g)` builds its result from `SpeciesConstructor(promise)`, so the
    /// settlement has to go through whatever `resolve`/`reject` that constructor produced.
    /// The user's handler therefore cannot be attached to `perform_then` directly — that
    /// would settle the engine's own derived promise — so it rides here and the shim calls
    /// it, then hands the result (or the throw) to the capability.
    ThenShim {
        /// The script's `onFulfilled`/`onRejected`, or `None` for a pass-through.
        handler: Option<Value>,
        /// `capability.[[Resolve]]`.
        resolve: Value,
        /// `capability.[[Reject]]`.
        reject: Value,
        /// Whether this leg delivers the value or the reason.
        fulfilled: bool,
    },
    /// Settle a promise with a fixed outcome when called.
    ///
    /// `finally` needs "wait for this promise, then re-deliver that value", and a
    /// `NativeFn` cannot carry the value to re-deliver.
    SettlePromise {
        /// The promise to settle.
        promise: Gc<JsObject>,
        /// The outcome to settle it with, which is the *original* one.
        value: Value,
        /// Whether that outcome is a rejection.
        rejected: bool,
    },
    /// One continuation of an `await` inside an async generator.
    GeneratorResume {
        /// The async generator to continue.
        generator: Gc<JsObject>,
        /// The promise the pending `next`/`return`/`throw` returned.
        promise: Gc<JsObject>,
        /// Whether this delivers the value or raises the reason.
        kind: crate::interp::ResumeKind,
    },
    /// Reads a module namespace's binding out of the cell it is stored in.
    ///
    /// A namespace object is an ordinary object whose exports are getters, so a getter
    /// is what `ns.x` calls — and it has to be a callable object carrying the cell, for
    /// the same reason `PromiseResolve` carries its promise.
    ModuleBinding {
        /// The binding's cell, shared with the exporting module.
        cell: Gc<Cell>,
    },
    /// Finish a completed async generator's `return(v)` once `v` has settled.
    CompletedReturn {
        /// The generator, so settling this request can start the next one.
        generator: Gc<JsObject>,
        /// The promise the `return` answered.
        promise: Gc<JsObject>,
        /// Whether the value rejected instead of settling.
        rejected: bool,
    },
    /// Answer a pending async-generator method with `{value, done: false}`.
    ///
    /// `yield v` in an async generator awaits `v` first, so the value can arrive after
    /// the body has already parked; this is what turns it into the result object.
    YieldResult {
        /// The generator, so settling this request can start the next one.
        generator: Gc<JsObject>,
        /// The promise the pending method returned.
        promise: Gc<JsObject>,
        /// Whether this answers a completed generator rather than a `yield`.
        done: bool,
    },
    /// One step of `AsyncDisposableStack.disposeAsync`.
    ///
    /// The remaining resources ride along as a JS array so the collector can see them:
    /// `disposeAsync` awaits each disposer in turn, which means the list has to survive
    /// across microtasks rather than living on the Rust stack.
    DisposeStep {
        /// Pairs of `[resource, disposeMethod]`, consumed from the end.
        remaining: Gc<JsObject>,
        /// The promise `disposeAsync` returned.
        promise: Gc<JsObject>,
        /// The `SuppressedError` chain built so far, or `Uninitialized` for none.
        error: Value,
        /// Whether this continuation is being called with a rejection reason.
        rejected: bool,
    },
    /// One of the two shims `Promise.prototype.finally` installs.
    FinallyShim {
        /// The script's callback, or `None` to pass the outcome straight through.
        callback: Option<Value>,
        /// Whether this is the fulfil side.
        fulfilled: bool,
        /// `C` from §27.2.5.3: the constructor whose `PromiseResolve` the callback's
        /// result goes through, so `mp1.finally(() => mp2)` reuses `mp2` rather than
        /// wrapping it in another capability.
        constructor: Value,
    },
}

impl Trace for Callable {
    fn trace(&self, tracer: &mut Tracer) {
        match self {
            Callable::Bytecode { code, env } => {
                tracer.visit(code);
                tracer.visit(env);
            }
            Callable::Bound { target, this, args } => {
                target.trace(tracer);
                this.trace(tracer);
                for argument in args {
                    argument.trace(tracer);
                }
            }
            Callable::Native { .. } => {}
            // Nothing to trace, by construction: the closure must not hold a `Gc`. See
            // `HostFn`'s documentation.
            Callable::Host { .. } => {}
            Callable::Revoker(slots) => slots.borrow().trace(tracer),
            Callable::CapabilityExecutor { state } => tracer.visit(state),
            Callable::ThenShim {
                handler,
                resolve,
                reject,
                fulfilled: _,
            } => {
                if let Some(handler) = handler {
                    handler.trace(tracer);
                }
                resolve.trace(tracer);
                reject.trace(tracer);
            }
            Callable::PromiseResolve(promise) | Callable::PromiseReject(promise) => {
                tracer.visit(promise)
            }
            Callable::AwaitResume {
                coroutine, promise, ..
            } => {
                tracer.visit(coroutine);
                tracer.visit(promise);
            }
            Callable::CombinatorSettle { state, .. } => tracer.visit(state),
            Callable::GeneratorResume {
                generator, promise, ..
            } => {
                tracer.visit(generator);
                tracer.visit(promise);
            }
            Callable::CompletedReturn {
                generator, promise, ..
            }
            | Callable::YieldResult {
                generator, promise, ..
            } => {
                tracer.visit(generator);
                tracer.visit(promise);
            }
            Callable::ModuleBinding { cell } => tracer.visit(cell),
            Callable::DisposeStep {
                remaining,
                promise,
                error,
                ..
            } => {
                tracer.visit(remaining);
                tracer.visit(promise);
                error.trace(tracer);
            }
            Callable::SettlePromise { promise, value, .. } => {
                tracer.visit(promise);
                value.trace(tracer);
            }
            Callable::FinallyShim {
                callback,
                constructor,
                ..
            } => {
                if let Some(callback) = callback {
                    callback.trace(tracer);
                }
                constructor.trace(tracer);
            }
        }
    }
}

/// The bytecode of one function, plus the slot-to-cell mapping.
///
/// This is a separate GC object from the closure so that a frame can hold a handle
/// to it and read it while the function object itself is free to be borrowed.
/// Holding a `RefCell` borrow across a call would deadlock the moment a function
/// referred to itself.
pub struct CompiledCode {
    /// The resolved bytecode.
    pub code: CompiledFunction,
    /// For each argument slot, the index of its reference cell, or `-1` when the
    /// slot holds its value directly.
    ///
    /// A captured binding lives in a cell so that closures outlive the frame; every
    /// other slot is a plain value. Precomputing the mapping keeps the hot
    /// `get_arg`/`put_arg` paths to one array read instead of a lookup.
    pub arg_cell: Vec<i32>,
    /// The same, for local slots.
    pub loc_cell: Vec<i32>,
    /// The bytecode decoded once, into fixed-width records.
    ///
    /// Decoding is per instruction and never changes its answer — the bytecode is
    /// immutable once compiled — so doing it at compile time is free and doing it on
    /// every dispatch is not. See [`crate::insn`].
    pub insns: Vec<crate::insn::Insn>,
    /// The atom table as property keys, built once.
    ///
    /// `get_field x` needs `x` as a [`PropertyKey`], and building one per access meant
    /// `Wtf8::from_rc_str`, which allocates a fresh `Rc<[u8]>` and copies the bytes —
    /// despite its name, it does not share the atom's storage. That put a `malloc` on
    /// every property read: 5.3% of `property:monomorphic`, plus 1.6% in the `memmove`
    /// inside it.
    ///
    /// Built here instead, so a lookup clones an `Rc` — a pointer bump — rather than
    /// allocating. Same trick, and the same reason, as `arg_cell` and `insns`.
    pub atom_keys: Vec<PropertyKey>,
}

impl CompiledCode {
    /// Build the slot-to-cell mapping for `code`.
    ///
    /// Cells are numbered the way [`CompiledFunction::var_ref_count`] counts them:
    /// the captured arguments first, then the captured locals, each in slot order.
    pub fn new(code: CompiledFunction) -> CompiledCode {
        let mut next = 0i32;
        let mut arg_cell = vec![-1; code.args.len()];
        for (slot, arg) in code.args.iter().enumerate() {
            if arg.is_captured {
                arg_cell[slot] = next;
                next += 1;
            }
        }
        let mut loc_cell = vec![-1; code.vars.len()];
        for (slot, local) in code.vars.iter().enumerate() {
            if local.is_captured {
                loc_cell[slot] = next;
                next += 1;
            }
        }
        let insns = crate::insn::predecode(&code.code);
        let atom_keys = code.atoms.iter().map(atom_key_of).collect();
        CompiledCode {
            code,
            arg_cell,
            loc_cell,
            insns,
            atom_keys,
        }
    }
}

impl Trace for CompiledCode {
    fn trace(&self, _tracer: &mut Tracer) {}

    /// The decoded instruction array, which is the one thing here that is not shared
    /// with the compiler's own table.
    ///
    /// Counted because `--memory-limit` has to see it: twenty bytes per instruction
    /// for every function in the program, and a program with ten thousand small
    /// functions is a few megabytes that used to be invisible.
    fn external_bytes(&self) -> usize {
        self.insns.len() * std::mem::size_of::<crate::insn::Insn>()
            + self.atom_keys.len() * std::mem::size_of::<PropertyKey>()
    }
}

/// One atom of a compiled function's atom table, as the property key a lookup needs.
///
/// Kept beside [`CompiledCode::new`] rather than inline in it so the three `Atom`
/// variants are matched in one place: `Str` shares its bytes through the `Rc` in
/// [`Wtf8::from_rc_str`], and `Index` formats the number once instead of once per read.
fn atom_key_of(atom: &js_compile::bytecode::Atom) -> PropertyKey {
    use js_compile::bytecode::Atom;
    PropertyKey::String(match atom {
        // Already a `Wtf8`, and cloning one is a refcount bump, so the atom's bytes are
        // shared rather than re-scanned the way `from_rc_str` would.
        Atom::Str(text) => text.clone(),
        Atom::Index(value) => crate::value::Wtf8::new(value.to_string()),
        // `JS_ATOM_NULL`: no name. The opcodes that take one never read it.
        Atom::Null => crate::value::Wtf8::new(String::new()),
    })
}

/// The reference cells a closure captured from enclosing scopes.
pub struct ClosureEnv {
    /// Indexed the way the bytecode's closure-variable table indexes them.
    pub cells: Vec<Gc<Cell>>,
    /// The `eval` scope this closure was created in, if any.
    ///
    /// A function built by `eval` has to keep seeing the caller's bindings after the
    /// eval has returned — `for (let i …) eval("push(() => i)")` collects closures that
    /// read `i` later. Those bindings live in the *caller's* frame, which is long gone
    /// by then, so the environment carries them by name instead. Ordinary closures leave
    /// this `None` and resolve globals exactly as before.
    pub eval_scope: Option<Gc<EvalScope>>,
    /// Variables a direct `eval` declared in the frame this closure was created in, and
    /// how much of that frame it may see.
    ///
    /// A closure is created at a *place* in a function, and a direct `eval` can add
    /// variables after that point. Those variables belong to the variable environment
    /// that was current at the closure's creation — the parameter list or the body — which
    /// is what `local_phase` records.
    pub local_vars: Option<Gc<LocalVars>>,
    /// `0` for a closure created in a parameter list, `1` for one in a body. A parameter
    /// list's closure must not see variables a later `eval` in the body declared:
    /// `function f(a, p = () => c) { eval("var c = 1") }` has `p()` resolve `c` outside
    /// the function entirely.
    pub local_phase: u8,
}

/// Variables a direct `eval` declared in one function call.
///
/// A sloppy `eval` declares its `var`s in the caller's variable environment, not on the
/// global object: `function f() { eval("var x = 1") } f(); x` is a `ReferenceError`, and
/// two calls to `f` get two `x`s. Each entry therefore records the phase it was declared
/// in, so a lookup from the parameter list cannot see a body declaration.
pub struct LocalVars {
    names: std::cell::RefCell<Vec<(String, Gc<Cell>, u8)>>,
}

impl Default for LocalVars {
    fn default() -> LocalVars {
        LocalVars::new()
    }
}

impl LocalVars {
    /// An empty set.
    pub fn new() -> LocalVars {
        LocalVars {
            names: std::cell::RefCell::new(Vec::new()),
        }
    }

    /// The cell `name` resolves to, when it was declared in `phase` or earlier.
    pub fn get(&self, name: &str, phase: u8) -> Option<Gc<Cell>> {
        self.names
            .borrow()
            .iter()
            .find(|(bound, _, at)| bound == name && *at <= phase)
            .map(|(_, cell, _)| cell.clone())
    }

    /// The cell for `name`, declaring it if this is the first time.
    pub fn declare(&self, name: &str, phase: u8, cell: Gc<Cell>) -> Gc<Cell> {
        let mut names = self.names.borrow_mut();
        if let Some((_, cell, _)) = names.iter().find(|(bound, _, _)| bound == name) {
            return cell.clone();
        }
        names.push((name.to_string(), cell.clone(), phase));
        cell
    }

    /// Whether `name` has been declared at all.
    pub fn contains(&self, name: &str) -> bool {
        self.names
            .borrow()
            .iter()
            .any(|(bound, _, _)| bound == name)
    }
}

impl Trace for LocalVars {
    fn trace(&self, tracer: &mut Tracer) {
        for (_, cell, _) in self.names.borrow().iter() {
            tracer.visit(cell);
        }
    }
}

impl Trace for ClosureEnv {
    fn trace(&self, tracer: &mut Tracer) {
        for cell in &self.cells {
            tracer.visit(cell);
        }
        if let Some(scope) = &self.eval_scope {
            tracer.visit(scope);
        }
        if let Some(local_vars) = &self.local_vars {
            tracer.visit(local_vars);
        }
    }
}

/// The bindings a direct `eval` made visible, as name → cell.
///
/// Only bindings that already live in a cell appear here, because sharing their
/// identity is the point: a closure created by the eval must observe later writes to
/// the same variable, and a copy would not. The compiler puts every binding of a
/// function that contains a direct `eval` into a cell, so in practice that is all of
/// them.
pub struct EvalScope {
    /// In lookup order: the innermost binding for a name first.
    pub names: Vec<(String, Gc<Cell>)>,
}

impl EvalScope {
    /// The cell `name` resolves to, if this scope binds it.
    pub fn get(&self, name: &str) -> Option<&Gc<Cell>> {
        self.names
            .iter()
            .find(|(bound, _)| bound == name)
            .map(|(_, cell)| cell)
    }
}

impl Trace for EvalScope {
    fn trace(&self, tracer: &mut Tracer) {
        for (_, cell) in &self.names {
            tracer.visit(cell);
        }
    }
}

/// What kind of object this is.
pub enum ObjectKind {
    /// An ordinary object: only its property table.
    Ordinary,
    /// An array: a dense element vector plus a property table for everything else.
    ///
    /// `length` is stored **separately** rather than derived from `elements.len()`, so a
    /// sparse array costs nothing to poke at a far index: the reference answers
    /// `a = []; a.length = 4294967295` instantly, while deriving the length from a dense
    /// vector meant allocating one `Value` per slot — 62 GB and 24 seconds for that one
    /// statement. An index past the vector is a hole, and `length` alone records how many
    /// holes there are at the end.
    ///
    /// Invariant: `elements.len() <= length`. A truncation drops both, so the reverse
    /// (`length < elements.len()`) never holds.
    Array {
        /// The dense prefix: everything before the first trailing hole.
        elements: Vec<Value>,
        /// The logical length, which may exceed `elements.len()`.
        length: usize,
    },
    /// A function or a class constructor.
    Function(Callable),
    /// A regular expression: the compiled pattern, plus `lastIndex` as a property.
    RegExp(crate::builtins::regexp::RegExpData),
    /// A `DisposableStack` or `AsyncDisposableStack`: the resources it holds.
    DisposableStack(crate::builtins::disposable::StackState),
    /// An `ArrayBuffer`: a byte range that typed-array views share.
    ///
    /// The bytes sit behind an `Rc<RefCell<…>>` rather than in the object so that every view
    /// of the buffer sees the same storage; the *views* hold the `Gc<JsObject>` of this
    /// buffer, which is what keeps it alive and what the collector traces.
    ArrayBuffer(std::rc::Rc<std::cell::RefCell<BufferStorage>>),
    /// A `Map` or a `Set`: insertion-ordered entries with `SameValueZero` key equality.
    ///
    /// One variant for both, because a `Set` is exactly a `Map` whose value is unused — the
    /// difference is a flag, and `is_set` is what makes `entries` yield `[v, v]` pairs.
    Collection {
        /// The entries, in insertion order.
        entries: Vec<(Value, Value)>,
        /// Whether this is a `Set` rather than a `Map`.
        is_set: bool,
    },
    /// A `DataView`: a byte-oriented window onto an `ArrayBuffer`.
    ///
    /// Separate from `TypedArray` because the two index differently: a typed array has an
    /// element type and counts *elements*, while a `DataView` is untyped and every accessor
    /// names its own width and byte offset. Sharing one variant would mean carrying an
    /// element type that is always "bytes" and a length that means something else.
    DataView {
        /// The buffer whose bytes this view reads.
        buffer: Gc<JsObject>,
        /// Byte offset of the view's first byte.
        offset: usize,
        /// How many bytes the view exposes, or that it follows the buffer.
        length: ViewLength,
    },
    /// A typed-array view: a window onto an `ArrayBuffer`.
    TypedArray {
        /// The buffer whose bytes this view reads.
        buffer: Gc<JsObject>,
        /// What one element is.
        element: crate::builtins::typedarray::ElementType,
        /// Byte offset of element zero.
        offset: usize,
        /// How many elements the view exposes, or that it follows the buffer.
        length: ViewLength,
    },
    /// A generator object: a detached frame plus how far it got.
    ///
    /// The frame lives here rather than in the interpreter because a suspended generator
    /// has to keep its locals and operand stack alive for as long as the script can reach
    /// the generator object — and the collector has to see them, which it only does for
    /// things hanging off a `Gc`.
    Generator(Box<crate::interp::GeneratorState>),
    /// A `Proxy`: a stand-in that forwards every internal method to a target through a
    /// handler's traps.
    ///
    /// The state sits behind an `Rc` because `Proxy.revocable` hands the script a
    /// `revoke` function that has to reach *this* proxy's two slots later, from a call
    /// site that has no pointer to the object. Revoking clears them, which also drops
    /// the collector's references to the target and the handler.
    Proxy(ProxyRef),
    /// A `Promise`.
    ///
    /// The state sits behind an `Rc` for the same reason a proxy's slots do: the
    /// `resolve`/`reject` pair handed to an executor has to settle *this* promise later,
    /// and those are function objects with no pointer back to it otherwise.
    Promise(PromiseRef),
    /// A `WeakMap` or `WeakSet`: like a collection, but the *keys* are weak.
    ///
    /// The distinction lives entirely in [`Trace`]: a `Collection` traces its keys, a
    /// `WeakCollection` does not. An entry keyed by an otherwise-unreachable object is
    /// therefore reclaimed together with that object instead of keeping it alive, and the
    /// entry simply stops being found — `upgrade` fails and a liveness sweep drops the
    /// pair. That is the "ephemeron" behaviour `WeakMap` promises, and it falls out of
    /// reference counting rather than needing a second collection pass.
    WeakCollection {
        /// The entries, in insertion order, keyed by a non-owning handle.
        entries: Vec<(WeakKey, Value)>,
        /// Whether this is a `WeakSet` rather than a `WeakMap`.
        is_set: bool,
    },
    /// A `WeakRef`: one non-owning handle to a target object.
    WeakRef {
        /// The target. Once `upgrade` fails the reference is dead for good, because a box
        /// whose strong count reached zero never comes back.
        ///
        /// A `WeakKey` rather than a `WeakGc<JsObject>`, because a symbol is a valid target
        /// too — `new WeakRef(Symbol())` works and `deref` has to answer it back.
        target: WeakKey,
    },
    /// A `FinalizationRegistry`: the cleanup callback and its live registrations.
    Finalization(Box<FinalizationState>),
    /// An instance of a class the host registered (`JS_NewObjectProtoClass`).
    ///
    /// Deliberately not folded into `Ordinary` with the payload in a private property:
    /// `JS_GetOpaque` has to be a class check as well as a pointer read, so that handing a
    /// `Date` to a method expecting a `Point` is a `TypeError` rather than a reinterpreted
    /// pointer.
    HostClass(Box<HostData>),
}

impl ObjectKind {
    /// This variant's name, for the memory report's per-class census.
    ///
    /// Not `Debug`: the census groups and sorts by these strings, so they have to be stable
    /// and human-readable, and several variants carry payloads that `Debug` would print.
    pub fn variant_name(&self) -> &'static str {
        match self {
            ObjectKind::Ordinary => "Object",
            ObjectKind::Array { .. } => "Array",
            ObjectKind::Function(_) => "Function",
            ObjectKind::RegExp(_) => "RegExp",
            ObjectKind::DisposableStack(_) => "DisposableStack",
            ObjectKind::ArrayBuffer(_) => "ArrayBuffer",
            ObjectKind::Collection { is_set, .. } => {
                if *is_set {
                    "Set"
                } else {
                    "Map"
                }
            }
            ObjectKind::DataView { .. } => "DataView",
            ObjectKind::TypedArray { .. } => "TypedArray",
            ObjectKind::Generator(_) => "Generator",
            ObjectKind::Proxy(_) => "Proxy",
            ObjectKind::Promise(_) => "Promise",
            ObjectKind::WeakCollection { .. } => "WeakCollection",
            ObjectKind::WeakRef { .. } => "WeakRef",
            ObjectKind::Finalization(_) => "Finalization",
            ObjectKind::HostClass(_) => "HostClass",
        }
    }
}

/// The mutable half of a `FinalizationRegistry`.
///
/// Boxed inside the [`ObjectKind`] variant because it holds a vector plus a value, and every
/// `ObjectKind` is stored inline in the object header — an unboxed field this wide would
/// make *every* object in the realm that much larger.
pub struct FinalizationState {
    /// One entry per successful `register` call.
    pub registrations: Vec<Registration>,
    /// The cleanup callback, validated as callable when the registry was built.
    pub cleanup: Value,
}

/// A key that can be held weakly: an object, or a symbol.
///
/// Both are heap allocations in this engine (`Value::Symbol` carries a `Gc<JsSymbol>`), so a
/// `WeakGc` holds either one just as well. Symbols became valid keys with the
/// `symbols-as-weakmap-keys` proposal, which is what test262 already tests.
#[derive(Clone)]
pub enum WeakKey {
    /// An object target.
    Object(WeakGc<JsObject>),
    /// A symbol target.
    Symbol(WeakGc<JsSymbol>),
}

impl WeakKey {
    /// Whether the allocation behind this key has been released.
    pub fn is_expired(&self) -> bool {
        match self {
            WeakKey::Object(handle) => handle.is_expired(),
            WeakKey::Symbol(handle) => handle.is_expired(),
        }
    }

    /// Whether two weak keys are the same allocation.
    pub fn same(&self, other: &WeakKey) -> bool {
        match (self, other) {
            (WeakKey::Object(left), WeakKey::Object(right)) => left.ptr_eq(right),
            (WeakKey::Symbol(left), WeakKey::Symbol(right)) => left.ptr_eq(right),
            _ => false,
        }
    }

    /// Whether this key is the same allocation as `value`, without upgrading it.
    ///
    /// Upgrading would resurrect the key, which for a `WeakMap` lookup is exactly what must
    /// not happen — a dead key has to compare equal to nothing.
    pub fn matches(&self, value: &Value) -> bool {
        match (self, value) {
            (WeakKey::Object(handle), Value::Object(object)) => object.upgrades_to(handle),
            (WeakKey::Symbol(handle), Value::Symbol(symbol)) => symbol.upgrades_to(handle),
            _ => false,
        }
    }

    /// The key as a strong value, when it is still alive.
    pub fn upgrade(&self) -> Option<Value> {
        match self {
            WeakKey::Object(handle) => handle.upgrade().map(Value::Object),
            WeakKey::Symbol(handle) => handle.upgrade().map(Value::Symbol),
        }
    }
}

impl Trace for WeakKey {
    fn trace(&self, _tracer: &mut Tracer) {}
}

/// Turn a script value into a weak key, if `CanBeHeldWeakly` allows it.
///
/// The rule is "an object, or a symbol that is not in the registry". A registered symbol —
/// one from `Symbol.for` — is refused on purpose: it lives in the realm's registry for the
/// lifetime of the realm, so it never dies, and a weak entry keyed by it could never be
/// observed to be collected. A plain `Symbol()` is a fresh allocation each time and so has
/// a lifetime worth observing.
pub fn weak_key(value: &Value) -> Option<WeakKey> {
    match value {
        Value::Object(object) => Some(WeakKey::Object(object.downgrade())),
        Value::Symbol(symbol) if symbol.registry_key().is_none() => {
            Some(WeakKey::Symbol(symbol.downgrade()))
        }
        _ => None,
    }
}

/// One `FinalizationRegistry.register` call.
///
/// `token` is compared with `SameValue`, not `SameValueZero`, which is why it is kept as
/// the original `Value` rather than normalised into a key.
pub struct Registration {
    /// The handle whose death fires the callback.
    pub target: WeakKey,
    /// What the callback receives: the script's held value, kept alive until it fires.
    pub held_value: Value,
    /// The cancellation token, if one was given.
    pub token: Option<Value>,
}

/// The two slots of a proxy, shared with its `revoke` function.
///
/// `None` in both slots means revoked: every operation then throws a `TypeError`, and
/// the target and handler are no longer reachable — which is the whole point of
/// `Proxy.revocable`.
#[derive(Default)]
pub struct ProxyState {
    /// The object the traps receive, or `None` once revoked.
    pub target: Option<Gc<JsObject>>,
    /// The trap table, or `None` once revoked.
    pub handler: Option<Value>,
    /// Whether this proxy has a `[[Call]]`, decided once when it is created.
    ///
    /// Revoking drops the target but does not take `[[Call]]` away, so this cannot be
    /// re-derived from `target` being `Some`: `typeof p.proxy` has to stay `"function"`
    /// after `Proxy.revocable(function(){}, {}).revoke()`, and the reference agrees.
    pub callable: bool,
    /// Whether this proxy has a `[[Construct]]`, decided once when it is created.
    ///
    /// Same reasoning as [`ProxyState::callable`], and the two are genuinely independent:
    /// `Proxy.revocable(function(){}, {})` is both callable and constructible, while a
    /// proxy over an arrow function is callable and not constructible.
    pub constructible: bool,
}

/// A `Promise`'s state, shared between the promise object and its resolve/reject
/// functions.
///
/// Behind an `Rc` for the same reason a proxy's slots are: the `resolve` and `reject`
/// functions handed to an executor have to settle *this* promise later, from a call site
/// that only has the function.
pub struct PromiseState {
    /// Pending, or the value it settled with.
    pub status: PromiseStatus,
    /// The `then` reactions waiting on it, in registration order.
    pub reactions: Vec<PromiseReaction>,
    /// Whether a rejection has been seen by a handler.
    ///
    /// A rejection that never is becomes an unhandled-rejection report, which the
    /// reference makes fatal at the end of the job queue.
    pub handled: bool,
}

impl Default for PromiseState {
    fn default() -> Self {
        PromiseState {
            status: PromiseStatus::Pending,
            reactions: Vec::new(),
            handled: false,
        }
    }
}

/// What a `Promise` combinator does when its elements settle.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CombinatorKind {
    /// The first rejection wins, otherwise an array in input order.
    All,
    /// Never rejects; each entry is `{status, value}` or `{status, reason}`.
    AllSettled,
    /// The first fulfilment wins, otherwise an `AggregateError`.
    Any,
    /// Whichever element settles first.
    Race,
}

/// Which of §27.2.1.2's three states a promise is in.
#[derive(Clone, Default)]
pub enum PromiseStatus {
    /// Neither settled: reactions queue up.
    #[default]
    Pending,
    /// Settled with a value, which no further settle may change.
    Fulfilled(Value),
    /// Settled with a reason.
    Rejected(Value),
}

/// One `then` registration.
#[derive(Clone)]
pub struct PromiseReaction {
    /// Called with the value if the promise fulfils.
    pub on_fulfilled: Option<Value>,
    /// Called with the reason if it rejects.
    pub on_rejected: Option<Value>,
    /// The promise to settle with whatever the handler returns.
    pub promise: Gc<JsObject>,
}

impl Trace for PromiseState {
    fn trace(&self, tracer: &mut Tracer) {
        match &self.status {
            PromiseStatus::Pending => {}
            PromiseStatus::Fulfilled(value) | PromiseStatus::Rejected(value) => value.trace(tracer),
        }
        for reaction in &self.reactions {
            if let Some(on_fulfilled) = &reaction.on_fulfilled {
                on_fulfilled.trace(tracer);
            }
            if let Some(on_rejected) = &reaction.on_rejected {
                on_rejected.trace(tracer);
            }
            tracer.visit(&reaction.promise);
        }
    }
}

/// A promise's shareable state.
pub type PromiseRef = std::rc::Rc<std::cell::RefCell<PromiseState>>;

/// A proxy's mutable state, shared between the proxy object and its `revoke`.
pub type ProxyRef = std::rc::Rc<std::cell::RefCell<ProxyState>>;

impl Trace for ProxyState {
    fn trace(&self, tracer: &mut Tracer) {
        if let Some(target) = &self.target {
            tracer.visit(target);
        }
        if let Some(handler) = &self.handler {
            handler.trace(tracer);
        }
    }
}

impl Trace for ObjectKind {
    fn trace(&self, tracer: &mut Tracer) {
        match self {
            // Nothing in a compiled pattern is a GC value: it holds characters and
            // integers only.
            ObjectKind::RegExp(_) => {}
            ObjectKind::DisposableStack(state) => state.trace(tracer),
            // A buffer's bytes are plain bytes and hold no GC values; a view keeps its
            // buffer alive through the `Gc` it carries.
            ObjectKind::ArrayBuffer(_) => {}
            ObjectKind::TypedArray { buffer, .. } | ObjectKind::DataView { buffer, .. } => {
                tracer.visit(buffer)
            }
            ObjectKind::Collection { entries, .. } => {
                for (key, value) in entries {
                    key.trace(tracer);
                    value.trace(tracer);
                }
            }
            ObjectKind::Ordinary => {}
            ObjectKind::Array { elements, .. } => {
                for element in elements {
                    element.trace(tracer);
                }
            }
            ObjectKind::Function(callable) => callable.trace(tracer),
            ObjectKind::Generator(state) => state.trace(tracer),
            ObjectKind::Proxy(state) => state.borrow().trace(tracer),
            ObjectKind::Promise(state) => state.borrow().trace(tracer),
            // The *keys* are deliberately not visited: that absence is what makes the
            // collection weak, and it is also why a `WeakMap` cannot keep its key alive
            // through a cycle that only the map closes. The values are traced, so
            // `wm.set(k, v)` keeping `v` alive while `k` is reachable is the right half of
            // the ephemeron rule to get right here — the other half (dropping the pair once
            // the key dies) needs no liveness test, because `upgrade` on a dead key fails.
            ObjectKind::WeakCollection { entries, .. } => {
                for (_, value) in entries {
                    value.trace(tracer);
                }
            }
            // A `WeakRef` owns nothing at all: that is its whole purpose.
            ObjectKind::WeakRef { .. } => {}
            // A registry keeps its held values and its callback alive — the held value has
            // to survive until the callback can run — but not the targets, which is the
            // handle type's job rather than the tracer's.
            ObjectKind::Finalization(state) => {
                state.cleanup.trace(tracer);
                for registration in &state.registrations {
                    registration.held_value.trace(tracer);
                    registration.token.trace(tracer);
                }
            }
            // An instance's own state is invisible unless the class declared a `gc_mark`.
            ObjectKind::HostClass(data) => data.trace(tracer),
        }
    }
}

/// The mutable half of an object.
/// What a property is keyed by.
///
/// A string and a symbol are separate key spaces even when they look alike: `o["a"]`
/// and `o[Symbol("a")]` are two properties, and `o[Symbol("a")]` is not reachable by
/// any string. Symbols are also invisible to `for`/`Object.keys`/`JSON.stringify`,
/// which is the whole point of them, so the distinction has to survive into the
/// property table rather than being flattened into a name.
#[derive(Clone)]
pub enum PropertyKey {
    /// An ordinary string key, held as WTF-8 so a key containing an unpaired surrogate
    /// addresses one property rather than colliding with its `U+FFFD` replacement.
    String(crate::value::Wtf8),
    /// A symbol key.
    Symbol(Gc<JsSymbol>),
}

impl PropertyKey {
    /// A cheap hash of this key, for an inline cache's slot choice.
    ///
    /// Not a hash of the whole string: a long property name would make the cache slower than
    /// the lookup it is caching. Mixing the length with the first and last byte is enough to
    /// separate the names that appear on one object (`x`/`y`, `value`/`add`), and a
    /// collision only costs a miss.
    pub fn hash_code(&self) -> usize {
        match self {
            PropertyKey::String(text) => {
                let bytes = text.as_bytes();
                let mut hash = bytes.len();
                for &byte in bytes.iter().take(4).chain(bytes.iter().rev().take(2)) {
                    hash = hash.wrapping_mul(31).wrapping_add(byte as usize);
                }
                hash
            }
            // A symbol's identity is its allocation, which is exactly what the cache needs —
            // two symbols with the same description are two keys.
            PropertyKey::Symbol(symbol) => symbol.identity(),
        }
    }
}

impl PropertyKey {
    /// The key as a string, for the operations that only accept one.
    ///
    /// A symbol has no string form that would address it, so this answers `None` —
    /// which is what makes `get_field` on a symbol key fall through to the general
    /// path instead of silently reading a same-named string property.
    pub fn as_str(&self) -> Option<&str> {
        match self {
            PropertyKey::String(text) => text.as_str(),
            PropertyKey::Symbol(_) => None,
        }
    }

    /// The key's bytes, which a string key always has and a symbol never does.
    pub fn as_wtf8(&self) -> Option<&crate::value::Wtf8> {
        match self {
            PropertyKey::String(text) => Some(text),
            PropertyKey::Symbol(_) => None,
        }
    }

    /// Whether this is an ordinary string key.
    pub fn is_symbol(&self) -> bool {
        matches!(self, PropertyKey::Symbol(_))
    }
}

impl fmt::Display for PropertyKey {
    /// How a key reads inside an error message: strings bare, symbols in their
    /// `Symbol(description)` form.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PropertyKey::String(text) => write!(f, "{}", text.to_string_lossy()),
            PropertyKey::Symbol(symbol) => write!(f, "{}", symbol.to_display_string()),
        }
    }
}

impl PartialEq for PropertyKey {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (PropertyKey::String(a), PropertyKey::String(b)) => a == b,
            // Symbols compare by identity, never by description.
            (PropertyKey::Symbol(a), PropertyKey::Symbol(b)) => a.ptr_eq(b),
            _ => false,
        }
    }
}

impl From<&str> for PropertyKey {
    fn from(text: &str) -> PropertyKey {
        PropertyKey::String(crate::value::Wtf8::new(text))
    }
}

impl From<String> for PropertyKey {
    fn from(text: String) -> PropertyKey {
        PropertyKey::String(crate::value::Wtf8::new(text))
    }
}

impl From<crate::value::Wtf8> for PropertyKey {
    fn from(text: crate::value::Wtf8) -> PropertyKey {
        PropertyKey::String(text)
    }
}

impl Trace for PropertyKey {
    fn trace(&self, tracer: &mut Tracer) {
        if let PropertyKey::Symbol(symbol) = self {
            tracer.visit(symbol);
        }
    }
}

/// An object's mutable state: its prototype, property table and internal slots.
pub struct ObjectData {
    /// The prototype, or `None` for `Object.prototype` and for a null-prototype
    /// object created with `Object.create(null)`.
    pub proto: Option<Gc<JsObject>>,
    /// Properties in definition order, string and symbol keys interleaved.
    pub props: Vec<(PropertyKey, Property)>,
    /// What kind of object this is.
    pub kind: ObjectKind,
    /// Whether new properties may be added. `Object.preventExtensions`, `seal` and
    /// `freeze` clear it, and nothing clears it back.
    pub extensible: bool,
    /// Whether array elements may be replaced.
    ///
    /// Elements are not in the property table, so their attributes need somewhere to
    /// live; `Object.freeze` clears this and `Object.isFrozen` reads it. A *single*
    /// non-writable element is recorded in the property table instead, which is what
    /// `Object.defineProperty(a, "3", {configurable: false})` does.
    pub elements_writable: bool,
    /// Whether any element of this array has a descriptor of its own — an accessor, or a
    /// `writable`/`enumerable`/`configurable` that is not the default.
    ///
    /// An array with none has nothing in its property table that a direct slot write could
    /// shadow, which is what makes the dense store path safe. Set once and never cleared:
    /// `delete` leaves a hole but not the attributes, and a flag that went back to `false`
    /// would have to prove the table is clean again.
    pub element_descriptors: bool,
    /// Whether an array's `length` may be changed.
    ///
    /// `Object.defineProperty(a, "length", {writable: false})` makes it read-only without
    /// touching the elements, so it cannot share `elements_writable`: the two mean
    /// different things and `Object.freeze` sets both.
    pub length_writable: bool,
    /// The object a method was defined on, which is what `super` resolves against.
    ///
    /// Kept here rather than as a property because it is not observable: the spec calls
    /// it `[[HomeObject]]` and no script can read it, so putting it in the property
    /// table would leak it to `Object.getOwnPropertyNames` and `JSON.stringify`.
    pub home_object: Option<Gc<JsObject>>,
    /// The brand symbol this object *owns*, when it is the home object of a class.
    ///
    /// The reference keeps two separate things under private names it never exposes. The
    /// first is `[[PrivateBrand]]`: one symbol per class, stored on the home object — the
    /// prototype for the instance brand, the constructor for the static one. Creating it the
    /// first time and reusing it after is what ties a prototype, its instances and the class
    /// itself to one identity.
    ///
    /// Kept off the property table for the same reason as `home_object`: a property would be
    /// reachable from `Object.getOwnPropertyNames`.
    pub private_brand: Option<Gc<crate::value::JsSymbol>>,
    /// The brand symbols this object *carries*, as an instance of one or more classes.
    ///
    /// A list rather than one symbol because brands accumulate down an inheritance chain:
    /// `class D extends C` with a private method in each means a `D` instance carries both,
    /// since `C`'s field initialiser runs on it and so does `D`'s. Membership is what
    /// `check_brand` — and so `#m()` and `#a` — tests before it runs.
    pub brands: Vec<Gc<crate::value::JsSymbol>>,
    /// Whether this function is a class constructor, which may not be called without
    /// `new`.
    pub class_constructor: bool,
    /// Whether this function has a `[[Construct]]`, i.e. may appear as the target of
    /// `new` or `Reflect.construct`.
    ///
    /// Not derivable from being callable, and that is the whole point: an ordinary
    /// method, an arrow function, a generator, an async function and most built-in
    /// methods are all callable and none of them may be constructed (§10.2.1,
    /// §15.3.1). Deriving it from `is_callable` made `new (Array.prototype.map)` succeed,
    /// which test262 checks for every built-in (`not-a-constructor.js`, 515 files).
    pub constructible: bool,
}

impl Trace for ObjectData {
    fn trace(&self, tracer: &mut Tracer) {
        if let Some(proto) = &self.proto {
            tracer.visit(proto);
        }
        if let Some(home) = &self.home_object {
            tracer.visit(home);
        }
        if let Some(brand) = &self.private_brand {
            tracer.visit(brand);
        }
        for brand in &self.brands {
            tracer.visit(brand);
        }
        for (key, property) in &self.props {
            key.trace(tracer);
            property.trace(tracer);
        }
        self.kind.trace(tracer);
    }
}

/// A JavaScript object.
///
/// The interior mutability is what makes `const o = {}; o.x = 1` work: the handle
/// is immutable, the object it points at is not.
pub struct JsObject {
    data: RefCell<ObjectData>,
}

impl JsObject {
    fn new(kind: ObjectKind, proto: Option<Gc<JsObject>>) -> JsObject {
        JsObject {
            data: RefCell::new(ObjectData {
                proto,
                props: Vec::new(),
                kind,
                extensible: true,
                elements_writable: true,
                element_descriptors: false,
                length_writable: true,
                home_object: None,
                private_brand: None,
                brands: Vec::new(),
                class_constructor: false,
                constructible: false,
            }),
        }
    }

    /// An ordinary object with the given prototype.
    pub fn ordinary(heap: &js_gc::Heap, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
        Gc::new(heap, JsObject::new(ObjectKind::Ordinary, proto))
    }

    /// An array with the given prototype and initial capacity.
    /// An empty array with room for `capacity` elements.
    ///
    /// The length starts at 0: `capacity` is a `Vec` hint, not a length. Callers that want
    /// holes use [`Self::array_set_length`], which no longer allocates them.
    pub fn array(heap: &js_gc::Heap, proto: Option<Gc<JsObject>>, capacity: usize) -> Gc<JsObject> {
        Gc::new(
            heap,
            JsObject::new(
                ObjectKind::Array {
                    elements: Vec::with_capacity(capacity),
                    length: 0,
                },
                proto,
            ),
        )
    }

    /// An instance of a host class (`JS_NewObjectProtoClass`).
    ///
    /// The opaque starts null; the host fills it with [`JsObject::set_host_opaque`], which
    /// is the order `point.c` uses (create the object, then hand it the payload) and the
    /// order that makes a finalizer's "the opaqued may still be null" note true.
    pub fn host_object(
        heap: &js_gc::Heap,
        proto: Option<Gc<JsObject>>,
        class_id: ClassId,
        class: Rc<ClassDef>,
    ) -> Gc<JsObject> {
        Gc::new(
            heap,
            JsObject::new(
                ObjectKind::HostClass(Box::new(HostData {
                    class_id,
                    class,
                    opaque: Opaque::NULL,
                })),
                proto,
            ),
        )
    }

    /// Whether this object is an instance of a host class.
    pub fn is_host_class(&self) -> bool {
        matches!(self.data.borrow().kind, ObjectKind::HostClass(_))
    }

    /// This object's class id, when it is a host class instance.
    pub fn host_class_id(&self) -> Option<ClassId> {
        match &self.data.borrow().kind {
            ObjectKind::HostClass(data) => Some(data.class_id),
            _ => None,
        }
    }

    /// The class definition this object belongs to, when it is a host class instance.
    pub fn host_class(&self) -> Option<Rc<ClassDef>> {
        match &self.data.borrow().kind {
            ObjectKind::HostClass(data) => Some(data.class.clone()),
            _ => None,
        }
    }

    /// The exotic methods of this object's class, if it has a class and the class has any.
    ///
    /// Cloned out of the object's data rather than borrowed, because every caller is about
    /// to call back into the interpreter and the trap may reach this very object.
    pub fn exotic(&self) -> Option<Rc<dyn Exotic>> {
        match &self.data.borrow().kind {
            ObjectKind::HostClass(data) => data.class.exotic.clone(),
            _ => None,
        }
    }

    /// The opaque payload, when this object is a host instance.
    ///
    /// `None` distinguishes "not a host instance" from an instance whose `JS_SetOpaque`
    /// never ran, which is the distinction `JS_GetOpaque` versus `JS_GetOpaque2` exists
    /// for: the first answers `NULL` for both, the second raises a `TypeError` for the
    /// class mismatch.
    pub fn host_opaque(&self) -> Option<Opaque> {
        match &self.data.borrow().kind {
            ObjectKind::HostClass(data) => Some(data.opaque),
            _ => None,
        }
    }

    /// Store the opaque payload (`JS_SetOpaque`). Answers whether the object is a host
    /// instance at all.
    pub fn set_host_opaque(&self, opaque: Opaque) -> bool {
        match &mut self.data.borrow_mut().kind {
            ObjectKind::HostClass(data) => {
                data.opaque = opaque;
                true
            }
            _ => false,
        }
    }

    /// A callable object.
    pub fn function(
        heap: &js_gc::Heap,
        proto: Option<Gc<JsObject>>,
        callable: Callable,
    ) -> Gc<JsObject> {
        Gc::new(heap, JsObject::new(ObjectKind::Function(callable), proto))
    }

    /// Run `f` with the object's data borrowed.
    pub fn with<R>(&self, f: impl FnOnce(&ObjectData) -> R) -> R {
        f(&self.data.borrow())
    }

    /// Run `f` with the object's data mutably borrowed.
    pub fn with_mut<R>(&self, f: impl FnOnce(&mut ObjectData) -> R) -> R {
        f(&mut self.data.borrow_mut())
    }

    /// Whether this object can be called.
    ///
    /// Covers every [`Callable`] variant, `Bound` included: `typeof bound ===
    /// "function"` and `bound()` works, so from a script's point of view a bound
    /// function is a function.
    pub fn is_callable(&self) -> bool {
        match &self.data.borrow().kind {
            ObjectKind::Function(_) => true,
            // A proxy is callable exactly when its target was when the proxy was built.
            // Not "when its target still is": revoking drops the target but leaves
            // `[[Call]]` in place, so a revoked proxy over a function stays a function.
            // This is what makes `typeof proxyOfFunction === "function"` survive revoke.
            ObjectKind::Proxy(state) => state.borrow().callable,
            _ => false,
        }
    }

    /// Whether this object has a `[[Construct]]`, i.e. may be the target of `new` or
    /// `Reflect.construct`.
    pub fn is_constructor(&self) -> bool {
        let data = self.data.borrow();
        match &data.kind {
            // The flag, not "is a function": a plain method is a function and is not a
            // constructor. Set at creation by whoever knows what was built.
            ObjectKind::Function(_) => data.constructible,
            // Recorded at creation for the same reason as callability: revoking drops the
            // target without taking `[[Construct]]` away.
            ObjectKind::Proxy(state) => state.borrow().constructible,
            _ => false,
        }
    }

    /// Give this function a `[[Construct]]`.
    ///
    /// Only for callables that are constructors by definition: ordinary functions, class
    /// constructors, and the built-in constructors. Everything else — methods, arrows,
    /// generators, async functions — keeps the default `false`.
    pub fn set_constructible(&self, yes: bool) {
        self.data.borrow_mut().constructible = yes;
    }

    /// This object's proxy slots, when it is one (revoked or not).
    pub fn proxy_state(&self) -> Option<ProxyRef> {
        match &self.data.borrow().kind {
            ObjectKind::Proxy(state) => Some(state.clone()),
            _ => None,
        }
    }

    /// A proxy over `target` reading its traps from `handler`.
    ///
    /// The prototype stays empty on purpose: `[[GetPrototypeOf]]` on a proxy forwards to
    /// the target through the `getPrototypeOf` trap, so copying the target's prototype
    /// here would be a second, disagreeing source of truth.
    pub fn proxy(heap: &js_gc::Heap, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
        // Read callability from the target *now*: it is the one moment the answer is
        // available, and it outlives revocation.
        let callable = target.is_callable();
        let constructible = target.is_constructor();
        Gc::new(
            heap,
            JsObject::new(
                ObjectKind::Proxy(std::rc::Rc::new(std::cell::RefCell::new(ProxyState {
                    callable,
                    constructible,
                    target: Some(target),
                    handler: Some(handler),
                }))),
                None,
            ),
        )
    }

    /// The prototype.
    pub fn proto(&self) -> Option<Gc<JsObject>> {
        self.data.borrow().proto.clone()
    }

    /// Replace the prototype.
    pub fn set_proto(&self, proto: Option<Gc<JsObject>>) {
        self.data.borrow_mut().proto = proto;
    }

    /// The object a method was defined on, for `super` to resolve against.
    pub fn home_object(&self) -> Option<Gc<JsObject>> {
        self.data.borrow().home_object.clone()
    }

    /// Record the object a method was defined on.
    ///
    /// A method has no `[[Construct]]` (§10.2.1): `new (o.m)` is a `TypeError` even
    /// though `o.m` is a function. Acquiring a home object is exactly the moment a
    /// function becomes a method, so the flag is cleared here rather than left to every
    /// method-defining call site to remember.
    pub fn set_home_object(&self, home: Option<Gc<JsObject>>) {
        let mut data = self.data.borrow_mut();
        data.home_object = home.clone();
        if home.is_some() {
            data.constructible = false;
        }
    }

    /// The brand symbol this object owns as a class home object, if it is one.
    pub fn private_brand(&self) -> Option<Gc<crate::value::JsSymbol>> {
        self.data.borrow().private_brand.clone()
    }

    /// Record `symbol` as the brand this object owns.
    pub fn set_private_brand(&self, symbol: Gc<crate::value::JsSymbol>) {
        self.data.borrow_mut().private_brand = Some(symbol);
    }

    /// Whether this object carries `symbol` among its brands.
    ///
    /// This is the question `check_brand` asks of the receiver, and the one `add_brand`
    /// asks before adding — a second `add_brand` with the same symbol is the reference's
    /// "private method is already present".
    pub fn carries_brand(&self, symbol: &Gc<crate::value::JsSymbol>) -> bool {
        self.data
            .borrow()
            .brands
            .iter()
            .any(|own| Gc::ptr_eq(own, symbol))
    }

    /// Give this object the brand `symbol`.
    pub fn add_brand(&self, symbol: Gc<crate::value::JsSymbol>) {
        self.data.borrow_mut().brands.push(symbol);
    }

    /// Whether this is a class constructor.
    pub fn is_class_constructor(&self) -> bool {
        self.data.borrow().class_constructor
    }

    /// Mark this function as a class constructor.
    pub fn set_class_constructor(&self, yes: bool) {
        self.data.borrow_mut().class_constructor = yes;
    }

    /// The elements of an array object, if this is one.
    pub fn array_elements(&self) -> Option<Vec<Value>> {
        match &self.data.borrow().kind {
            ObjectKind::Array { elements, .. } => Some(elements.clone()),
            _ => None,
        }
    }

    /// Every own key with its descriptor, array indices included.
    ///
    /// [`JsObject::own_property_keys`] answers the same question without the
    /// descriptors; a proxy invariant needs both at once, because it has to check the
    /// *value* of a key it is told about and the presence of a key it is not.
    pub fn property_entries(&self) -> Vec<(PropertyKey, Property)> {
        let data = self.data.borrow();
        let mut out: Vec<(PropertyKey, Property)> = data.props.to_vec();
        // An array's elements live in their own vector rather than the property table, so
        // they have to be synthesized — with the attributes an ordinary element has.
        if let ObjectKind::Array { elements, .. } = &data.kind {
            for (index, element) in elements.iter().enumerate() {
                if matches!(element, Value::Hole) {
                    continue;
                }
                let key = PropertyKey::from(index.to_string());
                if !out.iter().any(|(existing, _)| *existing == key) {
                    out.push((key, Property::data(element.clone())));
                }
            }
        }
        // `length` is own on an array without being in the property table either. It is
        // writable, non-enumerable and — the part proxy invariants care about —
        // non-configurable, so leaving it out let a handler hide or redefine it.
        if matches!(data.kind, ObjectKind::Array { .. })
            && let Some(length) = self.array_length()
        {
            let key = PropertyKey::from("length");
            if !out.iter().any(|(existing, _)| *existing == key) {
                out.push((
                    key,
                    Property {
                        value: Some(length_value(length)),
                        writable: self.length_writable(),
                        enumerable: false,
                        configurable: false,
                        getter: None,
                        setter: None,
                    },
                ));
            }
        }
        out
    }

    /// Whether this object has array elements at all.
    pub fn is_array(&self) -> bool {
        match &self.data.borrow().kind {
            ObjectKind::Array { .. } => true,
            // `Array.isArray` is specified to see *through* a proxy: it forwards
            // `[[Get]]`/prototype checks to the target, and the answer for a proxy of an
            // array is yes.
            ObjectKind::Proxy(state) => state
                .borrow()
                .target
                .as_ref()
                .is_some_and(|target| target.is_array()),
            _ => false,
        }
    }

    /// `length` for an array, reading it out of the element vector.
    /// The compiled pattern, when this object is a `RegExp`.
    pub fn regexp(&self) -> Option<crate::builtins::regexp::RegExpData> {
        match &self.data.borrow().kind {
            ObjectKind::RegExp(data) => Some(data.clone()),
            _ => None,
        }
    }

    /// The held resources, when this object is a `DisposableStack`.
    pub fn disposable_stack(&self) -> Option<crate::builtins::disposable::StackState> {
        match &self.data.borrow().kind {
            ObjectKind::DisposableStack(state) => Some(state.clone()),
            _ => None,
        }
    }

    /// Make this object a `DisposableStack` holding `state`.
    pub fn set_disposable_stack(&self, state: crate::builtins::disposable::StackState) {
        self.data.borrow_mut().kind = ObjectKind::DisposableStack(state);
    }

    /// Make this object a `RegExp` carrying `data`.
    pub fn set_regexp(&self, data: crate::builtins::regexp::RegExpData) {
        self.data.borrow_mut().kind = ObjectKind::RegExp(data);
    }

    /// Whether this object is a `RegExp`.
    pub fn is_regexp(&self) -> bool {
        matches!(self.data.borrow().kind, ObjectKind::RegExp(_))
    }

    /// An array's element count, when this object is an array.
    pub fn array_length(&self) -> Option<usize> {
        match &self.data.borrow().kind {
            ObjectKind::Array { length, .. } => Some(*length),
            _ => None,
        }
    }

    /// How many elements are actually allocated, which is at most the length.
    ///
    /// Distinct from [`Self::array_length`] on purpose: `new Array(5)` has a length of 5
    /// and nothing allocated, and the difference is what tells a store that fills a hole
    /// (it has to grow the vector) from one that overwrites an existing element.
    pub fn array_allocated(&self) -> usize {
        match &self.data.borrow().kind {
            ObjectKind::Array { elements, .. } => elements.len(),
            _ => 0,
        }
    }

    /// Read one array element.
    pub fn array_get(&self, index: usize) -> Option<Value> {
        match &self.data.borrow().kind {
            ObjectKind::Array { elements, .. } => elements.get(index).cloned(),
            _ => None,
        }
    }

    /// Append to an array and return the new length.
    pub fn array_push(&self, heap: &js_gc::Heap, value: Value) -> usize {
        let mut data = self.data.borrow_mut();
        match &mut data.kind {
            ObjectKind::Array { elements, length } => {
                let before = elements.capacity();
                elements.push(value);
                *length = elements.len();
                charge_capacity::<Value>(heap, before, elements.capacity());
                *length
            }
            _ => 0,
        }
    }

    /// Store into an array, and return whether the write happened.
    ///
    /// The gap an out-of-range store leaves behind is filled with [`Value::Hole`], not
    /// `undefined`: `a = [1]; a[3] = 4` has holes at 1 and 2, which `forEach` skips
    /// and the debug printer reports. A store *of* `undefined` is a real element.
    pub fn array_set(&self, heap: &js_gc::Heap, index: usize, value: Value) -> bool {
        let mut data = self.data.borrow_mut();
        match &mut data.kind {
            ObjectKind::Array { elements, length } => {
                let before = elements.capacity();
                // Growing has to fill the gap, and filling it means the vector really does
                // hold `index + 1` slots — a store at `2^32-2` is 68 GB whatever the length
                // field says, which is why the reference's allocation fails there. Refuse
                // instead of aborting the process, and let the caller take the sparse path
                // (an ordinary property plus a longer `length`).
                //
                // The bound is checked for *both* branches. It used to be checked only when
                // the index was past `length`, on the reasoning that an index inside the
                // length is at most `length` — true, and useless once `length` is 2^32-1:
                // `a.length` can be set to 4 billion without allocating anything, so the
                // very next store inside it asked for a 68 GB vector. That took eight
                // seconds and tens of gigabytes to discover.
                if index + 1 > ARRAY_ELEMENT_LIMIT {
                    return false;
                }
                if index >= *length {
                    elements.resize(index + 1, Value::Hole);
                    *length = elements.len();
                } else if index >= elements.len() {
                    // Inside the logical length but past the dense prefix: a hole that is
                    // being filled, so the vector has to catch up first.
                    elements.resize(index + 1, Value::Hole);
                }
                elements[index] = value;
                charge_capacity::<Value>(heap, before, elements.capacity());
                true
            }
            _ => false,
        }
    }

    /// Store an element, honouring its attributes, reporting whether it happened.
    ///
    /// Array methods that write back (`sort`, `reverse`, `splice`, …) use this rather
    /// than [`Self::array_set`]: the spec has them go through `[[Set]]`, so a frozen
    /// element makes them throw instead of being quietly overwritten.
    pub fn array_store(&self, heap: &js_gc::Heap, index: usize, value: Value) -> bool {
        // The ordinary array — nothing in it has ever been given an attribute of its own —
        // has no table entry that a slot write could shadow, so the vector is the answer.
        if !self.has_element_descriptors() {
            return self.elements_writable() && self.array_set(heap, index, value);
        }
        // Otherwise this index may be an accessor (which is not a slot at all) or
        // read-only. `false` sends the caller down the slow path, which is the only one
        // that can call a setter or raise the strict-mode `TypeError`.
        if let Some(property) = self.element_attributes(index as u32)
            && (property.is_accessor() || !property.writable)
        {
            return false;
        }
        self.elements_writable() && self.array_set(heap, index, value)
    }

    /// Store `value` as a plain element without creating holes, used by `push`.
    pub fn array_push_hole(&self, heap: &js_gc::Heap) -> bool {
        let mut data = self.data.borrow_mut();
        match &mut data.kind {
            ObjectKind::Array { elements, length } => {
                let before = elements.capacity();
                elements.push(Value::Hole);
                *length = elements.len();
                charge_capacity::<Value>(heap, before, elements.capacity());
                true
            }
            _ => false,
        }
    }

    /// Set the length of an array, truncating or extending with holes.
    ///
    /// `a.length = 5` on a two-element array leaves three holes, so the fill value is
    /// [`Value::Hole`] rather than `undefined`.
    /// Growing only records the new length: the extra slots are holes, and a hole needs
    /// no storage. That is what makes `a = []; a.length = 4294967295` an O(1) operation
    /// instead of a 62 GB allocation.
    pub fn array_set_length(&self, heap: &js_gc::Heap, new_length: usize) -> bool {
        let mut data = self.data.borrow_mut();
        let ObjectData { kind, props, .. } = &mut *data;
        match kind {
            ObjectKind::Array { elements, length } => {
                let before = elements.capacity();
                if new_length < *length {
                    // Shrinking really does drop the trailing elements.
                    elements.truncate(new_length);
                    // …and the sparse ones, which live in the property table: §10.4.2.4
                    // deletes *every* index at or above the new length, not only the dense
                    // prefix. An index past the dense limit is an ordinary property (see
                    // [`Self::array_set`]), so without this `x[4294967294] = 1; x.length = 2`
                    // left the value readable — `S15.4.5.2_A3_T4` is that case.
                    drop_sparse_indices(props, new_length);
                }
                *length = new_length;
                charge_capacity::<Value>(heap, before, elements.capacity());
                true
            }
            _ => false,
        }
    }

    /// Truncate an array to `length` elements without extending it.
    ///
    /// This is what `arr.length = n` does for `n` smaller than the current length;
    /// it is separate from [`Self::array_set_length`] because growing an array by
    /// assignment produces holes, which are indistinguishable from `undefined`
    /// here.
    pub fn array_truncate(&self, heap: &js_gc::Heap, new_length: usize) -> bool {
        let mut data = self.data.borrow_mut();
        let ObjectData { kind, props, .. } = &mut *data;
        match kind {
            ObjectKind::Array { elements, length } => {
                let before = elements.capacity();
                if new_length < elements.len() {
                    elements.truncate(new_length);
                }
                if new_length < *length {
                    *length = new_length;
                    drop_sparse_indices(props, new_length);
                }
                charge_capacity::<Value>(heap, before, elements.capacity());
                true
            }
            _ => false,
        }
    }

    /// The own data property `key`, if there is one.
    pub fn own_property_key(&self, key: &PropertyKey) -> Option<Property> {
        let data = self.data.borrow();
        data.props
            .iter()
            .find(|(existing, _)| existing == key)
            .map(|(_, property)| property.clone())
    }

    /// The address of this object, for an inline cache's hash.
    ///
    /// Only ever hashed, never dereferenced — and a hash collision is caught by the
    /// re-validation, never trusted. Compare a cached handle instead when identity matters.
    pub fn address(&self) -> usize {
        self as *const JsObject as usize
    }

    /// The data property at `index`, if the table still has `key` there as a plain value.
    ///
    /// This is the read half of an inline cache: the caller remembers *where* a property was
    /// found on a particular object, and this re-checks the two things that could have
    /// changed — the entry moving (the table is a `Vec`, so a delete shifts it) and the
    /// property becoming an accessor. Re-checking is what makes the cache safe without
    /// shape/hidden-class machinery: there is no pointer arithmetic on a remembered index,
    /// only a bounds-checked lookup followed by an equality test.
    /// The value at `index` if the table still has the shape the entry recorded.
    ///
    /// One borrow for what [`Self::props_len`] followed by [`Self::cached_data_property`]
    /// does with two, and it answers from a single lookup instead of two. That pair is the
    /// whole body of a monomorphic cache hit, so the extra `RefCell` borrow was per
    /// property read in every loop there is.
    pub fn cached_property_at(
        &self,
        index: usize,
        key: &PropertyKey,
        expected_len: usize,
    ) -> Option<Value> {
        let data = self.data.borrow();
        if data.props.len() != expected_len {
            return None;
        }
        let (existing, property) = data.props.get(index)?;
        if existing != key || property.is_accessor() {
            return None;
        }
        property.value.clone()
    }

    /// The data property at `index`, if the table still has `key` there as a plain value.
    ///
    /// The two-check form, for callers that have not already validated the table length.
    /// A cache hit on level 0 should use [`Self::cached_property_at`], which folds the
    /// length check into the same borrow.
    pub fn cached_data_property(&self, index: usize, key: &PropertyKey) -> Option<Value> {
        let data = self.data.borrow();
        let (existing, property) = data.props.get(index)?;
        if existing != key || property.is_accessor() {
            return None;
        }
        property.value.clone()
    }

    /// The own data property at `index`, if the key there is still `name`.
    ///
    /// The global-variable cache's validation. It takes a `&str` rather than a
    /// `PropertyKey` on purpose: building a key allocates, and a cache that allocates on
    /// every hit is not a cache. The index and the name together are enough — the caller
    /// has already compared the name to the one it recorded.
    /// The own data property at `index`, if the key there is still `name`.
    ///
    /// The global-variable cache's validation. The caller passes the name it is looking
    /// for and this compares it against *the table's* entry — catching both the property
    /// being replaced by an accessor and the entry moving when a delete shifted the `Vec`.
    ///
    /// It takes a `&str` rather than a `PropertyKey` on purpose: building a key allocates,
    /// and a cache that allocates on every hit is not a cache.
    pub fn data_property_at(&self, index: usize, name: &str) -> Option<Value> {
        let data = self.data.borrow();
        let (existing, property) = data.props.get(index)?;
        if existing.as_str() != Some(name) || property.is_accessor() {
            return None;
        }
        property.value.clone()
    }

    /// The number of own properties, for an inline cache's invalidation guard.
    ///
    /// A prototype-hit cache records this for every link of the chain it walked: adding or
    /// deleting *any* property moves it, which is what makes a stale entry a miss rather
    /// than a wrong answer.
    pub fn props_len(&self) -> usize {
        self.data.borrow().props.len()
    }

    /// The property table's allocated slot count.
    ///
    /// The memory report wants capacity rather than length: the difference is memory the
    /// object is holding and nobody can see from `Object.keys`.
    pub fn props_capacity(&self) -> usize {
        self.data.borrow().props.capacity()
    }

    /// Run `f` on this object's kind.
    ///
    /// A closure rather than `&ObjectKind`, for the same reason
    /// [`JsString::wtf8`](crate::value::JsString::wtf8) hands out a reference tied to
    /// `&self`: the kind lives behind a `RefCell`, so a borrow cannot outlive this call.
    /// Everything that needs to *inspect* rather than mutate goes through here.
    pub fn with_kind<R>(&self, f: impl FnOnce(&ObjectKind) -> R) -> R {
        f(&self.data.borrow().kind)
    }

    /// The index of the own **data** property `name`, for filling a cache.
    ///
    /// An accessor answers `None` — it must never be cached, because running its getter
    /// is the whole point of not caching it.
    pub fn own_data_index(&self, name: &str) -> Option<usize> {
        let data = self.data.borrow();
        let index = data
            .props
            .iter()
            .position(|(existing, _)| existing.as_str() == Some(name))?;
        let (_, property) = &data.props[index];
        if property.is_accessor() || property.value.is_none() {
            return None;
        }
        Some(index)
    }

    /// Where `key` sits in this object's own property table, for caching.
    pub fn own_property_index(&self, key: &PropertyKey) -> Option<(usize, Value)> {
        let data = self.data.borrow();
        let index = data
            .props
            .iter()
            .position(|(existing, _)| existing == key)?;
        let (_, property) = &data.props[index];
        if property.is_accessor() {
            return None;
        }
        Some((index, property.value.clone()?))
    }

    /// The own data property `name`, if there is one.
    pub fn own_property(&self, name: &str) -> Option<Property> {
        self.own_property_key(&PropertyKey::from(name))
    }

    /// Whether the object has an own property `key`.
    pub fn has_own_key(&self, key: &PropertyKey) -> bool {
        let data = self.data.borrow();
        data.props.iter().any(|(existing, _)| existing == key)
    }

    /// Whether the object has an own property `name`.
    pub fn has_own(&self, name: &str) -> bool {
        self.has_own_key(&PropertyKey::from(name))
    }

    /// Define or replace an own property, keeping the original position when the
    /// key already exists.
    pub fn define_key(&self, key: &PropertyKey, property: Property) {
        let mut data = self.data.borrow_mut();
        match data.props.iter_mut().find(|(existing, _)| existing == key) {
            Some((_, slot)) => *slot = property,
            None => data.props.push((key.clone(), property)),
        }
    }

    /// Define or replace an own property under a string key.
    pub fn define(&self, name: &str, property: Property) {
        self.define_key(&PropertyKey::from(name), property);
    }

    /// Define an own data property, with the default attributes.
    ///
    /// This *creates*: on an existing property it overwrites the attributes too, so
    /// it is the wrong call for a plain assignment. Use [`Self::write_value`] for that.
    pub fn define_data(&self, name: &str, value: Value) {
        self.define(name, Property::data(value));
    }

    /// Define an own data property under `key`.
    pub fn define_data_key(&self, key: &PropertyKey, value: Value) {
        self.define_key(key, Property::data(value));
    }

    /// Store a value into an existing own data property, keeping its attributes.
    ///
    /// Returns `false` when the property is absent, is an accessor, or is not
    /// writable. An assignment has to go through this rather than
    /// [`Self::define_data`], because redefining is how a non-configurable global
    /// silently became configurable again and started answering `delete` with `true`.
    pub fn write_value(&self, name: &str, value: Value) -> bool {
        self.write_value_key(&PropertyKey::from(name), value)
    }

    /// Store a value into an existing own data property under `key`.
    pub fn write_value_key(&self, key: &PropertyKey, value: Value) -> bool {
        let mut data = self.data.borrow_mut();
        let Some((_, property)) = data.props.iter_mut().find(|(existing, _)| existing == key)
        else {
            return false;
        };
        if property.is_accessor() || !property.writable {
            return false;
        }
        property.value = Some(value);
        true
    }

    /// Delete an own property, reporting whether it was there and removable.
    pub fn delete(&self, name: &str) -> bool {
        self.delete_key(&PropertyKey::from(name))
    }

    /// Delete an own property under `key`.
    pub fn delete_key(&self, key: &PropertyKey) -> bool {
        let mut data = self.data.borrow_mut();
        match data.props.iter().position(|(existing, _)| existing == key) {
            Some(index) => {
                if data.props[index].1.configurable {
                    data.props.remove(index);
                    true
                } else {
                    false
                }
            }
            None => true,
        }
    }

    /// Whether new properties may be added.
    pub fn is_extensible(&self) -> bool {
        self.data.borrow().extensible
    }

    /// Make the object non-extensible.
    pub fn set_extensible(&self, extensible: bool) {
        self.data.borrow_mut().extensible = extensible;
    }

    /// Whether array elements may be replaced.
    pub fn elements_writable(&self) -> bool {
        self.data.borrow().elements_writable
    }

    /// Whether any element of this array has a descriptor of its own.
    ///
    /// Until something has, [`JsObject::array_store`] may write the element vector
    /// directly; after, every store has to consult the property table for that index.
    pub fn has_element_descriptors(&self) -> bool {
        self.data.borrow().element_descriptors
    }

    /// Record that an element now has a descriptor of its own.
    pub fn note_element_descriptor(&self) {
        self.data.borrow_mut().element_descriptors = true;
    }

    /// Whether an array's `length` may be changed.
    pub fn length_writable(&self) -> bool {
        self.data.borrow().length_writable
    }

    /// Record whether `length` may be changed.
    pub fn set_length_writable(&self, writable: bool) {
        self.data.borrow_mut().length_writable = writable;
    }

    /// Make array elements read-only, as `Object.freeze` does.
    pub fn set_elements_writable(&self, writable: bool) {
        self.data.borrow_mut().elements_writable = writable;
    }

    /// The attributes recorded for an array index, if `defineProperty` set any.
    pub fn element_attributes(&self, index: u32) -> Option<Property> {
        self.own_property(&index.to_string())
    }

    /// Whether `delete` at `index` would be rejected.
    ///
    /// Separate from [`JsObject::element_is_locked`]: a store needs the element to be
    /// non-writable, but a *delete* — which is what truncating an array does — only needs
    /// it to be non-configurable. `Object.defineProperty(a, "3", {configurable: false})`
    /// leaves `a[3]` writable and yet undeletable, so `a.length = 2` must fail.
    pub fn element_is_undeletable(&self, index: u32) -> bool {
        if !self.elements_writable() {
            return true;
        }
        self.element_attributes(index)
            .is_some_and(|property| !property.configurable)
    }

    /// The lowest index at or above `from` whose element cannot be deleted.
    ///
    /// Callers use this to refuse a shrinking `length` (§10.4.2.4 deletes every index at or
    /// above the new length, and a non-configurable one makes that impossible). Scanning
    /// `from..length` instead is what a *sparse* array turns into an hour-long loop: after
    /// `x[2**32 - 2] = 1`, `x.length = 2` would ask `element_is_undeletable` four billion
    /// times. Only two things can be undeletable — a frozen object (every element) and an
    /// index with a recorded descriptor (a handful) — so this looks at exactly those.
    pub fn first_undeletable_at_or_above(&self, from: usize) -> Option<usize> {
        if !self.elements_writable() {
            return Some(from);
        }
        let data = self.data.borrow();
        data.props
            .iter()
            .filter_map(|(key, property)| {
                let index = key.as_str().and_then(array_index)? as usize;
                (index >= from && !property.configurable).then_some(index)
            })
            .min()
    }

    /// The highest index in `from..below` whose element cannot be deleted.
    ///
    /// The spec's `ArraySetLength` walks *down* from the current length and stops at the
    /// first element it cannot delete, so the answer it needs is the last one.
    pub fn last_undeletable_at_or_above(&self, from: usize, below: usize) -> Option<usize> {
        if below <= from {
            return None;
        }
        if !self.elements_writable() {
            return Some(below - 1);
        }
        let data = self.data.borrow();
        data.props
            .iter()
            .filter_map(|(key, property)| {
                let index = key.as_str().and_then(array_index)? as usize;
                (index >= from && index < below && !property.configurable).then_some(index)
            })
            .max()
    }

    /// Whether a store at `index` would be rejected.
    ///
    /// An element is locked either by `Object.freeze` on the whole object or by a
    /// non-configurable, non-writable descriptor recorded for that one index.
    pub fn element_is_locked(&self, index: u32) -> bool {
        if !self.elements_writable() {
            return true;
        }
        self.element_attributes(index)
            .is_some_and(|property| !property.writable && !property.configurable)
    }

    /// The own property *names*, in definition order. Symbol keys are excluded:
    /// `Object.keys` and `for…in` cannot see them.
    pub fn own_keys(&self) -> Vec<crate::value::Wtf8> {
        self.data
            .borrow()
            .props
            .iter()
            .filter_map(|(key, _)| key.as_wtf8().cloned())
            .collect()
    }

    /// The own *enumerable* property names, in definition order.
    pub fn own_enumerable_keys(&self) -> Vec<crate::value::Wtf8> {
        self.data
            .borrow()
            .props
            .iter()
            .filter(|(_, property)| property.enumerable)
            .filter_map(|(key, _)| key.as_wtf8().cloned())
            .collect()
    }

    /// The own symbol keys, in definition order, for `Object.getOwnPropertySymbols`.
    pub fn own_symbol_keys(&self) -> Vec<Gc<JsSymbol>> {
        self.data
            .borrow()
            .props
            .iter()
            .filter_map(|(key, _)| match key {
                // Private names are invisible to enumeration; see `JsSymbol::is_private`.
                PropertyKey::Symbol(symbol) if !symbol.is_private() => Some(symbol.clone()),
                PropertyKey::Symbol(_) | PropertyKey::String(_) => None,
            })
            .collect()
    }

    /// Every own key, strings first then symbols — the order `Reflect.ownKeys` and
    /// `Object.getOwnPropertyDescriptors` report, and the order `JSON.stringify`
    /// walks before it skips the symbols.
    pub fn own_property_keys(&self) -> Vec<PropertyKey> {
        let data = self.data.borrow();
        let mut strings: Vec<PropertyKey> = Vec::new();
        let mut symbols: Vec<PropertyKey> = Vec::new();
        for (key, _) in &data.props {
            if let PropertyKey::Symbol(symbol) = key {
                // A class-private name is not an own key for any observable purpose.
                if !symbol.is_private() {
                    symbols.push(key.clone());
                }
            } else {
                strings.push(key.clone());
            }
        }
        strings.extend(symbols);
        strings
    }

    /// Own property keys in **definition order**, with symbols interleaved.
    ///
    /// [`JsObject::own_property_keys`] answers in the spec's order — integer-like keys
    /// ascending, then strings, then symbols — because that is what `Reflect.ownKeys` and
    /// `for...in` must do. A dumper has the opposite requirement: quickjs's
    /// `JS_PrintValue` walks the shape, so `{[Symbol("t")]: 1, y: 2}` prints the symbol
    /// first. That is not observable from a script except through such a dump, which is
    /// why this is a separate accessor rather than a change to `own_property_keys`.
    pub fn own_property_keys_in_definition_order(&self) -> Vec<PropertyKey> {
        self.data
            .borrow()
            .props
            .iter()
            .map(|(key, _)| key.clone())
            .collect()
    }

    /// The prototype chain, starting with the prototypes of this object.
    pub fn chain(&self) -> Vec<Gc<JsObject>> {
        let mut out = Vec::new();
        let mut proto = self.proto();
        while let Some(object) = proto {
            proto = object.proto();
            out.push(object);
        }
        out
    }
}

/// Whether two prototypes are the same one, `None` included.
///
/// A proxy's prototype invariants have to compare "no prototype" against "no
/// prototype" without unwrapping either side first.
pub(crate) fn same_proto(a: Option<&Gc<JsObject>>, b: Option<&Gc<JsObject>>) -> bool {
    match (a, b) {
        (None, None) => true,
        (Some(a), Some(b)) => a.ptr_eq(b),
        _ => false,
    }
}

/// Walk the prototype chain from `object` looking for `name`.
///
/// Returns the object that owns the property along with the property itself. The
/// owner matters for a store: an inherited accessor is invoked on the receiver,
/// while an inherited *data* property is shadowed by a new own property.
/// The own property `key` names on `object`, arrays included.
///
/// An array keeps its elements in an element vector and derives its `length`, so its
/// property table knows about neither: a hole is a slot in the vector, not a missing
/// property, and `length` is not stored at all. `Array.prototype` is itself an array, so
/// every walk down the chain needs this same care — without it `1 in [1,,3]` stayed false
/// with `Array.prototype[1]` defined, `"length" in []` was false outright, and a hole did
/// not read an inherited element.
pub fn own_property_including_array(object: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
    if let Some(property) = object.own_property_key(key) {
        return Some(property);
    }
    // A typed array's indices are its elements in the buffer, which the property table
    // does not hold either. Checked before the `is_array` return below, because a typed
    // array is not one.
    if object.typed_array_parts().is_some() {
        // A detached view exposes no indices at all: `Reflect.has(detached, "0")` is false
        // even though index 0 was in range before the buffer went away.
        let index = key.as_str().and_then(array_index)?;
        let in_range = (index as usize) < object.typed_array_length()?;
        return match object.typed_array_element(index as usize) {
            Some(value) if in_range => Some(Property::data(value)),
            _ => None,
        };
    }
    if !object.is_array() {
        return None;
    }
    let text = key.as_str()?;
    // `length` is non-enumerable and non-configurable; `writable` unless a definition
    // turned it off.
    if text == "length" {
        return Some(Property {
            value: Some(length_value(object.array_length()?)),
            writable: object.length_writable(),
            enumerable: false,
            configurable: false,
            getter: None,
            setter: None,
        });
    }
    // An element is a plain writable/enumerable/configurable data property, and a hole is
    // not one at all.
    let index = array_index(text)?;
    match object.array_get(index as usize) {
        Some(Value::Hole) | None => None,
        Some(value) => Some(Property::data(value)),
    }
}

/// Whether `object` has `key` as an *own* property, arrays included.
pub fn has_own(object: &Gc<JsObject>, key: &PropertyKey) -> bool {
    own_property_including_array(object, key).is_some()
}

/// `key` on `object` or anywhere up its prototype chain, with the owner.
///
/// Array-aware at every step: an array's elements and its derived `length` are not in the
/// property table, and `Array.prototype` is itself an array.
pub fn lookup_key(object: &Gc<JsObject>, key: &PropertyKey) -> Option<(Gc<JsObject>, Property)> {
    if let Some(property) = own_property_including_array(object, key) {
        return Some((object.clone(), property));
    }
    lookup_key_above(object, key)
}

/// [`lookup_key`] starting *above* `object`: its prototype and upwards.
///
/// Split out for the exotic `[[GetOwnProperty]]` hook, which can report a key as absent on
/// the object itself — after which the read still has to find it on the prototype.
pub fn lookup_key_above(
    object: &Gc<JsObject>,
    key: &PropertyKey,
) -> Option<(Gc<JsObject>, Property)> {
    for ancestor in object.chain() {
        if let Some(property) = own_property_including_array(&ancestor, key) {
            return Some((ancestor, property));
        }
    }
    None
}

/// [`lookup_key`] for a string key.
pub fn lookup(object: &Gc<JsObject>, name: &str) -> Option<(Gc<JsObject>, Property)> {
    lookup_key(object, &PropertyKey::from(name))
}

/// The largest array index that may be *stored*, i.e. the largest dense vector this engine
/// will grow to an index for.
///
/// The spec's `length` limit is `2^32-1`, but the elements are a dense `Vec<Value>` here,
/// so a store at index `2^32-2` is a 68 GB reservation. The reference (which keeps
/// elements in a hash map) answers instantly. Refusing past this bound keeps the process
/// alive; the conformance tests that really do store near `2^32` are recorded in
/// `docs/test262-status.md` as a limitation rather than quietly answered wrong.
pub const ARRAY_ELEMENT_LIMIT: usize = 1 << 26;

/// An array's `length` as a JavaScript number.
///
/// `Value::Int` only holds an `i32`, and an array's length may legitimately reach
/// `2^32-1`, so a plain cast is not enough: `a[2**32-2] = 1; a.length` came back as `-1`,
/// and `Object.getOwnPropertyDescriptor(a, "length").value` with it. Every
/// `LengthOfArrayLike` over such an array then ran to `-1`, and the paths without their
/// own `RangeError` check turned into `memory allocation of 68719476720 bytes failed`.
pub fn length_value(length: usize) -> Value {
    if length <= i32::MAX as usize {
        Value::Int(length as i32)
    } else {
        Value::Float(length as f64)
    }
}

/// An array *index* as a JavaScript number.
///
/// Same problem as [`length_value`] and the same fix: an index may be as large as
/// `2^32-2`, which `Value::Int` cannot hold. `a[2**32-2] = 1; a.indexOf(1)` was answering
/// `-2` because the index was truncated on the way out.
pub fn index_value(index: usize) -> Value {
    length_value(index)
}

/// The array index a property key names, if it names one.
///
/// A key is an index when it is the canonical decimal spelling of an integer below
/// `2^32 - 1` — the same rule the atom table uses to decide whether a key is a
/// tagged index. `"01"` and `"-1"` are ordinary string keys.
pub fn array_index(key: &str) -> Option<u32> {
    if key.is_empty() || key.len() > 10 {
        return None;
    }
    let bytes = key.as_bytes();
    if !bytes.iter().all(u8::is_ascii_digit) {
        return None;
    }
    if bytes[0] == b'0' && bytes.len() != 1 {
        return None;
    }
    let value: u32 = key.parse().ok()?;
    // `2^32 - 1` is reserved for the array length, so it is not an index.
    (value < u32::MAX).then_some(value)
}

impl Trace for JsObject {
    fn trace(&self, tracer: &mut Tracer) {
        self.data.borrow().trace(tracer);
    }

    /// Everything this object holds that is not its own box: element slots, the property
    /// table, `Map`/`Set` entries, an `ArrayBuffer`'s bytes.
    ///
    /// Counted by **capacity**, not length, because that is what the allocator actually
    /// holds — a 1000-element array with a 1024-slot vector costs 1024 slots, and reporting
    /// 1000 would make the limit wrong by whatever the vectors over-allocate (up to 2×).
    ///
    /// Growth in place is reported to the heap as it happens (see `JsObject::array_push`
    /// and friends) and this same number is subtracted when the object is freed, which is
    /// why the two have to agree.
    ///
    /// `try_borrow` because this can be called from inside the collector, where a mutation
    /// elsewhere in the engine may hold the borrow; a container that is being mutated at
    /// this instant is a container we cannot measure, and answering 0 for it is better than
    /// panicking mid-allocation.
    fn external_bytes(&self) -> usize {
        let Ok(data) = self.data.try_borrow() else {
            return 0;
        };
        // The property table is *not* counted. Every payload reported here is subtracted
        // when the box is freed, so a payload that nothing reports on growth would be
        // taken away twice — that abort is exactly what this comment replaced
        // (`attempt to subtract with overflow` in `Heap::deregister`). Property growth is
        // bounded by distinct keys, each of which is at least one string box that *is*
        // counted, so leaving the table out costs a constant factor rather than the limit.
        let mut total = 0;
        match &data.kind {
            ObjectKind::Array { elements, .. } => {
                total += elements.capacity() * std::mem::size_of::<Value>();
            }
            ObjectKind::Collection { entries, .. } => {
                total += entries.capacity() * std::mem::size_of::<(Value, Value)>();
            }
            ObjectKind::ArrayBuffer(storage) => {
                if let Ok(storage) = storage.try_borrow() {
                    total += storage.bytes.capacity();
                }
            }
            _ => {}
        }
        total
    }
}

/// Drop the property-table entries whose key is an array index at or above `length`.
///
/// An index past the dense limit is kept as an ordinary property, so shrinking `length` has
/// to look there as well as in the element vector — the spec deletes every index at or above
/// the new length, wherever it was stored.
fn drop_sparse_indices(props: &mut Vec<(PropertyKey, Property)>, length: usize) {
    props.retain(|(key, _)| match key.as_str().and_then(array_index) {
        Some(index) => (index as usize) < length,
        None => true,
    });
}

/// Tell the heap that a container's payload changed in place.
///
/// Reported as a **capacity** delta, the same quantity [`Trace::external_bytes`] reports, so
/// that the subtraction at free time takes back exactly what was added. Reporting length
/// instead would leave the vector's over-allocation — up to 2× — counted for ever.
fn charge_capacity<T>(heap: &js_gc::Heap, before: usize, after: usize) {
    if before == after {
        return;
    }
    let slot = std::mem::size_of::<T>() as isize;
    heap.adjust_payload((after as isize - before as isize) * slot);
}