stator_jse 0.3.5

Stator JavaScript engine core — parser, bytecode compiler, Maglev JIT, interpreter, GC
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
//! A property map that stores ECMAScript property values alongside their
//! attribute flags (`[[Writable]]`, `[[Enumerable]]`, `[[Configurable]]`).
//!
//! [`PropertyMap`] is the backing store for [`JsValue::PlainObject`] and
//! provides a HashMap-like API that transparently attaches
//! [`PropertyAttributes`] to every entry.  Newly inserted properties default
//! to `WRITABLE | ENUMERABLE | CONFIGURABLE` (the ECMAScript default for
//! ordinary user-created data properties).
//!
//! ## ECMAScript enumeration order (§10.1.11)
//!
//! Properties are stored in **ECMAScript enumeration order**: integer-indexed
//! keys (array indices `0 ..= 2^32 − 2`) occupy the front of the storage in
//! ascending numeric order, followed by non-index string keys in the order
//! they were first inserted.  All iteration methods (`keys`, `iter`,
//! `enumerable_keys`, `iter_with_attrs`) naturally produce this order.
//!
//! Internally, property values are stored in a flat `Vec<JsValue>` for
//! cache-friendly iteration and O(1) slot-based access. Small objects keep
//! name lookup in a compact linear-scan mode that searches the key vector
//! directly, while larger objects promote to a secondary `HashMap<Rc<str>,
//! usize>` for O(1) slot lookup.
//!
//! An [`INLINE_CACHE_CAP`]-entry inline cache of recently accessed property
//! names sits in front of the lookup path to avoid repeated scans or
//! hash-table probes for hot property names.

use std::array;
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::rc::Rc;

use crate::builtins::symbol::{is_symbol_property_key, property_key_to_symbol};
use crate::objects::map::PropertyAttributes;
use crate::objects::value::JsValue;

/// Internal storage key used for an object's prototype link.
pub const INTERNAL_PROTO_PROPERTY_KEY: &str = "\0stator.internal.proto";
/// User-visible `__proto__` key used for prototype chain lookup.
const USER_VISIBLE_PROTO_PROPERTY_KEY: &str = "__proto__";

thread_local! {
    /// Monotonically-increasing counter used to assign unique shape
    /// identifiers to each [`PropertyMap`] structural configuration.
    static NEXT_SHAPE_ID: Cell<u64> = const { Cell::new(1) };
    /// Epoch counter incremented on every prototype-relevant mutation.
    /// Used to cheaply detect when a cached `proto_generation` may be stale.
    static GLOBAL_PROTO_MUTATION_EPOCH: Cell<u64> = const { Cell::new(0) };
}

/// Default attributes for properties created by ordinary JS assignment:
/// writable, enumerable, and configurable.
const DEFAULT_ATTRS: PropertyAttributes = PropertyAttributes::from_bits_truncate(
    PropertyAttributes::WRITABLE.bits()
        | PropertyAttributes::ENUMERABLE.bits()
        | PropertyAttributes::CONFIGURABLE.bits(),
);

/// Attributes for built-in methods per ES spec §10.4.7: writable,
/// non-enumerable, configurable.
const BUILTIN_ATTRS: PropertyAttributes = PropertyAttributes::from_bits_truncate(
    PropertyAttributes::WRITABLE.bits() | PropertyAttributes::CONFIGURABLE.bits(),
);

/// Maximum number of entries in the inline property-name cache.
///
/// Sixteen entries provide better coverage for moderately polymorphic property
/// access patterns while keeping probes short and cache-friendly.
const INLINE_CACHE_CAP: usize = 16;

/// Small objects keep name lookup in compact linear-scan mode until they grow
/// beyond this many properties.
const SMALL_PROPERTY_LINEAR_SCAN_CAP: usize = 6;

/// Number of reusable property-storage buffers kept per thread.
const PROPERTY_STORAGE_POOL_CAP: usize = 64;

/// Avoid retaining very large backing allocations in the pool.
const MAX_POOLED_PROPERTY_CAPACITY: usize = SMALL_PROPERTY_LINEAR_SCAN_CAP * 4;

/// Maximum number of `Rc<RefCell<PropertyMap>>` wrappers kept in the
/// per-thread object pool.  Sized to accommodate hot loops that create
/// many short-lived objects (e.g. 1000-iteration benchmarks).
const OBJECT_RC_POOL_CAP: usize = 1024;

thread_local! {
    static PROPERTY_STORAGE_POOL: RefCell<Vec<PropertyStorageBuffers>> =
        RefCell::new(Vec::with_capacity(PROPERTY_STORAGE_POOL_CAP));

    /// Pool for recycling values `Vec`s from template-instantiated objects
    /// whose shared keys/attrs prevent full-buffer recycling.
    static VALUES_VEC_POOL: RefCell<Vec<Vec<JsValue>>> =
        RefCell::new(Vec::with_capacity(PROPERTY_STORAGE_POOL_CAP));

    /// Pool of `Rc<RefCell<PropertyMap>>` wrappers for reuse.
    ///
    /// Entries are returned here by [`recycle_object_rc`] when the JIT
    /// heap is cleared.  [`acquire_object_rc_from_template`] pops an
    /// entry, reinitialises its inner [`PropertyMap`] in place (reusing
    /// both the `Rc` control-block allocation and the values `Vec`), and
    /// hands it back out — eliminating all per-object heap allocations on
    /// the hot path.
    static OBJECT_RC_POOL: RefCell<Vec<Rc<RefCell<PropertyMap>>>> =
        RefCell::new(Vec::with_capacity(64));
}

#[derive(Debug)]
struct PropertyStorageBuffers {
    keys: Vec<Rc<str>>,
    values: Vec<JsValue>,
    attrs: Vec<PropertyAttributes>,
}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
enum PropertyIndex {
    #[default]
    Inline,
    Map(HashMap<Rc<str>, usize>),
}

#[derive(Debug)]
struct InlinePropertyCache {
    hashes: [Cell<u64>; INLINE_CACHE_CAP],
    slots: [Cell<u32>; INLINE_CACHE_CAP],
}

impl InlinePropertyCache {
    fn new() -> Self {
        Self {
            hashes: Default::default(),
            slots: array::from_fn(|_| Cell::new(u32::MAX)),
        }
    }
}

impl Clone for InlinePropertyCache {
    fn clone(&self) -> Self {
        Self {
            hashes: array::from_fn(|i| Cell::new(self.hashes[i].get())),
            slots: array::from_fn(|i| Cell::new(self.slots[i].get())),
        }
    }
}

#[inline]
fn next_shape_id() -> u64 {
    NEXT_SHAPE_ID.with(|next| {
        let shape_id = next.get();
        next.set(shape_id.wrapping_add(1));
        shape_id
    })
}

#[inline]
fn current_global_proto_mutation_epoch() -> u64 {
    GLOBAL_PROTO_MUTATION_EPOCH.with(Cell::get)
}

#[inline]
fn bump_global_proto_mutation_epoch() {
    GLOBAL_PROTO_MUTATION_EPOCH.with(|epoch| {
        epoch.set(epoch.get().wrapping_add(1));
    });
}

fn acquire_storage_buffers(capacity: usize) -> PropertyStorageBuffers {
    PROPERTY_STORAGE_POOL
        .try_with(|pool| {
            let mut pool = pool.borrow_mut();
            if let Some(index) = pool.iter().position(|buffers| {
                buffers.keys.capacity() >= capacity
                    && buffers.values.capacity() >= capacity
                    && buffers.attrs.capacity() >= capacity
            }) {
                let mut buffers = pool.swap_remove(index);
                buffers.keys.clear();
                buffers.values.clear();
                buffers.attrs.clear();
                buffers
            } else {
                PropertyStorageBuffers {
                    keys: Vec::with_capacity(capacity),
                    values: Vec::with_capacity(capacity),
                    attrs: Vec::with_capacity(capacity),
                }
            }
        })
        .unwrap_or_else(|_| PropertyStorageBuffers {
            keys: Vec::with_capacity(capacity),
            values: Vec::with_capacity(capacity),
            attrs: Vec::with_capacity(capacity),
        })
}

fn release_storage_buffers(mut buffers: PropertyStorageBuffers) {
    if buffers.keys.capacity() > MAX_POOLED_PROPERTY_CAPACITY
        || buffers.values.capacity() > MAX_POOLED_PROPERTY_CAPACITY
        || buffers.attrs.capacity() > MAX_POOLED_PROPERTY_CAPACITY
    {
        return;
    }

    buffers.keys.clear();
    buffers.values.clear();
    buffers.attrs.clear();

    let _ = PROPERTY_STORAGE_POOL.try_with(|pool| {
        let mut pool = pool.borrow_mut();
        if pool.len() < PROPERTY_STORAGE_POOL_CAP {
            pool.push(buffers);
        }
    });
}

/// Acquire a pre-allocated values `Vec` from the thread-local pool,
/// sized to hold at least `cap` elements initialised to `Undefined`.
fn acquire_values_vec(cap: usize) -> Vec<JsValue> {
    VALUES_VEC_POOL
        .try_with(|pool| {
            let mut pool = pool.borrow_mut();
            if let Some(idx) = pool.iter().position(|v| v.capacity() >= cap) {
                let mut v = pool.swap_remove(idx);
                v.clear();
                v.resize(cap, JsValue::Undefined);
                v
            } else {
                vec![JsValue::Undefined; cap]
            }
        })
        .unwrap_or_else(|_| vec![JsValue::Undefined; cap])
}

/// Return a values `Vec` to the thread-local pool for reuse.
fn release_values_vec(v: Vec<JsValue>) {
    if v.capacity() > MAX_POOLED_PROPERTY_CAPACITY {
        return;
    }
    let _ = VALUES_VEC_POOL.try_with(|pool| {
        let mut pool = pool.borrow_mut();
        if pool.len() < PROPERTY_STORAGE_POOL_CAP {
            pool.push(v);
        }
    });
}

/// Acquire an `Rc<RefCell<PropertyMap>>` wrapper initialised from a
/// template, reusing a pooled allocation when possible.
///
/// On pool hit the inner `PropertyMap` is reinitialised in place —
/// reusing both the `Rc` control-block and the values `Vec`, which
/// eliminates **all** per-object heap allocations on the hot path.
#[inline]
pub(crate) fn acquire_object_rc_from_template(
    template: &ObjectLiteralTemplate,
) -> Rc<RefCell<PropertyMap>> {
    OBJECT_RC_POOL
        .try_with(|pool| {
            // SAFETY: single-threaded JIT runtime — no concurrent borrows.
            let pool = unsafe { &mut *pool.as_ptr() };
            if let Some(rc) = pool.pop() {
                // SAFETY: Rc exclusively owned (just popped, strong_count == 1).
                let map = unsafe { &mut *rc.as_ptr() };
                map.reinitialize_from_template(template);
                rc
            } else {
                Rc::new(RefCell::new(template.instantiate()))
            }
        })
        .unwrap_or_else(|_| Rc::new(RefCell::new(template.instantiate())))
}

/// Acquire an `Rc<RefCell<PropertyMap>>` wrapper initialised from a
/// template with pre-filled values, reusing a pooled allocation when
/// possible.
///
/// Like [`acquire_object_rc_from_template`] but copies `values` into the
/// existing values `Vec` instead of filling with `Undefined`.
///
/// On the hot path (pool hit with same template) this bypasses all
/// `Rc` refcount operations and `RefCell` borrow checks, reducing
/// per-object overhead to just overwriting the values buffer.
#[inline]
pub(crate) fn acquire_object_rc_from_template_with_values(
    template: &ObjectLiteralTemplate,
    values: &[JsValue],
) -> Rc<RefCell<PropertyMap>> {
    OBJECT_RC_POOL
        .try_with(|pool| {
            // SAFETY: single-threaded JIT runtime — no concurrent borrows
            // possible.  Bypassing the RefCell runtime borrow check on the
            // pool avoids one atomic-like flag write per object.
            let pool = unsafe { &mut *pool.as_ptr() };
            if let Some(rc) = pool.pop() {
                // SAFETY: same single-threaded guarantee — the Rc is
                // exclusively owned (just popped, strong_count == 1) so
                // there are no outstanding borrows.
                let map = unsafe { &mut *rc.as_ptr() };
                // reinitialize_from_template_with_values handles the
                // same-template fast path internally.
                map.reinitialize_from_template_with_values(template, values);
                rc
            } else {
                Rc::new(RefCell::new(
                    template.instantiate_with_values_from_slice(values),
                ))
            }
        })
        .unwrap_or_else(|_| {
            Rc::new(RefCell::new(
                template.instantiate_with_values_from_slice(values),
            ))
        })
}

/// Returns a raw pointer to the `OBJECT_RC_POOL` thread-local so it can
/// be cached in [`RtPtrs`] and reused across multiple object-creation
/// calls without repeating a TLS lookup each time.
///
/// # Safety
///
/// The returned pointer is valid for the current thread's lifetime.
/// The caller must ensure single-threaded access (no concurrent borrows).
#[cfg(any(
    stator_baseline_jit_x86_64,
    all(target_arch = "x86_64", any(unix, windows))
))]
pub(crate) fn object_rc_pool_ptr() -> *const RefCell<Vec<Rc<RefCell<PropertyMap>>>> {
    OBJECT_RC_POOL.with(|pool| pool as *const _)
}

/// Number of `Rc<RefCell<PropertyMap>>` entries to batch-allocate when
/// the pool is empty during the IC-hit hot path.  Amortises the cost
/// of `Rc::new` across subsequent loop iterations so they hit the
/// pool instead of falling back to per-object allocation.
#[cfg(any(
    stator_baseline_jit_x86_64,
    all(target_arch = "x86_64", any(unix, windows))
))]
const POOL_BATCH_SIZE: usize = 32;

/// Like [`acquire_object_rc_from_template_with_values`] but uses a
/// pre-cached raw pointer to the `OBJECT_RC_POOL`, eliminating a TLS
/// lookup on the hot path.
///
/// # Safety
///
/// `pool_ptr` must point to a live `RefCell<Vec<…>>` on the current
/// thread (as returned by [`object_rc_pool_ptr`]).
#[cfg(any(
    stator_baseline_jit_x86_64,
    all(target_arch = "x86_64", any(unix, windows))
))]
#[inline(always)]
pub(crate) fn acquire_object_rc_from_template_with_values_cached(
    template: &ObjectLiteralTemplate,
    values: &[JsValue],
    pool_ptr: *const RefCell<Vec<Rc<RefCell<PropertyMap>>>>,
) -> Rc<RefCell<PropertyMap>> {
    if !pool_ptr.is_null() {
        // SAFETY: caller guarantees the pointer is valid and we are on
        // the owning thread.  Bypass the RefCell borrow check (single-
        // threaded JIT, no concurrent borrows).
        let pool = unsafe { &mut *(&*pool_ptr).as_ptr() };
        if let Some(rc) = pool.pop() {
            // SAFETY: Rc exclusively owned (just popped, strong_count == 1).
            let map = unsafe { &mut *rc.as_ptr() };
            if Rc::ptr_eq(&map.keys, &template.keys) && map.values.len() == values.len() {
                map.reinitialize_values_inplace(values);
            } else {
                map.reinitialize_from_template_with_values(template, values);
            }
            return rc;
        }
        // Pool miss — batch-allocate entries so that subsequent loop
        // iterations hit the pool instead of allocating individually.
        for _ in 0..POOL_BATCH_SIZE
            .saturating_sub(1)
            .min(OBJECT_RC_POOL_CAP - pool.len())
        {
            pool.push(Rc::new(RefCell::new(template.instantiate())));
        }
    }
    Rc::new(RefCell::new(
        template.instantiate_with_values_from_slice(values),
    ))
}

/// Like [`acquire_object_rc_from_template`] but uses a pre-cached raw
/// pointer to the `OBJECT_RC_POOL`, eliminating a TLS lookup.
///
/// # Safety
///
/// Same as [`acquire_object_rc_from_template_with_values_cached`].
#[cfg(any(
    stator_baseline_jit_x86_64,
    all(target_arch = "x86_64", any(unix, windows))
))]
#[inline(always)]
pub(crate) fn acquire_object_rc_from_template_cached(
    template: &ObjectLiteralTemplate,
    pool_ptr: *const RefCell<Vec<Rc<RefCell<PropertyMap>>>>,
) -> Rc<RefCell<PropertyMap>> {
    if !pool_ptr.is_null() {
        // SAFETY: same single-threaded guarantee as the _with_values
        // variant.
        let pool = unsafe { &mut *(&*pool_ptr).as_ptr() };
        if let Some(rc) = pool.pop() {
            // SAFETY: Rc exclusively owned (just popped, strong_count == 1).
            let map = unsafe { &mut *rc.as_ptr() };
            map.reinitialize_from_template(template);
            return rc;
        }
        // Pool miss — batch-allocate entries for subsequent iterations.
        for _ in 0..POOL_BATCH_SIZE
            .saturating_sub(1)
            .min(OBJECT_RC_POOL_CAP - pool.len())
        {
            pool.push(Rc::new(RefCell::new(template.instantiate())));
        }
    }
    Rc::new(RefCell::new(template.instantiate()))
}

/// Return an `Rc<RefCell<PropertyMap>>` to the thread-local object pool
/// using a pre-cached raw pointer, bypassing both TLS lookup and RefCell
/// borrow checking.
///
/// # Safety
///
/// `pool_ptr` must point to a live `RefCell<Vec<…>>` on the current
/// thread (as returned by [`object_rc_pool_ptr`]).  The caller must
/// ensure no concurrent borrows exist (single-threaded JIT guarantee).
#[cfg(any(
    stator_baseline_jit_x86_64,
    all(target_arch = "x86_64", any(unix, windows))
))]
#[inline(always)]
#[allow(dead_code)]
pub(crate) fn recycle_object_rc_cached(
    rc: Rc<RefCell<PropertyMap>>,
    pool_ptr: *const RefCell<Vec<Rc<RefCell<PropertyMap>>>>,
) {
    if Rc::strong_count(&rc) != 1 {
        return;
    }
    if pool_ptr.is_null() {
        return;
    }
    // SAFETY: same single-threaded guarantee as acquire_object_rc_from_template_cached.
    let pool = unsafe { &mut *(&*pool_ptr).as_ptr() };
    if pool.len() < OBJECT_RC_POOL_CAP {
        pool.push(rc);
    }
}

/// Return an `Rc<RefCell<PropertyMap>>` to the thread-local object pool.
///
/// Called when the JIT heap is cleared so that future object-creation
/// calls can reuse the `Rc` control-block and `PropertyMap` allocations.
/// The `Rc` is pooled only if it is the **sole owner**
/// (`strong_count == 1`) and the pool has capacity.
///
/// On supported platforms this uses a raw-pointer fast path that avoids
/// the `RefCell` borrow check; elsewhere it falls back to
/// `borrow_mut()`.
pub(crate) fn recycle_object_rc(rc: Rc<RefCell<PropertyMap>>) {
    if Rc::strong_count(&rc) != 1 {
        return;
    }

    // Fast path: bypass RefCell overhead via raw pointer (x86_64 unix).
    #[cfg(any(
        stator_baseline_jit_x86_64,
        all(target_arch = "x86_64", any(unix, windows))
    ))]
    {
        let pool_ptr = object_rc_pool_ptr();
        if !pool_ptr.is_null() {
            // SAFETY: pointer obtained from current thread's TLS; single-
            // threaded execution guarantees no concurrent borrows.
            let pool = unsafe { &mut *(&*pool_ptr).as_ptr() };
            if pool.len() < OBJECT_RC_POOL_CAP {
                pool.push(rc);
            }
            return;
        }
    }

    let _ = OBJECT_RC_POOL.try_with(|pool| {
        let mut pool = pool.borrow_mut();
        if pool.len() < OBJECT_RC_POOL_CAP {
            pool.push(rc);
        }
    });
}

/// Drain all thread-local property-map pools so that cached
/// `Rc<RefCell<PropertyMap>>`, `Vec<JsValue>`, and storage buffers are
/// dropped while the thread-local variables they reference are still alive.
///
/// Called during full thread-local teardown (e.g. before benchmark process
/// exit) to prevent cascading drops during TLS destruction from accessing
/// already-destroyed thread-locals.
pub fn clear_property_map_pools() {
    OBJECT_RC_POOL.with(|pool| pool.borrow_mut().clear());
    VALUES_VEC_POOL.with(|pool| pool.borrow_mut().clear());
    PROPERTY_STORAGE_POOL.with(|pool| pool.borrow_mut().clear());
}

/// Returns `Some(n)` if `key` is a valid ECMAScript array index — a canonical
/// decimal string representing an integer in `0 ..= 2^32 − 2`.
///
/// Per ECMA-262 §6.1.7, an integer index is a String value that is a canonical
/// numeric string (no leading zeros except `"0"` itself) whose numeric value
/// *i* satisfies `0 ≤ i < 2^32 − 1`.
#[inline]
fn parse_integer_index(key: &str) -> Option<u32> {
    if key.is_empty() || (key.len() > 1 && key.as_bytes()[0] == b'0') {
        return None;
    }
    let n: u32 = key.parse().ok()?;
    // Array indices are 0 ..= 2^32 − 2 (u32::MAX is *not* an index).
    if n < u32::MAX { Some(n) } else { None }
}

/// Cheap 64-bit FNV-1a hash for inline-cache probing.
///
/// This is intentionally *not* `SipHash`: it trades collision resistance for
/// raw speed on the short property names typical of JavaScript.
#[inline]
fn name_hash(s: &str) -> u64 {
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
    for b in s.bytes() {
        h ^= b as u64;
        h = h.wrapping_mul(0x0100_0000_01b3);
    }
    h
}

/// Deterministically hashes a property layout so structurally identical maps
/// share the same layout identifier.
#[inline]
fn layout_hash(keys: &[Rc<str>], attrs: &[PropertyAttributes]) -> u64 {
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
    for (key, attr) in keys.iter().zip(attrs.iter()) {
        for b in key.bytes() {
            h ^= b as u64;
            h = h.wrapping_mul(0x0100_0000_01b3);
        }
        h ^= 0xff;
        h = h.wrapping_mul(0x0100_0000_01b3);
        for b in attr.bits().to_le_bytes() {
            h ^= b as u64;
            h = h.wrapping_mul(0x0100_0000_01b3);
        }
    }
    h ^= keys.len() as u64;
    h.wrapping_mul(0x0100_0000_01b3)
}

/// A map of named properties with ECMAScript attribute flags.
///
/// Property values are stored in a flat `Vec` in ECMAScript enumeration
/// order (integer indices ascending, then string keys in insertion order)
/// for cache-friendly, spec-compliant iteration. Small objects use compact
/// linear scans over the key vector for lookups; larger objects promote to a
/// `HashMap` of name-to-slot offsets.
///
/// An [`INLINE_CACHE_CAP`]-entry inline cache of recently accessed property
/// name hashes sits in front of the lookup path to avoid repeated scans or
/// hash-table probes on hot property names. The cache uses
/// [`Cell`]-based interior mutability so that read-only (`&self`) lookups
/// can still populate the cache.
#[derive(Debug)]
pub struct PropertyMap {
    /// Property names in ECMAScript enumeration order.
    ///
    /// Wrapped in [`Rc`] so that template-instantiated maps can share the
    /// key vector with the [`ObjectLiteralTemplate`] (and with each other)
    /// without cloning.  Copy-on-write via [`Rc::make_mut`] ensures that
    /// any structural mutation transparently unshares the data.
    keys: Rc<Vec<Rc<str>>>,
    /// Property values, one per key.
    values: Vec<JsValue>,
    /// Property attributes, one per key.
    ///
    /// Shared via [`Rc`] with the same copy-on-write semantics as `keys`.
    attrs: Rc<Vec<PropertyAttributes>>,
    /// Number of integer-indexed keys stored at the front of `keys`.
    integer_key_count: usize,
    /// Name → slot-index mapping, kept inline for small objects and promoted
    /// to a hash map once the object grows beyond
    /// [`SMALL_PROPERTY_LINEAR_SCAN_CAP`] properties.
    index: PropertyIndex,
    /// Optional inline cache of recently accessed property names.
    ///
    /// Small objects stay cache-free because their linear scans are already
    /// cheap and the cache state would dominate the object footprint.
    inline_cache: Option<Box<InlinePropertyCache>>,
    /// Shape identifier — a monotonically-increasing stamp that changes on
    /// every structural mutation (property add/remove or attribute change).
    shape_id: u64,
    /// Deterministic layout identifier shared by maps with the same property
    /// names, insertion order, and attributes.
    layout_id: u64,
    /// Cached prototype-chain generation for this map.
    proto_generation: Cell<u32>,
    /// Local mutation generation that contributes to `proto_generation`.
    proto_epoch: Cell<u32>,
    /// Global prototype-mutation epoch used to validate `proto_generation`.
    proto_global_epoch: Cell<u64>,
    /// Whether new properties may be added to this object (§10.1 `[[Extensible]]`).
    pub extensible: bool,
    /// Whether this map contains any accessor properties (`__get_*__` or `__set_*__` keys).
    /// Once set to `true` it is never cleared, so it is a conservative over-approximation.
    pub has_accessors: bool,
    /// Offset of the next property expected to be filled when this map was
    /// created via [`clone_shape`](Self::clone_shape),
    /// [`clone_template`](Self::clone_template), or
    /// [`from_boilerplate`](Self::from_boilerplate).
    ///
    /// When a `PropertyMap` is created from a cached object-literal
    /// template, all keys and attributes are pre-populated but values are
    /// [`JsValue::Undefined`].  This counter tracks the sequential
    /// fill position so that [`try_template_fill`](Self::try_template_fill)
    /// can write values in O(1) without hash lookups.
    ///
    /// A value of `usize::MAX` means this map is **not** in template-fill
    /// mode (the default for non-template-created maps).
    template_next_slot: usize,
    /// Original requested capacity for this map, preserved so shape clones
    /// can pre-size their secondary index consistently.
    capacity_hint: usize,
}

/// Cached object-literal layout used to instantiate repeated literals without
/// re-observing the first instance's values.
///
/// On [`capture`](Self::capture) the template pre-builds a
/// [`PropertyIndex`] so that [`instantiate`](Self::instantiate) can
/// construct a [`PropertyMap`] directly — bypassing the thread-local
/// buffer pool and the `build_index_from_keys` rebuild that the general
/// `from_shape_parts` path performs on every call.
#[derive(Debug, Clone)]
pub(crate) struct ObjectLiteralTemplate {
    keys: Rc<Vec<Rc<str>>>,
    attrs: Rc<Vec<PropertyAttributes>>,
    integer_key_count: usize,
    layout_id: u64,
    extensible: bool,
    has_accessors: bool,
    capacity_hint: usize,
    /// Pre-built property index cloned into each instantiated map.
    cached_index: PropertyIndex,
    /// Shared shape identifier for all instances from this template.
    ///
    /// Template instances have identical structure (same keys at same
    /// offsets), so they can share a single shape ID — matching the
    /// semantics of [`Clone`] for [`PropertyMap`] which also preserves
    /// `shape_id`.  This eliminates one TLS access per instantiation.
    cached_shape_id: u64,
}

#[derive(Debug, Clone, Copy)]
struct ShapeMetadata {
    integer_key_count: usize,
    layout_id: u64,
    extensible: bool,
    has_accessors: bool,
    capacity_hint: usize,
}

impl ObjectLiteralTemplate {
    pub(crate) fn capture(map: &PropertyMap) -> Option<Self> {
        (!map.is_empty()).then(|| {
            let keys = Rc::clone(&map.keys);
            let capacity_hint = map.capacity_hint;
            let cached_index =
                PropertyMap::build_index_from_keys(&keys, capacity_hint.max(keys.len()));
            Self {
                keys,
                attrs: Rc::clone(&map.attrs),
                integer_key_count: map.integer_key_count,
                layout_id: map.layout_id,
                extensible: map.extensible,
                has_accessors: map.has_accessors,
                capacity_hint,
                cached_index,
                cached_shape_id: map.shape_id,
            }
        })
    }

    /// Stamp out a fresh [`PropertyMap`] with the template's shape.
    ///
    /// This is the hot path for repeated object-literal creation.  It
    /// constructs the map directly from the cached fields, avoiding:
    ///
    /// * the thread-local buffer-pool lookup (`acquire_storage_buffers`),
    /// * the per-instantiation `build_index_from_keys` rebuild,
    /// * the intermediate `from_shape_parts` indirection.
    ///
    /// Values are initialised to [`JsValue::Undefined`]; the caller is
    /// expected to fill them via
    /// [`try_template_fill`](PropertyMap::try_template_fill).
    pub(crate) fn instantiate(&self) -> PropertyMap {
        let cap = self.keys.len();
        let capacity_hint = self.capacity_hint.max(cap);
        PropertyMap {
            keys: Rc::clone(&self.keys),
            values: acquire_values_vec(cap),
            attrs: Rc::clone(&self.attrs),
            integer_key_count: self.integer_key_count,
            index: if cap <= SMALL_PROPERTY_LINEAR_SCAN_CAP {
                PropertyIndex::Inline
            } else {
                self.cached_index.clone()
            },
            inline_cache: None,
            shape_id: self.cached_shape_id,
            layout_id: self.layout_id,
            proto_generation: Cell::new(0),
            proto_epoch: Cell::new(0),
            proto_global_epoch: Cell::new(0),
            extensible: self.extensible,
            has_accessors: self.has_accessors,
            template_next_slot: 0,
            capacity_hint,
        }
    }

    /// Stamp out a fresh [`PropertyMap`] with the template's shape and
    /// the given values pre-filled.
    ///
    /// This is faster than [`instantiate`](Self::instantiate) followed
    /// by [`try_template_fill`](PropertyMap::try_template_fill) because
    /// it:
    ///
    /// * skips the thread-local values-vec pool probe,
    /// * avoids the `Undefined` initialisation + overwrite cycle,
    /// * eliminates per-property key comparisons in `try_template_fill`.
    ///
    /// `values` must contain exactly `self.keys.len()` elements in
    /// template order.
    pub(crate) fn instantiate_with_values(&self, mut values: Vec<JsValue>) -> PropertyMap {
        let cap = self.keys.len();
        let filled = values.len().min(cap);
        // Pad values if the fused stub supplied fewer than the template expects.
        if values.len() < cap {
            values.resize(cap, JsValue::Undefined);
        }
        let capacity_hint = self.capacity_hint.max(cap);
        PropertyMap {
            keys: Rc::clone(&self.keys),
            values,
            attrs: Rc::clone(&self.attrs),
            integer_key_count: self.integer_key_count,
            index: if cap <= SMALL_PROPERTY_LINEAR_SCAN_CAP {
                PropertyIndex::Inline
            } else {
                self.cached_index.clone()
            },
            inline_cache: None,
            shape_id: self.cached_shape_id,
            layout_id: self.layout_id,
            proto_generation: Cell::new(0),
            proto_epoch: Cell::new(0),
            proto_global_epoch: Cell::new(0),
            extensible: self.extensible,
            has_accessors: self.has_accessors,
            template_next_slot: filled,
            capacity_hint,
        }
    }

    /// Like [`instantiate_with_values`] but takes a slice, avoiding the
    /// caller having to allocate a `Vec` via `to_vec()`.
    #[inline(always)]
    pub(crate) fn instantiate_with_values_from_slice(&self, values: &[JsValue]) -> PropertyMap {
        let cap = self.keys.len();
        let filled = values.len().min(cap);
        let mut vals = Vec::with_capacity(cap);
        vals.extend_from_slice(&values[..filled]);
        vals.resize(cap, JsValue::Undefined);
        let capacity_hint = self.capacity_hint.max(cap);
        PropertyMap {
            keys: Rc::clone(&self.keys),
            values: vals,
            attrs: Rc::clone(&self.attrs),
            integer_key_count: self.integer_key_count,
            index: if cap <= SMALL_PROPERTY_LINEAR_SCAN_CAP {
                PropertyIndex::Inline
            } else {
                self.cached_index.clone()
            },
            inline_cache: None,
            shape_id: self.cached_shape_id,
            layout_id: self.layout_id,
            proto_generation: Cell::new(0),
            proto_epoch: Cell::new(0),
            proto_global_epoch: Cell::new(0),
            extensible: self.extensible,
            has_accessors: self.has_accessors,
            template_next_slot: filled,
            capacity_hint,
        }
    }

    /// Pre-warm the thread-local object pool with entries instantiated
    /// from this template.  Called at template-promotion time so that
    /// subsequent IC-hit iterations find pool entries immediately,
    /// avoiding per-object `Rc::new` allocation.
    pub(crate) fn pre_warm_pool(&self) {
        const PRE_WARM_COUNT: usize = 32;
        let _ = OBJECT_RC_POOL.try_with(|pool| {
            // SAFETY: single-threaded JIT runtime.
            let pool = unsafe { &mut *pool.as_ptr() };
            let budget = PRE_WARM_COUNT.min(OBJECT_RC_POOL_CAP.saturating_sub(pool.len()));
            pool.reserve(budget);
            for _ in 0..budget {
                pool.push(Rc::new(RefCell::new(self.instantiate())));
            }
        });
    }
}

impl PartialEq for PropertyMap {
    fn eq(&self, other: &Self) -> bool {
        self.keys == other.keys
            && self.values == other.values
            && self.attrs == other.attrs
            && self.integer_key_count == other.integer_key_count
            && self.index == other.index
            && self.extensible == other.extensible
            && self.has_accessors == other.has_accessors
    }
}

impl Clone for PropertyMap {
    fn clone(&self) -> Self {
        Self {
            keys: Rc::clone(&self.keys),
            values: self.values.clone(),
            attrs: Rc::clone(&self.attrs),
            integer_key_count: self.integer_key_count,
            index: self.index.clone(),
            inline_cache: self
                .inline_cache
                .as_ref()
                .map(|cache| Box::new((**cache).clone())),
            shape_id: self.shape_id,
            layout_id: self.layout_id,
            proto_generation: Cell::new(self.proto_generation.get()),
            proto_epoch: Cell::new(self.proto_epoch.get()),
            proto_global_epoch: Cell::new(self.proto_global_epoch.get()),
            extensible: self.extensible,
            has_accessors: self.has_accessors,
            template_next_slot: self.template_next_slot,
            capacity_hint: self.capacity_hint,
        }
    }
}

impl PropertyMap {
    /// Creates an empty property map.
    pub fn new() -> Self {
        Self::with_capacity(0)
    }

    fn from_buffers(capacity: usize, buffers: PropertyStorageBuffers) -> Self {
        let index = Self::build_index_from_keys(&[], capacity);

        Self {
            keys: Rc::new(buffers.keys),
            values: buffers.values,
            attrs: Rc::new(buffers.attrs),
            integer_key_count: 0,
            index,
            inline_cache: None,
            shape_id: next_shape_id(),
            layout_id: layout_hash(&[], &[]),
            proto_generation: Cell::new(0),
            proto_epoch: Cell::new(0),
            proto_global_epoch: Cell::new(0),
            extensible: true,
            has_accessors: false,
            template_next_slot: usize::MAX,
            capacity_hint: capacity,
        }
    }

    /// Creates a property map pre-allocated for `capacity` entries.
    pub fn with_capacity(capacity: usize) -> Self {
        Self::from_buffers(capacity, acquire_storage_buffers(capacity))
    }

    /// Reinitialize this map from a template, reusing existing allocations.
    ///
    /// This is the pool-friendly counterpart of
    /// [`ObjectLiteralTemplate::instantiate`]: instead of building a fresh
    /// `PropertyMap`, it overwrites `self` in place — reusing the values
    /// `Vec` allocation and avoiding the values-pool lookup.
    ///
    /// When the recycled map was created from the **same** template
    /// (detected via [`Rc::ptr_eq`] on keys), the method takes an
    /// ultra-fast path that skips all `Rc` refcount operations and
    /// redundant scalar writes — reducing per-object overhead to ~4
    /// field writes on the hot loop.
    #[inline(always)]
    fn reinitialize_from_template(&mut self, template: &ObjectLiteralTemplate) {
        let cap = template.keys.len();

        // Ultra-fast path: same template — the structural shape (keys,
        // attrs, index, shape_id, layout_id, extensible, has_accessors)
        // is already correct.  Skip Rc refcount ops and most writes.
        if Rc::ptr_eq(&self.keys, &template.keys) && self.values.len() == cap {
            // For flat old values (Smi, HeapNumber, Bool, etc.) we can
            // skip the clear entirely: template fill will overwrite all
            // slots before anyone reads the object.  Non-flat values
            // (String, PlainObject, etc.) must be dropped to avoid leaks.
            if !Self::all_flat(&self.values[..cap]) {
                for v in self.values.iter_mut() {
                    *v = JsValue::Undefined;
                }
            }
            self.template_next_slot = 0;
            self.proto_generation.set(0);
            self.proto_epoch.set(0);
            self.proto_global_epoch.set(0);
            return;
        }

        let capacity_hint = template.capacity_hint.max(cap);

        self.values.clear();
        self.values.resize(cap, JsValue::Undefined);
        self.keys = Rc::clone(&template.keys);
        self.attrs = Rc::clone(&template.attrs);
        self.integer_key_count = template.integer_key_count;
        self.index = if cap <= SMALL_PROPERTY_LINEAR_SCAN_CAP {
            PropertyIndex::Inline
        } else {
            template.cached_index.clone()
        };
        self.inline_cache = None;
        self.shape_id = template.cached_shape_id;
        self.layout_id = template.layout_id;
        self.proto_generation.set(0);
        self.proto_epoch.set(0);
        self.proto_global_epoch.set(0);
        self.extensible = template.extensible;
        self.has_accessors = template.has_accessors;
        self.template_next_slot = 0;
        self.capacity_hint = capacity_hint;
    }

    /// Reinitialize this map from a template with pre-filled values.
    ///
    /// Like [`reinitialize_from_template`](Self::reinitialize_from_template)
    /// but copies `values` into the existing values `Vec` instead of
    /// filling with `Undefined`.
    ///
    /// When the recycled map was created from the same template, this
    /// delegates to [`reinitialize_values_inplace`] which skips all `Rc`
    /// refcount operations and uses `memcpy` for flat value types.
    #[inline(always)]
    fn reinitialize_from_template_with_values(
        &mut self,
        template: &ObjectLiteralTemplate,
        values: &[JsValue],
    ) {
        let cap = template.keys.len();
        // The fused CreateObjectLiteralWithProperties stub may supply
        // fewer values than the template has keys.
        let filled = values.len().min(cap);

        // Ultra-fast path: same template — overwrite values in place,
        // skipping Rc refcount ops.
        if Rc::ptr_eq(&self.keys, &template.keys) && self.values.len() == cap {
            self.values[..filled].clone_from_slice(&values[..filled]);
            for slot in &mut self.values[filled..cap] {
                *slot = JsValue::Undefined;
            }
            self.template_next_slot = filled;
            return;
        }

        let capacity_hint = template.capacity_hint.max(cap);

        // When the vec already has the right length, overwrite in place.
        if self.values.len() == cap {
            self.values[..filled].clone_from_slice(&values[..filled]);
            for slot in &mut self.values[filled..cap] {
                *slot = JsValue::Undefined;
            }
        } else {
            self.values.clear();
            self.values.extend_from_slice(&values[..filled]);
            self.values.resize(cap, JsValue::Undefined);
        }
        self.keys = Rc::clone(&template.keys);
        self.attrs = Rc::clone(&template.attrs);
        self.integer_key_count = template.integer_key_count;
        self.index = if cap <= SMALL_PROPERTY_LINEAR_SCAN_CAP {
            PropertyIndex::Inline
        } else {
            template.cached_index.clone()
        };
        self.inline_cache = None;
        self.shape_id = template.cached_shape_id;
        self.layout_id = template.layout_id;
        self.proto_generation.set(0);
        self.proto_epoch.set(0);
        self.proto_global_epoch.set(0);
        self.extensible = template.extensible;
        self.has_accessors = template.has_accessors;
        self.template_next_slot = filled;
        self.capacity_hint = capacity_hint;
    }

    /// Try to reinitialize this map in-place with new values from the
    /// same template, avoiding all pool operations.
    ///
    /// Returns `true` if the map was successfully reused (same template
    /// hit); `false` if the caller should fall back to the pool-based
    /// path.
    ///
    /// This is the ultimate fast path for tight object-creation loops:
    /// when the target register already holds a `PlainObject` with
    /// `strong_count == 1` from the same template, the caller can
    /// reinitialize it in-place — skipping both pool pop and pool push.
    #[inline(always)]
    pub(crate) fn try_reuse_with_values(
        &mut self,
        template: &ObjectLiteralTemplate,
        values: &[JsValue],
    ) -> bool {
        if Rc::ptr_eq(&self.keys, &template.keys) && self.values.len() == values.len() {
            self.reinitialize_values_inplace(values);
            true
        } else {
            false
        }
    }

    /// Ultra-fast reinitialize for recycled objects from the **same**
    /// template.
    ///
    /// Pre-condition: `self.keys` already points to the template's shared
    /// key vector (verified by the caller via [`Rc::ptr_eq`]) and
    /// `self.values.len() == values.len()`.
    ///
    /// Because the structural shape (keys, attrs, index, shape_id, etc.)
    /// is identical, this method only overwrites the values buffer and
    /// resets the prototype-chain caches.  This avoids:
    ///
    /// * two `Rc` refcount increments + decrements (keys, attrs),
    /// * the `Vec::clear` + `Vec::extend_from_slice` overhead,
    /// * ~10 redundant scalar field writes.
    #[inline(always)]
    fn reinitialize_values_inplace(&mut self, values: &[JsValue]) {
        let count = values.len();
        debug_assert_eq!(self.values.len(), count);

        // Fast path: when all old and new values are "flat" (no heap
        // resources — Smi, HeapNumber, Boolean, Undefined, Null, etc.),
        // skip the per-element Clone/Drop dispatch and memcpy instead.
        // This is the common case in hot object-creation loops like
        //   `{ x: i, y: i+1, z: i*2 }` where every value is a Smi.
        if count <= 3 && Self::all_flat(&self.values[..count]) && Self::all_flat(values) {
            // SAFETY: flat variants contain no heap resources (no Rc, Box,
            // Vec, etc.).  Overwriting them raw is equivalent to a series
            // of trivial drops + trivial clones.
            unsafe {
                std::ptr::copy_nonoverlapping(values.as_ptr(), self.values.as_mut_ptr(), count);
            }
        } else {
            // General path: element-wise clone_from_slice handles all
            // variant types including Rc-bearing ones.
            self.values[..count].clone_from_slice(&values[..count]);
        }
        self.template_next_slot = count;
        // Proto caches must be reset for a fresh object identity.
        self.proto_generation.set(0);
        self.proto_epoch.set(0);
        self.proto_global_epoch.set(0);
        // inline_cache is already None for short-lived template objects.
    }

    /// Returns `true` when every value in `slice` is a "flat" variant
    /// that contains no heap resources and needs no `Drop`.
    #[inline(always)]
    fn all_flat(slice: &[JsValue]) -> bool {
        slice.iter().all(|v| {
            matches!(
                v,
                JsValue::Undefined
                    | JsValue::Null
                    | JsValue::TheHole
                    | JsValue::Boolean(_)
                    | JsValue::Smi(_)
                    | JsValue::HeapNumber(_)
                    | JsValue::Symbol(_)
                    | JsValue::Object(_)
            )
        })
    }

    /// Creates a property map pre-populated with the given boilerplate
    /// keys and attribute flags.  All values are initialised to
    /// [`JsValue::Undefined`] and are expected to be overwritten by the
    /// constructor body. The returned map starts in template-fill mode.
    pub fn from_boilerplate(
        keys: &[Rc<str>],
        attrs: &[crate::objects::map::PropertyAttributes],
    ) -> Self {
        debug_assert_eq!(keys.len(), attrs.len());
        Self::from_shape_parts(
            keys,
            attrs,
            ShapeMetadata {
                integer_key_count: keys
                    .iter()
                    .filter(|key| parse_integer_index(key).is_some())
                    .count(),
                layout_id: layout_hash(keys, attrs),
                extensible: true,
                has_accessors: keys
                    .iter()
                    .any(|key| key.starts_with("__get_") || key.starts_with("__set_")),
                capacity_hint: keys.len(),
            },
            0,
        )
    }
    /// Returns a snapshot of the property keys and their attribute flags,
    /// suitable for caching as a constructor boilerplate.
    pub fn boilerplate_snapshot(
        &self,
    ) -> (Vec<Rc<str>>, Vec<crate::objects::map::PropertyAttributes>) {
        ((*self.keys).clone(), (*self.attrs).clone())
    }

    /// Clones only the property-map shape for object/constructor templates.
    ///
    /// The returned map has the same key names, insertion order, and
    /// attribute flags as `self`, but every value slot is reset to
    /// [`JsValue::Undefined`] and a fresh shape identifier is assigned.
    /// The map is placed in *template-fill mode* so that subsequent calls
    /// to [`try_template_fill`](Self::try_template_fill) can populate
    /// values in O(1) without hash lookups.
    pub fn clone_shape(&self) -> Self {
        Self::from_shape_parts(
            &self.keys,
            &self.attrs,
            ShapeMetadata {
                integer_key_count: self.integer_key_count,
                layout_id: self.layout_id,
                extensible: self.extensible,
                has_accessors: self.has_accessors,
                capacity_hint: self.capacity_hint,
            },
            0,
        )
    }

    /// Backwards-compatible alias for shape-only template cloning.
    #[inline]
    pub fn clone_template(&self) -> Self {
        self.clone_shape()
    }

    /// Attempts to write `value` into the next expected template slot.
    ///
    /// When a `PropertyMap` is in template-fill mode (created via
    /// [`clone_shape`](Self::clone_shape),
    /// [`clone_template`](Self::clone_template), or
    /// [`from_boilerplate`](Self::from_boilerplate)), this method checks
    /// whether `key` matches the property name at the next expected
    /// sequential position.  If so, the value is written directly by
    /// offset in O(1) — no hash lookup, no shape mutation, no prototype
    /// generation bump.
    ///
    /// Returns `Ok(offset)` if the fast path succeeded and `value` was
    /// consumed.  Returns `Err(value)` if the key did not match; the
    /// unconsumed value is returned to the caller for fallback via
    /// [`insert`](Self::insert).  On mismatch the template-fill mode is
    /// permanently disabled for this map.
    #[inline]
    pub fn try_template_fill(&mut self, key: &str, value: JsValue) -> Result<usize, JsValue> {
        let slot = self.template_next_slot;
        if slot < self.keys.len() && slot < self.values.len() && self.keys[slot].as_ref() == key {
            self.values[slot] = value;
            self.template_next_slot = slot + 1;
            Ok(slot)
        } else {
            self.template_next_slot = usize::MAX;
            Err(value)
        }
    }

    #[inline]
    fn build_index_from_keys(keys: &[Rc<str>], capacity_hint: usize) -> PropertyIndex {
        let capacity = capacity_hint.max(keys.len());
        if capacity > SMALL_PROPERTY_LINEAR_SCAN_CAP {
            let mut map = HashMap::with_capacity(capacity);
            for (slot, key) in keys.iter().enumerate() {
                map.insert(key.clone(), slot);
            }
            PropertyIndex::Map(map)
        } else {
            PropertyIndex::Inline
        }
    }

    fn from_shape_parts(
        keys: &[Rc<str>],
        attrs: &[PropertyAttributes],
        metadata: ShapeMetadata,
        template_next_slot: usize,
    ) -> Self {
        let cap = keys.len();
        let mut buffers = acquire_storage_buffers(cap);
        buffers.keys.extend_from_slice(keys);
        buffers.values.resize(cap, JsValue::Undefined);
        buffers.attrs.extend_from_slice(attrs);

        let capacity_hint = metadata.capacity_hint.max(cap);
        let index = Self::build_index_from_keys(&buffers.keys, capacity_hint);

        Self {
            keys: Rc::new(buffers.keys),
            values: buffers.values,
            attrs: Rc::new(buffers.attrs),
            integer_key_count: metadata.integer_key_count,
            index,
            inline_cache: (cap > SMALL_PROPERTY_LINEAR_SCAN_CAP)
                .then(|| Box::new(InlinePropertyCache::new())),
            shape_id: next_shape_id(),
            layout_id: metadata.layout_id,
            proto_generation: Cell::new(0),
            proto_epoch: Cell::new(0),
            proto_global_epoch: Cell::new(0),
            extensible: metadata.extensible,
            has_accessors: metadata.has_accessors,
            template_next_slot,
            capacity_hint,
        }
    }

    // ── Inline cache helpers ──────────────────────────────────────────────

    /// Probes the inline cache for `key`, returning its slot index on hit.
    #[inline]
    fn cache_probe(&self, key: &str) -> Option<usize> {
        let cache = self.inline_cache.as_ref()?;
        let h = name_hash(key);
        let idx = (h as usize) & (INLINE_CACHE_CAP - 1);
        if cache.hashes[idx].get() != h {
            return None;
        }
        let slot = cache.slots[idx].get() as usize;
        (slot < self.keys.len() && self.keys[slot].as_ref() == key).then_some(slot)
    }

    /// Records a `(key, slot)` pair in the inline cache.
    #[inline]
    fn cache_record(&self, key: &str, slot: usize) {
        let Some(cache) = self.inline_cache.as_ref() else {
            return;
        };
        let h = name_hash(key);
        let idx = (h as usize) & (INLINE_CACHE_CAP - 1);
        cache.hashes[idx].set(h);
        cache.slots[idx].set(slot as u32);
    }

    /// Invalidates all inline cache entries.
    #[inline]
    fn cache_invalidate(&self) {
        let Some(cache) = self.inline_cache.as_ref() else {
            return;
        };
        for entry in &cache.hashes {
            entry.set(0);
        }
        for slot in &cache.slots {
            slot.set(u32::MAX);
        }
    }

    /// Assigns a fresh shape identifier, signalling that the structural layout
    /// (set of property names or their attribute flags) has changed.
    #[inline]
    fn bump_shape_id(&mut self) {
        self.shape_id = next_shape_id();
        self.layout_id = layout_hash(&self.keys, &self.attrs);
    }

    /// Bumps the local prototype mutation epoch, invalidating any cached
    /// `proto_generation` values that depend on this map's state.
    #[inline]
    fn touch_proto_generation(&self) {
        self.proto_epoch.set(self.proto_epoch.get().wrapping_add(1));
        bump_global_proto_mutation_epoch();
        self.proto_global_epoch.set(u64::MAX);
    }

    // ── Shape / offset API ───────────────────────────────────────────────

    /// Returns the current shape identifier.
    ///
    /// The value changes on every structural mutation (property add, remove,
    /// or attribute change) but is stable across value-only updates.
    #[inline]
    pub fn shape_id(&self) -> u64 {
        self.shape_id
    }

    /// Returns the deterministic property-layout identifier shared by maps
    /// with the same keys, key order, and attributes.
    #[inline]
    pub fn layout_id(&self) -> u64 {
        self.layout_id
    }

    /// Returns the cached generation for this map's prototype chain.
    ///
    /// The generation is a composite of the local mutation epoch and the
    /// inherited generation from the prototype.  The value is cached and
    /// recomputed only when the global prototype-mutation epoch changes.
    #[inline]
    pub fn proto_generation(&self) -> u32 {
        let global_epoch = current_global_proto_mutation_epoch();
        if self.proto_global_epoch.get() == global_epoch {
            return self.proto_generation.get();
        }

        let inherited_generation = self
            .get(INTERNAL_PROTO_PROPERTY_KEY)
            .or_else(|| self.get(USER_VISIBLE_PROTO_PROPERTY_KEY))
            .and_then(|value| match value {
                JsValue::PlainObject(proto) => Some(proto.borrow().proto_generation()),
                _ => None,
            })
            .unwrap_or(0);
        let generation = self.proto_epoch.get().wrapping_add(inherited_generation);
        self.proto_generation.set(generation);
        self.proto_global_epoch.set(global_epoch);
        generation
    }

    /// Like [`proto_generation`] but accepts a pre-read global epoch so that
    /// callers that already obtained the epoch (e.g. after a failed
    /// `probe_epoch`) do not redundantly read the thread-local a second time.
    #[inline]
    pub fn proto_generation_with_epoch(&self, global_epoch: u64) -> u32 {
        if self.proto_global_epoch.get() == global_epoch {
            return self.proto_generation.get();
        }

        let inherited_generation = self
            .get(INTERNAL_PROTO_PROPERTY_KEY)
            .or_else(|| self.get(USER_VISIBLE_PROTO_PROPERTY_KEY))
            .and_then(|value| match value {
                JsValue::PlainObject(proto) => Some(proto.borrow().proto_generation()),
                _ => None,
            })
            .unwrap_or(0);
        let generation = self.proto_epoch.get().wrapping_add(inherited_generation);
        self.proto_generation.set(generation);
        self.proto_global_epoch.set(global_epoch);
        generation
    }

    /// Returns the global epoch used to invalidate prototype-dependent caches.
    #[inline]
    pub fn global_proto_mutation_epoch() -> u64 {
        current_global_proto_mutation_epoch()
    }

    /// Returns the slot index (offset) for `key`, or `None` if absent.
    ///
    /// The offset is valid as long as `shape_id()` does not change.
    #[inline]
    pub fn offset_of(&self, key: &str) -> Option<usize> {
        self.lookup_slot(key)
    }

    #[inline]
    fn lookup_slot(&self, key: &str) -> Option<usize> {
        match &self.index {
            PropertyIndex::Inline => self
                .keys
                .iter()
                .position(|candidate| candidate.as_ref() == key),
            PropertyIndex::Map(index) => index.get(key).copied(),
        }
    }

    #[inline]
    fn lookup_slot_cached(&self, key: &str) -> Option<usize> {
        if let Some(slot) = self.cache_probe(key) {
            return Some(slot);
        }
        let slot = self.lookup_slot(key)?;
        self.cache_record(key, slot);
        Some(slot)
    }

    fn promote_index(&mut self) {
        if matches!(self.index, PropertyIndex::Map(_)) {
            return;
        }
        let mut index = HashMap::with_capacity(self.capacity_hint.max(self.keys.len()));
        for (slot, key) in self.keys.iter().enumerate() {
            index.insert(key.clone(), slot);
        }
        self.index = PropertyIndex::Map(index);
        if self.inline_cache.is_none() {
            self.inline_cache = Some(Box::new(InlinePropertyCache::new()));
        }
    }

    fn refresh_index_mode(&mut self) {
        if self.keys.len() <= SMALL_PROPERTY_LINEAR_SCAN_CAP {
            self.index = PropertyIndex::Inline;
            self.inline_cache = None;
        } else {
            self.promote_index();
        }
    }

    /// Returns the value at a raw slot offset.
    ///
    /// # Safety contract (logical)
    ///
    /// The caller must ensure that `offset` was obtained from
    /// [`offset_of`](Self::offset_of) while `shape_id()` has not changed
    /// since.
    #[inline]
    pub fn get_by_offset(&self, offset: usize) -> Option<&JsValue> {
        self.values.get(offset)
    }

    /// Returns the value at a raw slot offset **without** bounds checking.
    ///
    /// # Safety
    ///
    /// The caller must guarantee that `offset < self.len()`.  This is
    /// satisfied when `offset` was obtained from [`offset_of`](Self::offset_of)
    /// and `shape_id()` has not changed since (the shape stamp is bumped on
    /// every structural mutation that could invalidate an offset).
    #[inline]
    pub unsafe fn get_by_offset_unchecked(&self, offset: usize) -> &JsValue {
        debug_assert!(offset < self.values.len());
        // SAFETY: caller guarantees `offset < self.values.len()`.
        unsafe { self.values.get_unchecked(offset) }
    }

    /// Returns the raw values slice.
    ///
    /// Used by the JIT layout probe to discover the byte offset of the
    /// `values` Vec data pointer within `PropertyMap`.
    #[inline]
    pub fn values_as_slice(&self) -> &[JsValue] {
        &self.values
    }

    /// Returns `true` when `offset` still names `key` in the current layout.
    #[inline]
    pub fn matches_key_at_offset(&self, offset: usize, key: &str) -> bool {
        self.keys
            .get(offset)
            .is_some_and(|candidate| candidate.as_ref() == key)
    }

    /// Overwrites the value at a raw slot offset, returning `true` on
    /// success.
    ///
    /// The same validity constraint as [`get_by_offset`](Self::get_by_offset)
    /// applies.
    #[inline]
    pub fn set_by_offset(&mut self, offset: usize, value: JsValue) -> bool {
        if let Some(slot) = self.values.get_mut(offset) {
            *slot = value;
            self.touch_proto_generation();
            true
        } else {
            false
        }
    }

    /// Returns `true` if the property at `offset` has the `WRITABLE` flag.
    #[inline]
    pub fn is_writable_by_offset(&self, offset: usize) -> bool {
        self.attrs
            .get(offset)
            .is_some_and(|a| a.contains(PropertyAttributes::WRITABLE))
    }

    // ── ECMAScript enumeration-order helpers ──────────────────────────────

    /// Returns the position at which `key` should be inserted to maintain
    /// ECMAScript §10.1.11 enumeration order: integer indices (ascending)
    /// first, then non-symbol string keys in insertion order, then symbol
    /// keys in insertion order.
    fn spec_insert_pos(&self, key: &str) -> usize {
        if let Some(n) = parse_integer_index(key) {
            self.keys[..self.integer_key_count]
                .binary_search_by(|existing| {
                    parse_integer_index(existing).unwrap_or(u32::MAX).cmp(&n)
                })
                .unwrap_or_else(|pos| pos)
        } else if is_symbol_property_key(key) {
            // Symbol keys go at the very end, after all string keys.
            self.keys.len()
        } else {
            // Non-symbol string key: insert before the first symbol key
            // (which, if any, occupies the tail of the keys vec).
            let mut pos = self.keys.len();
            while pos > 0 && is_symbol_property_key(&self.keys[pos - 1]) {
                pos -= 1;
            }
            pos
        }
    }

    /// Inserts a new property at `pos`, updating indices and integer-key
    /// bookkeeping as needed.
    fn insert_new(&mut self, key: Rc<str>, value: JsValue, attrs: PropertyAttributes, pos: usize) {
        if key.starts_with("__get_") || key.starts_with("__set_") {
            self.has_accessors = true;
        }
        let is_integer_key = parse_integer_index(&key).is_some();
        self.index_shift_right(pos);
        if let PropertyIndex::Map(index) = &mut self.index {
            index.insert(key.clone(), pos);
        }
        Rc::make_mut(&mut self.keys).insert(pos, key);
        // Defensive: ensure values vec can accommodate the insert position
        // (template COW keys may leave values shorter than keys).
        if pos > self.values.len() {
            self.values.resize(pos, JsValue::Undefined);
        }
        self.values.insert(pos, value);
        let attrs_vec = Rc::make_mut(&mut self.attrs);
        if pos > attrs_vec.len() {
            attrs_vec.resize(pos, DEFAULT_ATTRS);
        }
        attrs_vec.insert(pos, attrs);
        self.capacity_hint = self.capacity_hint.max(self.keys.len());
        if is_integer_key {
            self.integer_key_count += 1;
        }
        if self.keys.len() > SMALL_PROPERTY_LINEAR_SCAN_CAP {
            self.promote_index();
        }
    }

    /// Increments all HashMap index values `>= pos` by one, preparing for
    /// an element insertion at `pos`.
    fn index_shift_right(&mut self, pos: usize) {
        if let PropertyIndex::Map(index) = &mut self.index {
            for idx in index.values_mut() {
                if *idx >= pos {
                    *idx += 1;
                }
            }
        }
    }

    // ── HashMap-compatible API ────────────────────────────────────────────

    /// Returns the value for `key`, ignoring attributes.
    pub fn get(&self, key: &str) -> Option<&JsValue> {
        if let Some(slot) = self.cache_probe(key) {
            return self.values.get(slot);
        }
        let slot = self.lookup_slot(key)?;
        if slot >= self.values.len() {
            return None;
        }
        self.cache_record(key, slot);
        Some(&self.values[slot])
    }

    /// Returns the value for an interned key by trying pointer equality before
    /// falling back to the regular string lookup path.
    pub fn get_by_rc(&self, key: &Rc<str>) -> Option<&JsValue> {
        for (slot, candidate) in self.keys.iter().enumerate() {
            if Rc::ptr_eq(candidate, key) {
                if slot < self.values.len() {
                    self.cache_record(key.as_ref(), slot);
                    return Some(&self.values[slot]);
                }
                return None;
            }
        }
        self.get(key.as_ref())
    }

    /// Returns a clone of the value for `key`, ignoring attributes.
    pub fn get_cloned(&self, key: &str) -> Option<JsValue> {
        self.lookup_slot_cached(key)
            .and_then(|slot| self.values.get(slot).cloned())
    }

    /// Returns `true` if the map contains an entry for `key`.
    pub fn contains_key(&self, key: &str) -> bool {
        self.lookup_slot_cached(key).is_some()
    }

    /// Returns `true` if an accessor getter `__get_{key}__` exists in this
    /// map.  Uses a stack-allocated buffer to avoid heap `format!()`.
    #[inline]
    pub fn has_getter_for(&self, key: &str) -> bool {
        if !self.has_accessors {
            return false;
        }
        // Build "__get_{key}__" on the stack (max 128 bytes, fall back to
        // heap allocation for very long property names).
        let prefix = "__get_";
        let suffix = "__";
        let total = prefix.len() + key.len() + suffix.len();
        if total <= 128 {
            let mut buf = [0u8; 128];
            buf[..prefix.len()].copy_from_slice(prefix.as_bytes());
            buf[prefix.len()..prefix.len() + key.len()].copy_from_slice(key.as_bytes());
            buf[prefix.len() + key.len()..total].copy_from_slice(suffix.as_bytes());
            // SAFETY: both prefix, key, and suffix are valid UTF-8.
            let getter_key = unsafe { std::str::from_utf8_unchecked(&buf[..total]) };
            self.contains_key(getter_key)
        } else {
            self.contains_key(&format!("__get_{key}__"))
        }
    }

    /// Returns `true` if an accessor setter `__set_{key}__` exists in this
    /// map.  Uses a stack-allocated buffer to avoid heap `format!()`.
    #[inline]
    pub fn has_setter_for(&self, key: &str) -> bool {
        if !self.has_accessors {
            return false;
        }
        let prefix = "__set_";
        let suffix = "__";
        let total = prefix.len() + key.len() + suffix.len();
        if total <= 128 {
            let mut buf = [0u8; 128];
            buf[..prefix.len()].copy_from_slice(prefix.as_bytes());
            buf[prefix.len()..prefix.len() + key.len()].copy_from_slice(key.as_bytes());
            buf[prefix.len() + key.len()..total].copy_from_slice(suffix.as_bytes());
            // SAFETY: both prefix, key, and suffix are valid UTF-8.
            let setter_key = unsafe { std::str::from_utf8_unchecked(&buf[..total]) };
            self.contains_key(setter_key)
        } else {
            self.contains_key(&format!("__set_{key}__"))
        }
    }

    /// Returns the getter function for `key` (`__get_{key}__`) if one
    /// exists.  Stack-allocated key avoids heap `format!()`.
    #[inline]
    pub fn get_getter_for(&self, key: &str) -> Option<&JsValue> {
        if !self.has_accessors {
            return None;
        }
        let prefix = "__get_";
        let suffix = "__";
        let total = prefix.len() + key.len() + suffix.len();
        if total <= 128 {
            let mut buf = [0u8; 128];
            buf[..prefix.len()].copy_from_slice(prefix.as_bytes());
            buf[prefix.len()..prefix.len() + key.len()].copy_from_slice(key.as_bytes());
            buf[prefix.len() + key.len()..total].copy_from_slice(suffix.as_bytes());
            // SAFETY: both prefix, key, and suffix are valid UTF-8.
            let getter_key = unsafe { std::str::from_utf8_unchecked(&buf[..total]) };
            self.get(getter_key)
        } else {
            self.get(&format!("__get_{key}__"))
        }
    }

    /// Returns the setter function for `key` (`__set_{key}__`) if one
    /// exists.  Stack-allocated key avoids heap `format!()`.
    #[inline]
    pub fn get_setter_for(&self, key: &str) -> Option<&JsValue> {
        if !self.has_accessors {
            return None;
        }
        let prefix = "__set_";
        let suffix = "__";
        let total = prefix.len() + key.len() + suffix.len();
        if total <= 128 {
            let mut buf = [0u8; 128];
            buf[..prefix.len()].copy_from_slice(prefix.as_bytes());
            buf[prefix.len()..prefix.len() + key.len()].copy_from_slice(key.as_bytes());
            buf[prefix.len() + key.len()..total].copy_from_slice(suffix.as_bytes());
            // SAFETY: both prefix, key, and suffix are valid UTF-8.
            let setter_key = unsafe { std::str::from_utf8_unchecked(&buf[..total]) };
            self.get(setter_key)
        } else {
            self.get(&format!("__set_{key}__"))
        }
    }

    /// Inserts a property with default attributes (writable, enumerable,
    /// configurable).  If the key already exists the value is replaced but
    /// the existing attributes are preserved.
    ///
    /// New properties are placed according to ECMAScript enumeration order:
    /// integer-indexed keys occupy the front of the storage (sorted
    /// numerically), followed by string keys in insertion order.
    pub fn insert(&mut self, key: String, value: JsValue) {
        self.insert_rc(key.into(), value);
    }

    /// Inserts a property using an already-interned key.
    pub fn insert_rc(&mut self, key: Rc<str>, value: JsValue) {
        if let Some(i) = self.lookup_slot_cached(&key) {
            // Key already exists — extend values vec if template left it
            // shorter than keys (COW keys from object-literal templates
            // can have more entries than the values vec).
            if i >= self.values.len() {
                self.values.resize(i + 1, JsValue::Undefined);
                Rc::make_mut(&mut self.attrs).resize(i + 1, DEFAULT_ATTRS);
            }
            self.values[i] = value;
            self.touch_proto_generation();
            return;
        }
        // Non-extensible objects reject new properties (except internal __dunder__ keys).
        if !self.extensible && !key.starts_with("__") {
            return;
        }
        // The internal prototype link must never be enumerable.
        let attrs = if key.as_ref() == INTERNAL_PROTO_PROPERTY_KEY {
            BUILTIN_ATTRS
        } else {
            DEFAULT_ATTRS
        };
        let pos = self.spec_insert_pos(&key);
        self.insert_new(key, value, attrs, pos);
        self.bump_shape_id();
        if pos != self.keys.len() - 1 {
            self.cache_invalidate();
        }
        self.touch_proto_generation();
    }

    /// Insert a built-in method or constructor property (writable,
    /// non-enumerable, configurable — per ES spec).
    pub fn insert_builtin(&mut self, key: String, value: JsValue) {
        self.insert_builtin_rc(key.into(), value);
    }

    /// Inserts a built-in property using an already-interned key.
    pub fn insert_builtin_rc(&mut self, key: Rc<str>, value: JsValue) {
        if let Some(i) = self.lookup_slot_cached(&key) {
            // Key already exists — extend values vec if needed (same as insert_rc).
            if i >= self.values.len() {
                self.values.resize(i + 1, JsValue::Undefined);
                Rc::make_mut(&mut self.attrs).resize(i + 1, BUILTIN_ATTRS);
            }
            self.values[i] = value;
            Rc::make_mut(&mut self.attrs)[i] = BUILTIN_ATTRS;
            self.touch_proto_generation();
            return;
        }
        let pos = self.spec_insert_pos(&key);
        self.insert_new(key, value, BUILTIN_ATTRS, pos);
        self.bump_shape_id();
        if pos != self.keys.len() - 1 {
            self.cache_invalidate();
        }
        self.touch_proto_generation();
    }

    /// Set all existing properties to non-enumerable.
    ///
    /// Called after populating built-in prototype objects whose methods
    /// should not appear in `for…in` or `Object.keys()`.
    pub fn make_all_non_enumerable(&mut self) {
        for attr in Rc::make_mut(&mut self.attrs).iter_mut() {
            attr.remove(PropertyAttributes::ENUMERABLE);
        }
        if !self.attrs.is_empty() {
            self.bump_shape_id();
            self.touch_proto_generation();
        }
    }

    /// Removes the entry for `key`, returning the old value (if any).
    ///
    /// Uses an order-preserving shift-remove so that the ECMAScript
    /// enumeration order of the remaining properties is maintained.
    pub fn remove(&mut self, key: &str) -> Option<JsValue> {
        if let Some(i) = self.lookup_slot(key) {
            if let PropertyIndex::Map(index) = &mut self.index {
                index.remove(key);
            }
            if parse_integer_index(&self.keys[i]).is_some() {
                self.integer_key_count -= 1;
            }
            let val = self.values[i].clone();
            Rc::make_mut(&mut self.keys).remove(i);
            self.values.remove(i);
            Rc::make_mut(&mut self.attrs).remove(i);
            // Decrement indices for every slot that shifted left.
            if let PropertyIndex::Map(index) = &mut self.index {
                for idx in index.values_mut() {
                    if *idx > i {
                        *idx -= 1;
                    }
                }
            }
            self.refresh_index_mode();
            self.bump_shape_id();
            self.cache_invalidate();
            self.touch_proto_generation();
            Some(val)
        } else {
            None
        }
    }

    /// Returns an iterator over the property keys.
    pub fn keys(&self) -> impl Iterator<Item = &Rc<str>> {
        self.keys.iter()
    }

    /// Returns an iterator over `(key, value)` pairs, ignoring attributes.
    pub fn iter(&self) -> impl Iterator<Item = (&Rc<str>, &JsValue)> {
        self.keys.iter().zip(self.values.iter())
    }

    /// Returns the number of entries.
    pub fn len(&self) -> usize {
        self.keys.len()
    }

    /// Returns `true` if the map contains no entries.
    pub fn is_empty(&self) -> bool {
        self.keys.is_empty()
    }

    // ── Attribute-aware API ───────────────────────────────────────────────

    /// Returns the value and attribute flags for `key`.
    pub fn get_with_attrs(&self, key: &str) -> Option<(&JsValue, PropertyAttributes)> {
        self.lookup_slot_cached(key).and_then(|slot| {
            let v = self.values.get(slot)?;
            let a = self.attrs.get(slot).copied()?;
            Some((v, a))
        })
    }

    /// Inserts a property with explicit attribute flags.
    ///
    /// New properties are placed according to ECMAScript enumeration order
    /// (see [`insert`][Self::insert]).
    pub fn insert_with_attrs(&mut self, key: String, value: JsValue, attrs: PropertyAttributes) {
        self.insert_with_attrs_rc(key.into(), value, attrs);
    }

    /// Inserts a property with explicit attributes using an already-interned key.
    pub fn insert_with_attrs_rc(
        &mut self,
        key: Rc<str>,
        value: JsValue,
        attrs: PropertyAttributes,
    ) {
        if let Some(i) = self.lookup_slot_cached(&key) {
            // Extend values/attrs if template left them shorter than keys.
            if i >= self.values.len() {
                self.values.resize(i + 1, JsValue::Undefined);
                Rc::make_mut(&mut self.attrs).resize(i + 1, DEFAULT_ATTRS);
            }
            self.values[i] = value;
            Rc::make_mut(&mut self.attrs)[i] = attrs;
            self.touch_proto_generation();
        } else {
            let pos = self.spec_insert_pos(&key);
            self.insert_new(key, value, attrs, pos);
            self.bump_shape_id();
            if pos != self.keys.len() - 1 {
                self.cache_invalidate();
            }
            self.touch_proto_generation();
        }
    }

    /// Updates the attribute flags for an existing property.
    /// Returns `true` if the property existed and was updated.
    pub fn set_attrs(&mut self, key: &str, attrs: PropertyAttributes) -> bool {
        if let Some(i) = self.lookup_slot_cached(key) {
            let attrs_vec = Rc::make_mut(&mut self.attrs);
            if i >= attrs_vec.len() {
                attrs_vec.resize(i + 1, DEFAULT_ATTRS);
            }
            attrs_vec[i] = attrs;
            self.bump_shape_id();
            self.touch_proto_generation();
            true
        } else {
            false
        }
    }

    /// Returns the attribute flags for `key`, or `None` if absent.
    pub fn attrs(&self, key: &str) -> Option<PropertyAttributes> {
        self.lookup_slot_cached(key)
            .and_then(|slot| self.attrs.get(slot).copied())
    }

    /// Returns `true` if the property exists and is writable.
    pub fn is_writable(&self, key: &str) -> bool {
        self.lookup_slot_cached(key)
            .and_then(|i| self.attrs.get(i))
            .map(|a| a.contains(PropertyAttributes::WRITABLE))
            .unwrap_or(false)
    }

    /// Returns `true` if the property exists and is configurable.
    pub fn is_configurable(&self, key: &str) -> bool {
        self.lookup_slot_cached(key)
            .and_then(|i| self.attrs.get(i))
            .map(|a| a.contains(PropertyAttributes::CONFIGURABLE))
            .unwrap_or(false)
    }

    /// Returns `true` if the property exists and is enumerable.
    pub fn is_enumerable(&self, key: &str) -> bool {
        self.lookup_slot_cached(key)
            .and_then(|i| self.attrs.get(i))
            .map(|a| a.contains(PropertyAttributes::ENUMERABLE))
            .unwrap_or(false)
    }

    /// Set or clear the `WRITABLE` flag for an existing property.
    pub fn set_writable(&mut self, key: &str, writable: bool) {
        if let Some(i) = self.lookup_slot_cached(key) {
            let attrs_vec = Rc::make_mut(&mut self.attrs);
            if i >= attrs_vec.len() {
                attrs_vec.resize(i + 1, DEFAULT_ATTRS);
            }
            let a = &mut attrs_vec[i];
            if writable {
                a.insert(PropertyAttributes::WRITABLE);
            } else {
                a.remove(PropertyAttributes::WRITABLE);
            }
            self.bump_shape_id();
            self.touch_proto_generation();
        }
    }

    /// Set or clear the `ENUMERABLE` flag for an existing property.
    pub fn set_enumerable(&mut self, key: &str, enumerable: bool) {
        if let Some(i) = self.lookup_slot_cached(key) {
            let attrs_vec = Rc::make_mut(&mut self.attrs);
            if i >= attrs_vec.len() {
                attrs_vec.resize(i + 1, DEFAULT_ATTRS);
            }
            let a = &mut attrs_vec[i];
            if enumerable {
                a.insert(PropertyAttributes::ENUMERABLE);
            } else {
                a.remove(PropertyAttributes::ENUMERABLE);
            }
            self.bump_shape_id();
            self.touch_proto_generation();
        }
    }

    /// Set or clear the `CONFIGURABLE` flag for an existing property.
    pub fn set_configurable(&mut self, key: &str, configurable: bool) {
        if let Some(i) = self.lookup_slot_cached(key) {
            let attrs_vec = Rc::make_mut(&mut self.attrs);
            if i >= attrs_vec.len() {
                attrs_vec.resize(i + 1, DEFAULT_ATTRS);
            }
            let a = &mut attrs_vec[i];
            if configurable {
                a.insert(PropertyAttributes::CONFIGURABLE);
            } else {
                a.remove(PropertyAttributes::CONFIGURABLE);
            }
            self.bump_shape_id();
            self.touch_proto_generation();
        }
    }

    /// Returns an iterator over only the enumerable property keys.
    pub fn enumerable_keys(&self) -> impl Iterator<Item = &Rc<str>> {
        self.keys
            .iter()
            .zip(self.attrs.iter())
            .filter(|(k, a)| {
                a.contains(PropertyAttributes::ENUMERABLE) && !is_symbol_property_key(k)
            })
            .map(|(k, _)| k)
    }

    /// Returns an iterator over `(key, value)` pairs for only enumerable
    /// properties — the set that ES `EnumerableOwnProperties` would return.
    pub fn enumerable_iter(&self) -> impl Iterator<Item = (&Rc<str>, &JsValue)> {
        self.keys
            .iter()
            .zip(self.values.iter())
            .zip(self.attrs.iter())
            .filter(|((k, _), a)| {
                a.contains(PropertyAttributes::ENUMERABLE) && !is_symbol_property_key(k)
            })
            .map(|((k, v), _)| (k, v))
    }

    /// Returns an iterator over `(key, value, attrs)` triples.
    pub fn iter_with_attrs(
        &self,
    ) -> impl Iterator<Item = (&Rc<str>, &JsValue, PropertyAttributes)> {
        self.keys
            .iter()
            .zip(self.values.iter())
            .zip(self.attrs.iter())
            .map(|((k, v), a)| (k, v, *a))
    }

    /// Returns the own symbol-keyed property identifiers in insertion order.
    pub fn own_symbol_keys(&self) -> Vec<u64> {
        self.keys
            .iter()
            .filter_map(|key| property_key_to_symbol(key))
            .collect()
    }

    /// Mark all properties as non-writable and non-configurable, and prevent
    /// new properties from being added (ES §20.1.2.6).
    pub fn freeze(&mut self) {
        for a in Rc::make_mut(&mut self.attrs).iter_mut() {
            a.remove(PropertyAttributes::WRITABLE);
            a.remove(PropertyAttributes::CONFIGURABLE);
        }
        self.extensible = false;
        self.bump_shape_id();
        self.touch_proto_generation();
    }

    /// Returns `true` if the object is frozen: non-extensible with all
    /// properties non-writable and non-configurable (ES §20.1.2.15).
    pub fn is_frozen(&self) -> bool {
        if self.extensible {
            return false;
        }
        self.attrs.iter().all(|a| {
            !a.contains(PropertyAttributes::WRITABLE)
                && !a.contains(PropertyAttributes::CONFIGURABLE)
        })
    }

    /// Mark all properties as non-configurable and prevent new properties
    /// from being added (ES §20.1.2.20).
    pub fn seal(&mut self) {
        for a in Rc::make_mut(&mut self.attrs).iter_mut() {
            a.remove(PropertyAttributes::CONFIGURABLE);
        }
        self.extensible = false;
        self.bump_shape_id();
        self.touch_proto_generation();
    }

    /// Returns `true` if the object is sealed: non-extensible with all
    /// properties non-configurable (ES §20.1.2.16).
    pub fn is_sealed(&self) -> bool {
        if self.extensible {
            return false;
        }
        self.attrs
            .iter()
            .all(|a| !a.contains(PropertyAttributes::CONFIGURABLE))
    }
}

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

impl Drop for PropertyMap {
    fn drop(&mut self) {
        // Recycle buffers only when we are the sole owner of the shared
        // keys and attrs vectors.  When other maps (or a template) still
        // reference them, let the Rcs drop naturally.
        let keys_rc = std::mem::take(&mut self.keys);
        let attrs_rc = std::mem::take(&mut self.attrs);
        let values = std::mem::take(&mut self.values);

        if let (Ok(keys), Ok(attrs)) = (Rc::try_unwrap(keys_rc), Rc::try_unwrap(attrs_rc)) {
            release_storage_buffers(PropertyStorageBuffers {
                keys,
                values,
                attrs,
            });
        } else {
            // Template-instantiated: keys/attrs are shared, but
            // the values Vec can still be recycled independently.
            release_values_vec(values);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_insert_get_default_attrs() {
        let mut pm = PropertyMap::new();
        pm.insert("x".to_string(), JsValue::Smi(42));
        assert_eq!(pm.get("x"), Some(&JsValue::Smi(42)));
        let attrs = pm.attrs("x").unwrap();
        assert!(attrs.contains(PropertyAttributes::WRITABLE));
        assert!(attrs.contains(PropertyAttributes::ENUMERABLE));
        assert!(attrs.contains(PropertyAttributes::CONFIGURABLE));
    }

    #[test]
    fn test_insert_with_attrs() {
        let mut pm = PropertyMap::new();
        pm.insert_with_attrs(
            "ro".to_string(),
            JsValue::Smi(1),
            PropertyAttributes::empty(),
        );
        assert!(!pm.is_writable("ro"));
        assert!(!pm.is_enumerable("ro"));
        assert!(!pm.is_configurable("ro"));
    }

    #[test]
    fn test_insert_preserves_existing_attrs() {
        let mut pm = PropertyMap::new();
        pm.insert_with_attrs(
            "p".to_string(),
            JsValue::Smi(1),
            PropertyAttributes::ENUMERABLE,
        );
        // Re-insert with default insert — should preserve ENUMERABLE-only.
        pm.insert("p".to_string(), JsValue::Smi(2));
        assert_eq!(pm.get("p"), Some(&JsValue::Smi(2)));
        let attrs = pm.attrs("p").unwrap();
        assert_eq!(attrs, PropertyAttributes::ENUMERABLE);
    }

    #[test]
    fn test_remove() {
        let mut pm = PropertyMap::new();
        pm.insert("a".to_string(), JsValue::Boolean(true));
        assert!(pm.contains_key("a"));
        let removed = pm.remove("a");
        assert_eq!(removed, Some(JsValue::Boolean(true)));
        assert!(!pm.contains_key("a"));
    }

    #[test]
    fn test_enumerable_keys() {
        let mut pm = PropertyMap::new();
        pm.insert("visible".to_string(), JsValue::Smi(1));
        pm.insert_with_attrs(
            "hidden".to_string(),
            JsValue::Smi(2),
            PropertyAttributes::WRITABLE,
        );
        let enum_keys: Vec<&str> = pm.enumerable_keys().map(|k| &**k).collect();
        assert!(enum_keys.contains(&"visible"));
        assert!(!enum_keys.contains(&"hidden"));
    }

    #[test]
    fn test_len_and_is_empty() {
        let mut pm = PropertyMap::new();
        assert!(pm.is_empty());
        assert_eq!(pm.len(), 0);
        pm.insert("k".to_string(), JsValue::Null);
        assert!(!pm.is_empty());
        assert_eq!(pm.len(), 1);
    }

    #[test]
    fn test_set_attrs() {
        let mut pm = PropertyMap::new();
        pm.insert("p".to_string(), JsValue::Smi(1));
        assert!(pm.is_writable("p"));
        pm.set_attrs("p", PropertyAttributes::ENUMERABLE);
        assert!(!pm.is_writable("p"));
        assert!(pm.is_enumerable("p"));
        assert!(!pm.is_configurable("p"));
    }

    #[test]
    fn test_get_with_attrs() {
        let mut pm = PropertyMap::new();
        pm.insert_with_attrs(
            "x".to_string(),
            JsValue::Smi(5),
            PropertyAttributes::WRITABLE | PropertyAttributes::ENUMERABLE,
        );
        let (val, attrs) = pm.get_with_attrs("x").unwrap();
        assert_eq!(val, &JsValue::Smi(5));
        assert!(attrs.contains(PropertyAttributes::WRITABLE));
        assert!(attrs.contains(PropertyAttributes::ENUMERABLE));
        assert!(!attrs.contains(PropertyAttributes::CONFIGURABLE));
    }

    #[test]
    fn test_iter_with_attrs() {
        let mut pm = PropertyMap::new();
        pm.insert_with_attrs(
            "a".to_string(),
            JsValue::Smi(1),
            PropertyAttributes::WRITABLE,
        );
        let entries: Vec<_> = pm.iter_with_attrs().collect();
        assert_eq!(entries.len(), 1);
        assert_eq!(&**entries[0].0, "a");
        assert_eq!(entries[0].1, &JsValue::Smi(1));
        assert_eq!(entries[0].2, PropertyAttributes::WRITABLE);
    }

    #[test]
    fn test_enumerable_keys_skip_symbol_keys() {
        let mut pm = PropertyMap::new();
        pm.insert("visible".to_string(), JsValue::Smi(1));
        pm.insert(
            crate::builtins::symbol::symbol_to_property_key(123),
            JsValue::Smi(2),
        );
        let keys: Vec<&str> = pm.enumerable_keys().map(|s| &**s).collect();
        assert_eq!(keys, vec!["visible"]);
    }

    #[test]
    fn test_own_symbol_keys_returns_symbols() {
        let mut pm = PropertyMap::new();
        pm.insert(
            crate::builtins::symbol::symbol_to_property_key(321),
            JsValue::Boolean(true),
        );
        assert_eq!(pm.own_symbol_keys(), vec![321]);
    }

    #[test]
    fn test_missing_key_attr_queries() {
        let pm = PropertyMap::new();
        assert!(!pm.is_writable("nope"));
        assert!(!pm.is_enumerable("nope"));
        assert!(!pm.is_configurable("nope"));
        assert!(pm.attrs("nope").is_none());
    }

    #[test]
    fn test_with_capacity() {
        let pm = PropertyMap::with_capacity(16);
        assert!(pm.is_empty());
    }

    #[test]
    fn test_small_maps_skip_inline_cache() {
        let mut pm = PropertyMap::new();
        pm.insert("x".to_string(), JsValue::Smi(1));
        pm.insert("y".to_string(), JsValue::Smi(2));

        assert_eq!(pm.get("x"), Some(&JsValue::Smi(1)));
        assert!(pm.inline_cache.is_none());
    }

    #[test]
    fn test_clone_shape_resets_values_and_preserves_layout() {
        let mut pm = PropertyMap::with_capacity(SMALL_PROPERTY_LINEAR_SCAN_CAP + 4);
        for idx in 0..(SMALL_PROPERTY_LINEAR_SCAN_CAP + 1) {
            pm.insert(format!("k{idx}"), JsValue::Smi(idx as i32));
        }
        let shape_id = pm.shape_id();
        let layout_id = pm.layout_id();

        let cloned = pm.clone_shape();

        assert_eq!(cloned.keys, pm.keys);
        assert!(
            cloned
                .values
                .iter()
                .all(|value| matches!(value, JsValue::Undefined))
        );
        assert_eq!(cloned.attrs, pm.attrs);
        assert_ne!(cloned.shape_id(), shape_id);
        assert_eq!(cloned.layout_id(), layout_id);
        assert!(matches!(cloned.index, PropertyIndex::Map(_)));
        assert_eq!(cloned.template_next_slot, 0);
        assert_eq!(cloned.capacity_hint, pm.capacity_hint);
    }

    #[test]
    fn test_try_template_fill_returns_offset_and_disables_on_miss() {
        let mut pm = PropertyMap::from_boilerplate(
            &[Rc::from("first"), Rc::from("second")],
            &[DEFAULT_ATTRS, DEFAULT_ATTRS],
        );

        assert_eq!(pm.try_template_fill("first", JsValue::Smi(1)), Ok(0));
        assert_eq!(pm.try_template_fill("second", JsValue::Smi(2)), Ok(1));
        assert_eq!(pm.get("first"), Some(&JsValue::Smi(1)));
        assert_eq!(pm.get("second"), Some(&JsValue::Smi(2)));

        let err = pm.try_template_fill("third", JsValue::Smi(3));
        assert_eq!(err, Err(JsValue::Smi(3)));
        assert_eq!(pm.template_next_slot, usize::MAX);
    }

    // ── Inline cache tests ───────────────────────────────────────────────

    #[test]
    fn test_cache_populated_on_get() {
        let mut pm = PropertyMap::new();
        for i in 0..=SMALL_PROPERTY_LINEAR_SCAN_CAP {
            pm.insert(format!("k{i}"), JsValue::Smi(i as i32));
        }

        // First access populates the cache.
        assert_eq!(pm.get("k0"), Some(&JsValue::Smi(0)));

        // Second access of same key hits the cache.
        assert_eq!(pm.get("k0"), Some(&JsValue::Smi(0)));

        // Different key adds another cache entry.
        assert_eq!(pm.get("k1"), Some(&JsValue::Smi(1)));
        assert!(pm.inline_cache.is_some());
    }

    #[test]
    fn test_cache_invalidated_on_remove() {
        let mut pm = PropertyMap::new();
        for i in 0..=SMALL_PROPERTY_LINEAR_SCAN_CAP {
            pm.insert(format!("k{i}"), JsValue::Smi(i as i32));
        }

        // Populate cache.
        assert_eq!(pm.get("k0"), Some(&JsValue::Smi(0)));

        // Remove invalidates cache.
        pm.remove("k0");
    }

    #[test]
    fn test_cache_wraps_around() {
        let mut pm = PropertyMap::new();
        for i in 0..(INLINE_CACHE_CAP as i32 + 2) {
            pm.insert(format!("k{i}"), JsValue::Smi(i));
        }
        // Access more keys than fit in the cache so insertion wraps via the cursor.
        for i in 0..(INLINE_CACHE_CAP as i32 + 2) {
            assert_eq!(pm.get(&format!("k{i}")), Some(&JsValue::Smi(i)));
        }
        // All lookups should still work (cache or HashMap fallback).
        for i in 0..(INLINE_CACHE_CAP as i32 + 2) {
            assert_eq!(pm.get(&format!("k{i}")), Some(&JsValue::Smi(i)));
        }
    }

    #[test]
    fn test_cache_hit_moves_entry_to_front() {
        let mut pm = PropertyMap::new();
        for i in 0..=SMALL_PROPERTY_LINEAR_SCAN_CAP {
            pm.insert(format!("k{i}"), JsValue::Smi(i as i32));
        }

        assert_eq!(pm.get("k0"), Some(&JsValue::Smi(0)));
        assert_eq!(pm.get("k1"), Some(&JsValue::Smi(1)));

        // With a 16-entry direct-mapped hash cache, each key hashes to a
        // specific slot.  Verify that both are cached at their hash slots.
        let hash_a = name_hash("k0");
        let hash_b = name_hash("k1");
        let idx_a = (hash_a as usize) & (INLINE_CACHE_CAP - 1);
        let idx_b = (hash_b as usize) & (INLINE_CACHE_CAP - 1);
        let cache = pm
            .inline_cache
            .as_ref()
            .expect("large map should allocate cache");
        assert_eq!(cache.hashes[idx_a].get(), hash_a);
        assert_eq!(cache.hashes[idx_b].get(), hash_b);

        // Re-access "k1" — still at the same hash slot.
        assert_eq!(pm.get("k1"), Some(&JsValue::Smi(1)));
        assert_eq!(cache.hashes[idx_b].get(), hash_b);
    }

    #[test]
    fn test_cache_contains_key_fast_path() {
        let mut pm = PropertyMap::new();
        for i in 0..=SMALL_PROPERTY_LINEAR_SCAN_CAP {
            pm.insert(format!("k{i}"), JsValue::Smi(i as i32));
        }
        // Populate cache via get.
        let _ = pm.get("k0");
        // contains_key should hit the cache.
        assert!(pm.contains_key("k0"));
        assert!(!pm.contains_key("missing"));
    }

    #[test]
    fn test_cache_get_with_attrs_fast_path() {
        let mut pm = PropertyMap::new();
        for i in 0..SMALL_PROPERTY_LINEAR_SCAN_CAP {
            pm.insert(format!("k{i}"), JsValue::Smi(i as i32));
        }
        pm.insert_with_attrs(
            format!("k{SMALL_PROPERTY_LINEAR_SCAN_CAP}"),
            JsValue::Smi(42),
            PropertyAttributes::WRITABLE | PropertyAttributes::ENUMERABLE,
        );
        // First call: populates cache.
        let (val, attrs) = pm
            .get_with_attrs(&format!("k{SMALL_PROPERTY_LINEAR_SCAN_CAP}"))
            .unwrap();
        assert_eq!(val, &JsValue::Smi(42));
        assert!(attrs.contains(PropertyAttributes::WRITABLE));
        // Second call: should hit cache.
        let (val2, attrs2) = pm
            .get_with_attrs(&format!("k{SMALL_PROPERTY_LINEAR_SCAN_CAP}"))
            .unwrap();
        assert_eq!(val2, &JsValue::Smi(42));
        assert_eq!(attrs, attrs2);
    }

    #[test]
    fn test_cache_equality_ignores_cache_state() {
        let mut pm1 = PropertyMap::new();
        let mut pm2 = PropertyMap::new();
        pm1.insert("x".to_string(), JsValue::Smi(1));
        pm2.insert("x".to_string(), JsValue::Smi(1));
        // pm1 has a populated cache, pm2 does not.
        let _ = pm1.get("x");
        // They should still be equal.
        assert_eq!(pm1, pm2);
    }

    // ── ECMAScript enumeration-order tests ───────────────────────────────

    #[test]
    fn test_parse_integer_index() {
        assert_eq!(parse_integer_index("0"), Some(0));
        assert_eq!(parse_integer_index("1"), Some(1));
        assert_eq!(parse_integer_index("42"), Some(42));
        assert_eq!(parse_integer_index("4294967294"), Some(u32::MAX - 1));
        // u32::MAX is NOT a valid array index.
        assert_eq!(parse_integer_index("4294967295"), None);
        // Leading zeros are not canonical.
        assert_eq!(parse_integer_index("01"), None);
        assert_eq!(parse_integer_index("007"), None);
        // Non-numeric strings.
        assert_eq!(parse_integer_index(""), None);
        assert_eq!(parse_integer_index("abc"), None);
        assert_eq!(parse_integer_index("-1"), None);
        assert_eq!(parse_integer_index("1.5"), None);
    }

    #[test]
    fn test_integer_indices_sorted_before_strings() {
        let mut pm = PropertyMap::new();
        // Insert in non-spec order: strings first, then integers.
        pm.insert("b".to_string(), JsValue::Smi(1));
        pm.insert("2".to_string(), JsValue::Smi(2));
        pm.insert("a".to_string(), JsValue::Smi(3));
        pm.insert("0".to_string(), JsValue::Smi(4));
        // Expected spec order: 0, 2, b, a
        let keys: Vec<&str> = pm.keys().map(|k| &**k).collect();
        assert_eq!(keys, vec!["0", "2", "b", "a"]);
    }

    #[test]
    fn test_integer_indices_ascending_numeric_order() {
        let mut pm = PropertyMap::new();
        pm.insert("10".to_string(), JsValue::Smi(10));
        pm.insert("2".to_string(), JsValue::Smi(2));
        pm.insert("1".to_string(), JsValue::Smi(1));
        pm.insert("20".to_string(), JsValue::Smi(20));
        let keys: Vec<&str> = pm.keys().map(|s| &**s).collect();
        assert_eq!(keys, vec!["1", "2", "10", "20"]);
        assert_eq!(pm.integer_key_count, 4);
    }

    #[test]
    fn test_string_and_symbol_inserts_do_not_change_integer_key_count() {
        use crate::builtins::symbol::{symbol_create, symbol_to_property_key};

        let mut pm = PropertyMap::new();
        pm.insert("2".to_string(), JsValue::Smi(2));
        pm.insert("name".to_string(), JsValue::Smi(1));
        pm.insert(symbol_to_property_key(symbol_create(None)), JsValue::Smi(3));

        assert_eq!(pm.integer_key_count, 1);
    }

    #[test]
    fn test_string_keys_preserve_insertion_order() {
        let mut pm = PropertyMap::new();
        pm.insert("z".to_string(), JsValue::Smi(1));
        pm.insert("a".to_string(), JsValue::Smi(2));
        pm.insert("m".to_string(), JsValue::Smi(3));
        let keys: Vec<&str> = pm.keys().map(|s| &**s).collect();
        assert_eq!(keys, vec!["z", "a", "m"]);
    }

    #[test]
    fn test_mixed_integer_and_string_order() {
        let mut pm = PropertyMap::new();
        // Simulate: obj.z = 1; obj[5] = 2; obj.a = 3; obj[1] = 4; obj.m = 5; obj[3] = 6;
        pm.insert("z".to_string(), JsValue::Smi(1));
        pm.insert("5".to_string(), JsValue::Smi(2));
        pm.insert("a".to_string(), JsValue::Smi(3));
        pm.insert("1".to_string(), JsValue::Smi(4));
        pm.insert("m".to_string(), JsValue::Smi(5));
        pm.insert("3".to_string(), JsValue::Smi(6));
        // Spec: integer indices ascending, then strings in insertion order.
        let keys: Vec<&str> = pm.keys().map(|s| &**s).collect();
        assert_eq!(keys, vec!["1", "3", "5", "z", "a", "m"]);
    }

    #[test]
    fn test_remove_preserves_order() {
        let mut pm = PropertyMap::new();
        pm.insert("a".to_string(), JsValue::Smi(1));
        pm.insert("b".to_string(), JsValue::Smi(2));
        pm.insert("c".to_string(), JsValue::Smi(3));
        pm.remove("b");
        let keys: Vec<&str> = pm.keys().map(|s| &**s).collect();
        assert_eq!(keys, vec!["a", "c"]);
        // Remaining entries still accessible.
        assert_eq!(pm.get("a"), Some(&JsValue::Smi(1)));
        assert_eq!(pm.get("c"), Some(&JsValue::Smi(3)));
    }

    #[test]
    fn test_remove_preserves_spec_order() {
        let mut pm = PropertyMap::new();
        pm.insert("x".to_string(), JsValue::Smi(1));
        pm.insert("3".to_string(), JsValue::Smi(2));
        pm.insert("y".to_string(), JsValue::Smi(3));
        pm.insert("1".to_string(), JsValue::Smi(4));
        // Before remove: 1, 3, x, y
        pm.remove("3");
        let keys: Vec<&str> = pm.keys().map(|s| &**s).collect();
        assert_eq!(keys, vec!["1", "x", "y"]);
        assert_eq!(pm.integer_key_count, 1);
    }

    #[test]
    fn test_enumerable_keys_spec_order() {
        let mut pm = PropertyMap::new();
        pm.insert("b".to_string(), JsValue::Smi(1));
        pm.insert("2".to_string(), JsValue::Smi(2));
        pm.insert_with_attrs(
            "hidden".to_string(),
            JsValue::Smi(99),
            PropertyAttributes::WRITABLE, // not enumerable
        );
        pm.insert("0".to_string(), JsValue::Smi(3));
        // Enumerable keys should follow spec order, excluding "hidden".
        let keys: Vec<&str> = pm.enumerable_keys().map(|s| &**s).collect();
        assert_eq!(keys, vec!["0", "2", "b"]);
    }

    #[test]
    fn test_iter_values_match_spec_ordered_keys() {
        let mut pm = PropertyMap::new();
        pm.insert("b".to_string(), JsValue::Smi(10));
        pm.insert("1".to_string(), JsValue::Smi(20));
        pm.insert("0".to_string(), JsValue::Smi(30));
        // Spec order: 0, 1, b — values should follow.
        let pairs: Vec<(&str, &JsValue)> = pm.iter().map(|(k, v)| (&**k, v)).collect();
        assert_eq!(
            pairs,
            vec![
                ("0", &JsValue::Smi(30)),
                ("1", &JsValue::Smi(20)),
                ("b", &JsValue::Smi(10)),
            ]
        );
    }

    #[test]
    fn test_insert_existing_integer_key_no_reorder() {
        let mut pm = PropertyMap::new();
        pm.insert("1".to_string(), JsValue::Smi(10));
        pm.insert("a".to_string(), JsValue::Smi(20));
        // Re-insert "1" — should update value, not move it.
        pm.insert("1".to_string(), JsValue::Smi(99));
        let keys: Vec<&str> = pm.keys().map(|s| &**s).collect();
        assert_eq!(keys, vec!["1", "a"]);
        assert_eq!(pm.get("1"), Some(&JsValue::Smi(99)));
    }

    // ── Shape ID / offset API tests ──────────────────────────────────────

    #[test]
    fn test_shape_id_stable_on_value_update() {
        let mut pm = PropertyMap::new();
        pm.insert("x".to_string(), JsValue::Smi(1));
        let id_after_insert = pm.shape_id();
        // Updating an existing value does not change the shape.
        pm.insert("x".to_string(), JsValue::Smi(2));
        assert_eq!(pm.shape_id(), id_after_insert);
    }

    #[test]
    fn test_shape_id_changes_on_new_property() {
        let mut pm = PropertyMap::new();
        let id0 = pm.shape_id();
        pm.insert("x".to_string(), JsValue::Smi(1));
        assert_ne!(pm.shape_id(), id0);
    }

    #[test]
    fn test_shape_id_changes_on_remove() {
        let mut pm = PropertyMap::new();
        pm.insert("x".to_string(), JsValue::Smi(1));
        let id1 = pm.shape_id();
        pm.remove("x");
        assert_ne!(pm.shape_id(), id1);
    }

    #[test]
    fn test_shape_id_changes_on_attr_change() {
        let mut pm = PropertyMap::new();
        pm.insert("x".to_string(), JsValue::Smi(1));
        let id1 = pm.shape_id();
        pm.set_writable("x", false);
        assert_ne!(pm.shape_id(), id1);
    }

    #[test]
    fn test_layout_id_shared_for_identical_property_sequences() {
        let mut first = PropertyMap::new();
        first.insert("x".to_string(), JsValue::Smi(1));
        first.insert("y".to_string(), JsValue::Smi(2));

        let mut second = PropertyMap::new();
        second.insert("x".to_string(), JsValue::Smi(10));
        second.insert("y".to_string(), JsValue::Smi(20));

        assert_eq!(first.layout_id(), second.layout_id());
    }

    #[test]
    fn test_layout_id_changes_for_different_layouts() {
        let mut attrs = PropertyMap::new();
        attrs.insert("x".to_string(), JsValue::Smi(1));
        attrs.set_writable("x", false);

        let mut order = PropertyMap::new();
        order.insert("y".to_string(), JsValue::Smi(1));
        order.insert("x".to_string(), JsValue::Smi(2));

        let mut baseline = PropertyMap::new();
        baseline.insert("x".to_string(), JsValue::Smi(3));

        assert_ne!(baseline.layout_id(), attrs.layout_id());
        assert_ne!(baseline.layout_id(), order.layout_id());
    }

    #[test]
    fn test_offset_of_and_get_by_offset() {
        let mut pm = PropertyMap::new();
        pm.insert("a".to_string(), JsValue::Smi(10));
        pm.insert("b".to_string(), JsValue::Smi(20));
        let off_a = pm.offset_of("a").unwrap();
        let off_b = pm.offset_of("b").unwrap();
        assert_eq!(pm.get_by_offset(off_a), Some(&JsValue::Smi(10)));
        assert_eq!(pm.get_by_offset(off_b), Some(&JsValue::Smi(20)));
        assert!(pm.offset_of("missing").is_none());
        assert!(pm.get_by_offset(999).is_none());
    }

    #[test]
    fn test_set_by_offset() {
        let mut pm = PropertyMap::new();
        pm.insert("x".to_string(), JsValue::Smi(1));
        let off = pm.offset_of("x").unwrap();
        assert!(pm.set_by_offset(off, JsValue::Smi(42)));
        assert_eq!(pm.get("x"), Some(&JsValue::Smi(42)));
        assert!(!pm.set_by_offset(999, JsValue::Null));
    }

    #[test]
    fn test_is_writable_by_offset() {
        let mut pm = PropertyMap::new();
        pm.insert("w".to_string(), JsValue::Smi(1));
        pm.insert_with_attrs(
            "ro".to_string(),
            JsValue::Smi(2),
            PropertyAttributes::ENUMERABLE,
        );
        let off_w = pm.offset_of("w").unwrap();
        let off_ro = pm.offset_of("ro").unwrap();
        assert!(pm.is_writable_by_offset(off_w));
        assert!(!pm.is_writable_by_offset(off_ro));
        assert!(!pm.is_writable_by_offset(999));
    }

    #[test]
    fn test_unique_shape_ids_across_maps() {
        let pm1 = PropertyMap::new();
        let pm2 = PropertyMap::new();
        assert_ne!(pm1.shape_id(), pm2.shape_id());
    }

    // ── freeze / seal / is_frozen / is_sealed ────────────────────────────

    #[test]
    fn test_freeze_makes_all_non_writable_non_configurable() {
        let mut pm = PropertyMap::new();
        pm.insert("a".to_string(), JsValue::Smi(1));
        pm.insert("b".to_string(), JsValue::Smi(2));
        pm.freeze();
        assert!(!pm.is_writable("a"));
        assert!(!pm.is_configurable("a"));
        assert!(!pm.is_writable("b"));
        assert!(!pm.is_configurable("b"));
        assert!(!pm.extensible);
    }

    #[test]
    fn test_seal_preserves_writable_removes_configurable() {
        let mut pm = PropertyMap::new();
        pm.insert("a".to_string(), JsValue::Smi(1));
        pm.seal();
        assert!(pm.is_writable("a"), "seal should preserve writable");
        assert!(!pm.is_configurable("a"), "seal should remove configurable");
        assert!(!pm.extensible);
    }

    #[test]
    fn test_is_frozen_empty_non_extensible() {
        let mut pm = PropertyMap::new();
        pm.extensible = false;
        assert!(pm.is_frozen(), "empty non-extensible map should be frozen");
    }

    #[test]
    fn test_is_frozen_with_writable_property() {
        let mut pm = PropertyMap::new();
        pm.insert("x".to_string(), JsValue::Smi(1));
        pm.extensible = false;
        assert!(
            !pm.is_frozen(),
            "non-extensible map with writable prop is not frozen"
        );
    }

    #[test]
    fn test_is_sealed_with_configurable_property() {
        let mut pm = PropertyMap::new();
        pm.insert("x".to_string(), JsValue::Smi(1));
        pm.extensible = false;
        assert!(
            !pm.is_sealed(),
            "non-extensible map with configurable prop is not sealed"
        );
    }

    #[test]
    fn test_non_extensible_insert_rejected() {
        let mut pm = PropertyMap::new();
        pm.extensible = false;
        pm.insert("newkey".to_string(), JsValue::Smi(42));
        assert!(
            !pm.contains_key("newkey"),
            "non-extensible map should reject new property"
        );
    }

    #[test]
    fn test_non_extensible_allows_existing_update() {
        let mut pm = PropertyMap::new();
        pm.insert("x".to_string(), JsValue::Smi(1));
        pm.extensible = false;
        pm.insert("x".to_string(), JsValue::Smi(2));
        assert_eq!(
            pm.get("x"),
            Some(&JsValue::Smi(2)),
            "updating existing property should succeed on non-extensible"
        );
    }

    // ── enumerable_keys / enumerable_iter ────────────────────────────────

    #[test]
    fn test_enumerable_keys_skips_non_enumerable() {
        let mut pm = PropertyMap::new();
        pm.insert("a".to_string(), JsValue::Smi(1)); // default = enumerable
        pm.insert_with_attrs(
            "b".to_string(),
            JsValue::Smi(2),
            PropertyAttributes::WRITABLE | PropertyAttributes::CONFIGURABLE,
        ); // not enumerable
        pm.insert("c".to_string(), JsValue::Smi(3)); // default = enumerable
        let keys: Vec<&str> = pm.enumerable_keys().map(|k| &**k).collect();
        assert_eq!(keys.len(), 2);
        assert_eq!(keys[0], "a");
        assert_eq!(keys[1], "c");
    }

    #[test]
    fn test_enumerable_iter_returns_only_enumerable_pairs() {
        let mut pm = PropertyMap::new();
        pm.insert("x".to_string(), JsValue::Smi(10));
        pm.insert_with_attrs(
            "hidden".to_string(),
            JsValue::Smi(99),
            PropertyAttributes::empty(),
        );
        pm.insert("y".to_string(), JsValue::Smi(20));
        let pairs: Vec<(&str, &JsValue)> = pm.enumerable_iter().map(|(k, v)| (&**k, v)).collect();
        assert_eq!(pairs.len(), 2);
        assert_eq!(pairs[0].0, "x");
        assert_eq!(pairs[1].0, "y");
    }

    // ── iter_with_attrs ──────────────────────────────────────────────────

    #[test]
    fn test_iter_with_attrs_returns_all_triples() {
        let mut pm = PropertyMap::new();
        pm.insert("a".to_string(), JsValue::Smi(1));
        pm.insert_with_attrs(
            "b".to_string(),
            JsValue::Smi(2),
            PropertyAttributes::WRITABLE,
        );
        let triples: Vec<(&str, &JsValue, PropertyAttributes)> =
            pm.iter_with_attrs().map(|(k, v, a)| (&**k, v, a)).collect();
        assert_eq!(triples.len(), 2);
        assert!(triples[0].2.contains(PropertyAttributes::ENUMERABLE));
        assert!(!triples[1].2.contains(PropertyAttributes::ENUMERABLE));
    }

    // ── freeze / seal ────────────────────────────────────────────────────

    #[test]
    fn test_freeze_makes_non_writable_non_configurable() {
        let mut pm = PropertyMap::new();
        pm.insert("x".to_string(), JsValue::Smi(1));
        pm.freeze();
        assert!(!pm.is_writable("x"));
        assert!(!pm.is_configurable("x"));
        assert!(!pm.extensible);
        assert!(pm.is_frozen());
    }

    #[test]
    fn test_seal_makes_non_configurable() {
        let mut pm = PropertyMap::new();
        pm.insert("x".to_string(), JsValue::Smi(1));
        pm.seal();
        assert!(pm.is_writable("x")); // seal doesn't remove writable
        assert!(!pm.is_configurable("x"));
        assert!(!pm.extensible);
        assert!(pm.is_sealed());
    }

    // ── __proto__ key is non-enumerable ──────────────────────────────────

    #[test]
    fn test_proto_key_non_enumerable() {
        let mut pm = PropertyMap::new();
        pm.insert(INTERNAL_PROTO_PROPERTY_KEY.to_string(), JsValue::Null);
        pm.insert("visible".to_string(), JsValue::Smi(1));
        let enum_keys: Vec<&str> = pm.enumerable_keys().map(|k| &**k).collect();
        assert_eq!(enum_keys.len(), 1);
        assert_eq!(enum_keys[0], "visible");
    }

    // ── make_all_non_enumerable ──────────────────────────────────────────

    #[test]
    fn test_make_all_non_enumerable() {
        let mut pm = PropertyMap::new();
        pm.insert("a".to_string(), JsValue::Smi(1));
        pm.insert("b".to_string(), JsValue::Smi(2));
        assert!(pm.is_enumerable("a"));
        pm.make_all_non_enumerable();
        assert!(!pm.is_enumerable("a"));
        assert!(!pm.is_enumerable("b"));
    }

    // ── proto_generation ─────────────────────────────────────────────────

    #[test]
    fn test_proto_generation_tracks_prototype_mutations() {
        use std::cell::RefCell;
        use std::rc::Rc;

        let proto = Rc::new(RefCell::new(PropertyMap::new()));
        proto.borrow_mut().insert("x".to_string(), JsValue::Smi(1));

        let child = Rc::new(RefCell::new(PropertyMap::new()));
        child.borrow_mut().insert(
            "__proto__".to_string(),
            JsValue::PlainObject(Rc::clone(&proto)),
        );

        let before = child.borrow().proto_generation();
        proto.borrow_mut().insert("x".to_string(), JsValue::Smi(2));
        let after = child.borrow().proto_generation();

        assert_ne!(after, before);
    }

    // ── set_writable / set_enumerable / set_configurable ─────────────────

    #[test]
    fn test_set_writable_toggle() {
        let mut pm = PropertyMap::new();
        pm.insert("x".to_string(), JsValue::Smi(1));
        assert!(pm.is_writable("x"));
        pm.set_writable("x", false);
        assert!(!pm.is_writable("x"));
        pm.set_writable("x", true);
        assert!(pm.is_writable("x"));
    }

    #[test]
    fn test_set_enumerable_toggle() {
        let mut pm = PropertyMap::new();
        pm.insert("x".to_string(), JsValue::Smi(1));
        assert!(pm.is_enumerable("x"));
        pm.set_enumerable("x", false);
        assert!(!pm.is_enumerable("x"));
    }

    #[test]
    fn test_set_configurable_toggle() {
        let mut pm = PropertyMap::new();
        pm.insert("x".to_string(), JsValue::Smi(1));
        assert!(pm.is_configurable("x"));
        pm.set_configurable("x", false);
        assert!(!pm.is_configurable("x"));
    }

    // ── Property enumeration order conformance ────────────────────────────

    #[test]
    fn test_enum_order_integer_indices_sorted_ascending() {
        let mut pm = PropertyMap::new();
        pm.insert("2".to_string(), JsValue::Smi(2));
        pm.insert("0".to_string(), JsValue::Smi(0));
        pm.insert("1".to_string(), JsValue::Smi(1));
        let keys: Vec<&str> = pm.keys().map(|k| &**k).collect();
        assert_eq!(keys, &["0", "1", "2"]);
    }

    #[test]
    fn test_enum_order_strings_after_integers() {
        let mut pm = PropertyMap::new();
        pm.insert("b".to_string(), JsValue::Smi(1));
        pm.insert("1".to_string(), JsValue::Smi(2));
        pm.insert("a".to_string(), JsValue::Smi(3));
        pm.insert("0".to_string(), JsValue::Smi(4));
        let keys: Vec<&str> = pm.keys().map(|k| &**k).collect();
        assert_eq!(keys, &["0", "1", "b", "a"]);
    }

    #[test]
    fn test_enum_order_symbols_after_strings() {
        use crate::builtins::symbol::{symbol_create, symbol_to_property_key};
        let mut pm = PropertyMap::new();
        pm.insert("a".to_string(), JsValue::Smi(1));
        let sym = symbol_create(Some("s".into()));
        let sym_key = symbol_to_property_key(sym);
        pm.insert(sym_key.clone(), JsValue::Smi(2));
        pm.insert("b".to_string(), JsValue::Smi(3));
        let keys: Vec<&str> = pm.keys().map(|k| &**k).collect();
        // "a", "b" (strings in insertion order), then symbol
        assert_eq!(keys, &["a", "b", sym_key.as_str()]);
    }

    #[test]
    fn test_enum_order_integers_strings_symbols_combined() {
        use crate::builtins::symbol::{symbol_create, symbol_to_property_key};
        let mut pm = PropertyMap::new();
        let sym = symbol_create(Some("sym".into()));
        let sym_key = symbol_to_property_key(sym);
        pm.insert("z".to_string(), JsValue::Smi(1));
        pm.insert(sym_key.clone(), JsValue::Smi(2));
        pm.insert("5".to_string(), JsValue::Smi(3));
        pm.insert("a".to_string(), JsValue::Smi(4));
        pm.insert("0".to_string(), JsValue::Smi(5));
        let keys: Vec<&str> = pm.keys().map(|k| &**k).collect();
        assert_eq!(keys, &["0", "5", "z", "a", sym_key.as_str()]);
    }

    #[test]
    fn test_enum_order_sparse_array_indices() {
        let mut pm = PropertyMap::new();
        pm.insert("2".to_string(), JsValue::String("c".into()));
        pm.insert("0".to_string(), JsValue::String("a".into()));
        pm.insert("1".to_string(), JsValue::String("b".into()));
        let keys: Vec<&str> = pm.keys().map(|k| &**k).collect();
        assert_eq!(keys, &["0", "1", "2"]);
    }

    #[test]
    fn test_enum_order_large_integer_indices() {
        let mut pm = PropertyMap::new();
        pm.insert("100".to_string(), JsValue::Smi(1));
        pm.insert("5".to_string(), JsValue::Smi(2));
        pm.insert("42".to_string(), JsValue::Smi(3));
        pm.insert("3".to_string(), JsValue::Smi(4));
        let keys: Vec<&str> = pm.keys().map(|k| &**k).collect();
        assert_eq!(keys, &["3", "5", "42", "100"]);
    }

    #[test]
    fn test_enum_order_u32_max_not_array_index() {
        let mut pm = PropertyMap::new();
        let max_str = u32::MAX.to_string();
        pm.insert("0".to_string(), JsValue::Smi(1));
        pm.insert(max_str.clone(), JsValue::Smi(2));
        pm.insert("a".to_string(), JsValue::Smi(3));
        let keys: Vec<&str> = pm.keys().map(|k| &**k).collect();
        // u32::MAX is NOT an array index, so treated as string
        assert_eq!(keys, &["0", max_str.as_str(), "a"]);
    }

    #[test]
    fn test_enum_order_leading_zero_not_array_index() {
        let mut pm = PropertyMap::new();
        pm.insert("01".to_string(), JsValue::Smi(1));
        pm.insert("0".to_string(), JsValue::Smi(2));
        pm.insert("1".to_string(), JsValue::Smi(3));
        let keys: Vec<&str> = pm.keys().map(|k| &**k).collect();
        // "01" is not a valid array index, so it's a string key
        assert_eq!(keys, &["0", "1", "01"]);
    }

    #[test]
    fn test_enum_order_string_insertion_order_preserved() {
        let mut pm = PropertyMap::new();
        pm.insert("c".to_string(), JsValue::Smi(1));
        pm.insert("a".to_string(), JsValue::Smi(2));
        pm.insert("b".to_string(), JsValue::Smi(3));
        let keys: Vec<&str> = pm.keys().map(|k| &**k).collect();
        assert_eq!(keys, &["c", "a", "b"]);
    }

    #[test]
    fn test_enum_order_multiple_symbols_insertion_order() {
        use crate::builtins::symbol::{symbol_create, symbol_to_property_key};
        let mut pm = PropertyMap::new();
        let s1 = symbol_create(Some("s1".into()));
        let s2 = symbol_create(Some("s2".into()));
        let k1 = symbol_to_property_key(s1);
        let k2 = symbol_to_property_key(s2);
        pm.insert(k1.clone(), JsValue::Smi(1));
        pm.insert("a".to_string(), JsValue::Smi(2));
        pm.insert(k2.clone(), JsValue::Smi(3));
        let keys: Vec<&str> = pm.keys().map(|k| &**k).collect();
        // Strings first, then symbols in insertion order
        assert_eq!(keys, &["a", k1.as_str(), k2.as_str()]);
    }

    #[test]
    fn test_enumerable_keys_skips_symbols() {
        use crate::builtins::symbol::{symbol_create, symbol_to_property_key};
        let mut pm = PropertyMap::new();
        pm.insert("a".to_string(), JsValue::Smi(1));
        let sym = symbol_create(Some("hidden".into()));
        let sym_key = symbol_to_property_key(sym);
        pm.insert(sym_key, JsValue::Smi(2));
        pm.insert("b".to_string(), JsValue::Smi(3));
        let enumerable: Vec<&str> = pm.enumerable_keys().map(|k| &**k).collect();
        assert_eq!(enumerable, &["a", "b"]);
    }

    #[test]
    fn test_enumerable_keys_skips_non_enumerable_v2() {
        let mut pm = PropertyMap::new();
        pm.insert("visible".to_string(), JsValue::Smi(1));
        pm.insert_with_attrs(
            "hidden".to_string(),
            JsValue::Smi(2),
            PropertyAttributes::WRITABLE | PropertyAttributes::CONFIGURABLE,
        );
        let enumerable: Vec<&str> = pm.enumerable_keys().map(|k| &**k).collect();
        assert_eq!(enumerable, &["visible"]);
    }

    #[test]
    fn test_enumerable_iter_follows_spec_order() {
        let mut pm = PropertyMap::new();
        pm.insert("z".to_string(), JsValue::Smi(1));
        pm.insert("3".to_string(), JsValue::Smi(2));
        pm.insert("1".to_string(), JsValue::Smi(3));
        pm.insert("a".to_string(), JsValue::Smi(4));
        let pairs: Vec<(&str, &JsValue)> = pm.enumerable_iter().map(|(k, v)| (&**k, v)).collect();
        let keys: Vec<&str> = pairs.iter().map(|(k, _)| *k).collect();
        assert_eq!(keys, &["1", "3", "z", "a"]);
    }

    #[test]
    fn test_own_symbol_keys_returns_symbols_only() {
        use crate::builtins::symbol::{symbol_create, symbol_to_property_key};
        let mut pm = PropertyMap::new();
        pm.insert("a".to_string(), JsValue::Smi(1));
        let s1 = symbol_create(None);
        let s2 = symbol_create(None);
        let k1 = symbol_to_property_key(s1);
        let k2 = symbol_to_property_key(s2);
        pm.insert(k1, JsValue::Smi(2));
        pm.insert(k2, JsValue::Smi(3));
        pm.insert("b".to_string(), JsValue::Smi(4));
        let syms = pm.own_symbol_keys();
        assert_eq!(syms.len(), 2);
        assert_eq!(syms[0], s1);
        assert_eq!(syms[1], s2);
    }

    #[test]
    fn test_remove_preserves_spec_order_v2() {
        let mut pm = PropertyMap::new();
        pm.insert("1".to_string(), JsValue::Smi(1));
        pm.insert("0".to_string(), JsValue::Smi(2));
        pm.insert("a".to_string(), JsValue::Smi(3));
        pm.insert("b".to_string(), JsValue::Smi(4));
        pm.remove("a");
        let keys: Vec<&str> = pm.keys().map(|k| &**k).collect();
        assert_eq!(keys, &["0", "1", "b"]);
    }

    #[test]
    fn test_iter_with_attrs_follows_spec_order() {
        let mut pm = PropertyMap::new();
        pm.insert("b".to_string(), JsValue::Smi(1));
        pm.insert("10".to_string(), JsValue::Smi(2));
        pm.insert("2".to_string(), JsValue::Smi(3));
        pm.insert("a".to_string(), JsValue::Smi(4));
        let keys: Vec<&str> = pm.iter_with_attrs().map(|(k, _, _)| &**k).collect();
        assert_eq!(keys, &["2", "10", "b", "a"]);
    }

    #[test]
    fn test_insert_with_attrs_follows_spec_order() {
        let mut pm = PropertyMap::new();
        pm.insert_with_attrs(
            "b".to_string(),
            JsValue::Smi(1),
            PropertyAttributes::ENUMERABLE,
        );
        pm.insert_with_attrs(
            "3".to_string(),
            JsValue::Smi(2),
            PropertyAttributes::ENUMERABLE,
        );
        pm.insert_with_attrs(
            "1".to_string(),
            JsValue::Smi(3),
            PropertyAttributes::ENUMERABLE,
        );
        let keys: Vec<&str> = pm.keys().map(|k| &**k).collect();
        assert_eq!(keys, &["1", "3", "b"]);
    }

    #[test]
    fn test_small_maps_stay_inline_until_threshold() {
        let mut pm = PropertyMap::with_capacity(SMALL_PROPERTY_LINEAR_SCAN_CAP);
        for idx in 0..SMALL_PROPERTY_LINEAR_SCAN_CAP {
            pm.insert(format!("k{idx}"), JsValue::Smi(idx as i32));
        }
        assert!(matches!(pm.index, PropertyIndex::Inline));
        let last_key = format!("k{}", SMALL_PROPERTY_LINEAR_SCAN_CAP - 1);
        assert_eq!(
            pm.get(&last_key),
            Some(&JsValue::Smi((SMALL_PROPERTY_LINEAR_SCAN_CAP - 1) as i32))
        );

        pm.insert(
            format!("k{SMALL_PROPERTY_LINEAR_SCAN_CAP}"),
            JsValue::Smi(SMALL_PROPERTY_LINEAR_SCAN_CAP as i32),
        );
        assert!(matches!(pm.index, PropertyIndex::Map(_)));
        assert_eq!(
            pm.get(&format!("k{SMALL_PROPERTY_LINEAR_SCAN_CAP}")),
            Some(&JsValue::Smi(SMALL_PROPERTY_LINEAR_SCAN_CAP as i32))
        );
    }

    #[test]
    fn test_small_map_remove_demotes_to_inline() {
        let mut pm = PropertyMap::with_capacity(SMALL_PROPERTY_LINEAR_SCAN_CAP + 1);
        for idx in 0..=SMALL_PROPERTY_LINEAR_SCAN_CAP {
            pm.insert(format!("k{idx}"), JsValue::Smi(idx as i32));
        }
        assert!(matches!(pm.index, PropertyIndex::Map(_)));

        assert_eq!(
            pm.remove(&format!("k{SMALL_PROPERTY_LINEAR_SCAN_CAP}")),
            Some(JsValue::Smi(SMALL_PROPERTY_LINEAR_SCAN_CAP as i32))
        );
        assert!(matches!(pm.index, PropertyIndex::Inline));
        assert_eq!(pm.get("k0"), Some(&JsValue::Smi(0)));
    }

    /// Verify that `reinitialize_from_template` takes the same-template
    /// fast path when the recycled map already matches (Rc::ptr_eq on keys).
    #[test]
    fn test_reinitialize_same_template_fast_path() {
        let mut pm = PropertyMap::new();
        pm.insert("x".to_string(), JsValue::Smi(1));
        pm.insert("y".to_string(), JsValue::Smi(2));
        pm.insert("z".to_string(), JsValue::Smi(3));
        let template = ObjectLiteralTemplate::capture(&pm).unwrap();

        // First reinit - installs the template's keys Rc.
        pm.reinitialize_from_template(&template);
        assert!(Rc::ptr_eq(&pm.keys, &template.keys));
        assert_eq!(pm.template_next_slot, 0);

        // Set values so they are non-Undefined.
        pm.values[0] = JsValue::Smi(10);
        pm.values[1] = JsValue::Smi(20);
        pm.values[2] = JsValue::Smi(30);

        // Second reinit - same template; should hit the fast path.
        // keys Rc must remain pointer-identical (no clone+drop cycle).
        let keys_ptr_before = Rc::as_ptr(&pm.keys);
        pm.reinitialize_from_template(&template);
        assert_eq!(Rc::as_ptr(&pm.keys), keys_ptr_before);
        assert_eq!(pm.template_next_slot, 0);
    }

    /// Verify that `reinitialize_from_template_with_values` takes the
    /// same-template fast path and installs the provided values directly.
    #[test]
    fn test_reinitialize_same_template_with_values_fast_path() {
        let mut pm = PropertyMap::new();
        pm.insert("a".to_string(), JsValue::Smi(0));
        pm.insert("b".to_string(), JsValue::Smi(0));
        let template = ObjectLiteralTemplate::capture(&pm).unwrap();

        // First reinit with values.
        let vals = [JsValue::Smi(7), JsValue::Smi(8)];
        pm.reinitialize_from_template_with_values(&template, &vals);
        assert_eq!(pm.values[0], JsValue::Smi(7));
        assert_eq!(pm.values[1], JsValue::Smi(8));
        assert!(Rc::ptr_eq(&pm.keys, &template.keys));

        // Second reinit - same template fast path.
        let keys_ptr_before = Rc::as_ptr(&pm.keys);
        let vals2 = [JsValue::Smi(42), JsValue::Smi(99)];
        pm.reinitialize_from_template_with_values(&template, &vals2);
        assert_eq!(Rc::as_ptr(&pm.keys), keys_ptr_before);
        assert_eq!(pm.values[0], JsValue::Smi(42));
        assert_eq!(pm.values[1], JsValue::Smi(99));
    }
}