elisprs 0.1.20

Emacs Lisp as a fusevm frontend: a reader and compiler to fusevm::Chunk on an ElispHost object heap, with no bespoke VM or JIT
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
//! The ElispHost: the elisp object heap, the symbol obarray, dynamic binding,
//! and the primitive subrs — reached from fusevm's extension handler. elisprs
//! has no VM; fusevm executes the lowered bytecode and calls back here.
//!
//! Functions (subrs AND user closures) are heap objects; a symbol's function
//! cell holds a `Value` pointing at one. A user closure carries a precompiled
//! `fusevm::Chunk` body, so calling it = running that chunk on a (nested) fusevm
//! VM. Binding is dynamic this milestone (classic elisp; lexical is next): a
//! `let`/closure param saves the symbol's value cell on `specstack` and restores
//! it on unwind.
//!
//! Re-entrancy: a subr that calls back into elisp (`funcall`/`mapcar`/…) must not
//! hold the host borrow while the callee runs. [`call_function`] is the single
//! re-entrant entry point and only ever borrows the host for short, nested-free
//! operations.

use fusevm::{Chunk, NumOp, VMResult, Value, VM};
use indexmap::IndexMap;
use num_bigint::BigInt;
use serde::{Deserialize, Serialize};
use std::cell::{Cell, RefCell};
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use std::sync::{Arc, Weak};

/// Sentinel prefix marking the AOT heap image stashed in `chunk.names`.
pub const HEAP_IMAGE_TAG: &str = "\u{0}ELHEAP\u{0}";

/// Largest valid character code (`(max-char)` in Emacs 30.2 = #x3FFFFF). Char
/// indices into a char-table run `0..=MAX_CHAR`.
pub const MAX_CHAR: u32 = 0x3F_FFFF;

/// A serializable mirror of a heap object — everything except `Subr` (a native
/// fn pointer, re-installed by `install`). Used to ship the user/prelude heap
/// into an AOT object so `Value::Obj` handles resolve in the AOT-runtime host.
#[derive(Serialize, Deserialize, Clone)]
pub enum SerObj {
    Cons(Value, Value),
    Symbol {
        name: String,
        value: Option<Value>,
        function: Option<Value>,
        special: bool,
        #[serde(default)]
        buffer_local_auto: bool,
        #[serde(default)]
        alias_of: Option<u32>,
        /// Whether the global obarray maps `name` to *this* symbol.
        ///
        /// An uninterned symbol (a `make-symbol`/gensym result, a lambda
        /// parameter, a `let` binding in a macro body) has a name but no obarray
        /// entry. Without this flag the image cannot tell the two apart, and
        /// re-interning every symbol on import silently rebinds the global name
        /// to the uninterned copy: the prelude binds a local named `exp`
        /// (`prelude.rs`), so a cache hit used to shadow the `exp` builtin with a
        /// symbol that has no function cell — `(exp 1)` answered `void-function`
        /// on a warm cache and worked on a cold one.
        #[serde(default)]
        interned: bool,
    },
    Vector(Vec<Value>),
    Record(Vec<Value>),
    BoolVector(Vec<bool>),
    HashTable {
        test: u8,
        /// Slots in allocation order, `None` for a freed one — the shape
        /// [`Obj::HashTable`] stores, because slot order and the free list are
        /// observable through `maphash` and the printer.
        slots: Vec<Option<(Value, Value)>>,
        /// Freed slot indices, newest last — the order `puthash` pops them in.
        free: Vec<u32>,
        size: usize,
        weakness: Value,
        /// `(NAME TESTFN HASHFN)` for a `define-hash-table-test` table.
        /// Appended at the END of the variant on purpose: bincode encodes a
        /// struct variant's fields in declaration order, so inserting one
        /// mid-variant misdecodes an older image (`cache::SHARD_FORMAT_VERSION`
        /// is bumped alongside it anyway).
        user_test: Option<(Value, Value, Value)>,
    },
    CharTable {
        subtype: Value,
        default: Value,
        parent: Value,
        extra: Vec<Value>,
        /// The tree, flattened by [`CharTable::flatten`].
        contents: Vec<CtSer>,
        /// The cached ASCII slot when it is a plain value; `None` when it is
        /// the tree's depth-3 table.
        ascii: Option<Value>,
    },
    Closure {
        required: Vec<u32>,
        optional: Vec<u32>,
        rest: Option<u32>,
        body: Chunk,
        is_macro: bool,
        /// The captured lexical environment, innermost binding first, as
        /// `(symbol-handle, value)`, the value None for a local special
        /// declaration. A closure without its captures is a closure whose body
        /// cannot run.
        #[serde(default)]
        env: Vec<(u32, Option<Value>)>,
        /// Dynamic-binding closure — see [`Obj::Closure::dynamic`].
        #[serde(default)]
        dynamic: bool,
        /// The closure's printable source: its arglist as written and its body
        /// forms ([`ClosureSrc`]). Both are ordinary heap `Value`s already in
        /// this image, so they cost handles, not a second encoding.
        ///
        /// Omitting them was a silent wrong answer, not a missing feature: the
        /// closure still *ran*, but printed as `#[nil () (t)]` because the
        /// importer rebuilt it with `ClosureSrc::default()`. That hit both
        /// non-interpreted paths — an `--aot-exe` binary, and the ordinary rkyv
        /// script cache from the second run onward:
        ///
        /// ```text
        /// (princ (prin1-to-string (lambda (x) (* x 2))))   ; lexical-binding: t
        ///   emacs 30.2   #[(x) ((* x 2)) (t)]
        ///   cold run     #[(x) ((* x 2)) (t)]
        ///   cache hit    #[nil () (t)]        <- source gone
        /// ```
        ///
        /// `#[serde(default)]` only helps the AOT image, which is serde_json and
        /// therefore self-describing. bincode — the script cache's encoding —
        /// reads fields positionally and ignores the attribute entirely, so a
        /// heap image written before these fields does NOT load: the decode runs
        /// off the end of the closure and into the next object. That is why
        /// `cache::SHARD_FORMAT_VERSION` is bumped to 6 alongside this field;
        /// the header check rejects a stale shard before any inner decode.
        #[serde(default)]
        arglist: Value,
        /// See `arglist`.
        #[serde(default)]
        src_body: Vec<Value>,
    },
    Bignum(BigInt),
    /// A string object ([`Obj::Str`]). Appended at the END of the enum on
    /// purpose: bincode encodes a variant by its ordinal, so inserting one
    /// mid-enum renumbers every later variant and misdecodes an older image.
    /// (`cache::SHARD_FORMAT_VERSION` is bumped alongside it anyway, since a
    /// pre-`Str` image's string literals are transients the new build would not
    /// accept as objects.)
    Str(String),
}

/// Extension-op IDs emitted by the compiler and dispatched here.
pub mod ops {
    pub const TRUTHY: u16 = 0; // pop v; push Bool(elisp-truthy(v))
    pub const CALL: u16 = 1; // arg=argc; stack [sym, args...] -> result
    pub const GETVAR: u16 = 2; // pop sym; push value cell
    pub const SETVAR: u16 = 3; // pop val, pop sym; set value cell; push val
    pub const FSET: u16 = 4; // pop def, pop sym; set function cell; push sym
    pub const SPECBIND: u16 = 5; // pop sym, pop val; bind into current scope (BIND1)
    pub const LETBIND: u16 = 6; // wide n: open scope; pop n (val,sym) pairs; bind all
    pub const UNBIND: u16 = 7; // wide: close the innermost scope (keep stack value)
    pub const SCOPE_OPEN: u16 = 8; // open an empty lexical scope (for let*)
    pub const MAKE_CLOSURE: u16 = 9; // pop a closure template; push one capturing the env
    pub const DBG_LINE: u16 = 10; // DAP statement marker (debug only): fire dap::check_line
    pub const CHECK_ARITY: u16 = 11; // arg=argc; pop sym; signal if it names a subr rejecting argc
    pub const DEFVAR_INIT: u16 = 12; // pop val, pop sym; set value cell only if void; push val
}

pub type SubrFn = fn(&mut ElispHost, &[Value]) -> Result<Value, String>;

/// One dynamic (`let`) binding recorded on the specstack, restored by `unbind_to`.
#[derive(Clone)]
enum SpecEntry {
    /// A binding of a symbol's global (default) value cell: (sym, the buffer
    /// current when it was bound, previous value). The buffer matters for an
    /// automatically buffer-local variable bound this way (SPECPDL_LET_DEFAULT):
    /// a `setq` in that same buffer sets the default rather than making a local.
    Global(u32, usize, Option<Value>),
    /// A binding of a buffer-local slot, matching Emacs `let` over a buffer-local
    /// variable: (sym, buffer index, previous local slot). The previous slot is
    /// `None` when no local existed (a temporary local created for the binding's
    /// extent) or `Some(prev)` when one did.
    Local(u32, usize, Option<Option<Value>>),
}

/// A parsed lambda list (symbol handles).
pub struct Params {
    pub required: Vec<u32>,
    pub optional: Vec<u32>,
    pub rest: Option<u32>,
}

/// One lexical binding: a `symbol → value` cell plus a link to the rest of the
/// environment. The environment is a persistent singly-linked list — each
/// binding conses a fresh node onto the front (matching Emacs's lexical
/// environment alist). A closure captures the current head (`Rc` clone); later
/// bindings cons *new* heads, so they are invisible to an already-captured
/// closure. `setq` mutates the found cell in place (via `RefCell`), so a
/// binding shared by a closure and its enclosing body updates for both.
pub struct Scope {
    sym: u32,
    /// The binding's value CELL, shared rather than owned.
    ///
    /// A closure captures a *pruned* copy of the chain (see
    /// [`ElispHost::instantiate_closure`]), which means the same binding is
    /// reachable through two different `Scope` nodes. Emacs's interpreted
    /// environment is an alist and its pruning is `(mapcar (lambda (fv) (assq fv
    /// env)) …)`, which re-uses the very cons cells — so a `setq` through the
    /// closure is visible in the enclosing body and vice versa:
    ///
    /// ```text
    /// (let ((n 1)) (funcall (lambda () (setq n 2))) n)   ; => 2
    /// ```
    ///
    /// An owned `RefCell<Value>` per node would give the closure a private copy
    /// and answer 1.
    val: Rc<RefCell<Value>>,
    parent: Lex,
    /// A bare SYMBOL in Emacs's environment rather than a `(SYMBOL . VALUE)`
    /// binding: what eval.c `Fdefvar` conses on for a value-less `(defvar
    /// SYMBOL)`, declaring SYMBOL dynamically bound for the rest of the scope.
    /// It binds nothing, so lookups and `setq` pass over it.
    special: bool,
}
pub type Lex = Option<Rc<Scope>>;

impl Scope {
    /// A single binding, linked in front of `parent`.
    pub(crate) fn new(sym: u32, val: Value, parent: Lex) -> Self {
        Scope {
            sym,
            val: Rc::new(RefCell::new(val)),
            parent,
            special: false,
        }
    }

    /// A local special declaration of SYM, linked in front of `parent`.
    pub(crate) fn declaration(sym: u32, parent: Lex) -> Self {
        Scope {
            special: true,
            ..Scope::new(sym, Value::Undef, parent)
        }
    }
    /// Whether this node is a local special declaration, not a binding.
    pub(crate) fn is_declaration(&self) -> bool {
        self.special
    }

    /// A node re-using an existing binding's value cell — the pruned-capture
    /// counterpart of Emacs's `(assq fv env)`, which hands back the same cons.
    pub(crate) fn sharing(sym: u32, val: Rc<RefCell<Value>>, parent: Lex) -> Self {
        Scope {
            sym,
            val,
            parent,
            special: false,
        }
    }

    /// The bound symbol's arena handle.
    pub(crate) fn sym_handle(&self) -> u32 {
        self.sym
    }
    /// The binding's current value.
    pub(crate) fn value(&self) -> Value {
        self.val.borrow().clone()
    }
    /// The binding's value cell, for a capture that must share it.
    pub(crate) fn value_cell(&self) -> Rc<RefCell<Value>> {
        Rc::clone(&self.val)
    }
    /// The enclosing scope.
    pub(crate) fn parent_lex(&self) -> Lex {
        self.parent.clone()
    }

    fn lookup(self: &Rc<Scope>, sym: u32) -> Option<Value> {
        let mut cur = Some(self.clone());
        while let Some(s) = cur {
            // Head is the newest binding: the first match down the chain
            // shadows older same-name bindings (Emacs lexical `let*`).
            if s.sym == sym && !s.special {
                return Some(s.val.borrow().clone());
            }
            cur = s.parent.clone();
        }
        None
    }
    fn set(self: &Rc<Scope>, sym: u32, val: &Value) -> bool {
        let mut cur = Some(self.clone());
        while let Some(s) = cur {
            // Newest binding wins (see `lookup`): `setq` updates the most
            // recently established cell for the symbol.
            if s.sym == sym && !s.special {
                *s.val.borrow_mut() = val.clone();
                return true;
            }
            cur = s.parent.clone();
        }
        false
    }
    /// eval.c `Flet`'s `Fmemq (var, Vinternal_interpreter_environment)`: a
    /// local special declaration of SYM is in force.
    fn declares_special(self: &Rc<Scope>, sym: u32) -> bool {
        let mut cur = Some(self.clone());
        while let Some(s) = cur {
            if s.sym == sym && s.special {
                return true;
            }
            cur = s.parent.clone();
        }
        false
    }
    /// Whether the chain holds a lexical binding (not only declarations).
    pub(crate) fn has_bindings(self: &Rc<Scope>) -> bool {
        let mut cur = Some(self.clone());
        while let Some(s) = cur {
            if !s.special {
                return true;
            }
            cur = s.parent.clone();
        }
        false
    }
}

#[derive(Clone)]
pub struct SymbolData {
    pub name: String,
    pub value: Option<Value>,
    pub function: Option<Value>, // points at an Obj::Subr / Obj::Closure / alias symbol
    pub special: bool,
    /// Set by `make-variable-buffer-local`: any `set`/`setq` in a buffer that has
    /// no local binding yet automatically creates one (Emacs "automatically
    /// buffer-local"). Persisted in the AOT heap image so a cache hit keeps it.
    pub buffer_local_auto: bool,
    /// Set by `defvaralias`: this symbol is a variable alias forwarding all value
    /// operations to the base symbol at this arena handle (Emacs `SYMBOL_VARALIAS`).
    /// `None` for an ordinary variable. Chains are followed by `indirect_var`.
    pub alias_of: Option<u32>,
}

#[derive(Clone)]
pub enum Obj {
    Cons(Value, Value),
    Symbol(SymbolData),
    Vector(Vec<Value>),
    /// An Emacs record (`record`/`make-record`, `#s(NAME …)`). Slot 0 holds the
    /// type symbol (the bare NAME, exactly as passed — `(aref rec 0)` returns it),
    /// slots 1.. hold the fields. A record is a *distinct* type from a vector:
    /// `recordp` is true and `vectorp` is nil, and — unlike a vector — a record is
    /// NOT a sequence (`vconcat`/`append`/`mapcar` signal `sequencep`), only
    /// `aref`/`aset`/`length`/`copy-sequence` apply. This is the storage for every
    /// `cl-defstruct` instance (and the cl-generic/EIEIO class descriptors built on
    /// them), whose slot 0 is the struct type symbol.
    Record(Vec<Value>),
    /// An Emacs bool-vector (`make-bool-vector`/`bool-vector`, `#&N"…"`). Each
    /// element is `t` or `nil`; stored one `bool` per element (the LSB-first byte
    /// packing is materialized only for the `#&N"…"` printed/read form). A
    /// bool-vector is an array and a sequence (so `aref`/`aset`/`length`/`elt`/
    /// `append`/`mapcar` apply) but NOT a vector (`vectorp` is nil).
    BoolVector(Vec<bool>),
    /// An elisp STRING object.
    ///
    /// An Emacs string is a mutable object with identity: `aset`,
    /// `store-substring` and `clear-string` write through *every* reference to
    /// it, and `eq` compares the object rather than the text. `Value::Str`
    /// cannot model that. It is an `Arc<String>` *value*, and the only way to
    /// write through a shared `Arc` is `Arc::make_mut`, which copies whenever
    /// the buffer is shared — so the write would land on a private copy and be
    /// invisible to every alias, which is the opposite of what Emacs does:
    ///
    /// ```text
    /// (let* ((a (copy-sequence "ab")) (b a)) (aset a 0 ?z) b)   ; => "zb"
    /// ```
    ///
    /// A string therefore lives in the arena like every other elisp object, and
    /// the arena handle IS its identity — the same thing that makes `eq` work
    /// for conses. Emacs 30 removed pure space, so this holds for a *literal*
    /// too: `(progn (defun f () "ab") (aset (f) 0 ?z) (f))` answers `"zb"`,
    /// which is why the reader allocates one cell per string literal and the
    /// compiler loads that handle as the constant.
    ///
    /// The payload stays an `Arc<String>` so [`ElispHost::str_view`] can hand a
    /// builtin a plain `Value::Str` of the current text for the price of a
    /// refcount bump rather than a copy. A write installs a fresh `Arc` and
    /// carries the string's text-property entry over to it
    /// ([`ElispHost::set_string_text`]).
    Str(Arc<String>),
    Subr {
        name: String,
        min: usize,
        max: Option<usize>,
        f: SubrFn,
    },
    Closure {
        params: Rc<Params>,
        body: Rc<Chunk>,
        is_macro: bool,
        /// Captured lexical environment (`None` for a template / dynamic macro).
        env: Lex,
        /// Dynamic-binding closure (`lexical-binding` nil): it captures nothing,
        /// binds its parameters on the specstack, and runs its body in dynamic
        /// mode, so every free variable resolves through the symbols' value cells
        /// at *call* time. Emacs prints such a function with a `nil` environment
        /// (`#[(y) (x) nil]`) where a lexical one with no captures prints `(t)`.
        dynamic: bool,
        /// The closure's *source*: its arglist and its body forms, kept so it can
        /// print the way Emacs prints an interpreted closure —
        /// `#[(x) ((list x x)) (t)]` — rather than as an opaque `#<closure>`.
        /// Emacs's interpreted closure is its source; elisprs lowers the body to a
        /// `Chunk`, so the forms would otherwise be gone. Shared (`Rc`) with every
        /// instance made from the same template, so capturing a closure in a loop
        /// does not copy the source.
        src: Rc<ClosureSrc>,
    },
    /// An elisp hash table; see [`ElHashTable`] for the slot model.
    HashTable(ElHashTable),
    /// An Emacs char-table (`make-char-table`). Maps char codes `0..=MAX_CHAR`
    /// to values, with a `subtype` symbol, a `default` slot, an optional `parent`
    /// char-table for lookup fallback, and `extra` slots. See [`CharTable`].
    CharTable(CharTable),
    /// An editing buffer object (`get-buffer-create`/`generate-new-buffer`). The
    /// payload is the index into `ElispHost::buffers`, which is stable for the
    /// buffer's whole lifetime (killed buffers keep their slot, marked dead by a
    /// `None` name). Buffer objects are runtime-only and never serialized.
    Buffer(usize),
    /// A general marker object (`make-marker`/`point-marker`/`copy-marker`). The
    /// payload is shared (`Rc<RefCell<..>>`) with the buffer's live-marker registry
    /// so a single edit updates every reference; see [`MarkerData`]. Runtime-only,
    /// never serialized.
    Marker(Rc<RefCell<MarkerData>>),
    Overlay(Rc<RefCell<OverlayData>>),
    /// A window, frame or saved window configuration: an index into the
    /// host's tables (see [`crate::window`]). Runtime-only, never serialized.
    Window(usize),
    Frame(usize),
    WindowConfig(usize),
    /// A first-class obarray (`obarray-make`): a private namespace of interned
    /// symbols. Each name maps to a distinct symbol arena id created via
    /// [`ElispHost::make_symbol`], so a private obarray's symbols never collide
    /// with the global ones. The single global obarray (the value of the
    /// `obarray` variable) is the one with `global == true`; its symbol set is
    /// `ElispHost::obarray`, not `symbols`. See [`ObarrayData`].
    Obarray(ObarrayData),
    /// An integer too large for a fixnum. Emacs has no fixed-width integers: an
    /// arithmetic result that leaves fixnum range (±2^61, see
    /// `most-positive-fixnum`) becomes a bignum, and stays exact. `type-of` still
    /// answers `integer` — bignum-ness is an implementation detail of the same
    /// type, which is why `integerp` accepts these and `fixnump` does not.
    ///
    /// Never in fixnum range: [`ElispHost::make_integer`] is the only constructor
    /// and it demotes a small value back to `Value::Int`, so `eql`/`equal` can
    /// compare a bignum against a fixnum by value without a cross-representation
    /// case, and two equal bignums always have the same printed form.
    Bignum(BigInt),
}

/// An `Obj::Obarray` payload. A private obarray owns its `symbols` map
/// (name → symbol arena id); the global obarray (`global == true`) leaves
/// `symbols` empty and routes every operation to `ElispHost::obarray`.
#[derive(Clone)]
pub struct ObarrayData {
    pub symbols: HashMap<String, u32>,
    pub global: bool,
}

/// The mutable state of an Emacs marker. A marker points into a buffer at a
/// 1-based `pos`; `buffer` is the buffer's slot index, or `None` for a detached
/// marker (`make-marker`, or `set-marker … nil`) whose `pos` is meaningless.
/// `insertion_type` t means text inserted exactly at the marker moves the marker
/// past it (nil = the marker stays before the inserted text). The `Rc<RefCell>`
/// is shared between the `Obj::Marker` and the owning buffer's `markers` list, so
/// [`ElispHost::cur_insert`]/[`ElispHost::cur_delete`] adjust every live marker.
pub struct MarkerData {
    pub buffer: Option<usize>,
    pub pos: usize,
    pub insertion_type: bool,
}

/// An overlay: a range of buffer positions carrying a property list.
///
/// Like a marker, the data is shared (`Rc`) between the [`Obj::Overlay`] and
/// the owning buffer's `overlays` list, so an edit adjusts both ends through
/// one borrow. The two advance flags are what `make-overlay`'s FRONT-ADVANCE
/// and REAR-ADVANCE control, and they are exactly a marker's insertion type
/// applied to each end: text inserted AT the start goes inside the overlay
/// unless FRONT-ADVANCE, and text inserted at the end goes outside it unless
/// REAR-ADVANCE.
///
/// `buffer` is `None` for a deleted overlay, which is why `overlay-start` and
/// `overlay-buffer` both answer nil after `delete-overlay` while the object
/// itself stays an overlay.
pub struct OverlayData {
    pub buffer: Option<usize>,
    pub start: usize,
    pub end: usize,
    pub front_advance: bool,
    pub rear_advance: bool,
    /// Property list, newest first — the order `overlay-properties` reports.
    pub props: Vec<(Value, Value)>,
}

/// An elisp hash table, in Emacs's slot model (`struct Lisp_Hash_Table`, fns.c).
///
/// Storage is a SLOT VECTOR in allocation order plus a free list, not a packed
/// association vector, because Emacs's slot order is directly observable:
/// `maphash`, the `#s(hash-table …)` printer and `hash-table-keys` all walk
/// slots in index order, and `remhash` frees a slot that the NEXT `puthash`
/// reuses (LIFO). A packed vector answered
///
/// ```text
/// (let ((h (make-hash-table)))
///   (dotimes (i 5) (puthash i i h))
///   (remhash 2 h) (puthash 9 9 h)
///   (let (acc) (maphash (lambda (k _v) (push k acc)) h) (nreverse acc)))
///
///   emacs 30.2   (0 1 9 3 4)      ; 9 took the slot 2 freed
///   packed       (0 1 3 4 9)      ; 9 appended
/// ```
///
/// `index` maps a key hash to the slots holding keys with that hash, which is
/// what makes `gethash`/`puthash` O(1). Before it, every lookup was a linear
/// scan over a freshly CLONED entry vector — O(n) comparisons and one O(n)
/// allocation per operation, so a 20 000-key build-then-read took 30 s.
///
/// The hash is computed once, when the key goes in, exactly as Emacs does. A key
/// mutated after insertion therefore becomes unfindable, which is Emacs's
/// behaviour too (`(puthash k 'v h)` then `(setcar k 2)` then `(gethash k h)`
/// answers nil in both).
#[derive(Clone)]
pub struct ElHashTable {
    /// Comparison test: 0 = `eq`, 1 = `eql`, 2 = `equal`, 3 = a
    /// `define-hash-table-test` test (whose functions are in `user_test`).
    pub test: u8,
    /// `(NAME TESTFN HASHFN)` when `test` is 3.
    ///
    /// The functions are elisp, so every lookup on such a table has to CALL
    /// elisp — which is why `gethash`/`puthash`/`remhash` are dispatched from
    /// [`crate::host::call_function`] rather than run inside a host borrow.
    pub user_test: Option<(Value, Value, Value)>,
    /// Slots in allocation order; `None` is a freed slot.
    pub slots: Vec<Option<(Value, Value)>>,
    /// Freed slot indices, popped LIFO — Emacs's `next_free` chain.
    free: Vec<u32>,
    /// Key hash → the slots whose key hashes to it.
    index: HashMap<u64, Vec<u32>>,
    /// Live entry count, kept incrementally so `hash-table-count` is O(1).
    live: usize,
    /// Whether `index` is populated. A table restored from a serialized image
    /// arrives with its slots but WITHOUT hashes: rebuilding them needs the
    /// host, to resolve the arena handles inside `equal`-test keys, and at
    /// import time the arena is still being filled. The first lookup calls
    /// [`ElHashTable::reindex`] instead.
    indexed: bool,
    /// Emacs's allocation size (`hash-table-size`), grown by the measured Emacs growth series.
    pub size: usize,
    /// The `:weakness` symbol as given. elisprs has no GC that can drop entries,
    /// so this is reported back and nothing more.
    pub weakness: Value,
}

impl ElHashTable {
    pub fn new(test: u8, size: usize, weakness: Value) -> ElHashTable {
        ElHashTable {
            test,
            user_test: None,
            slots: Vec::new(),
            free: Vec::new(),
            index: HashMap::new(),
            live: 0,
            indexed: true,
            size,
            weakness,
        }
    }

    /// Rebuild a table from a serialized image. The index is left empty and
    /// filled by the first lookup (see `needs_index`).
    pub fn from_slots(
        test: u8,
        slots: Vec<Option<(Value, Value)>>,
        free: Vec<u32>,
        size: usize,
        weakness: Value,
    ) -> ElHashTable {
        let live = slots.iter().flatten().count();
        ElHashTable {
            test,
            user_test: None,
            slots,
            free,
            index: HashMap::new(),
            live,
            indexed: false,
            size,
            weakness,
        }
    }

    pub fn needs_index(&self) -> bool {
        !self.indexed
    }

    /// Install the hashes computed by the caller (which has the host the
    /// `equal` test needs), one per live slot in slot order.
    pub fn reindex(&mut self, hashes: &[(u32, u64)]) {
        self.index.clear();
        for &(slot, hk) in hashes {
            self.index.entry(hk).or_default().push(slot);
        }
        self.indexed = true;
    }

    /// The allocation size a full table of `size` grows to. Measured on GNU
    /// Emacs 30.2 by filling tables made with each `:size` and reading
    /// `hash-table-size` back: 0→6, then ×4 with a floor of 24 up to 64, ×2
    /// above it (3→24, 5→24, 6→24, 7→28, 10→40, 24→96, 64→256, 65→130).
    fn grown(size: usize) -> usize {
        match size {
            0 => 6,
            n if n <= 64 => (n * 4).max(24),
            n => n * 2,
        }
    }

    pub fn count(&self) -> usize {
        self.live
    }

    /// Live `(key, value)` pairs in slot order — what `maphash`, the printer and
    /// `hash-table-keys` all walk.
    pub fn pairs(&self) -> impl Iterator<Item = &(Value, Value)> {
        self.slots.iter().flatten()
    }

    /// The slots whose key hashes to `hk`. The caller confirms each with the
    /// table's test; a hash collision is a candidate, not a match.
    pub fn candidates(&self, hk: u64) -> &[u32] {
        self.index.get(&hk).map_or(&[][..], |v| v.as_slice())
    }

    pub fn key_at(&self, slot: u32) -> Option<&Value> {
        self.slots[slot as usize].as_ref().map(|(k, _)| k)
    }

    pub fn value_at(&self, slot: u32) -> Option<&Value> {
        self.slots[slot as usize].as_ref().map(|(_, v)| v)
    }

    pub fn set_value_at(&mut self, slot: u32, val: Value) {
        if let Some(e) = self.slots[slot as usize].as_mut() {
            e.1 = val;
        }
    }

    /// Add a key that is not already present, reusing the most recently freed
    /// slot if there is one.
    pub fn insert(&mut self, hk: u64, key: Value, val: Value) {
        if self.live >= self.size {
            self.size = Self::grown(self.size);
        }
        let slot = match self.free.pop() {
            Some(i) => {
                self.slots[i as usize] = Some((key, val));
                i
            }
            None => {
                self.slots.push(Some((key, val)));
                (self.slots.len() - 1) as u32
            }
        };
        self.index.entry(hk).or_default().push(slot);
        self.live += 1;
    }

    /// Free `slot`, whose key hashed to `hk`.
    pub fn remove(&mut self, hk: u64, slot: u32) {
        if self.slots[slot as usize].take().is_none() {
            return;
        }
        if let Some(bucket) = self.index.get_mut(&hk) {
            bucket.retain(|&i| i != slot);
            if bucket.is_empty() {
                self.index.remove(&hk);
            }
        }
        self.free.push(slot);
        self.live -= 1;
    }

    /// `clrhash`: Emacs drops the whole slot vector, so the next `puthash`
    /// starts again at slot 0 rather than reusing a free list.
    pub fn clear(&mut self) {
        self.slots.clear();
        self.free.clear();
        self.index.clear();
        self.live = 0;
    }
}

/// `chartab_size`: the number of slots of a char-table (depth 0) and of a
/// sub-char-table at depth 1, 2 and 3.
pub(crate) const CT_SIZE: [usize; 4] = [64, 16, 32, 128];
/// `chartab_chars`: how many characters one slot covers at each depth.
pub(crate) const CT_CHARS: [u32; 4] = [65_536, 4_096, 128, 1];

/// One slot of a char-table or sub-char-table: a value, or a deeper table that
/// covers the slot's characters.
#[derive(Clone)]
pub enum CtSlot {
    Val(Value),
    Sub(Box<SubCharTable>),
}

/// Emacs's `struct Lisp_Sub_Char_Table`.
#[derive(Clone)]
pub struct SubCharTable {
    pub depth: u8,
    pub min_char: u32,
    pub contents: Vec<CtSlot>,
}

impl SubCharTable {
    /// `make_sub_char_table`: every slot holds `init`.
    fn new(depth: u8, min_char: u32, init: &Value) -> SubCharTable {
        SubCharTable {
            depth,
            min_char,
            contents: vec![CtSlot::Val(init.clone()); CT_SIZE[depth as usize]],
        }
    }

    fn index(&self, c: u32) -> usize {
        ((c - self.min_char) / CT_CHARS[self.depth as usize]) as usize
    }

    /// `optimize_sub_char_table`: `Some(value)` when every slot, after its own
    /// optimisation, is a plain value SAME as the first.
    fn optimize(&mut self, same: &dyn Fn(&Value, &Value) -> bool) -> Option<Value> {
        for slot in &mut self.contents {
            if let CtSlot::Sub(s) = slot {
                if let Some(v) = s.optimize(same) {
                    *slot = CtSlot::Val(v);
                }
            }
        }
        let CtSlot::Val(first) = &self.contents[0] else {
            return None;
        };
        let all_same = self.contents[1..]
            .iter()
            .all(|slot| matches!(slot, CtSlot::Val(v) if same(v, first)));
        all_same.then(|| first.clone())
    }

    /// `sub_char_table_set`.
    fn set(&mut self, c: u32, val: Value) {
        let i = self.index(c);
        if self.depth == 3 {
            self.contents[i] = CtSlot::Val(val);
            return;
        }
        let depth = self.depth;
        let min = self.min_char + i as u32 * CT_CHARS[depth as usize];
        let slot = &mut self.contents[i];
        if let CtSlot::Val(old) = slot {
            let sub = SubCharTable::new(depth + 1, min, old);
            *slot = CtSlot::Sub(Box::new(sub));
        }
        if let CtSlot::Sub(sub) = slot {
            sub.set(c, val);
        }
    }

    /// `sub_char_table_set_range`.
    fn set_range(&mut self, from: u32, to: u32, val: &Value) {
        let depth = self.depth as usize;
        let block = CT_CHARS[depth];
        let from = from.max(self.min_char);
        let mut i = self.index(from);
        let mut c = self.min_char + block * i as u32;
        while i < CT_SIZE[depth] {
            if c > to {
                break;
            }
            if from <= c && c + block - 1 <= to {
                self.contents[i] = CtSlot::Val(val.clone());
            } else {
                let slot = &mut self.contents[i];
                if let CtSlot::Val(old) = slot {
                    let sub = SubCharTable::new(self.depth + 1, c, old);
                    *slot = CtSlot::Sub(Box::new(sub));
                }
                if let CtSlot::Sub(sub) = slot {
                    sub.set_range(from, to, val);
                }
            }
            i += 1;
            c += block;
        }
    }
}

/// The `ascii` slot of a char-table: Emacs caches the table or value covering
/// the ASCII block, and refreshes it only when an operation touches ASCII.
#[derive(Clone)]
pub enum CtAscii {
    /// A plain value (also a stale one, after a non-ASCII operation).
    Val(Value),
    /// The depth-3 sub-char-table at slot `[0][0][0]` of the tree.
    Tree,
}

/// An Emacs char-table, laid out as `chartab.c` lays it out: 64 top-level slots
/// each covering 65536 characters, refined through sub-char-tables of 16, 32 and
/// 128 slots. The layout is observable — `prin1` prints it, and a range that
/// covers a whole block stores a value where a single character stores a chain
/// of sub-tables — so operations follow the C ones step for step.
///
/// Lookup (`aref`, `char-table-range`) falls back like Emacs's `char_table_ref`:
/// own char value; if nil → `default`; if that is nil and `parent` is a
/// char-table → recurse into the parent.
#[derive(Clone)]
pub struct CharTable {
    pub subtype: Value,
    pub default: Value,
    pub parent: Value,
    pub extra: Vec<Value>,
    pub contents: Vec<CtSlot>,
    pub ascii: CtAscii,
}

/// Shallow `eq`-style equality for coalescing adjacent char-table runs. Mirrors
/// [`ElispHost::values_eq`] but is a free function usable while the arena is
/// mutably borrowed.
fn ct_val_eq(a: &Value, b: &Value) -> bool {
    if !el_truthy(a) && !el_truthy(b) {
        return true;
    }
    match (a, b) {
        (Value::Int(x), Value::Int(y)) => x == y,
        (Value::Float(x), Value::Float(y)) => x.to_bits() == y.to_bits(),
        (Value::Obj(x), Value::Obj(y)) => x == y,
        (Value::Bool(true), Value::Bool(true)) => true,
        _ => false,
    }
}

/// High bit of a print-label key: names the sub-char-table `ascii` shares with
/// the tree of the char-table whose heap id is the low bits.
const CT_ASCII_LABEL: u32 = 0x8000_0000;

impl SubCharTable {
    /// Every plain value stored below this table, in slot order.
    fn leaf_values(&self, out: &mut Vec<Value>) {
        for slot in &self.contents {
            slot.leaf_values(out, false);
        }
    }
}

impl CtSlot {
    /// The values below this slot, depth first. With SKIP_ASCII the depth-3
    /// table at min-char 0 is skipped: it is the one `ascii` already listed.
    fn leaf_values(&self, out: &mut Vec<Value>, skip_ascii: bool) {
        match self {
            CtSlot::Val(v) => out.push(v.clone()),
            CtSlot::Sub(s) => {
                if skip_ascii && s.depth == 3 && s.min_char == 0 {
                    return;
                }
                for slot in &s.contents {
                    slot.leaf_values(out, skip_ascii);
                }
            }
        }
    }
}

impl CharTable {
    /// `Fmake_char_table`: every slot — default, ascii and extras included —
    /// starts as INIT, then the parent is nil.
    pub fn new(subtype: Value, init: Value, n_extra: usize) -> CharTable {
        CharTable {
            subtype,
            default: init.clone(),
            parent: Value::Undef,
            extra: vec![init.clone(); n_extra],
            contents: vec![CtSlot::Val(init.clone()); CT_SIZE[0]],
            ascii: CtAscii::Val(init),
        }
    }

    /// The raw value stored for char `c` in this table alone (no parent/default
    /// fallback).
    pub fn raw_get(&self, c: u32) -> Value {
        let mut slot = &self.contents[(c / CT_CHARS[0]) as usize];
        loop {
            match slot {
                CtSlot::Val(v) => return v.clone(),
                CtSlot::Sub(s) => slot = &s.contents[s.index(c)],
            }
        }
    }

    /// The depth-3 sub-char-table at `[0][0][0]`, when the tree reaches that deep.
    pub fn ascii_table(&self) -> Option<&SubCharTable> {
        let CtSlot::Sub(s1) = &self.contents[0] else {
            return None;
        };
        let CtSlot::Sub(s2) = &s1.contents[0] else {
            return None;
        };
        match &s2.contents[0] {
            CtSlot::Sub(s3) => Some(s3),
            CtSlot::Val(_) => None,
        }
    }

    /// `copy_char_table`: a deep copy, with the cached ASCII slot recomputed.
    pub fn copied(&self) -> CharTable {
        let mut copy = self.clone();
        copy.ascii = copy.derived_ascii();
        copy
    }

    /// A deep copy that keeps the cached ASCII slot as it is.
    pub fn copied_exact(&self) -> CharTable {
        self.clone()
    }

    /// `Foptimize_char_table`: collapse every sub-table whose slots are all
    /// SAME-equal, then refresh the cached ASCII slot.
    pub fn optimize(&mut self, same: &dyn Fn(&Value, &Value) -> bool) {
        for slot in &mut self.contents {
            if let CtSlot::Sub(s) = slot {
                if let Some(v) = s.optimize(same) {
                    *slot = CtSlot::Val(v);
                }
            }
        }
        self.ascii = self.derived_ascii();
    }

    /// `char_table_ascii`: the value or depth-3 table covering the ASCII block,
    /// reduced to `Val` when some level above it is uniform.
    fn derived_ascii(&self) -> CtAscii {
        let CtSlot::Sub(s1) = &self.contents[0] else {
            return CtAscii::Val(match &self.contents[0] {
                CtSlot::Val(v) => v.clone(),
                CtSlot::Sub(_) => Value::Undef,
            });
        };
        match &s1.contents[0] {
            CtSlot::Val(v) => CtAscii::Val(v.clone()),
            CtSlot::Sub(s2) => match &s2.contents[0] {
                CtSlot::Val(v) => CtAscii::Val(v.clone()),
                CtSlot::Sub(_) => CtAscii::Tree,
            },
        }
    }

    /// `char_table_set`.
    pub fn set(&mut self, c: u32, val: Value) {
        let i = (c / CT_CHARS[0]) as usize;
        let slot = &mut self.contents[i];
        if let CtSlot::Val(old) = slot {
            let sub = SubCharTable::new(1, i as u32 * CT_CHARS[0], old);
            *slot = CtSlot::Sub(Box::new(sub));
        }
        if let CtSlot::Sub(sub) = slot {
            sub.set(c, val);
        }
        if c < 128 {
            self.ascii = self.derived_ascii();
        }
    }

    /// `char_table_set_range`: set every char in `from..=to` to `val`.
    pub fn set_range(&mut self, from: u32, to: u32, val: Value) {
        if from == to {
            self.set(from, val);
            return;
        }
        let lim = (to / CT_CHARS[0]) as usize;
        let mut i = (from / CT_CHARS[0]) as usize;
        let mut c = i as u32 * CT_CHARS[0];
        while i <= lim {
            if c > to {
                break;
            }
            if from <= c && c + CT_CHARS[0] - 1 <= to {
                self.contents[i] = CtSlot::Val(val.clone());
            } else {
                let slot = &mut self.contents[i];
                if let CtSlot::Val(old) = slot {
                    let sub = SubCharTable::new(1, c, old);
                    *slot = CtSlot::Sub(Box::new(sub));
                }
                if let CtSlot::Sub(sub) = slot {
                    sub.set_range(from, to, &val);
                }
            }
            i += 1;
            c += CT_CHARS[0];
        }
        if from < 128 {
            self.ascii = self.derived_ascii();
        }
    }

    /// `(set-char-table-range TABLE t VALUE)`: every top-level slot, and the
    /// cached ASCII slot, becomes VALUE.
    pub fn set_all(&mut self, val: Value) {
        for slot in &mut self.contents {
            *slot = CtSlot::Val(val.clone());
        }
        self.ascii = CtAscii::Val(val);
    }

    /// The table as `(start, value)` runs, coalescing neighbours holding the
    /// same value; the first run starts at 0 and the last runs to `MAX_CHAR`.
    pub fn runs(&self) -> Vec<(u32, Value)> {
        fn walk(slots: &[CtSlot], min: u32, block: u32, out: &mut Vec<(u32, Value)>) {
            for (i, slot) in slots.iter().enumerate() {
                let start = min + i as u32 * block;
                match slot {
                    CtSlot::Val(v) => match out.last() {
                        Some((_, last)) if ct_val_eq(last, v) => {}
                        _ => out.push((start, v.clone())),
                    },
                    CtSlot::Sub(s) => {
                        walk(&s.contents, s.min_char, CT_CHARS[s.depth as usize], out)
                    }
                }
            }
        }
        let mut out = Vec::new();
        walk(&self.contents, 0, CT_CHARS[0], &mut out);
        out
    }

    /// The tree flattened for the heap image: each top-level slot in order, a
    /// sub-table as a `Sub` marker followed by its own slots, depth first.
    pub fn flatten(&self) -> Vec<CtSer> {
        fn walk(slots: &[CtSlot], out: &mut Vec<CtSer>) {
            for slot in slots {
                match slot {
                    CtSlot::Val(v) => out.push(CtSer::Val(v.clone())),
                    CtSlot::Sub(s) => {
                        out.push(CtSer::Sub);
                        walk(&s.contents, out);
                    }
                }
            }
        }
        let mut out = Vec::new();
        walk(&self.contents, &mut out);
        out
    }

    /// Inverse of [`CharTable::flatten`].
    pub fn unflatten(flat: &[CtSer]) -> Vec<CtSlot> {
        fn read(flat: &[CtSer], pos: &mut usize, depth: usize, min: u32) -> Vec<CtSlot> {
            let mut slots = Vec::with_capacity(CT_SIZE[depth]);
            for i in 0..CT_SIZE[depth] {
                let item = flat.get(*pos).cloned().unwrap_or(CtSer::Val(Value::Undef));
                *pos += 1;
                match item {
                    CtSer::Val(v) => slots.push(CtSlot::Val(v)),
                    CtSer::Sub => {
                        let child_min = min + i as u32 * CT_CHARS[depth];
                        let contents = read(flat, pos, depth + 1, child_min);
                        slots.push(CtSlot::Sub(Box::new(SubCharTable {
                            depth: (depth + 1) as u8,
                            min_char: child_min,
                            contents,
                        })));
                    }
                }
            }
            slots
        }
        let mut pos = 0;
        read(flat, &mut pos, 0, 0)
    }
}

/// A char-table slot in a heap image ([`CharTable::flatten`]).
#[derive(Serialize, Deserialize, Clone)]
pub enum CtSer {
    Val(Value),
    Sub,
}

/// Resolution of a function designator to something callable.
pub enum Resolved {
    Subr {
        f: SubrFn,
        min: usize,
        max: Option<usize>,
        name: String,
    },
    Closure {
        params: Rc<Params>,
        body: Rc<Chunk>,
        is_macro: bool,
        env: Lex,
        /// Dynamic-binding function — see [`Obj::Closure::dynamic`].
        dynamic: bool,
        /// The closure object indirection landed on. `funcall_lambda` signals
        /// `(wrong-number-of-arguments FUN NARGS)` with `fun`, the *resolved*
        /// function — never the symbol the caller wrote — so a wrong-arity call
        /// to a `defun` names `#[(a) (a) (t)]`, not `f1`. (A subr is the other
        /// way round: `eval_sub` signals with `original_fun`, the symbol.)
        object: Value,
    },
}

/// What a designator's function cell names *right now*, for the pre-argument
/// arity guard. Deliberately cheaper than [`ElispHost::resolve_function`]: it
/// clones no closure body, parameter list or captured environment, because on
/// the shape it exists to wave through it must cost as little as possible.
pub enum FnKind {
    /// A subr, with its `(min, max)` arity (`max: None` is Emacs's `MANY`).
    Subr(usize, Option<usize>),
    /// A closure, a macro, or any other callable object.
    Other,
    /// Nothing callable: no function cell, or an alias chain that dead-ends.
    Vacant,
}

impl FnKind {
    /// Whether Emacs rejects a call of `argc` arguments *before* evaluating any
    /// of them. Only a subr's arity is checked that early: `eval_sub` reads
    /// `XSUBR (fun)->max_args` and signals straight from the argument-count
    /// switch, while a closure reaches `funcall_lambda` only after its arguments
    /// have already been evaluated into a vector.
    pub fn rejects_before_args(&self, argc: usize) -> bool {
        match self {
            FnKind::Subr(min, max) => argc < *min || max.is_some_and(|m| argc > m),
            _ => false,
        }
    }
}

/// Prelude functions whose Emacs counterpart is a C subr, so a wrong-arity call
/// names the callee as written (`(wrong-number-of-arguments cl-first 2)`) instead
/// of the `(MANDATORY . NONREST)` template every other preloaded function reports
/// (see [`ElispHost::signal_closure_wrong_nargs`]). A name belongs here iff
/// `(subrp (symbol-function NAME))` is non-nil in Emacs while the prelude defines
/// NAME as Lisp; sorted, because it is binary-searched.
const PRELUDE_C_SUBR_NAMES: &[&str] = &[
    "/=",
    "all-completions",
    "arrayp",
    "assoc-string",
    "autoload",
    "backward-prefix-chars",
    "bare-symbol",
    "barf-if-buffer-read-only",
    "bindings--define-key",
    "buffer-enable-undo",
    "buffer-file-name",
    "buffer-hash",
    "byte-code-function-p",
    "capitalize",
    "capitalize-region",
    "capitalize-word",
    "car-safe",
    "cdr-safe",
    "char-syntax",
    "characterp",
    "check-coding-system",
    "cl-first",
    "cl-rest",
    "cl-type-of",
    "cl-values",
    "coding-system-base",
    "coding-system-eol-type",
    "coding-system-p",
    "command-remapping",
    "commandp",
    "compare-buffer-substrings",
    "copy-alist",
    "copy-sequence",
    "copy-syntax-table",
    "current-message",
    "current-time-zone",
    "defalias",
    "define-hash-table-test",
    "define-key",
    "delete",
    "delq",
    "directory-files",
    "documentation",
    "documentation-property",
    "documentation-stringp",
    "downcase-region",
    "downcase-word",
    "equal-including-properties",
    "error-message-string",
    "featurep",
    "following-char",
    "force-mode-line-update",
    "format-message",
    "forward-comment",
    "get",
    "get-char-property",
    "get-load-suffixes",
    "hash-table-rehash-size",
    "hash-table-rehash-threshold",
    "insert-and-inherit",
    "insert-before-markers",
    "integer-or-marker-p",
    "interactive-form",
    "internal--define-uninitialized-variable",
    "key-description",
    "keymap-parent",
    "keymapp",
    "kill-all-local-variables",
    "length<",
    "length=",
    "length>",
    "locate-file-internal",
    "lookup-key",
    "make-char-table",
    "make-sparse-keymap",
    "make-temp-name",
    "mapcan",
    "matching-paren",
    "modify-syntax-entry",
    "multibyte-string-p",
    "nconc",
    "next-property-change",
    "next-single-property-change",
    "ngettext",
    "nreverse",
    "ntake",
    "number-or-marker-p",
    "overlay-recenter",
    "parse-partial-sexp",
    "plist-get",
    "plist-member",
    "plist-put",
    "preceding-char",
    "prefix-numeric-value",
    "previous-single-property-change",
    "proper-list-p",
    "provide",
    "purecopy",
    "put",
    "remove-list-of-text-properties",
    "require",
    "run-hook-with-args",
    "run-hook-with-args-until-failure",
    "run-hook-with-args-until-success",
    "run-hook-wrapped",
    "run-hooks",
    "safe-length",
    "scan-lists",
    "scan-sexps",
    "sequencep",
    "set-default-toplevel-value",
    "set-keymap-parent",
    "set-syntax-table",
    "setplist",
    "single-key-description",
    "skip-syntax-backward",
    "skip-syntax-forward",
    "standard-syntax-table",
    "string-as-multibyte",
    "string-as-unibyte",
    "string-bytes",
    "string-collate-equalp",
    "string-collate-lessp",
    "string-equal",
    "string-lessp",
    "string-reverse",
    "string-to-multibyte",
    "string-to-syntax",
    "string-to-unibyte",
    "string-version-lessp",
    "string-width",
    "string<",
    "string=",
    "substitute-in-file-name",
    "symbol-plist",
    "symbol-with-pos-p",
    "syntax-class-to-char",
    "syntax-table",
    "syntax-table-p",
    "take",
    "test-completion",
    "text-property-any",
    "text-property-not-all",
    "text-quoting-style",
    "time-add",
    "time-convert",
    "time-equal-p",
    "time-less-p",
    "time-subtract",
    "try-completion",
    "upcase-initials",
    "upcase-initials-region",
    "upcase-region",
    "upcase-word",
    "value<",
    "wholenump",
];

/// Emacs's `exec_byte_code` arity template — `(MANDATORY, NONREST)` — for every
/// function elisprs implements as a Rust subr while Emacs implements it in
/// *byte-compiled Lisp*.
///
/// The two differ only in what a wrong-arity call reports, and only because
/// elisprs moved the implementation into Rust. Emacs reaches these through
/// `exec_byte_code`, which signals `(wrong-number-of-arguments (MANDATORY .
/// NONREST) NARGS)`; a Rust subr would otherwise report the callee, so
/// `(split-string)` answered `(wrong-number-of-arguments split-string 0)` where
/// Emacs answers `(wrong-number-of-arguments (1 . 4) 0)`. Every entry in the
/// list was measured, not inferred: it is `(logand ARGLIST 127)` and `(ash
/// ARGLIST -8)` read off the compiled object's own arglist word under the pinned
/// oracle. NONREST is NOT `func-arity`'s cdr — `error` is `(1 . many)` by
/// `func-arity` and `(1 . 1)` here, because NONREST counts formals before
/// `&rest`.
///
/// A name belongs here if and only if `(subrp (symbol-function NAME))` is nil in
/// Emacs and non-nil in elisprs. Porting one of these into the prelude as real
/// Lisp removes its entry; adding a new Rust subr that shadows a Lisp function
/// adds one.
const LISP_LEVEL_ARITY: &[(&str, u16, u16)] = &[
    ("backward-word", 0, 1),
    ("bignump", 1, 1),
    ("caaaar", 1, 1),
    ("caaadr", 1, 1),
    ("caaar", 1, 1),
    ("caadar", 1, 1),
    ("caaddr", 1, 1),
    ("caadr", 1, 1),
    ("caar", 1, 1),
    ("cadaar", 1, 1),
    ("cadadr", 1, 1),
    ("cadar", 1, 1),
    ("caddar", 1, 1),
    ("cadddr", 1, 1),
    ("caddr", 1, 1),
    ("cadr", 1, 1),
    ("cdaaar", 1, 1),
    ("cdaadr", 1, 1),
    ("cdaar", 1, 1),
    ("cdadar", 1, 1),
    ("cdaddr", 1, 1),
    ("cdadr", 1, 1),
    ("cdar", 1, 1),
    ("cddaar", 1, 1),
    ("cddadr", 1, 1),
    ("cddar", 1, 1),
    ("cdddar", 1, 1),
    ("cddddr", 1, 1),
    ("cdddr", 1, 1),
    ("cddr", 1, 1),
    ("char-uppercase-p", 1, 1),
    ("count-lines", 2, 3),
    ("error", 1, 1),
    ("fixnump", 1, 1),
    ("generate-new-buffer", 1, 2),
    ("hash-table-keys", 1, 1),
    ("hash-table-values", 1, 1),
    ("looking-at-p", 1, 1),
    ("lsh", 2, 2),
    ("macroexpand-1", 1, 2),
    ("macroexpand-all", 1, 2),
    ("macrop", 1, 1),
    ("match-string", 1, 2),
    ("member-ignore-case", 2, 2),
    ("oclosure--copy", 2, 2),
    ("oclosure--fix-type", 2, 2),
    ("oclosure--get", 3, 3),
    ("oclosure--set", 3, 3),
    ("oclosure-type", 1, 1),
    ("sha1", 1, 4),
    ("shell-command-to-string", 1, 1),
    ("special-form-p", 1, 1),
    ("split-string", 1, 4),
    ("store-substring", 3, 3),
    ("string-empty-p", 1, 1),
    ("string-join", 1, 2),
    ("string-match-p", 2, 3),
    ("string-prefix-p", 2, 3),
    ("string-suffix-p", 2, 3),
    ("string-to-list", 1, 1),
    ("string-to-vector", 1, 1),
    ("url-hexify-string", 1, 2),
    ("url-unhex-string", 1, 2),
    ("user-error", 1, 1),
];

/// The `(MANDATORY, NONREST)` template for a subr Emacs implements in
/// byte-compiled Lisp. See [`LISP_LEVEL_ARITY`].
fn lisp_level_arity(name: &str) -> Option<(u16, u16)> {
    LISP_LEVEL_ARITY
        .iter()
        .find(|(n, _, _)| *n == name)
        .map(|(_, m, r)| (*m, *r))
}

/// print.c `PRINT_CIRCLE`: the max print nesting depth. With `print-circle`
/// nil, an object nested this deep signals "Apparently circular structure being
/// printed" instead of printing (Emacs errors at exactly this depth).
const PRINT_CIRCLE: usize = 200;

/// The standard input `read-from-minibuffer` reads in batch: the process
/// stdin for the `elisp` binary, or a fixed buffer an embedder feeds in.
#[derive(Clone)]
pub enum StdinSource {
    Process,
    Fed(std::io::Cursor<Vec<u8>>),
}

impl std::io::Read for StdinSource {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        match self {
            StdinSource::Process => std::io::stdin().read(buf),
            StdinSource::Fed(c) => c.read(buf),
        }
    }
}

#[derive(Clone)]
pub struct ElispHost {
    pub(crate) arena: Vec<Obj>,
    /// The windows, frames and window configurations of [`crate::window`],
    /// the selected ones, and window.c's counters.
    pub(crate) windows: Vec<crate::window::WindowData>,
    pub(crate) frames: Vec<crate::window::FrameData>,
    pub(crate) window_configs: Vec<crate::window::WindowConfig>,
    pub(crate) selected_window: usize,
    pub(crate) selected_frame: usize,
    pub(crate) window_count: i64,
    pub(crate) window_select_count: i64,
    /// The next buffer-list order key (`EditBuffer::list_order`).
    pub(crate) buffer_order_seq: i64,
    /// `b->last_window_start`: where each buffer's window started when a window
    /// last stopped showing it.
    pub(crate) last_window_start: HashMap<usize, usize>,
    /// undo.c `point_before_last_command_or_undo` and
    /// `buffer_before_last_command_or_undo`: set by `undo-boundary` (there is
    /// no command loop), read by `record_point`.
    point_before_last_command_or_undo: Option<usize>,
    buffer_before_last_command_or_undo: Option<usize>,
    obarray: HashMap<String, u32>,
    /// Arena length right after `install` (the builtin objects). Everything at or
    /// above this index is user/prelude data — the portion serialized for AOT.
    builtin_count: usize,
    /// Arena length right after the prelude loaded (0 before). A closure below
    /// this line models Emacs's preloaded, byte-compiled Lisp, whose arity
    /// errors name the `(MANDATORY . NONREST)` template rather than the function.
    prelude_end: usize,
    /// Dynamic-binding save stack. Each `let`/param binding of a special variable
    /// pushes one entry; `unbind_to` pops and restores.
    specstack: Vec<SpecEntry>,
    /// Current lexical environment (the chain of `let`/closure frames).
    lex: Lex,
    /// Whether the code now running was evaluated with `lexical-binding` nil.
    /// Emacs picks the binding mode per *evaluated form* — `eval`'s LEXICAL
    /// argument, or the file-local variable a file was loaded with — so this is a
    /// dynamic-extent flag, saved and restored around `eval` and around every call
    /// into a closure that remembers the mode it was made in.
    ///
    /// While set: `let`/`let*`/parameter bindings all go on the specstack (every
    /// symbol behaves as if `defvar`'d), and a `lambda` captures nothing. Default
    /// `false` — elisprs's own prelude and every file it loads are lexical.
    pub(crate) dynamic_binding: bool,
    /// Elisp call depth (`run_closure` nesting), bounded by `max-lisp-eval-depth`.
    pub(crate) eval_depth: usize,
    /// Arena handle of `max-lisp-eval-depth`, resolved once on first use so the
    /// per-call limit check is an array index rather than an obarray lookup.
    max_depth_sym: Option<u32>,
    /// `(macro . FUNCTION)` stand-ins for the macros the compiler lowers as
    /// intrinsics — see [`ElispHost::introspect_function_cell`].
    intrinsic_macro_cells: HashMap<u32, Value>,
    /// Whether the code now running is *compiling* rather than executing: set
    /// around the macro-expand + lower half of each top-level form. See
    /// [`Self::compile_interned`].
    compiling_form: bool,
    /// Symbols the COMPILER interned, as opposed to symbols the running program
    /// interned. A cached heap image has to tell them apart, because it re-claims
    /// the global obarray name of every symbol it carries: a symbol a run created
    /// with `(intern "x")` was baked into the image and re-interned on every
    /// later hit of the same script, so the script answered differently on a warm
    /// cache than on a cold one — with input it had never seen:
    ///
    /// ```text
    ///   FUZZ_CORPUS=interns-zqleak.el elisp drive.el   # writes the cache
    ///   FUZZ_CORPUS=asks-only.el      elisp drive.el   # warm: =zqleak
    ///   FUZZ_CORPUS=asks-only.el      elisp drive.el   # cold: =nil  (and Emacs: nil)
    /// ```
    ///
    /// A symbol the compiler interned is different: it is a literal of the file,
    /// the chunk references its handle, and a hit does not compile — so the image
    /// must carry it interned or the replay resolves a name to nothing.
    compile_interned: HashSet<u32>,
    /// Per-scope unwind info: (saved lexical env, specstack depth at entry).
    frame_stack: Vec<(Lex, usize)>,
    pub(crate) error: Option<String>,
    /// A pending `throw`: (tag, value). Set by `throw`, consumed by `catch`.
    /// Distinguishes a non-local `throw` from an ordinary error during unwinding.
    pub(crate) pending_throw: Option<(Value, Value)>,
    /// Tags of the `catch` frames currently active, so `throw` can detect when no
    /// matching catch exists and signal `no-catch` (like Emacs) instead of leaking.
    pub(crate) catch_tags: Vec<Value>,
    /// The structured error object `(ERROR-SYMBOL . DATA)` from the most recent
    /// `signal`/`error`, so `condition-case` can bind the handler variable to the
    /// real list (not a re-parsed string). Cleared when entering a c-c body.
    pub(crate) pending_error: Option<(String, Value)>,
    /// Regexp match data from the last successful `string-match`: the subject
    /// string plus char-position spans for the whole match (group 0) and each
    /// capture group. `match-beginning`/`match-end`/`match-string` read it.
    pub(crate) match_data: Option<MatchData>,
    /// print.c `printchar_stdout_last`: the last character written to stdout,
    /// which is what `(terpri t t)` consults in batch. NUL before any output.
    pub(crate) stdout_last: char,
    /// In-process stdout sink. When `Some`, everything the program writes to
    /// stdout is appended here instead of reaching the process; an embedder
    /// ([`crate::embed::run_program`]) turns it on. `None` is the `elisp` binary.
    pub capture: Option<String>,
    /// Where `read-from-minibuffer` / `read-string` read their line from in
    /// batch; see [`StdinSource`].
    pub stdin: StdinSource,
    /// Set by `print_inner` when nesting reaches `PRINT_CIRCLE`; the print entry
    /// points (`prin1`/`print`/`princ`/`format`) read it to signal Emacs's
    /// `error "Apparently circular structure being printed"`. `Cell` so the
    /// `&self` printer can record it. Reset at the top of every `print` call.
    pub(crate) print_overflow: Cell<bool>,
    /// print.c `new_backquote_output`: how many enclosing `` (\` X) `` forms the
    /// printer is inside, which is what lets `(\, X)` print as `,X`.
    pub(crate) print_backquote_depth: Cell<u32>,
    /// `print-circle` label table for ONE print call: arena id → print.c's status
    /// field, using the same encoding `Vprint_number_table` does. `0` is `Qt`
    /// ("candidate, seen once, no label"); `-N` is "label N assigned by
    /// [`ElispHost::print_preprocess`], not yet printed"; `N` is "already printed
    /// as `#N=`, so print `#N#`". Populated before printing when `print-circle` is
    /// non-nil, empty otherwise. `RefCell` because the printer runs on `&self`.
    pub(crate) print_labels: RefCell<HashMap<u32, i64>>,
    /// print.c `print_number_index`: the next unused `#N=` label. Assigned during
    /// [`ElispHost::print_preprocess`], not while printing.
    pub(crate) print_next_label: Cell<usize>,
    /// print.c `being_printed[PRINT_CIRCLE]`: the chain of objects currently open,
    /// indexed by print nesting depth. With `print-circle` nil, print.c scans
    /// `being_printed[0 .. print_depth)` for `BASE_EQ (obj, …)` and emits `#I`
    /// instead of recursing — that is how a self-referencing *car* (or vector,
    /// record or hash-table slot) terminates: `(let ((x (list 1))) (setcar x x) x)`
    /// prints `(#0)`. Only an aggregate can occupy an index below the current
    /// depth (print.c writes a scalar's slot and decrements `print_depth` again
    /// immediately), and every elisprs aggregate is a `Value::Obj`, so the slot
    /// holds an arena id and `None` stands for "not a heap object" — comparing ids
    /// is `BASE_EQ` restricted to the cases that can ever match.
    pub(crate) print_being: RefCell<Vec<Option<u32>>>,
    /// `Vprint_circle` sampled once at the top of a `print` call. print.c re-reads
    /// the global at every object; caching it keeps the per-object cost to a `Cell`
    /// read while preserving the branch it selects — the `being_printed` scan *and*
    /// the `PRINT_CIRCLE` depth ceiling live inside `if (NILP (Vprint_circle))`, so
    /// with the label table on a 250-deep nest prints instead of signalling.
    pub(crate) print_circle_on: Cell<bool>,
    /// `Vprint_gensym` sampled once at the top of a `print` call: an uninterned
    /// symbol prints with a `#:` prefix and, under `print-circle`, becomes a
    /// label candidate (print.c `PRINT_CIRCLE_CANDIDATE_P`).
    pub(crate) print_gensym_on: Cell<bool>,
    /// The global buffer registry. Index 0 is the default buffer (`*scratch*`).
    /// Slots are never removed — `kill-buffer` marks a buffer dead (`name: None`)
    /// so its index (and any live buffer object referencing it) stays valid.
    pub(crate) buffers: Vec<EditBuffer>,
    /// buffer.c's always-local per-buffer slots (`buffer_local_flags` of -1 in
    /// `init_buffer_once`): every buffer has its own value from birth, so
    /// `local-variable-p` is t in a fresh buffer and `kill-local-variable` leaves
    /// them alone. Each entry is the symbol and the value a new buffer starts with.
    pub(crate) always_local: Vec<(u32, SlotInit)>,
    /// Index into `buffers` of the current buffer (`current-buffer`/`set-buffer`).
    pub(crate) current: usize,
    /// xdisp.c `noninteractive_need_newline`: stdout has been written since the
    /// last `message`, so the next one owes stderr a leading newline. See
    /// [`ElispHost::emit`] and the `message` builtin.
    pub(crate) need_newline: bool,
    /// Index into `buffers` of the reserved ` *load*` slot — the buffer `load`
    /// reads the top-level script through (see [`ElispHost::open_load_buffer`]).
    /// Dead until a file is loaded, so `elisp -e` (which models `emacs --eval`)
    /// still reports only the three startup buffers.
    pub(crate) load_buf: usize,
    /// Text properties for strings. `Value::Str` is an `Arc<String>` value with no
    /// room for interval storage, so a propertized string's per-char plists live in
    /// this side table keyed by the `Arc`'s pointer identity. The stored `Weak`
    /// guards against pointer reuse: a lookup only trusts the entry when the weak
    /// still upgrades to the same allocation (a freed-then-reused address fails to
    /// upgrade → treated as unpropertized). Properties therefore travel with cheap
    /// `Arc` clones (`eq` strings) exactly like Emacs, but are lost across `concat`/
    /// `substring` (which mint fresh allocations) unless re-registered explicitly.
    pub(crate) string_props: HashMap<usize, StrProps>,
    /// Free-variable sets per closure TEMPLATE handle — the analysis
    /// [`Self::trim_lex`] runs, memoized so a `lambda` evaluated in a loop pays
    /// for it once. Derived from the template's source, so it is never
    /// serialized: a cache hit recomputes it on the first instantiation.
    pub(crate) closure_free: HashMap<u32, Rc<std::collections::HashSet<u32>>>,
    /// The `eval` walk's expanded `(lambda ...)` forms (by cons handle) and
    /// the body each had as written; the compiler moves it into the
    /// template's [`ClosureSrc::raw_body`] when it lowers that form.
    pub(crate) eval_lambda_raw: HashMap<u32, Vec<Value>>,
    /// `(defun|defmacro NAME ARGLIST . BODY)` forms with a `declare` that were
    /// expanded before the prelude defined the declaration bridge; the prelude
    /// replays their declarations once it exists (`--early-declarations--`).
    pub(crate) early_declarations: Vec<Value>,
    /// The interactive specs of the primitives that are commands (the
    /// `intspec` of a C `DEFUN`), keyed by the subr object's handle.
    pub(crate) subr_intspecs: HashMap<u32, Value>,
    /// Symbols a `compiler-macro` property has been put on.
    ///
    /// [`macroexpand_all`] has to ask whether a call's head has one, and the
    /// property lives in an elisp plist — so asking costs an elisp call, on
    /// every call form in every file. This set is the cheap pre-filter: the one
    /// place the property is written (`function-put`, prelude) records the
    /// handle here, so the elisp lookup only happens for a head that really has
    /// one. Derived state, never serialized; the prelude re-registers on a cold
    /// run and a warm one inherits the compiled expansions already made.
    pub(crate) compiler_macros: std::collections::HashSet<u32>,
    /// The one shared empty string object. Emacs allocates `empty_unibyte_string`
    /// once (alloc.c) and every zero-length string IS that object, so
    /// `(eq "" (make-string 0 ?a))` is `t`. Allocated in the built-in arena
    /// prefix, so the handle is identical on the cache-hit and cache-miss paths
    /// and is never serialized as user heap. Nothing can mutate it: `aset` on a
    /// zero-length string is `args-out-of-range` and `clear-string` is a no-op.
    pub(crate) empty_string: Value,
    /// The one shared empty vector. alloc.c `zero_vector` is allocated once and
    /// every zero-length vector IS that object, so `(eq (vector) [])` is `t`.
    /// Same placement and immutability argument as `empty_string`: `aset` on it
    /// is `args-out-of-range` and `fillarray` touches nothing.
    pub(crate) empty_vector: Value,
    /// OClosure metadata, keyed by the closure object's arena handle. An OClosure
    /// (`oclosure.el`) is an ordinary [`Obj::Closure`] that also carries a *type*
    /// symbol and an ordered list of *slot* symbol handles. The slot *values* are
    /// not stored here — they live in the closure's captured lexical env (the same
    /// storage the closure body reads), so `oclosure--set` and a body `setq` stay
    /// mutually visible, exactly as Emacs stores oclosure slots in the closure's
    /// env alist. This side table (rather than a field on `Obj::Closure`) keeps the
    /// compiler's closure-template construction untouched. Session-local: not part
    /// of the AOT heap image (oclosure-heavy libraries load at runtime).
    pub(crate) oclosure_meta: HashMap<u32, OClosureMeta>,
    /// Registered AOP pattern-intercepts (elisprs extension, ported from zshrs's
    /// `src/extensions/intercepts.rs`). This is the GLOB/pattern-matching advice
    /// layer — distinct from elisp's per-symbol nadvice (`advice-add`): one
    /// registration fires across every symbol whose name matches a glob such as
    /// `"forward-*"`, `"_*"`, or `"all"`, with before/after/around timing and a
    /// `proceed` protocol. Fired from [`call_function`]. Runtime-only (never
    /// serialized). See [`crate::intercepts`].
    pub(crate) intercepts: Vec<crate::intercepts::Intercept>,
    /// Symbols that elisp-level `fset`/`defalias` has pointed at a **subr**.
    ///
    /// Such a symbol has shown it can change what kind of function it names, so
    /// a later call to it gets the pre-argument arity guard even when the cell
    /// live at compile time would accept the count: the next `fset` can retarget
    /// it at a narrower subr before the call runs, and Emacs checks the cell
    /// that is live at the call. Only the `fset` subr records here — `defun`
    /// lowers to the `FSET` op and `defsubr` installs the builtins, so neither
    /// puts an ordinary definition in this set. Runtime-only (never serialized).
    pub(crate) subr_aliased: std::collections::HashSet<u32>,
    /// Re-entrancy guard for the intercept layer: set while an advice body (or a
    /// proceeded original) runs so nested function calls dispatch normally instead
    /// of re-triggering intercepts (prevents infinite recursion when advice calls
    /// a function its own pattern matches).
    pub(crate) intercept_active: bool,
    /// The callee + argument values of the function currently under an `around`
    /// intercept, so `(intercept-proceed)` can run the original. `None` outside an
    /// active around advice.
    pub(crate) intercept_current: Option<(Value, Vec<Value>)>,
    /// Set by `(intercept-proceed)` — records that an around advice ran the
    /// original command (mirrors zshrs's `__intercept_proceed` flag).
    pub(crate) intercept_proceeded: bool,
    /// Source line (1-based) of each list form, keyed by the head cons's arena
    /// handle. Populated by the reader; read by the compiler in debug mode to
    /// emit the DAP statement markers that drive line-level breakpoints/stepping.
    /// Session-local (never serialized); a fresh `reset_host` clears it.
    pub(crate) form_lines: HashMap<u32, u32>,
}

/// What [`ElispHost::closure_parts`] reports: `(is_macro, dynamic, arglist,
/// body, captures)`, where `captures` is the lexical chain innermost-first as
/// `(symbol-handle, value)`, a local special declaration's value being None.
/// This is exactly the `#[ARGLIST BODY ENV]` structure Emacs's `equal` walks
/// for an interpreted closure.
pub type ClosureParts = (bool, bool, Value, Vec<Value>, Vec<(u32, Option<Value>)>);

/// A closure's printable source: the arglist as written and the body forms.
#[derive(Default)]
pub struct ClosureSrc {
    pub arglist: Value,
    pub body: Vec<Value>,
    /// For a `lambda` reached by the `eval` walk: its body as written, before
    /// any expansion. eval.c `Ffunction` hands that unexpanded body to
    /// `cconv-make-interpreted-closure`, which keeps it when no lexical
    /// variable is in scope and otherwise replaces it by its `macroexpand-all`
    /// — see `eval_closure_source`.
    pub raw_body: Option<Vec<Value>>,
}

/// A closure's source body split the way eval.c `Ffunction` splits a lambda
/// before `make-interpreted-closure` stores it: a leading string is the
/// docstring unless it is the only form, an `(interactive ...)` form after
/// that is the interactive spec, and an empty remainder becomes `(nil)`.
pub struct ClosureSlots {
    pub body: Vec<Value>,
    pub doc: Option<Value>,
    pub iform: Option<Value>,
}

impl ClosureSrc {
    pub fn slots(&self, h: &ElispHost) -> ClosureSlots {
        let mut body: &[Value] = &self.body;
        let mut doc = None;
        if body.len() > 1 && h.is_string(&body[0]) {
            doc = Some(body[0].clone());
            body = &body[1..];
        }
        let mut iform = None;
        if let Some(first) = body.first() {
            let is_interactive = match h.obj(first) {
                Some(Obj::Cons(head, _)) => h.sym_name(head).as_deref() == Some("interactive"),
                _ => false,
            };
            if is_interactive {
                iform = Some(first.clone());
                body = &body[1..];
            }
        }
        let body = if body.is_empty() {
            vec![Value::Undef]
        } else {
            body.to_vec()
        };
        ClosureSlots { body, doc, iform }
    }
}

/// The cells of a symbol that the *running* file may mutate, snapshotted before
/// it runs so a cached heap image can roll them back (the cached chunks replay
/// every one of them on a hit). `special` is absent on purpose: the compiler sets
/// it, and a cache hit does not compile.
/// The prelude-built per-buffer state a cache hit has to restore; see
/// [`ElispHost::export_buffer_state`].
#[derive(Clone, Default, Serialize, Deserialize)]
pub struct BufferState {
    pub always_local: Vec<(u32, SlotInit)>,
    /// One entry per buffer slot, by index: `(variable handle, binding)`.
    pub locals: Vec<Vec<(u32, Option<Value>)>>,
}

#[derive(Clone, Default, Serialize, Deserialize)]
pub struct SymbolBaseline {
    pub value: Option<Value>,
    pub function: Option<Value>,
    pub buffer_local_auto: bool,
    pub alias_of: Option<u32>,
}

/// Type + slot layout attached to an [`Obj::Closure`] to make it an OClosure.
/// `ty` is the type symbol's handle; `slots` are the slot symbols' handles in
/// declaration order (index 0 = first slot). Values live in the closure's env.
#[derive(Clone)]
pub struct OClosureMeta {
    pub ty: u32,
    pub slots: Vec<u32>,
}

/// A string's text-property entry: the weak handle guarding against a reused
/// pointer, one plist per character, and the recorded interval boundaries.
pub(crate) type StrProps = (Weak<String>, Vec<Value>, Vec<u32>);

/// An editing buffer: a char vector, a 1-based point, narrowing bounds, the mark,
/// plus the buffer-local variable slots and the local keymap slot. Positions are
/// 1-based (`point-min` = `begv`, `point-max` = `zv`). `begv`/`zv`/`mark`/the
/// save stacks track edits with Emacs marker semantics (see
/// [`ElispHost::cur_insert`]/[`ElispHost::cur_delete`]).
#[derive(Default, Clone)]
pub struct EditBuffer {
    /// The buffer's name, or `None` once killed (the slot is retained so existing
    /// buffer objects keep resolving; `buffer-live-p` reads this).
    pub name: Option<String>,
    /// `inhibit_buffer_hooks`: made with INHIBIT-BUFFER-HOOKS, so killing it
    /// runs neither `kill-buffer-query-functions` nor `kill-buffer-hook`.
    pub inhibit_hooks: bool,
    /// This buffer's own `Obj::Buffer` handle, allocated once so buffer objects
    /// are `eq`-stable. `Value::Undef` only during initial construction.
    pub self_obj: Value,
    pub text: Vec<char>,
    /// Text-property plists, one per character (parallel to `text`, same length).
    /// Each entry is a plist `Value` (`Value::Undef` = no properties). Kept in sync
    /// with every `cur_insert`/`cur_delete` (inserted chars get nil props — plain
    /// `insert` does not inherit, matching Emacs).
    pub props: Vec<Value>,
    /// Recorded interval boundaries of `props` (0-based char indices; see
    /// [`crate::textprop`]).
    pub prop_bounds: Vec<u32>,
    /// Live markers pointing into this buffer, adjusted on every edit. Shared
    /// (`Rc`) with the corresponding `Obj::Marker`; a marker is removed here when
    /// it is re-pointed (`set-marker`) elsewhere or detached.
    pub markers: Vec<Rc<RefCell<MarkerData>>>,
    /// Overlays in this buffer, in creation order — which is the order
    /// `overlays-in` reports them in.
    pub overlays: Vec<Rc<RefCell<OverlayData>>>,
    /// Point: 1-based, always kept within `[begv, zv]`.
    pub point: usize,
    /// Narrowing lower bound (`point-min`); 1 when un-narrowed. Marker-like with
    /// insertion-type nil.
    pub begv: usize,
    /// Narrowing upper bound (`point-max`); `text.len()+1` when un-narrowed.
    /// Marker-like with insertion-type t (text inserted at `zv` extends the region).
    pub zv: usize,
    /// The buffer's mark marker (`BVAR (b, mark)`), allocated on first use;
    /// `Value::Undef` until then. It is an ordinary marker in `markers`, so
    /// edits adjust it like any other.
    pub mark: Value,
    /// `save-excursion` point markers (insertion-type nil), a per-buffer LIFO
    /// stack: unwind-protect guarantees strict nesting, so the top entry is always
    /// the matching one.
    pub se_markers: Vec<usize>,
    /// `save-restriction` saved `(begv, zv)` pairs, adjusted for edits inside the
    /// body so the restored restriction tracks intervening insertions/deletions.
    pub restrict_stack: Vec<(usize, usize)>,
    /// Buffer-local variable bindings. `Some(v)` is a bound local; `None` is a
    /// *void* local (created by `make-local-variable` on a void variable — reading
    /// it still signals `void-variable`, but `local-variable-p` is non-nil). Key
    /// absence means the variable is not local in this buffer.
    pub locals: IndexMap<u32, Option<Value>>,
    /// The buffer's local keymap slot (`use-local-map`/`current-local-map`).
    pub local_map: Value,
    /// `MODIFF`, `CHARS_MODIFF`, `SAVE_MODIFF` and `AUTOSAVE_MODIFF`.
    pub mods: ModCounts,
    /// Whether the buffer has an interval tree: set by the first text-property
    /// change, cleared when all of its text is deleted
    /// (`adjust_intervals_for_deletion`). `set-text-properties` with nil
    /// PROPERTIES answers nil and changes nothing when there is none.
    pub has_intervals: bool,
    /// Where the buffer sits in `(buffer-list)`: buffers are listed by
    /// ascending key; a new buffer takes the next key (the end), `record_buffer`
    /// a key before every other (the front), `bury-buffer` one after.
    pub list_order: i64,
}

/// What a new buffer's always-local slot starts as (buffer.c `reset_buffer`,
/// `reset_buffer_local_variables` and `Fget_buffer_create`).
#[derive(Clone, Serialize, Deserialize)]
pub enum SlotInit {
    /// A fixed value, whatever the default has since been set to.
    Value(Value),
    /// `bset_directory (b, BVAR (current_buffer, directory))`: the creating
    /// buffer's value.
    Inherit,
    /// `bset_undo_list (b, SREF (name, 0) != ' ' ? Qnil : Qt)`: undo is off in
    /// a buffer whose name starts with a space.
    UndoList,
}

/// A buffer's modification counters (buffer.h). A text change of N characters
/// advances `modiff` by `modiff_incr` (`floor(log2 N) + 1`) and sets
/// `chars_modiff` to it; a text-property change advances `modiff` by 1 only.
/// The buffer is modified while `save_modiff < modiff`.
#[derive(Clone, Copy)]
pub struct ModCounts {
    pub modiff: i64,
    pub chars_modiff: i64,
    pub save_modiff: i64,
    pub autosave_modiff: i64,
}

impl Default for ModCounts {
    /// `Fget_buffer_create` starts every counter at 1, and `reset_buffer` the
    /// auto-save counter at 0.
    fn default() -> Self {
        ModCounts {
            modiff: 1,
            chars_modiff: 1,
            save_modiff: 1,
            autosave_modiff: 0,
        }
    }
}

impl ModCounts {
    /// `modiff_incr` (lisp.h) for a change of LEN characters.
    pub fn incr(&mut self, len: usize) {
        self.modiff += if len == 0 { 1 } else { len.ilog2() as i64 + 1 };
    }
}

/// Adjust a marker-like position `m` for an insertion of `len` chars at `pos`.
/// `advance_at_pos` selects insertion-type t (a marker exactly at `pos` moves
/// past the inserted text) vs nil (it stays before it).
fn adj_ins(m: &mut usize, pos: usize, len: usize, advance_at_pos: bool) {
    if *m > pos || (advance_at_pos && *m == pos) {
        *m += len;
    }
}

/// Adjust a marker-like position `m` for a deletion of the region `[from, to)`.
fn adj_del(m: &mut usize, from: usize, to: usize) {
    if *m >= to {
        *m -= to - from;
    } else if *m > from {
        *m = from;
    }
}

/// Result of the most recent `string-match`, in *character* positions (elisp
/// indexes strings by character, not byte).
#[derive(Clone, Debug)]
pub struct MatchData {
    pub subject: String,
    /// `spans[0]` is the whole match; `spans[n]` is capture group `n`. A group
    /// that did not participate is `None`.
    pub spans: Vec<Option<(usize, usize)>>,
    /// True if the last match was a buffer search: spans are 1-based buffer
    /// positions and `match-string` reads from `subject` accordingly.
    pub from_buffer: bool,
    /// The buffer slot a buffer match was made in (`last_thing_searched`), which
    /// `match-data` hands back as markers into it, or appends under INTEGERS.
    pub buffer: Option<usize>,
}

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

impl ElispHost {
    pub fn new() -> Self {
        let mut h = ElispHost {
            arena: Vec::new(),
            windows: Vec::new(),
            frames: Vec::new(),
            window_configs: Vec::new(),
            selected_window: 0,
            selected_frame: 0,
            window_count: 0,
            window_select_count: 0,
            buffer_order_seq: 0,
            last_window_start: HashMap::new(),
            point_before_last_command_or_undo: None,
            buffer_before_last_command_or_undo: None,
            obarray: HashMap::new(),
            builtin_count: 0,
            prelude_end: 0,
            specstack: Vec::new(),
            lex: None,
            dynamic_binding: false,
            eval_depth: 0,
            max_depth_sym: None,
            intrinsic_macro_cells: HashMap::new(),
            compiling_form: false,
            compile_interned: HashSet::new(),
            frame_stack: Vec::new(),
            error: None,
            pending_throw: None,
            catch_tags: Vec::new(),
            pending_error: None,
            match_data: None,
            stdout_last: '\0',
            capture: None,
            stdin: StdinSource::Process,
            print_overflow: Cell::new(false),
            print_backquote_depth: Cell::new(0),
            print_labels: RefCell::new(HashMap::new()),
            print_next_label: Cell::new(1),
            print_being: RefCell::new(Vec::new()),
            print_circle_on: Cell::new(false),
            print_gensym_on: Cell::new(false),
            buffers: vec![EditBuffer {
                overlays: Vec::new(),
                name: Some("*scratch*".to_string()),
                self_obj: Value::Undef,
                text: Vec::new(),
                props: Vec::new(),
                prop_bounds: Vec::new(),
                markers: Vec::new(),
                point: 1,
                begv: 1,
                zv: 1,
                mark: Value::Undef,
                se_markers: Vec::new(),
                restrict_stack: Vec::new(),
                locals: IndexMap::new(),
                local_map: Value::Undef,
                mods: ModCounts::default(),
                has_intervals: false,
                list_order: 0,
                inhibit_hooks: false,
            }],
            always_local: Vec::new(),
            current: 0,
            need_newline: false,
            load_buf: 0, // fixed below, once the slot exists
            string_props: HashMap::new(),
            closure_free: HashMap::new(),
            eval_lambda_raw: HashMap::new(),
            early_declarations: Vec::new(),
            subr_intspecs: HashMap::new(),
            compiler_macros: std::collections::HashSet::new(),
            empty_string: Value::Undef, // fixed below, once the arena exists
            empty_vector: Value::Undef,
            oclosure_meta: HashMap::new(),
            intercepts: Vec::new(),
            subr_aliased: std::collections::HashSet::new(),
            intercept_active: false,
            intercept_current: None,
            intercept_proceeded: false,
            form_lines: HashMap::new(),
        };
        crate::builtins::install(&mut h);
        // The default buffer's own object handle (allocated after the arena
        // exists, before `builtin_count` is fixed so it stays in the stable
        // built-in prefix and is never serialized as user heap).
        // The one shared empty string object (see `ElispHost::empty_string`),
        // allocated in the built-in prefix so its handle is stable across a
        // cache hit and it is never serialized as user heap.
        h.empty_string = h.alloc(Obj::Str(Arc::new(String::new())));
        h.empty_vector = h.alloc(Obj::Vector(Vec::new()));
        let scratch = h.alloc(Obj::Buffer(0));
        h.buffers[0].self_obj = scratch;
        // The other two buffers a bare `emacs -Q --batch` starts with, in the
        // order `buffer-list` reports them: `("*scratch*" " *Minibuf-0*"
        // "*Messages*")`. They are not decoration — `(get-buffer "*Messages*")`
        // answers a live buffer, `message` has somewhere to append, and the
        // leading space on ` *Minibuf-0*` is what marks it hidden. Created here
        // so they land in the built-in prefix alongside `*scratch*` and are
        // never serialized as user heap.
        let minibuf = h.new_buffer(" *Minibuf-0*".to_string());
        let minibuf = h.buffer_slot(&minibuf).expect("minibuffer slot");
        crate::window::init(&mut h, 0, minibuf);
        h.new_buffer("*Messages*".to_string());
        // The ` *load*` slot, reserved here (in the built-in prefix) but left dead
        // so it stays invisible to `buffer-list` until a file is actually loaded.
        // `emacs -Q --batch --eval` reports three buffers; `emacs -Q --batch -l
        // FILE` reports four, because `load` reads the file through a buffer of
        // its own (mule.el `load-with-code-conversion`: `(generate-new-buffer
        // " *load*")`). Reserving the slot up front rather than allocating it in
        // `eval_file` is what keeps the bytecode cache honest: the arena handle is
        // below `builtin_count`, so it is identical on the cache-hit and
        // cache-miss paths and is never serialized into the heap image.
        let load_slot = h.new_buffer(" *load*".to_string());
        h.load_buf = h.buffer_slot(&load_slot).expect("reserved load slot");
        h.buffers[h.load_buf].name = None;
        // The global obarray object — the value of the `obarray` variable. Its
        // symbol set lives in `self.obarray` (the HashMap), so its own `symbols`
        // map stays empty and `global` routes every lookup there. Allocated in
        // the built-in prefix so it is never serialized as user heap.
        let global_ob = h.alloc(Obj::Obarray(ObarrayData {
            symbols: HashMap::new(),
            global: true,
        }));
        if let Value::Obj(sid) = h.intern("obarray") {
            if let Some(Obj::Symbol(s)) = h.arena.get_mut(sid as usize) {
                s.value = Some(global_ob);
                s.special = true;
            }
        }
        // buffer.c: every buffer is multibyte here (there is no
        // `set-buffer-multibyte`), and the variable is SYMBOL_NOWRITE, so a
        // `setq`, `let` or `set-default` of it is `setting-constant` (see
        // `constant_symbol_name`).
        if let Value::Obj(sid) = h.intern("enable-multibyte-characters") {
            if let Some(Obj::Symbol(s)) = h.arena.get_mut(sid as usize) {
                s.value = Some(Value::Bool(true));
                s.special = true;
            }
        }
        h.builtin_count = h.arena.len();
        h
    }

    // ── arena / interning ──
    pub fn alloc(&mut self, obj: Obj) -> Value {
        // Every zero-length vector is `zero_vector` (see `empty_vector`). The
        // first allocation, during construction, is the singleton itself.
        if let Obj::Vector(items) = &obj {
            if items.is_empty() && !matches!(self.empty_vector, Value::Undef) {
                return self.empty_vector.clone();
            }
        }
        let id = self.arena.len() as u32;
        self.arena.push(obj);
        Value::Obj(id)
    }

    // ── string objects ──
    //
    // An elisp string is an arena cell ([`Obj::Str`]); a bare `Value::Str` is a
    // TRANSIENT — the form a builtin builds its result in before it is promoted
    // at the call boundary, and the form `str_view` hands back for reading. The
    // accessors below take either, so a builtin that only reads text never has
    // to know which one it was given.

    /// The current text of `v`, if `v` is a string (cell or transient).
    pub fn str_text<'a>(&'a self, v: &'a Value) -> Option<&'a str> {
        match v {
            Value::Str(s) => Some(s.as_str()),
            Value::Obj(id) => match self.arena.get(*id as usize) {
                Some(Obj::Str(s)) => Some(s.as_str()),
                _ => None,
            },
            _ => None,
        }
    }

    /// The current text of `v` as a shared `Arc` — a refcount bump, not a copy.
    /// This is also the key `string_props` is stored under, so a caller that
    /// needs a string's properties must go through here rather than re-wrapping
    /// the text in a fresh `Arc`.
    pub fn str_arc(&self, v: &Value) -> Option<Arc<String>> {
        match v {
            Value::Str(s) => Some(Arc::clone(s)),
            Value::Obj(id) => match self.arena.get(*id as usize) {
                Some(Obj::Str(s)) => Some(Arc::clone(s)),
                _ => None,
            },
            _ => None,
        }
    }

    /// `v` viewed as a plain `Value::Str` when it is a string cell, so a
    /// `match` written against `Value::Str(..)` sees the cell's current text.
    /// Anything else (including a transient) comes back unchanged.
    ///
    /// The view is a refcount bump and is valid only until the string is
    /// written: it carries the text, not the identity. A builtin that STORES
    /// its argument (`cons`, `list`, `puthash`, `aset` into a vector) must store
    /// the original value, never the view, or the stored string would no longer
    /// be `eq` to the one the caller passed.
    pub fn str_view(&self, v: &Value) -> Value {
        match v {
            Value::Obj(id) => match self.arena.get(*id as usize) {
                Some(Obj::Str(s)) => Value::Str(Arc::clone(s)),
                _ => v.clone(),
            },
            _ => v.clone(),
        }
    }

    /// Whether `v` is a string — `stringp`.
    pub fn is_string(&self, v: &Value) -> bool {
        self.str_text(v).is_some()
    }

    /// Allocate a fresh elisp string object holding `s`.
    ///
    /// The empty string is the one shared object Emacs shares
    /// (`ElispHost::empty_string`); everything else gets its own cell, because
    /// two separately-built strings are never `eq` in Emacs.
    pub fn new_string(&mut self, s: impl Into<String>) -> Value {
        self.new_string_arc(Arc::new(s.into()))
    }

    /// [`Self::new_string`] for text that is already behind an `Arc` — keeps the
    /// allocation (and therefore any `string_props` entry keyed on it) intact.
    pub fn new_string_arc(&mut self, s: Arc<String>) -> Value {
        if s.is_empty() {
            return self.empty_string.clone();
        }
        self.alloc(Obj::Str(s))
    }

    /// [`Self::new_string`] that also hands back the `Arc` the fresh cell holds.
    ///
    /// `string_props` is keyed by that `Arc`, so a caller that carries text
    /// properties onto the string it just built needs it. Looking it up again
    /// through [`Self::str_arc`] would work but costs a second arena probe and
    /// invites the caller to key on a *re-wrapped* `Arc`, which would silently
    /// address a different (empty) property entry.
    pub fn new_string_keyed(&mut self, s: String) -> (Value, Arc<String>) {
        let v = self.new_string(s);
        // Read the `Arc` back OUT of the cell rather than handing back the one
        // that went in: an empty string is the one shared `empty_string` object,
        // whose `Arc` is not the caller's.
        let arc = self.str_arc(&v).expect("new_string yields a string cell");
        (v, arc)
    }

    /// Promote a transient `Value::Str` into a string object. Values that are
    /// already objects (and non-strings) pass through untouched, so this is
    /// idempotent and safe to apply at every boundary a value crosses.
    pub fn promote_string(&mut self, v: Value) -> Value {
        match v {
            Value::Str(s) => self.new_string_arc(s),
            other => other,
        }
    }

    /// Replace a string object's text in place. Every reference to the object
    /// sees the new text — that is the whole point of the cell.
    ///
    /// The text-property entry travels with it: `string_props` is keyed by the
    /// `Arc` allocation, and a write installs a fresh one, so without the
    /// re-key `(aset (propertize "abc" 'p 1) 0 ?z)` would drop the property that
    /// Emacs keeps (`#("zbc" 0 3 (p 1))`).
    ///
    /// Answers `false` when `v` is not a string cell (a transient cannot be
    /// written through — there is nothing shared to write to).
    pub fn set_string_text(&mut self, v: &Value, text: String) -> bool {
        let Value::Obj(id) = v else { return false };
        let Some(Obj::Str(old)) = self.arena.get(*id as usize) else {
            return false;
        };
        let old_key = Arc::as_ptr(old) as usize;
        let fresh = Arc::new(text);
        let new_key = Arc::as_ptr(&fresh) as usize;
        if let Some((_, props, bounds)) = self.string_props.remove(&old_key) {
            self.string_props
                .insert(new_key, (Arc::downgrade(&fresh), props, bounds));
        }
        self.arena[*id as usize] = Obj::Str(fresh);
        true
    }

    /// The only way to make an elisp integer: a value inside fixnum range is a
    /// `Value::Int`, anything else a heap `Obj::Bignum`.
    ///
    /// Normalizing here is what lets the rest of the interpreter stay simple —
    /// `eql`, `equal`, `sxhash` and the printer never have to consider a bignum
    /// that happens to hold a small value, because one cannot exist.
    pub fn make_integer(&mut self, n: BigInt) -> Value {
        use num_traits::ToPrimitive;
        match n.to_i64() {
            Some(i) if (MOST_NEGATIVE_FIXNUM..=MOST_POSITIVE_FIXNUM).contains(&i) => Value::Int(i),
            _ => self.alloc(Obj::Bignum(n)),
        }
    }

    /// The integer value of `v`, if it is one (fixnum or bignum).
    pub fn as_bigint(&self, v: &Value) -> Option<BigInt> {
        match v {
            Value::Int(n) => Some(BigInt::from(*n)),
            Value::Obj(_) => match self.obj(v) {
                Some(Obj::Bignum(b)) => Some(b.clone()),
                _ => None,
            },
            _ => None,
        }
    }

    /// Whether `v` is an integer (fixnum or bignum) — elisp `integerp`.
    pub fn is_integer(&self, v: &Value) -> bool {
        matches!(v, Value::Int(_)) || matches!(self.obj(v), Some(Obj::Bignum(_)))
    }

    /// Whether `v` is a number — elisp `numberp`.
    pub fn is_number(&self, v: &Value) -> bool {
        matches!(v, Value::Int(_) | Value::Float(_)) || self.is_bignum(v)
    }

    /// Whether `v` is specifically a bignum — elisp `bignump`.
    pub fn is_bignum(&self, v: &Value) -> bool {
        matches!(self.obj(v), Some(Obj::Bignum(_)))
    }

    /// Apply a fusevm arithmetic/comparison op to two elisp numbers.
    ///
    /// Reached only from the numeric hook, i.e. only for the operands fusevm
    /// could not compute natively. Integer arithmetic is exact (promoting to a
    /// bignum as needed); any float operand makes the result a float, as in
    /// Emacs. Comparison is exact for *every* pair — including an integer
    /// against a float, which Emacs decides on real values and not on `f64`
    /// images (see [`num_cmp`]).
    pub fn apply_num_op(&mut self, op: NumOp, a: Num, b: Num) -> Result<Value, String> {
        use NumOp::*;
        // Comparisons first: they answer a bool for any pair, and no comparison
        // may detour through `f64` — not integer/integer (which would call 2^62
        // and 2^62+1 equal) and not integer/float either, which is why
        // [`num_cmp`] compares exact values throughout.
        if matches!(op, Lt | Gt | Le | Ge | Eq | Ne) {
            let ord = match num_cmp(&a, &b) {
                Some(o) => o,
                // A NaN operand: every comparison is false, `/=` is true.
                None => return Ok(Value::Bool(matches!(op, Ne))),
            };
            let yes = match op {
                Lt => ord.is_lt(),
                Gt => ord.is_gt(),
                Le => ord.is_le(),
                Ge => ord.is_ge(),
                Eq => ord.is_eq(),
                _ => ord.is_ne(),
            };
            return Ok(Value::Bool(yes));
        }

        match (a, b) {
            (Num::Int(x), Num::Int(y)) => {
                let r = match op {
                    Add => x + y,
                    Sub => x - y,
                    Mul => x * y,
                    Neg => -x,
                    Mod => {
                        if y == BigInt::from(0) {
                            return Err("arith-error".to_string());
                        }
                        x % y
                    }
                    // `/` and `expt` are elisp builtins, not lowered to VM ops, so
                    // the VM never asks us for them with integer operands.
                    Div | Pow => return Ok(Value::Float(bigint_to_f64(&x) / bigint_to_f64(&y))),
                    Lt | Gt | Le | Ge | Eq | Ne => unreachable!("handled above"),
                };
                Ok(self.make_integer(r))
            }
            // Float-contagious, exactly like Emacs.
            (a, b) => {
                let (x, y) = (a.to_f64(), b.to_f64());
                Ok(Value::Float(match op {
                    Add => x + y,
                    Sub => x - y,
                    Mul => x * y,
                    Neg => -x,
                    Div => x / y,
                    Mod => x % y,
                    Pow => x.powf(y),
                    Lt | Gt | Le | Ge | Eq | Ne => unreachable!("handled above"),
                }))
            }
        }
    }
    pub fn intern(&mut self, name: &str) -> Value {
        if let Some(&id) = self.obarray.get(name) {
            // The compiler RESOLVING a name claims it exactly as creating it
            // does: the chunk that comes out references this handle, and a warm
            // hit does not compile, so the image has to carry the symbol
            // interned or the replay hands the call site an orphan.
            //
            // Only creation was recorded before, and elisprs compiles and runs
            // form by form — so a name a RUNNING form interned first (`(setf
            // point3--z)`, which `oclosure-define` installs at run time) and a
            // LATER form compiled against was written out uninterned. On the
            // warm hit the restored symbol was not the obarray's, the replayed
            // `oclosure-define` defined the function on the obarray's one, and
            // the call site answered `void-function (setf point3--z)` —
            // examples/oclosure.el passed cold and failed warm.
            //
            // The `zqleak` leak this flag exists to stop is untouched: a symbol
            // a run interns out of DATA is only claimed here if the compiler
            // asked for that name too, which means the file spells it.
            if self.compiling_form {
                self.compile_interned.insert(id);
            }
            return Value::Obj(id);
        }
        let id = self.arena.len() as u32;
        // `intern_driver` (lread.c) gives a `:`-prefixed name interned in the
        // standard obarray the keyword treatment: the symbol becomes its own
        // value, is declared special, and its value cell is made constant. That
        // is why `(symbol-value :a)` is `:a` and `(boundp :a)` is `t` for a
        // keyword nothing has ever mentioned before. The treatment is keyed on
        // the obarray, so `make_symbol` and the private-obarray `intern` below
        // deliberately do not apply it — a `:`-spelled symbol outside the
        // standard obarray is an ordinary, writable, unbound symbol.
        let keyword = name.starts_with(':');
        self.arena.push(Obj::Symbol(SymbolData {
            name: name.to_string(),
            value: keyword.then_some(Value::Obj(id)),
            function: None,
            special: keyword,
            buffer_local_auto: false,
            alias_of: None,
        }));
        self.obarray.insert(name.to_string(), id);
        if self.compiling_form {
            self.compile_interned.insert(id);
        }
        Value::Obj(id)
    }
    /// Allocate a fresh *uninterned* symbol: it carries `name` but is not put in
    /// the obarray, so each call yields a distinct object (`make-symbol`).
    pub fn make_symbol(&mut self, name: &str) -> Value {
        self.alloc(Obj::Symbol(SymbolData {
            name: name.to_string(),
            value: None,
            function: None,
            special: false,
            buffer_local_auto: false,
            alias_of: None,
        }))
    }
    pub fn obj(&self, v: &Value) -> Option<&Obj> {
        match v {
            Value::Obj(id) => self.arena.get(*id as usize),
            _ => None,
        }
    }
    // ── first-class obarrays (`obarray-make` and friends) ──
    /// `(intern NAME OB)` into the private obarray at arena id `ob_id`: return the
    /// existing interned symbol if present, else create a fresh symbol (like
    /// `make-symbol`) and record it. Mirrors C `intern`, which allocates a new
    /// symbol on a miss.
    pub fn obarray_intern(&mut self, ob_id: u32, name: &str) -> Value {
        if let Some(Obj::Obarray(d)) = self.arena.get(ob_id as usize) {
            if let Some(&sid) = d.symbols.get(name) {
                return Value::Obj(sid);
            }
        }
        let sym = self.make_symbol(name);
        if let Value::Obj(sid) = sym {
            if let Some(Obj::Obarray(d)) = self.arena.get_mut(ob_id as usize) {
                d.symbols.insert(name.to_string(), sid);
            }
        }
        sym
    }
    /// `(intern-soft NAME OB)` into the private obarray at arena id `ob_id`: the
    /// interned symbol if present, else `nil` (`Value::Undef`).
    pub fn obarray_intern_soft(&self, ob_id: u32, name: &str) -> Value {
        match self.arena.get(ob_id as usize) {
            Some(Obj::Obarray(d)) => d
                .symbols
                .get(name)
                .map(|&sid| Value::Obj(sid))
                .unwrap_or(Value::Undef),
            _ => Value::Undef,
        }
    }
    /// `(unintern NAME OB)` from the private obarray at arena id `ob_id`: remove
    /// the mapping, returning whether a symbol was actually removed.
    pub fn obarray_unintern(&mut self, ob_id: u32, name: &str) -> bool {
        match self.arena.get_mut(ob_id as usize) {
            Some(Obj::Obarray(d)) => d.symbols.remove(name).is_some(),
            _ => false,
        }
    }
    /// `(unintern NAME)` from the global obarray: drop NAME's mapping (the symbol
    /// object itself survives in the arena but is no longer interned), returning
    /// whether it was present.
    pub fn obarray_unintern_global(&mut self, name: &str) -> bool {
        self.obarray.remove(name).is_some()
    }
    /// The symbol objects interned in an obarray (private map values, or the
    /// global obarray's), for `mapatoms`.
    pub fn obarray_symbols(&self, ob: &Value) -> Vec<Value> {
        match self.obj(ob) {
            Some(Obj::Obarray(d)) if d.global => {
                self.obarray.values().map(|&id| Value::Obj(id)).collect()
            }
            Some(Obj::Obarray(d)) => d.symbols.values().map(|&id| Value::Obj(id)).collect(),
            _ => Vec::new(),
        }
    }
    /// Public form of `Self::sym_handle`: the arena handle of `v` if it is a
    /// symbol object, else `None`. Used by the OClosure builtins.
    pub fn as_sym_handle(&self, v: &Value) -> Option<u32> {
        self.sym_handle(v)
    }
    fn sym_handle(&self, v: &Value) -> Option<u32> {
        match v {
            Value::Obj(id) if matches!(self.arena.get(*id as usize), Some(Obj::Symbol(_))) => {
                Some(*id)
            }
            _ => None,
        }
    }
    pub fn sym_name(&self, v: &Value) -> Option<String> {
        match self.obj(v) {
            Some(Obj::Symbol(s)) => Some(s.name.clone()),
            _ => match v {
                Value::Bool(true) => Some("t".to_string()),
                _ if el_nil(v) => Some("nil".to_string()),
                _ => None,
            },
        }
    }
    /// True if the symbol object at `id` is the one the standard obarray holds
    /// under its own name — i.e. it was produced by `intern`, not `make-symbol`
    /// and not `(intern NAME PRIVATE-OBARRAY)`.
    fn interned_in_standard_obarray(&self, id: u32) -> bool {
        match &self.arena[id as usize] {
            Obj::Symbol(s) => self.obarray.get(&s.name) == Some(&id),
            _ => false,
        }
    }
    /// `(keywordp V)` — V is a symbol interned in the *standard* obarray whose
    /// name begins with `:`.
    ///
    /// The obarray is part of the test, not just the spelling: Emacs applies the
    /// keyword treatment in `intern_driver` only for `initial_obarray`, so
    /// `(keywordp (make-symbol ":u"))` and `(keywordp (intern ":u" (obarray-make)))`
    /// are both nil even though the names start with a colon. `:` itself is a
    /// keyword — there is no exception for the one-character name.
    pub fn is_keyword(&self, v: &Value) -> bool {
        match self.sym_handle(v) {
            Some(id) => match &self.arena[id as usize] {
                Obj::Symbol(s) => s.name.starts_with(':') && self.interned_in_standard_obarray(id),
                _ => false,
            },
            None => false,
        }
    }
    /// The name of the constant symbol `v` denotes, if writing its value cell is
    /// forbidden; None for every ordinary symbol.
    ///
    /// Emacs marks `nil`, `t`, and every standard-obarray keyword constant
    /// (`make_symbol_constant`), and `set_internal` — the single funnel under
    /// `set`, `setq`, `set-default`, `makunbound`, `let`, and
    /// `make-local-variable` — signals `setting-constant` for them. An
    /// uninterned symbol merely *named* "t" is not constant, so the check is on
    /// obarray identity rather than on the name alone.
    pub fn constant_symbol_name(&self, v: &Value) -> Option<String> {
        if matches!(v, Value::Bool(true)) {
            return Some("t".to_string());
        }
        if el_nil(v) {
            return Some("nil".to_string());
        }
        let id = self.sym_handle(v)?;
        let Obj::Symbol(s) = &self.arena[id as usize] else {
            return None;
        };
        // `enable-multibyte-characters` is buffer.c's SYMBOL_NOWRITE variable.
        let constant_name = s.name == "nil"
            || s.name == "t"
            || s.name.starts_with(':')
            || s.name == "enable-multibyte-characters";
        (constant_name && self.interned_in_standard_obarray(id)).then(|| s.name.clone())
    }
    /// `Err("setting-constant: NAME")` if `v` names a constant symbol.
    pub fn check_settable(&self, v: &Value) -> Result<(), String> {
        match self.constant_symbol_name(v) {
            Some(name) => Err(format!("setting-constant: {name}")),
            None => Ok(()),
        }
    }

    // ── cons ──
    pub fn cons(&mut self, a: Value, b: Value) -> Value {
        self.alloc(Obj::Cons(a, b))
    }
    pub fn list_from(&mut self, items: Vec<Value>) -> Value {
        let mut acc = Value::Undef;
        for x in items.into_iter().rev() {
            acc = self.cons(x, acc);
        }
        acc
    }
    pub fn list_vec(&self, v: &Value) -> Option<Vec<Value>> {
        let mut out = Vec::new();
        let mut cur = v.clone();
        loop {
            if el_nil(&cur) {
                return Some(out);
            }
            match &cur {
                Value::Obj(id) => match self.arena.get(*id as usize) {
                    Some(Obj::Cons(a, d)) => {
                        out.push(a.clone());
                        let next = d.clone();
                        cur = next;
                    }
                    _ => return None,
                },
                _ => return None,
            }
        }
    }
    /// Coerce any sequence — list, vector, or string — to a `Vec<Value>` (string
    /// chars become integer char codes). `mapcar`/`seq-*` accept all of these.
    pub fn seq_vec(&self, v: &Value) -> Option<Vec<Value>> {
        match v {
            Value::Str(s) => Some(s.chars().map(|c| Value::Int(c as i64)).collect()),
            Value::Obj(id) => match self.arena.get(*id as usize) {
                Some(Obj::Str(s)) => Some(s.chars().map(|c| Value::Int(c as i64)).collect()),
                Some(Obj::Vector(items)) => Some(items.clone()),
                // A bool-vector's elements are `t`/`nil`.
                Some(Obj::BoolVector(bits)) => Some(
                    bits.iter()
                        .map(|&b| if b { Value::Bool(true) } else { Value::Undef })
                        .collect(),
                ),
                _ => self.list_vec(v),
            },
            _ => self.list_vec(v),
        }
    }

    // ── symbol cells (dynamic / value cell) ──
    /// Follow the `defvaralias` chain from SYM's handle to the base variable's
    /// handle (Emacs `indirect_variable`). Ordinary variables resolve to
    /// themselves. Bounded to break any accidental cycle.
    pub fn indirect_var(&self, id: u32) -> u32 {
        let mut cur = id;
        for _ in 0..64 {
            match self.arena.get(cur as usize) {
                Some(Obj::Symbol(s)) => match s.alias_of {
                    Some(base) if base != cur => cur = base,
                    _ => return cur,
                },
                _ => return cur,
            }
        }
        cur
    }
    /// `(defvaralias ALIAS BASE)` — make ALIAS forward all value operations to
    /// BASE (Emacs `Fdefvaralias`). If BASE is unbound and ALIAS holds a value,
    /// BASE inherits it; BASE (and thus ALIAS) becomes special. Returns BASE.
    /// Signals `cyclic-variable-indirection` if the alias chain would loop.
    pub fn defvaralias(&mut self, alias: &Value, base: &Value) -> Result<Value, String> {
        // A constant cannot be given a forwarding cell. `Fdefvaralias` reports
        // this as a plain `error`, not as `setting-constant`, and names the
        // alias. (The `error: ` prefix is stripped by `make_error_object`, which
        // splits on the first colon only, so the message keeps its own colon.)
        if let Some(name) = self.constant_symbol_name(alias) {
            return Err(format!("error: Cannot make a constant an alias: {name}"));
        }
        let aid = self
            .sym_handle(alias)
            .ok_or_else(|| self.wrong_type_symbolp(alias))?;
        let bid = self
            .sym_handle(base)
            .ok_or_else(|| self.wrong_type_symbolp(base))?;
        // Reject a chain that would make BASE indirect back to ALIAS.
        let mut probe = bid;
        for _ in 0..64 {
            if probe == aid {
                return Err(format!(
                    "cyclic-variable-indirection: {}",
                    self.sym_name(alias).unwrap_or_default()
                ));
            }
            match self.arena.get(probe as usize) {
                Some(Obj::Symbol(s)) => match s.alias_of {
                    Some(next) if next != probe => probe = next,
                    _ => break,
                },
                _ => break,
            }
        }
        let base_id = self.indirect_var(bid);
        // If BASE is void but ALIAS has a value, BASE inherits ALIAS's value.
        let base_void =
            matches!(self.arena.get(base_id as usize), Some(Obj::Symbol(s)) if s.value.is_none());
        if base_void {
            let alias_val = match self.arena.get(aid as usize) {
                Some(Obj::Symbol(s)) => s.value.clone(),
                _ => None,
            };
            if let Some(val) = alias_val {
                if let Obj::Symbol(s) = &mut self.arena[base_id as usize] {
                    s.value = Some(val);
                }
            }
        }
        // Aliased variables are special (Emacs marks the base variable forwarded).
        if let Obj::Symbol(s) = &mut self.arena[base_id as usize] {
            s.special = true;
        }
        if let Obj::Symbol(s) = &mut self.arena[aid as usize] {
            s.alias_of = Some(base_id);
            s.special = true;
        }
        Ok(base.clone())
    }
    /// Assign a variable reference (`setq`): a lexical binding shadows both the
    /// buffer-local and the global cell.
    pub fn set_value(&mut self, v: &Value, val: Value) -> Result<(), String> {
        self.set_value_in(v, val, true)
    }
    /// The `set` primitive: data.c `Fset` goes through `set_internal`, which
    /// never sees a lexical binding — `(let ((x 1)) (set 'x 2) x)` is 1 and
    /// leaves the global `x` at 2.
    pub fn set_dynamic_value(&mut self, v: &Value, val: Value) -> Result<(), String> {
        self.set_value_in(v, val, false)
    }
    fn set_value_in(&mut self, v: &Value, val: Value, lexical: bool) -> Result<(), String> {
        self.check_settable(v)?;
        // data.c `set_internal`: `CHECK_SYMBOL (symbol)`.
        let Some(id0) = self.sym_handle(v) else {
            return Err(self.signal_wrong_type("symbolp", v));
        };
        let id = self.indirect_var(id0);
        if lexical && self.lex.as_ref().is_some_and(|s| s.set(id, &val)) {
            return Ok(());
        }
        // Write the current buffer's local slot if it already has one, or if the
        // variable is automatically buffer-local (create the local on first set).
        let bi = self.cur_buf_idx();
        if self.buffers[bi].locals.contains_key(&id)
            || (self.is_auto_local(id) && !self.let_shadows_buffer_binding(id, bi))
        {
            self.buffers[bi].locals.insert(id, Some(val));
            return Ok(());
        }
        if let Obj::Symbol(s) = &mut self.arena[id as usize] {
            s.value = Some(val);
        }
        Ok(())
    }
    /// data.c `let_shadows_buffer_binding_p`: a `let` made in buffer BI bound
    /// the default of automatically buffer-local ID, so setting it in BI sets
    /// that default instead of creating a local. In another buffer it does
    /// create one.
    fn let_shadows_buffer_binding(&self, id: u32, bi: usize) -> bool {
        self.specstack
            .iter()
            .any(|e| matches!(e, SpecEntry::Global(i, b, _) if *i == id && *b == bi))
    }
    fn is_auto_local(&self, id: u32) -> bool {
        matches!(self.arena.get(id as usize), Some(Obj::Symbol(s)) if s.buffer_local_auto)
    }

    // ── buffer-local variables ──
    /// `(make-local-variable SYM)` — give SYM a buffer-local binding in the
    /// current buffer. The local starts with the value SYM currently has (its
    /// default), snapshotting it; a void default yields a void local. No-op if a
    /// local already exists. Returns SYM.
    pub fn make_local_variable(&mut self, v: &Value) -> Result<Value, String> {
        self.check_settable(v)?;
        let id0 = self
            .sym_handle(v)
            .ok_or_else(|| self.wrong_type_symbolp(v))?;
        let id = self.indirect_var(id0);
        let bi = self.cur_buf_idx();
        if !self.buffers[bi].locals.contains_key(&id) {
            let snapshot = match &self.arena[id as usize] {
                Obj::Symbol(s) => s.value.clone(),
                _ => None,
            };
            self.buffers[bi].locals.insert(id, snapshot);
        }
        Ok(v.clone())
    }
    /// `(make-variable-buffer-local SYM)` — mark SYM automatically buffer-local
    /// (and special, like Emacs). Returns SYM.
    pub fn make_variable_buffer_local(&mut self, v: &Value) -> Result<Value, String> {
        self.check_settable(v)?;
        let id0 = self
            .sym_handle(v)
            .ok_or_else(|| self.wrong_type_symbolp(v))?;
        let id = self.indirect_var(id0);
        if let Obj::Symbol(s) = &mut self.arena[id as usize] {
            s.buffer_local_auto = true;
            s.special = true;
        }
        Ok(v.clone())
    }
    /// `(local-variable-p SYM BUFFER)` — non-nil if SYM has a buffer-local
    /// binding in the buffer at index BI.
    pub fn local_variable_p(&self, v: &Value, bi: usize) -> bool {
        match self.sym_handle(v) {
            Some(id) => self.buffers[bi].locals.contains_key(&self.indirect_var(id)),
            None => false,
        }
    }
    /// Register SYM as an always-local per-buffer slot whose new-buffer value
    /// is INIT. Every existing buffer gets a local holding the value SYM has
    /// there now, as the C slot would have had all along.
    pub fn make_always_local(&mut self, v: &Value, init: SlotInit) -> Result<Value, String> {
        let id0 = self
            .sym_handle(v)
            .ok_or("--make-always-local--: not a symbol")?;
        let id = self.indirect_var(id0);
        if let Obj::Symbol(s) = &mut self.arena[id as usize] {
            s.special = true;
        }
        let default = match &self.arena[id as usize] {
            Obj::Symbol(s) => s.value.clone(),
            _ => None,
        };
        for b in &mut self.buffers {
            b.locals.entry(id).or_insert_with(|| default.clone());
        }
        self.always_local.retain(|(s, _)| *s != id);
        self.always_local.push((id, init));
        Ok(v.clone())
    }
    /// The always-local slots a buffer named NAME starts with, made while the
    /// current buffer is still the creator.
    fn initial_slots(&self, name: &str) -> IndexMap<u32, Option<Value>> {
        let creator = &self.buffers[self.cur_buf_idx()];
        self.always_local
            .iter()
            .map(|(id, init)| {
                let val = match init {
                    SlotInit::Value(v) => Some(v.clone()),
                    SlotInit::Inherit => creator.locals.get(id).cloned().flatten(),
                    SlotInit::UndoList => Some(if name.starts_with(' ') {
                        Value::Bool(true)
                    } else {
                        Value::Undef
                    }),
                };
                (*id, val)
            })
            .collect()
    }
    /// Whether any buffer has a local binding of SYM: Emacs's
    /// `SYMBOL_LOCALIZED`, as opposed to a plain variable.
    pub fn has_any_local(&self, v: &Value) -> bool {
        self.sym_handle(v).is_some_and(|id0| {
            let id = self.indirect_var(id0);
            self.buffers.iter().any(|b| b.locals.contains_key(&id))
        })
    }
    /// Whether SYM is automatically buffer-local, the case in which
    /// `local-variable-if-set-p` answers t without consulting BUFFER.
    pub fn is_auto_local_var(&self, v: &Value) -> bool {
        self.sym_handle(v)
            .is_some_and(|id0| self.is_auto_local(self.indirect_var(id0)))
    }
    /// `(kill-local-variable SYM)` — remove the current buffer's local binding for
    /// SYM (the default becomes effective again). Returns SYM.
    /// data.c `CHECK_SYMBOL`: `(wrong-type-argument symbolp OBJECT)`.
    pub fn wrong_type_symbolp(&self, v: &Value) -> String {
        format!("wrong-type-argument: symbolp {}", self.print(v, true))
    }
    pub fn kill_local_variable(&mut self, v: &Value) -> Result<Value, String> {
        if self.sym_handle(v).is_none() && !el_nil(v) && !matches!(v, Value::Bool(true)) {
            return Err(self.wrong_type_symbolp(v));
        }
        if let Some(id0) = self.sym_handle(v) {
            let id = self.indirect_var(id0);
            // data.c `Fkill_local_variable`: a per-buffer slot resets only when
            // its `buffer_local_flags` index is positive; an always-local one
            // (index -1) keeps its value.
            if self.always_local.iter().any(|(s, _)| *s == id) {
                return Ok(v.clone());
            }
            let bi = self.cur_buf_idx();
            self.buffers[bi].locals.shift_remove(&id);
        }
        Ok(v.clone())
    }
    /// Symbol handles with a buffer-local binding in the current buffer, for the
    /// prelude port of `kill-all-local-variables`/`buffer-local-variables`.
    pub fn buffer_local_symbols(&mut self) -> Value {
        let ids: Vec<u32> = self.buffers[self.cur_buf_idx()]
            .locals
            .keys()
            .copied()
            .collect();
        let items: Vec<Value> = ids.into_iter().map(Value::Obj).collect();
        self.list_from(items)
    }
    /// `(use-local-map MAP)` — install MAP as the current buffer's local keymap.
    pub fn use_local_map(&mut self, map: Value) {
        let bi = self.cur_buf_idx();
        self.buffers[bi].local_map = map;
    }
    /// `(current-local-map)` — the current buffer's local keymap, or nil.
    pub fn current_local_map(&self) -> Value {
        self.buffers[self.cur_buf_idx()].local_map.clone()
    }
    /// `(buffer-local-value SYM BUFFER)` — SYM's value in BUFFER: its buffer-local
    /// slot if present, else the global default. Skips lexical bindings (this reads
    /// a buffer's variable, not the caller's scope). `buf_idx` is BUFFER's slot; the
    /// caller resolves it (defaulting to the current buffer).
    pub fn buffer_local_or_default(&self, v: &Value, buf_idx: usize) -> Result<Value, String> {
        if let Some(id0) = self.sym_handle(v) {
            let id = self.indirect_var(id0);
            if let Some(slot) = self.buffers[buf_idx].locals.get(&id) {
                return slot.clone().ok_or_else(|| {
                    format!("void-variable: {}", self.sym_name(v).unwrap_or_default())
                });
            }
        }
        self.raw_global_value(v)
    }
    /// Clear a symbol's global value cell (`makunbound`). Lexical bindings are
    /// left untouched — they shadow the cell and unwind on their own.
    pub fn unset_value(&mut self, v: &Value) -> Result<(), String> {
        self.check_settable(v)?;
        let id0 = self
            .sym_handle(v)
            .ok_or_else(|| self.wrong_type_symbolp(v))?;
        let id = self.indirect_var(id0);
        if let Obj::Symbol(s) = &mut self.arena[id as usize] {
            s.value = None;
        }
        Ok(())
    }
    /// Read a variable reference. Precedence: lexical binding, then the current
    /// buffer's local binding, then the global (default) value cell.
    pub fn get_value(&self, v: &Value) -> Result<Value, String> {
        self.get_value_in(v, true)
    }
    /// The dynamic value only — what data.c `Fsymbol_value` and `Fboundp` read.
    /// A lexical binding is invisible to them: under `lexical-binding` t,
    /// `(let ((x 1)) (boundp 'x))` is nil.
    pub fn get_dynamic_value(&self, v: &Value) -> Result<Value, String> {
        self.get_value_in(v, false)
    }
    fn get_value_in(&self, v: &Value, lexical: bool) -> Result<Value, String> {
        if let Some(id0) = self.sym_handle(v) {
            let id = self.indirect_var(id0);
            if lexical {
                if let Some(val) = self.lex.as_ref().and_then(|s| s.lookup(id)) {
                    return Ok(val);
                }
            }
            if let Some(slot) = self.buffers[self.cur_buf_idx()].locals.get(&id) {
                return slot.clone().ok_or_else(|| {
                    format!("void-variable: {}", self.sym_name(v).unwrap_or_default())
                });
            }
            return match &self.arena[id as usize] {
                Obj::Symbol(s) => s
                    .value
                    .clone()
                    .ok_or_else(|| format!("void-variable: {}", s.name)),
                _ => Err(self.wrong_type_symbolp(v)),
            };
        }
        // `nil` and `t` are self-evaluating symbols; `nil` arrives either as
        // `Undef` (a literal) or as `Bool(false)` (a comparison that answered
        // false), and both are the same symbol.
        match v {
            Value::Bool(true) => Ok(Value::Bool(true)),
            _ if el_nil(v) => Ok(Value::Undef),
            _ => Err(self.wrong_type_symbolp(v)),
        }
    }
    /// Index of the current buffer.
    fn cur_buf_idx(&self) -> usize {
        self.current
    }
    /// The global (default) value cell, bypassing lexical and buffer-local
    /// bindings — the reader used by `default-value`/`default-boundp`.
    pub fn raw_global_value(&self, v: &Value) -> Result<Value, String> {
        if let Some(id0) = self.sym_handle(v) {
            let id = self.indirect_var(id0);
            return match &self.arena[id as usize] {
                Obj::Symbol(s) => s
                    .value
                    .clone()
                    .ok_or_else(|| format!("void-variable: {}", s.name)),
                _ => Err(self.wrong_type_symbolp(v)),
            };
        }
        // `nil` and `t` are self-evaluating symbols; `nil` arrives either as
        // `Undef` (a literal) or as `Bool(false)` (a comparison that answered
        // false), and both are the same symbol.
        match v {
            Value::Bool(true) => Ok(Value::Bool(true)),
            _ if el_nil(v) => Ok(Value::Undef),
            _ => Err(self.wrong_type_symbolp(v)),
        }
    }
    /// True if the global (default) value cell is bound (`default-boundp`).
    pub fn default_boundp_raw(&self, v: &Value) -> bool {
        // `nil`, `t`, and keywords are their own value and can never be void.
        // `nil` and `t` are not arena symbols here, so the handle lookup below
        // would otherwise call them unbound and let `(defvar nil 1)` try a write.
        if self.constant_symbol_name(v).is_some() {
            return true;
        }
        match self.sym_handle(v) {
            Some(id0) => {
                let id = self.indirect_var(id0);
                matches!(self.arena.get(id as usize), Some(Obj::Symbol(s)) if s.value.is_some())
            }
            None => false,
        }
    }
    /// Write the global (default) value cell directly (`set-default`), bypassing
    /// lexical and buffer-local bindings.
    pub fn set_raw_global(&mut self, v: &Value, val: Value) -> Result<(), String> {
        self.check_settable(v)?;
        let id0 = self
            .sym_handle(v)
            .ok_or_else(|| self.wrong_type_symbolp(v))?;
        let id = self.indirect_var(id0);
        if let Obj::Symbol(s) = &mut self.arena[id as usize] {
            s.value = Some(val);
        }
        Ok(())
    }
    /// Mark a symbol special (dynamically scoped) — used by `defvar`/`defconst`.
    /// eval.c `Fdefvar` with no VALUE: under lexical binding, a variable that
    /// is not already special becomes dynamically bound for the rest of the
    /// current scope only — a bare symbol consed onto the environment — and
    /// `special-variable-p` stays nil. Under dynamic binding it does nothing.
    pub fn declare_special_locally(&mut self, v: &Value) {
        let Some(id0) = self.sym_handle(v) else {
            return;
        };
        let id = self.indirect_var(id0);
        if !self.dynamic_binding && !self.is_special(id) {
            self.lex = Some(Rc::new(Scope::declaration(id, self.lex.take())));
        }
    }
    pub fn set_special(&mut self, v: &Value) {
        if let Some(id) = self.sym_handle(v) {
            if let Obj::Symbol(s) = &mut self.arena[id as usize] {
                s.special = true;
            }
        }
    }
    fn is_special(&self, id: u32) -> bool {
        matches!(self.arena.get(id as usize), Some(Obj::Symbol(s)) if s.special)
    }
    /// True if V is a symbol marked special (defvar/defconst), for `special-variable-p`.
    pub fn symbol_special(&self, v: &Value) -> bool {
        // `nil`, `t`, and keywords are permanently declared special, so
        // `special-variable-p` answers t for them even though no `defvar` ever
        // mentioned them.
        if self.constant_symbol_name(v).is_some() {
            return true;
        }
        self.sym_handle(v)
            .map(|id| self.is_special(self.indirect_var(id)))
            .unwrap_or(false)
    }
    pub fn set_function_value(&mut self, sym: &Value, def: Value) -> Result<(), String> {
        // `Ffset` guards only `nil` (and `unbound`), not the whole constant set:
        // `t` and keywords have constant *value* cells but writable *function*
        // cells, so `(fset t (lambda ()))` is legal and returns the definition.
        if matches!(self.constant_symbol_name(sym).as_deref(), Some("nil")) {
            return Err("setting-constant: nil".to_string());
        }
        let id = match self.sym_handle(sym) {
            Some(id) => id,
            // `CHECK_SYMBOL`, which names the offender.
            None => {
                return Err(format!(
                    "wrong-type-argument: symbolp {}",
                    self.print(sym, true)
                ))
            }
        };
        // A nil definition IS the empty cell: data.c `Ffboundp` is
        // `!NILP (XSYMBOL (symbol)->u.s.function)`, so `(fset 'f nil)` and
        // `fmakunbound` leave F unbound rather than bound to nil.
        if let Obj::Symbol(s) = &mut self.arena[id as usize] {
            s.function = if el_truthy(&def) { Some(def) } else { None };
        }
        Ok(())
    }
    pub fn set_function(&mut self, name: &str, def: Value) {
        let v = self.intern(name);
        let _ = self.set_function_value(&v, def);
    }
    /// The symbol's function cell (what `symbol-function` returns), if any.
    pub fn function_cell(&self, sym: &Value) -> Option<Value> {
        match self.obj(sym) {
            Some(Obj::Symbol(s)) => s.function.clone(),
            _ => None,
        }
    }
    /// The function cell **as introspection sees it**: the real cell, or — for a
    /// compiler intrinsic that Emacs implements as an ordinary macro — the
    /// registered `(macro . FUNCTION)` stand-in.
    ///
    /// `when`/`unless` are lowered by name in `compiler.rs`, so they have no
    /// function cell at all and `(type-of (symbol-function 'when))` answered
    /// `symbol` where Emacs answers `cons`. The stand-in is deliberately kept
    /// OUT of the symbol's real function cell: putting it there would make
    /// `resolve_function` — and therefore `macroexpand_1` on the compile path —
    /// treat every `when` in the prelude as a macro call to run, losing the
    /// dedicated `compile_when` lowering. The expansion the stand-in produces is
    /// the same `subr.el` one [`expand_intrinsic_macro`] already reproduces.
    pub fn introspect_function_cell(&self, sym: &Value) -> Option<Value> {
        if let Some(cell) = self.function_cell(sym) {
            return Some(cell);
        }
        self.sym_handle(sym)
            .and_then(|id| self.intrinsic_macro_cells.get(&id))
            .cloned()
    }
    /// Register the `(macro . FUNCTION)` stand-in for a compiler intrinsic.
    pub fn set_intrinsic_macro_cell(&mut self, sym: &Value, cell: Value) {
        if let Some(id) = self.sym_handle(sym) {
            self.intrinsic_macro_cells.insert(id, cell);
        }
    }
    /// The `#<subr NAME>` object behind `v` when `v` designates a *special form* —
    /// either the symbol (`(funcall 'if …)`) or the subr itself
    /// (`(funcall (symbol-function 'if) …)`).
    ///
    /// A special form is fbound but not callable: Emacs's `funcall` refuses a subr
    /// whose `max_args` is `UNEVALLED` with `(invalid-function #<subr if>)`.
    pub fn special_form_object(&self, v: &Value) -> Option<Value> {
        if let Some(Obj::Subr { name, .. }) = self.obj(v) {
            return crate::builtins::is_special_form(name).then(|| v.clone());
        }
        let cell = self
            .sym_handle(v)
            .and_then(|id| self.intrinsic_macro_cells.get(&id))?;
        match self.obj(cell) {
            Some(Obj::Subr { name, .. }) if crate::builtins::is_special_form(name) => {
                Some(cell.clone())
            }
            _ => None,
        }
    }
    /// Signal `(invalid-function FUNCTION)` carrying FUNCTION as the *object*.
    /// A subr prints as `#<subr if>`, which no reader can turn back into the
    /// subr, so the datum has to travel out of band like `signal_wrong_type`'s.
    pub fn signal_invalid_function(&mut self, fun: &Value) -> String {
        let msg = format!("invalid-function: {}", self.print(fun, true));
        let sym = self.intern("invalid-function");
        let data = self.list_from(vec![fun.clone()]);
        let obj = self.cons(sym, data);
        self.set_pending_error(&msg, obj);
        msg
    }
    /// The introspection side table (special-form and intrinsic-macro function
    /// cells), for serialization into the script cache.
    pub fn export_intrinsic_macro_cells(&self) -> Vec<(u32, Value)> {
        let mut out: Vec<(u32, Value)> = self
            .intrinsic_macro_cells
            .iter()
            .map(|(&id, v)| (id, v.clone()))
            .collect();
        out.sort_by_key(|(id, _)| *id);
        out
    }
    /// Restore cells captured by [`Self::export_intrinsic_macro_cells`].
    ///
    /// Only entries the current `install` did not already provide are taken, so a
    /// stale cached special-form cell can never displace the live one.
    pub fn import_intrinsic_macro_cells(&mut self, cells: Vec<(u32, Value)>) {
        for (id, v) in cells {
            self.intrinsic_macro_cells.entry(id).or_insert(v);
        }
    }
    /// Look up an already-interned symbol by name without creating one
    /// (`intern-soft`); returns `None` if absent.
    pub fn find_symbol(&self, name: &str) -> Option<Value> {
        self.obarray.get(name).map(|&id| Value::Obj(id))
    }
    pub fn defsubr(&mut self, name: &str, min: usize, max: Option<usize>, f: SubrFn) {
        let subr = self.alloc(Obj::Subr {
            name: name.to_string(),
            min,
            max,
            f,
        });
        self.set_function(name, subr);
    }
    pub fn is_bound(&self, v: &Value) -> bool {
        match self.sym_handle(v) {
            Some(id0) => {
                let id = self.indirect_var(id0);
                matches!(self.arena.get(id as usize), Some(Obj::Symbol(s)) if s.value.is_some())
            }
            None => false,
        }
    }
    pub fn is_fbound(&self, v: &Value) -> bool {
        matches!(self.obj(v), Some(Obj::Symbol(s)) if s.function.is_some())
    }

    // ── dynamic binding ──
    pub fn specdepth(&self) -> usize {
        self.specstack.len()
    }
    pub fn specbind(&mut self, sym: &Value, val: Value) -> Result<(), String> {
        let id0 = self.sym_handle(sym).ok_or("cannot bind a non-symbol")?;
        let id = self.indirect_var(id0);
        let bi = self.cur_buf_idx();
        // eval.c `specbind`: `let` over a variable that HAS a local binding in
        // the current buffer rebinds that local (SPECPDL_LET_LOCAL). One that is
        // merely automatically buffer-local, with no local here yet, binds the
        // DEFAULT (SPECPDL_LET_DEFAULT), so every buffer without its own value —
        // including one made inside the `let` — sees the bound value:
        // `(let ((case-fold-search nil)) (with-temp-buffer case-fold-search))`.
        if self.buffers[bi].locals.contains_key(&id) {
            let old = self.buffers[bi].locals.get(&id).cloned();
            self.specstack.push(SpecEntry::Local(id, bi, old));
            self.buffers[bi].locals.insert(id, Some(val));
            return Ok(());
        }
        let old = if let Obj::Symbol(s) = &self.arena[id as usize] {
            s.value.clone()
        } else {
            None
        };
        self.specstack.push(SpecEntry::Global(id, bi, old));
        if let Obj::Symbol(s) = &mut self.arena[id as usize] {
            s.value = Some(val);
        }
        Ok(())
    }
    pub fn unbind_to(&mut self, depth: usize) {
        while self.specstack.len() > depth {
            match self.specstack.pop().unwrap() {
                SpecEntry::Global(id, _, old) => {
                    if let Obj::Symbol(s) = &mut self.arena[id as usize] {
                        s.value = old;
                    }
                }
                SpecEntry::Local(id, buf, old) => {
                    if let Some(b) = self.buffers.get_mut(buf) {
                        match old {
                            None => {
                                b.locals.shift_remove(&id);
                            }
                            Some(prev) => {
                                b.locals.insert(id, prev);
                            }
                        }
                    }
                }
            }
        }
    }
    // ── lexical scope management ──
    /// Open a lexical scope: record an unwind boundary (the current lexical
    /// head + specstack depth). No binding node is created yet — each
    /// `bind_here` conses one; `close_scope` restores the saved head, dropping
    /// every node bound within this scope.
    pub fn open_scope(&mut self) {
        self.frame_stack
            .push((self.lex.clone(), self.specstack.len()));
    }
    /// Open a scope whose bindings extend `env` (a closure's captured env):
    /// record the unwind boundary, then make `env` the active lexical head so
    /// subsequent `bind_here` calls cons the params onto it.
    pub fn open_scope_in(&mut self, env: Lex) {
        self.frame_stack
            .push((self.lex.clone(), self.specstack.len()));
        self.lex = env;
    }
    /// Pop the innermost scope: restore the prior lexical env and unwind any
    /// dynamic (special-var) bindings made within it.
    pub fn close_scope(&mut self) {
        if let Some((saved, depth)) = self.frame_stack.pop() {
            self.unbind_to(depth);
            self.lex = saved;
        }
    }
    /// Pop scopes until `frame_stack` is back to `target_len`. A non-local exit
    /// (`throw`/error) out of an inner `let` skips its `UNBIND`, leaking the
    /// Record the source line of a list form (keyed by its head-cons handle).
    /// Called by the reader as it builds each `(...)`. No-op for non-`Obj` forms.
    pub fn record_form_line(&mut self, form: &Value, line: u32) {
        if let Value::Obj(id) = form {
            self.form_lines.insert(*id, line);
        }
    }
    /// The recorded source line of a form, if the reader saw it as a list.
    pub fn form_line(&self, form: &Value) -> Option<u32> {
        match form {
            Value::Obj(id) => self.form_lines.get(id).copied(),
            _ => None,
        }
    }

    /// lexical scope; `run_closure` calls this to recover, so the caller's
    /// lexical environment isn't corrupted.
    pub fn unwind_scopes_to(&mut self, target_len: usize) {
        while self.frame_stack.len() > target_len {
            self.close_scope();
        }
    }
    pub fn scope_depth(&self) -> usize {
        self.frame_stack.len()
    }
    /// Bind `id` to `val` in the current scope — lexically, unless the symbol is
    /// special (`defvar`'d), in which case dynamically (saved on the specstack).
    ///
    /// Under `lexical-binding` nil (`Self::dynamic_binding`) *every* symbol takes
    /// the dynamic path, which is what makes a `lambda` made in that mode see the
    /// caller's bindings and not its birthplace's.
    pub fn bind_here(&mut self, id: u32, val: Value) {
        if self.dynamic_binding
            || self.is_special(id)
            || self.lex.as_ref().is_some_and(|s| s.declares_special(id))
        {
            let _ = self.specbind(&Value::Obj(id), val);
        } else {
            // Cons a fresh single-binding node onto the lexical chain. A later
            // same-name rebind conses another node in front (shadows it);
            // closures that captured the earlier head never see it.
            self.lex = Some(Rc::new(Scope::new(id, val, self.lex.take())));
        }
    }
    /// Bind a symbol value into the current scope (lexical/dynamic per special).
    pub fn bind_value(&mut self, symv: &Value, val: Value) {
        if let Some(id) = self.sym_handle(symv) {
            self.bind_here(id, val);
        }
    }
    /// Enter one elisp call frame, or `Err` with Emacs's `excessive-lisp-nesting`
    /// when `max-lisp-eval-depth` is already reached.
    ///
    /// Emacs's eval.c raises this *before* the native stack runs out, so runaway
    /// recursion is a catchable signal — `(condition-case e … (error e))` yields
    /// `(excessive-lisp-nesting 1601)`. elisprs previously had no limit at all
    /// and simply aborted the process with `fatal runtime error: stack
    /// overflow`, which nothing can catch and which loses the rest of the
    /// session. The limit is read from the variable on every call so a `let`
    /// around it takes effect (it is `defvar`'d, so the binding is on the
    /// specstack and lives in the global value cell — an array index, not a
    /// scope walk).
    pub fn enter_eval_frame(&mut self) -> Result<(), String> {
        let sym = match self.max_depth_sym {
            Some(s) => s,
            None => {
                let s = self.intern("max-lisp-eval-depth");
                let h = self.sym_handle(&s);
                self.max_depth_sym = h;
                match h {
                    Some(h) => h,
                    None => {
                        self.eval_depth += 1;
                        return Ok(());
                    }
                }
            }
        };
        let limit = match &self.arena[sym as usize] {
            Obj::Symbol(s) => match s.value {
                // eval.c clamps the variable up to a floor of 100, so a smaller
                // value cannot lock the session out of running anything:
                // `(let ((max-lisp-eval-depth 5)) …)` still signals at 101.
                Some(Value::Int(n)) => (n.max(100)) as usize,
                _ => usize::MAX,
            },
            _ => usize::MAX,
        };
        if self.eval_depth >= limit {
            return Err(format!("excessive-lisp-nesting: {}", self.eval_depth + 1));
        }
        self.eval_depth += 1;
        Ok(())
    }
    /// Leave one elisp call frame (paired with [`Self::enter_eval_frame`]).
    pub fn leave_eval_frame(&mut self) {
        self.eval_depth = self.eval_depth.saturating_sub(1);
    }

    /// Instantiate a closure from a compile-time template, capturing the current
    /// lexical environment. Templates are stored with `env: None`.
    ///
    /// Under dynamic binding (`lexical-binding` nil — see `Self::dynamic_binding`)
    /// nothing is captured: Emacs's `eval` returns the `lambda` form itself, whose
    /// free variables are looked up in the symbols' value cells when it is *called*.
    /// The instance records the mode so its body and parameters run dynamically too,
    /// however far from the `eval` it is finally funcalled.
    pub fn instantiate_closure(&mut self, template: &Value) -> Value {
        if let Some(Obj::Closure {
            params,
            body,
            is_macro,
            src,
            ..
        }) = self.obj(template)
        {
            let (params, body, is_macro, src) =
                (params.clone(), body.clone(), *is_macro, src.clone());
            let dynamic = self.dynamic_binding;
            let template_id = match template {
                Value::Obj(id) => *id,
                _ => u32::MAX,
            };
            let env = if dynamic {
                None
            } else {
                self.trim_lex(template_id, &src)
            };
            return self.alloc(Obj::Closure {
                params,
                body,
                is_macro,
                env,
                dynamic,
                src,
            });
        }
        template.clone()
    }

    // ── OClosure seam (oclosure.el's C primitives) ──
    // These implement the host-specific primitives `oclosure.el` builds on. In
    // Emacs they poke at an interpreted-function's `aref` slots; elisprs closures
    // are compiled (a `Chunk` + captured env), so the seam instead attaches a
    // type + slot-name list (side table) and reads/writes slot values in the
    // closure's captured lexical env by symbol. The observable oclosure API
    // (define / lambda / accessors / `oclosure-type`) matches Emacs exactly.

    /// The lexical environment a closure created from `template` captures:
    /// the bindings in force, pruned to the ones its body actually references.
    ///
    /// Emacs does this in `cconv-make-interpreted-closure` (cconv.el), whose own
    /// doc says why: "reduce ENV to the part actually used by the function, so we
    /// are closer to the ideal of 'safe for space'. In practice it has two
    /// benefits: it makes closures a bit more predictable and human-readable, and
    /// more importantly it avoids accidentally including values that we cannot
    /// print `read'ably". It is observable — `(let ((n 1) (m 2)) (lambda () n))`
    /// prints `#[nil (n) ((n . 1))]`, not `((m . 2) (n . 1))` — and it changes
    /// `equal` on closures, which compares the captured environment.
    ///
    /// Three details are load-bearing:
    ///
    /// - The surviving bindings keep the ENVIRONMENT's order, not the order the
    ///   body mentions them in: `(let ((a 1) (b 2) (c 3)) (lambda () (list a c)))`
    ///   and `… (list c a)` both close over `((c . 3) (a . 1))`.
    /// - Only the INNERMOST binding of a shadowed name survives, because Emacs's
    ///   `assq` stops at the first match.
    /// - The kept nodes SHARE their value cells with the enclosing chain (see
    ///   [`Scope::val`]), so `setq` still crosses the closure boundary in both
    ///   directions.
    ///
    /// The free-variable set is computed once per closure TEMPLATE and cached:
    /// a `lambda` inside a loop instantiates a fresh closure per iteration off
    /// one template, and re-walking its source every time would put an O(body)
    /// cost on every evaluation of the `lambda` form.
    fn trim_lex(&mut self, template_id: u32, src: &Rc<ClosureSrc>) -> Lex {
        // cconv.el skips the analysis when the environment has no lexical
        // binding (`(null lexvars)`), keeping it — local special declarations
        // included — exactly as it is.
        if !self.lex.as_ref()?.has_bindings() {
            return self.lex.clone();
        }
        let free = match self.closure_free.get(&template_id) {
            Some(f) => Rc::clone(f),
            None => {
                let f = Rc::new(crate::freevars::free_vars(self, &src.arglist, &src.body));
                if template_id != u32::MAX {
                    self.closure_free.insert(template_id, Rc::clone(&f));
                }
                f
            }
        };
        let mut kept: Vec<(u32, Rc<RefCell<Value>>)> = Vec::new();
        let mut declared: Vec<u32> = Vec::new();
        let mut seen: std::collections::HashSet<u32> = std::collections::HashSet::new();
        let mut cur = self.lex.clone();
        while let Some(scope) = cur {
            let sym = scope.sym_handle();
            if scope.is_declaration() {
                declared.push(sym);
            } else if free.contains(&sym) && seen.insert(sym) {
                kept.push((sym, scope.value_cell()));
            }
            cur = scope.parent_lex();
        }
        // `newenv` is `(nconc LEXICAL-CAPTURES DYNS)`: the declarations kept are
        // the ones the body `let`-binds (`cconv--dynbindings`), after the
        // captured bindings.
        let dyns: Vec<u32> = if declared.is_empty() {
            Vec::new()
        } else {
            crate::freevars::let_bound_vars(self, &src.arglist, &src.body)
                .into_iter()
                .filter(|s| declared.contains(s))
                .collect()
        };
        // Re-link from the outermost in so the head stays the innermost binding.
        let mut env: Lex = None;
        for &sym in dyns.iter().rev() {
            env = Some(Rc::new(Scope::declaration(sym, env)));
        }
        for (sym, cell) in kept.into_iter().rev() {
            env = Some(Rc::new(Scope::sharing(sym, cell, env)));
        }
        env
    }

    /// True if `v` is a closure (`closurep`).
    pub fn is_closure(&self, v: &Value) -> bool {
        matches!(self.obj(v), Some(Obj::Closure { .. }))
    }

    /// Mark closure `v` as an OClosure of type `ty` with the given ordered slot
    /// symbols (`oclosure--fix-type`). No-op if `v` is not a closure.
    pub fn oclosure_set_meta(&mut self, v: &Value, ty: u32, slots: Vec<u32>) {
        if let Value::Obj(id) = v {
            if matches!(self.arena.get(*id as usize), Some(Obj::Closure { .. })) {
                self.oclosure_meta.insert(*id, OClosureMeta { ty, slots });
            }
        }
    }

    /// The type symbol handle of OClosure `v`, or `None` (`oclosure-type`).
    pub fn oclosure_type_of(&self, v: &Value) -> Option<u32> {
        match v {
            Value::Obj(id) if self.is_closure(v) => self.oclosure_meta.get(id).map(|m| m.ty),
            _ => None,
        }
    }

    /// The parts of a closure that Emacs's `equal` compares.
    ///
    /// An interpreted closure in Emacs IS its `#[ARGLIST BODY ENV]` structure,
    /// and `equal` descends into it like any other vector-like — which is why
    /// `(equal (lambda () 1) (lambda () 1))` answers t there. Returned as
    /// `(is_macro, dynamic, arglist, body, captures)`; `captures` is the lexical
    /// chain innermost-first as `(symbol-handle, value)`.
    pub fn closure_parts(&self, v: &Value) -> Option<ClosureParts> {
        match self.obj(v) {
            Some(Obj::Closure {
                is_macro,
                dynamic,
                src,
                env,
                ..
            }) => {
                let mut captures = Vec::new();
                let mut cur = env.clone();
                while let Some(scope) = cur {
                    let val = (!scope.is_declaration()).then(|| scope.value());
                    captures.push((scope.sym_handle(), val));
                    cur = scope.parent_lex();
                }
                Some((
                    *is_macro,
                    *dynamic,
                    src.arglist.clone(),
                    src.body.clone(),
                    captures,
                ))
            }
            _ => None,
        }
    }

    /// The slots of an interpreted closure as eval.c `make-interpreted-closure`
    /// lays them out: ARGS, BODY, ENV, nil, DOCSTRING, INTERACTIVE-SPEC, cut
    /// after the last one present (3, 5 or 6 slots). `None` when V is not a
    /// closure.
    pub fn closure_slots(&mut self, v: &Value) -> Option<Vec<Value>> {
        let (dynamic, src, env) = match self.obj(v) {
            Some(Obj::Closure {
                dynamic, src, env, ..
            }) => (*dynamic, src.clone(), env.clone()),
            _ => return None,
        };
        let slots = src.slots(self);
        let body = self.list_from(slots.body);
        let env = if dynamic {
            Value::Undef
        } else {
            let mut cells = Vec::new();
            let only_declarations = env.as_ref().is_some_and(|s| !s.has_bindings());
            let mut cur = env;
            while let Some(scope) = cur {
                let name = Value::Obj(scope.sym_handle());
                if scope.is_declaration() {
                    cells.push(name);
                } else {
                    cells.push(self.cons(name, scope.value()));
                }
                cur = scope.parent_lex();
            }
            // An environment of declarations only was kept whole, down to the
            // `t` that ends every lexical environment.
            if cells.is_empty() || only_declarations {
                cells.push(Value::Bool(true));
            }
            self.list_from(cells)
        };
        let mut out = vec![src.arglist.clone(), body, env];
        if slots.doc.is_some() || slots.iform.is_some() {
            out.push(Value::Undef);
            out.push(slots.doc.unwrap_or(Value::Undef));
        }
        if let Some(iform) = slots.iform {
            let spec = self.list_vec(&iform).unwrap_or_default();
            let value = if spec.len() <= 2 {
                spec.get(1).cloned().unwrap_or(Value::Undef)
            } else {
                let modes = self.list_from(spec[2..].to_vec());
                self.alloc(Obj::Vector(vec![spec[1].clone(), modes]))
            };
            out.push(value);
        }
        Some(out)
    }

    /// Clone a closure's captured env (for slot access), or `None`.
    fn closure_env(&self, v: &Value) -> Option<Lex> {
        match self.obj(v) {
            Some(Obj::Closure { env, .. }) => Some(env.clone()),
            _ => None,
        }
    }

    /// Read slot `index` of OClosure `v` (`oclosure--get`): look up the slot
    /// symbol in the closure's captured env.
    pub fn oclosure_get(&self, v: &Value, index: usize) -> Option<Value> {
        let id = match v {
            Value::Obj(id) => *id,
            _ => return None,
        };
        let sym = *self.oclosure_meta.get(&id)?.slots.get(index)?;
        let env = self.closure_env(v)?;
        env.as_ref().and_then(|h| h.lookup(sym))
    }

    /// Write slot `index` of OClosure `v` (`oclosure--set`): mutate the slot
    /// symbol's cell in the closure's captured env. Returns false if not found.
    pub fn oclosure_set(&self, v: &Value, index: usize, val: &Value) -> bool {
        let id = match v {
            Value::Obj(id) => *id,
            _ => return false,
        };
        let sym = match self.oclosure_meta.get(&id).and_then(|m| m.slots.get(index)) {
            Some(s) => *s,
            None => return false,
        };
        match self.closure_env(v).flatten() {
            Some(head) => head.set(sym, val),
            None => false,
        }
    }

    /// Functional copy of OClosure `src` (`oclosure--copy`): a new closure with the
    /// same code + type, whose first `args.len()` slots take the new values and
    /// whose remaining slots keep `src`'s values. Fresh slot bindings are prepended
    /// to `src`'s env so they shadow the originals (the copy's body reads the new
    /// values). Returns `None` if `src` is not an OClosure closure.
    pub fn oclosure_copy(&mut self, src: &Value, args: &[Value]) -> Option<Value> {
        let id = match src {
            Value::Obj(id) => *id,
            _ => return None,
        };
        let slots = self.oclosure_meta.get(&id)?.slots.clone();
        let ty = self.oclosure_meta.get(&id)?.ty;
        let (params, body, is_macro, base_env, csrc, dynamic) = match self.obj(src) {
            Some(Obj::Closure {
                params,
                body,
                is_macro,
                env,
                src: csrc,
                dynamic,
            }) => (
                params.clone(),
                body.clone(),
                *is_macro,
                env.clone(),
                csrc.clone(),
                *dynamic,
            ),
            _ => return None,
        };
        // New value for each slot: the passed arg, else the original slot value.
        let mut vals: Vec<Value> = Vec::with_capacity(slots.len());
        for (k, &sym) in slots.iter().enumerate() {
            let v = if k < args.len() {
                args[k].clone()
            } else {
                base_env
                    .as_ref()
                    .and_then(|h| h.lookup(sym))
                    .unwrap_or(Value::Undef)
            };
            vals.push(v);
        }
        // Prepend in reverse so slot[0] ends up frontmost (found first on lookup).
        let mut env = base_env;
        for (k, &sym) in slots.iter().enumerate().rev() {
            env = Some(Rc::new(Scope::new(sym, vals[k].clone(), env.take())));
        }
        let newv = self.alloc(Obj::Closure {
            params,
            body,
            is_macro,
            env,
            dynamic,
            src: csrc,
        });
        if let Value::Obj(nid) = newv {
            self.oclosure_meta.insert(nid, OClosureMeta { ty, slots });
        }
        Some(newv)
    }

    // ── AOT heap image ──
    /// Serialize the user/prelude heap (arena ≥ `builtin_count`) for embedding
    /// into an AOT object. Builtins are excluded — they are re-created by
    /// `install` in the AOT-runtime host, at the same handles.
    pub fn export_heap_image(&self) -> Vec<SerObj> {
        self.arena[self.builtin_count..]
            .iter()
            .enumerate()
            .map(|(off, o)| match o {
                Obj::Cons(a, b) => SerObj::Cons(a.clone(), b.clone()),
                Obj::Symbol(s) => SerObj::Symbol {
                    name: s.name.clone(),
                    value: s.value.clone(),
                    function: s.function.clone(),
                    special: s.special,
                    buffer_local_auto: s.buffer_local_auto,
                    alias_of: s.alias_of,
                    interned: self.symbol_is_interned(s, (self.builtin_count + off) as u32),
                },
                Obj::Vector(v) => SerObj::Vector(v.clone()),
                Obj::Record(v) => SerObj::Record(v.clone()),
                Obj::BoolVector(v) => SerObj::BoolVector(v.clone()),
                Obj::Str(s) => SerObj::Str(s.to_string()),
                Obj::Bignum(b) => SerObj::Bignum(b.clone()),
                Obj::HashTable(t) => SerObj::HashTable {
                    test: t.test,
                    slots: t.slots.clone(),
                    free: t.free.clone(),
                    size: t.size,
                    weakness: t.weakness.clone(),
                    user_test: t.user_test.clone(),
                },
                Obj::CharTable(t) => SerObj::CharTable {
                    subtype: t.subtype.clone(),
                    default: t.default.clone(),
                    parent: t.parent.clone(),
                    extra: t.extra.clone(),
                    contents: t.flatten(),
                    ascii: match &t.ascii {
                        CtAscii::Val(v) => Some(v.clone()),
                        CtAscii::Tree => None,
                    },
                },
                // Buffer/marker/obarray objects are runtime-only (created after
                // prelude load) and never appear in a compiled/AOT heap image;
                // emit a harmless placeholder so the match stays exhaustive.
                Obj::Buffer(_)
                | Obj::Marker(_)
                | Obj::Overlay(_)
                | Obj::Window(_)
                | Obj::Frame(_)
                | Obj::WindowConfig(_)
                | Obj::Obarray(_) => SerObj::Symbol {
                    name: "--unexpected-runtime-obj--".to_string(),
                    value: None,
                    function: None,
                    special: false,
                    buffer_local_auto: false,
                    alias_of: None,
                    interned: false,
                },
                Obj::Closure {
                    params,
                    body,
                    is_macro,
                    env,
                    dynamic,
                    src,
                } => SerObj::Closure {
                    required: params.required.clone(),
                    optional: params.optional.clone(),
                    rest: params.rest,
                    body: (**body).clone(),
                    is_macro: *is_macro,
                    env: self.flatten_lex(env),
                    dynamic: *dynamic,
                    arglist: src.arglist.clone(),
                    src_body: src.body.clone(),
                },
                // No Subr ever lives in the user range (only `install` makes them).
                Obj::Subr { .. } => SerObj::Symbol {
                    name: "--unexpected-subr--".to_string(),
                    value: None,
                    function: None,
                    special: false,
                    buffer_local_auto: false,
                    alias_of: None,
                    interned: false,
                },
            })
            .collect()
    }
    pub fn builtin_count(&self) -> usize {
        self.builtin_count
    }
    pub fn set_prelude_end(&mut self, end: usize) {
        self.prelude_end = end;
    }
    /// Whether `v` is an object the prelude created (see `prelude_end`).
    pub fn is_prelude_object(&self, v: &Value) -> bool {
        matches!(v, Value::Obj(id) if (*id as usize) >= self.builtin_count && (*id as usize) < self.prelude_end)
    }
    /// The captured lexical environment as Emacs prints it in a closure: an alist
    /// of the captured bindings, newest first, or `(t)` when nothing is captured
    /// (`t` is Emacs's marker that the closure is lexically bound).
    fn captured_alist(&self, env: &Lex, readable: bool, depth: usize) -> String {
        let mut cells = Vec::new();
        let only_declarations = env.as_ref().is_some_and(|s| !s.has_bindings());
        let mut cur = env.clone();
        while let Some(scope) = cur {
            let name = match self.arena.get(scope.sym_handle() as usize) {
                Some(Obj::Symbol(s)) => s.name.clone(),
                _ => break,
            };
            if scope.is_declaration() {
                cells.push(name);
            } else {
                let val = self.print_inner(&scope.value(), readable, depth + 1);
                cells.push(format!("({name} . {val})"));
            }
            cur = scope.parent_lex();
        }
        // An environment of declarations only was kept whole (cconv.el's
        // `(null lexvars)` case), down to the `t` that ends it.
        if only_declarations {
            cells.push("t".to_string());
        }
        if cells.is_empty() {
            "(t)".to_string()
        } else {
            format!("({})", cells.join(" "))
        }
    }

    /// Whether the global obarray maps this symbol's name to *this* handle — i.e.
    /// the symbol is interned, not a `make-symbol` result, a lambda parameter, or
    /// a macro-local binding that merely shares a name with something interned.
    fn symbol_is_interned(&self, s: &SymbolData, id: u32) -> bool {
        self.obarray.get(&s.name) == Some(&id)
    }

    /// Mark the macro-expand + lower phase of a top-level form. Returns the
    /// previous setting, which the caller restores — `load` and `eval` nest.
    pub fn set_compiling_form(&mut self, on: bool) -> bool {
        std::mem::replace(&mut self.compiling_form, on)
    }

    /// Whether the symbol at `id` was interned while compiling. See
    /// [`Self::compile_interned`].
    fn interned_at_compile_time(&self, id: u32) -> bool {
        self.compile_interned.contains(&id)
    }

    /// A fingerprint of the builtin object layout: the ordered names of every
    /// interned builtin symbol. Compiled chunks bake in builtin arena handles, so
    /// adding / removing / reordering subrs must invalidate the on-disk bytecode
    /// cache; folding this into the cache key makes that automatic (see
    /// `cache::schema_key`).
    pub fn builtin_fingerprint(&self) -> u64 {
        use std::hash::{Hash, Hasher};
        let mut hasher = std::collections::hash_map::DefaultHasher::new();
        self.builtin_count.hash(&mut hasher);
        for obj in &self.arena[..self.builtin_count] {
            if let Obj::Symbol(s) = obj {
                s.name.hash(&mut hasher);
            }
        }
        hasher.finish()
    }
    /// True if `name`'s function cell still holds its original primitive subr
    /// (not redefined by the user). The compiler only lowers `+`/`<`/… to native
    /// fusevm ops when this holds, so a user `(defun + …)` keeps host semantics.
    /// The subr in `name`'s function cell, or None when the cell holds anything
    /// else (a closure, an advice oclosure, nothing). The compiler loads this
    /// *value* — rather than the symbol — for the primitives Emacs's byte
    /// compiler open-codes, so a call from the prelude reaches the primitive
    /// even after `advice-add` has replaced the symbol's cell.
    pub fn primitive_fn_value(&self, name: &str) -> Option<Value> {
        let f = self
            .obarray
            .get(name)
            .and_then(|&id| self.arena.get(id as usize))
            .and_then(|o| match o {
                Obj::Symbol(s) => s.function.clone(),
                _ => None,
            })?;
        matches!(self.obj(&f), Some(Obj::Subr { .. })).then_some(f)
    }
    pub fn is_primitive_fn(&self, name: &str) -> bool {
        self.obarray
            .get(name)
            .and_then(|&id| self.arena.get(id as usize))
            .and_then(|o| match o {
                Obj::Symbol(s) => s.function.clone(),
                _ => None,
            })
            .map(|f| matches!(self.obj(&f), Some(Obj::Subr { .. })))
            .unwrap_or(false)
    }
    pub fn arena_len(&self) -> usize {
        self.arena.len()
    }
    /// Snapshot the value cells of symbols in `[start, end)` (used to capture the
    /// post-prelude baseline before running a user script for the cache).
    /// A scope chain as `(symbol-handle, value)` pairs, innermost first; a
    /// local special declaration has no value.
    pub fn flatten_lex(&self, env: &Lex) -> Vec<(u32, Option<Value>)> {
        let mut out = Vec::new();
        let mut cur = env.clone();
        while let Some(scope) = cur {
            let val = (!scope.is_declaration()).then(|| scope.value());
            out.push((scope.sym_handle(), val));
            cur = scope.parent_lex();
        }
        out
    }

    /// Rebuild a scope chain from [`Self::flatten_lex`]'s output.
    pub fn rebuild_lex(&self, pairs: Vec<(u32, Option<Value>)>) -> Lex {
        let mut env: Lex = None;
        // Innermost first on the way out, so re-link from the outermost in.
        for (sym, val) in pairs.into_iter().rev() {
            env = Some(Rc::new(match val {
                Some(val) => Scope::new(sym, val, env),
                None => Scope::declaration(sym, env),
            }));
        }
        env
    }

    /// One heap object in its serializable form. `id` is its arena handle (needed
    /// to decide whether a symbol owns its name in the obarray).
    fn ser_obj(&self, o: &Obj, id: u32) -> SerObj {
        match o {
            Obj::Bignum(b) => SerObj::Bignum(b.clone()),
            Obj::Symbol(s) => SerObj::Symbol {
                name: s.name.clone(),
                value: s.value.clone(),
                function: s.function.clone(),
                special: s.special,
                buffer_local_auto: s.buffer_local_auto,
                alias_of: s.alias_of,
                interned: self.symbol_is_interned(s, id),
            },
            Obj::Cons(a, b) => SerObj::Cons(a.clone(), b.clone()),
            Obj::Vector(v) => SerObj::Vector(v.clone()),
            Obj::Record(v) => SerObj::Record(v.clone()),
            Obj::BoolVector(v) => SerObj::BoolVector(v.clone()),
            Obj::Str(s) => SerObj::Str(s.to_string()),
            Obj::HashTable(t) => SerObj::HashTable {
                test: t.test,
                slots: t.slots.clone(),
                free: t.free.clone(),
                size: t.size,
                weakness: t.weakness.clone(),
                user_test: t.user_test.clone(),
            },
            Obj::CharTable(t) => SerObj::CharTable {
                subtype: t.subtype.clone(),
                default: t.default.clone(),
                parent: t.parent.clone(),
                extra: t.extra.clone(),
                contents: t.flatten(),
                ascii: match &t.ascii {
                    CtAscii::Val(v) => Some(v.clone()),
                    CtAscii::Tree => None,
                },
            },
            Obj::Closure {
                params,
                body,
                is_macro,
                env,
                dynamic,
                src,
            } => SerObj::Closure {
                required: params.required.clone(),
                optional: params.optional.clone(),
                rest: params.rest,
                body: (**body).clone(),
                is_macro: *is_macro,
                env: self.flatten_lex(env),
                dynamic: *dynamic,
                arglist: src.arglist.clone(),
                src_body: src.body.clone(),
            },
            // Runtime-only objects (and subrs, which `install` recreates): a
            // placeholder keeps the arena indices aligned.
            Obj::Subr { .. }
            | Obj::Buffer(_)
            | Obj::Marker(_)
            | Obj::Overlay(_)
            | Obj::Window(_)
            | Obj::Frame(_)
            | Obj::WindowConfig(_)
            | Obj::Obarray(_) => SerObj::Symbol {
                name: "--unexpected-runtime-obj--".to_string(),
                value: None,
                function: None,
                special: false,
                buffer_local_auto: false,
                alias_of: None,
                interned: false,
            },
        }
    }

    /// Serialize an arena range exactly as it stands. Taken right after the
    /// prelude, this is the clean state the cached chunks expect to replay onto.
    pub fn export_heap_range(&self, start: usize, end: usize) -> Vec<SerObj> {
        self.arena[start..end]
            .iter()
            .enumerate()
            .map(|(off, o)| self.ser_obj(o, (start + off) as u32))
            .collect()
    }

    /// The cells the prelude installed on symbols that already existed when
    /// `builtins::install` finished — the arena's `[0, builtin_count)` prefix.
    ///
    /// `export_heap_range` starts AT `builtin_count`, because a builtin object is
    /// rebuilt by `install` on every run and re-importing one would be wrong (an
    /// `Obj::Subr` has a function pointer and does not survive `SerObj` at all).
    /// But the prelude *writes* to symbols in that prefix, and those writes were
    /// silently dropped from every heap image:
    ///
    /// ```text
    ///   elisp probe.el   # cold: (macrop 'save-current-buffer) => t
    ///   elisp probe.el   # warm: (macrop 'save-current-buffer) => nil
    /// ```
    ///
    /// and the warm run then could not compile a `save-current-buffer` form at
    /// all, because the macro that lowers it was gone. `install` is
    /// deterministic, so the prefix's *objects* are identical on both runs and
    /// only their cells need carrying — which is what this exports and
    /// [`Self::import_builtin_cells`] applies.
    pub fn export_builtin_cells(&self) -> Vec<Option<SymbolBaseline>> {
        self.snapshot_values(0, self.builtin_count)
    }

    /// Apply an [`Self::export_builtin_cells`] snapshot. Indices beyond this
    /// build's builtin prefix are ignored: a shard from a binary with a
    /// different builtin set is already rejected by the schema key, and
    /// tolerating a short or long vector here costs nothing.
    pub fn import_builtin_cells(&mut self, cells: Vec<Option<SymbolBaseline>>) {
        for (i, cell) in cells.into_iter().enumerate() {
            let (Some(cell), Some(Obj::Symbol(sym))) = (cell, self.arena.get_mut(i)) else {
                continue;
            };
            sym.value = cell.value;
            sym.function = cell.function;
            sym.buffer_local_auto = cell.buffer_local_auto;
            sym.alias_of = cell.alias_of;
        }
    }

    /// The per-buffer state the prelude builds outside the arena: the
    /// always-local slot registry and every buffer's local bindings
    /// (`default-directory`, `major-mode`, the syntax table, ...).
    ///
    /// A cache hit skips the prelude, so without this a warm run starts with
    /// `default-directory` unbound in the initial buffer where a cold run has
    /// the working directory (`(expand-file-name "a")` then signals
    /// `(wrong-type-argument arrayp nil)`). Values are arena handles, valid
    /// because the image is imported into an arena of the same length.
    pub fn export_buffer_state(&self) -> BufferState {
        BufferState {
            always_local: self.always_local.clone(),
            locals: self
                .buffers
                .iter()
                .map(|b| {
                    // In binding order: `buffer-local-variables` reports it.
                    b.locals
                        .iter()
                        .map(|(k, v)| (*k, v.clone()))
                        .collect::<Vec<_>>()
                })
                .collect(),
        }
    }

    /// Apply an [`Self::export_buffer_state`] snapshot. Buffers past this
    /// host's own are ignored, as in [`Self::import_builtin_cells`].
    pub fn import_buffer_state(&mut self, state: BufferState) {
        self.always_local = state.always_local;
        for (b, locals) in self.buffers.iter_mut().zip(state.locals) {
            b.locals = locals.into_iter().collect();
        }
    }

    pub fn snapshot_values(&self, start: usize, end: usize) -> Vec<Option<SymbolBaseline>> {
        (start..end)
            .map(|i| match self.arena.get(i) {
                Some(Obj::Symbol(s)) => Some(SymbolBaseline {
                    value: s.value.clone(),
                    function: s.function.clone(),
                    buffer_local_auto: s.buffer_local_auto,
                    alias_of: s.alias_of,
                }),
                _ => None,
            })
            .collect()
    }
    /// The part of a clean heap image this FILE owns: `arena[prelude_end..]`,
    /// with every run-time mutation cleared.
    ///
    /// The other part — `arena[builtin_count, prelude_end)` — is
    /// [`Self::export_heap_range`] taken before the file ran, and is the same
    /// bytes for every file compiled by this binary against this prelude. It is
    /// therefore stored once per shard rather than once per entry (`cache.rs`
    /// shard format v13); the full image a cache hit replays is that base
    /// followed by this tail, concatenated in `cache::get`.
    pub fn export_heap_tail_clean(&self, prelude_end: usize) -> Vec<SerObj> {
        // The image a cache hit replays onto must be the heap as it stood BEFORE
        // this file ran, because the cached chunks re-apply every effect the file
        // had. Exporting the post-run heap double-applies them:
        //
        //   - a prelude object the file mutated comes back already mutated. The
        //     symbol-plist table is the visible case — `(get 'g 'custom-group)`
        //     returned the previous run's entries, and the replay appended to
        //     them again.
        //   - an order-dependent symbol flag changes the result outright: a
        //     `make-variable-buffer-local` left `buffer_local_auto` set, so
        //     replaying the file's own `(defvar bl-y nil)` created a buffer-local
        //     binding the cold run never had.
        //
        // So: prelude objects come from the snapshot taken before the run, and
        // objects the file itself created keep only what the COMPILER gave them
        // (`special` — a cache hit does not compile, so nothing would set it
        // again); everything the chunks set at run time is cleared.
        let mut out: Vec<SerObj> = Vec::with_capacity(self.arena.len() - prelude_end);
        for (off, o) in self.arena[prelude_end..].iter().enumerate() {
            let id = (prelude_end + off) as u32;
            let ser = match o {
                Obj::Symbol(s) => SerObj::Symbol {
                    name: s.name.clone(),
                    value: None,
                    function: None,
                    special: s.special,
                    buffer_local_auto: false,
                    alias_of: None,
                    // NOT `symbol_is_interned`: a symbol the RUN interned is not
                    // part of the file, and re-claiming its name on every later
                    // hit leaks one invocation's data into the next.
                    interned: self.symbol_is_interned(s, id) && self.interned_at_compile_time(id),
                },
                other => self.ser_obj(other, id),
            };
            out.push(ser);
        }
        out
    }
    /// Rebuild the user/prelude heap from an image. Must be called on a fresh
    /// host (arena == builtins only) so handles line up with compile time.
    pub fn import_heap_image(&mut self, image: Vec<SerObj>) {
        for ser in image {
            let id = self.arena.len() as u32;
            let obj = match ser {
                SerObj::Cons(a, b) => Obj::Cons(a, b),
                SerObj::Bignum(b) => Obj::Bignum(b),
                SerObj::Symbol {
                    name,
                    value,
                    function,
                    special,
                    buffer_local_auto,
                    alias_of,
                    interned,
                } => {
                    // Only a symbol that *was* the global binding for its name may
                    // claim that name again. Re-interning an uninterned symbol
                    // here would shadow a builtin of the same name with a copy
                    // that has no function cell.
                    if interned {
                        self.obarray.insert(name.clone(), id);
                    }
                    Obj::Symbol(SymbolData {
                        name,
                        value,
                        function,
                        special,
                        buffer_local_auto,
                        alias_of,
                    })
                }
                SerObj::Vector(v) => Obj::Vector(v),
                SerObj::Record(v) => Obj::Record(v),
                SerObj::BoolVector(v) => Obj::BoolVector(v),
                SerObj::Str(s) => Obj::Str(Arc::new(s)),
                SerObj::HashTable {
                    test,
                    slots,
                    free,
                    size,
                    weakness,
                    user_test,
                } => {
                    let mut t = ElHashTable::from_slots(test, slots, free, size, weakness);
                    t.user_test = user_test;
                    Obj::HashTable(t)
                }
                SerObj::CharTable {
                    subtype,
                    default,
                    parent,
                    extra,
                    contents,
                    ascii,
                } => Obj::CharTable(CharTable {
                    subtype,
                    default,
                    parent,
                    extra,
                    contents: CharTable::unflatten(&contents),
                    ascii: match ascii {
                        Some(v) => CtAscii::Val(v),
                        None => CtAscii::Tree,
                    },
                }),
                SerObj::Closure {
                    required,
                    optional,
                    rest,
                    body,
                    is_macro,
                    env,
                    dynamic,
                    arglist,
                    src_body,
                } => Obj::Closure {
                    params: Rc::new(Params {
                        required,
                        optional,
                        rest,
                    }),
                    src: Rc::new(ClosureSrc {
                        arglist,
                        body: src_body,
                        raw_body: None,
                    }),
                    body: Rc::new(body),
                    is_macro,
                    env: self.rebuild_lex(env),
                    dynamic,
                },
            };
            self.arena.push(obj);
        }
    }
    /// Bind a closure's params into the already-open current scope.
    pub fn bind_params_into_scope(
        &mut self,
        params: &Params,
        args: &[Value],
    ) -> Result<(), String> {
        if args.len() < params.required.len() {
            return Err("wrong-number-of-arguments".to_string());
        }
        let max = params.required.len() + params.optional.len();
        if params.rest.is_none() && args.len() > max {
            return Err("wrong-number-of-arguments".to_string());
        }
        let mut i = 0;
        for &id in &params.required {
            self.bind_here(id, args[i].clone());
            i += 1;
        }
        for &id in &params.optional {
            let v = args.get(i).cloned().unwrap_or(Value::Undef);
            self.bind_here(id, v);
            i += 1;
        }
        if let Some(id) = params.rest {
            let rest = args.get(i..).map(|s| s.to_vec()).unwrap_or_default();
            let lst = self.list_from(rest);
            self.bind_here(id, lst);
        }
        Ok(())
    }

    /// Parse a lambda list form into structured params (interning the symbols).
    pub fn parse_params(&mut self, arglist: &Value) -> Result<Params, String> {
        let items = self.list_vec(arglist).ok_or("malformed lambda list")?;
        let mut p = Params {
            required: vec![],
            optional: vec![],
            rest: None,
        };
        let mut mode = 0u8;
        for it in items {
            let id = self.sym_handle(&it).ok_or("lambda list: expected symbol")?;
            let name = self.sym_name(&it).unwrap_or_default();
            match name.as_str() {
                "&optional" => mode = 1,
                "&rest" => mode = 2,
                _ => match mode {
                    0 => p.required.push(id),
                    1 => p.optional.push(id),
                    _ => p.rest = Some(id),
                },
            }
        }
        Ok(p)
    }

    /// What `f` currently names, following the same alias chain as
    /// [`Self::resolve_function`] but building none of the callable — see
    /// [`FnKind`]. Used by the pre-argument arity guard at both compile and run
    /// time, so the two always agree on what counts as a subr.
    pub fn fn_kind(&self, f: &Value) -> FnKind {
        let mut cur = f.clone();
        for _ in 0..64 {
            let next = match self.obj(&cur) {
                Some(Obj::Subr { min, max, .. }) => return FnKind::Subr(*min, *max),
                Some(Obj::Symbol(s)) => s.function.clone(),
                Some(_) => return FnKind::Other,
                None => return FnKind::Vacant,
            };
            match next {
                Some(v) => cur = v,
                None => return FnKind::Vacant,
            }
        }
        FnKind::Other
    }

    /// Record that elisp-level `fset`/`defalias` pointed `sym` at a subr. See
    /// `Self::subr_aliased`.
    pub fn note_subr_alias(&mut self, sym: &Value, def: &Value) {
        if matches!(self.fn_kind(def), FnKind::Subr(..)) {
            if let Some(id) = self.sym_handle(sym) {
                self.subr_aliased.insert(id);
            }
        }
    }

    /// Whether `sym` has ever been `fset` to a subr. See `Self::subr_aliased`.
    pub fn is_subr_aliased(&self, sym: &Value) -> bool {
        self.sym_handle(sym)
            .is_some_and(|id| self.subr_aliased.contains(&id))
    }

    /// Resolve a function designator (symbol → function cell, following aliases;
    /// or a literal closure/subr object).
    /// Follow `f` through symbol function cells; `Some(list)` when it ends at a
    /// cons whose car is `lambda` (eval.c `funcall_general`'s `Qlambda` case).
    pub fn indirect_lambda_list(&self, f: &Value) -> Option<Value> {
        let mut cur = f.clone();
        for _ in 0..64 {
            match self.obj(&cur) {
                Some(Obj::Symbol(s)) => cur = s.function.clone()?,
                Some(Obj::Cons(car, _)) => {
                    return (self.sym_name(car).as_deref() == Some("lambda")).then_some(cur);
                }
                _ => return None,
            }
        }
        None
    }
    /// Follow `f` through symbol function cells; `Some(fundef)` when it ends at
    /// an `(autoload FILE ...)` object (eval.c `funcall_general`'s autoload
    /// case), which a call must load before it can run.
    pub fn indirect_autoload(&self, f: &Value) -> Option<Value> {
        let mut cur = f.clone();
        for _ in 0..64 {
            match self.obj(&cur) {
                Some(Obj::Symbol(s)) => cur = s.function.clone()?,
                Some(Obj::Cons(car, _)) => {
                    return (self.sym_name(car).as_deref() == Some("autoload")).then_some(cur);
                }
                _ => return None,
            }
        }
        None
    }
    pub fn resolve_function(&self, f: &Value) -> Result<Resolved, String> {
        let mut cur = f.clone();
        for _ in 0..64 {
            match self.obj(&cur) {
                Some(Obj::Subr { f, min, max, name }) => {
                    return Ok(Resolved::Subr {
                        f: *f,
                        min: *min,
                        max: *max,
                        name: name.clone(),
                    })
                }
                Some(Obj::Closure {
                    params,
                    body,
                    is_macro,
                    env,
                    dynamic,
                    ..
                }) => {
                    return Ok(Resolved::Closure {
                        params: params.clone(),
                        body: body.clone(),
                        is_macro: *is_macro,
                        env: env.clone(),
                        dynamic: *dynamic,
                        object: cur.clone(),
                    })
                }
                Some(Obj::Symbol(s)) => match &s.function {
                    Some(def) => cur = def.clone(),
                    None => return Err(format!("void-function: {}", s.name)),
                },
                // NOTE: no `pending_error` here. This function is also called
                // speculatively (`macroexpand_1` asks whether a head names a
                // macro), so a side effect would outlive the failed probe and be
                // mistaken for the next real error.
                //
                // `t` and `nil` ARE symbols in Emacs — they just have no function
                // cell — so calling one is `void-function`, not `invalid-function`.
                // elisprs represents them as `Value::Bool`/`Value::Undef` rather
                // than heap symbols, so they need naming here.
                None if matches!(cur, Value::Bool(true)) => {
                    return Err("void-function: t".to_string())
                }
                None if matches!(cur, Value::Undef | Value::Bool(false)) => {
                    return Err("void-function: nil".to_string())
                }
                _ => return Err(format!("invalid-function: {}", self.print(&cur, true))),
            }
        }
        Err("function indirection too deep".to_string())
    }

    // ── printing ──
    pub fn print(&self, v: &Value, readable: bool) -> String {
        self.print_overflow.set(false);
        self.print_backquote_depth.set(0);
        self.print_labels.borrow_mut().clear();
        self.print_being.borrow_mut().clear();
        self.print_next_label.set(1);
        // `print-circle` is opt-in: only then does the printer pay for the
        // reference-counting pre-pass that finds the objects needing `#N=` labels.
        self.print_circle_on.set(self.print_flag("print-circle"));
        self.print_gensym_on.set(self.print_flag("print-gensym"));
        if self.print_circle_on.get() {
            self.print_next_label.set(1);
            self.print_preprocess(v);
        }
        self.print_inner(v, readable, 0)
    }

    /// print.c `print_preprocess`: fill the label table from the structure of V.
    ///
    /// The label NUMBER is assigned here, at the moment an object is met for the
    /// SECOND time in this traversal — not when it is finally printed. The two
    /// orders differ, and the difference is observable: in
    /// `(let ((print-circle t)) (prin1-to-string ROOT))` over a graph where the
    /// vector element printed first is met-twice later than a cons printed after
    /// it, Emacs answers `([#2=#s(r …) [#1=(9 . 9) …]] #1# (#2# 3))` — `#2` before
    /// `#1` in the output. Numbering at print time gets the labels backwards.
    ///
    /// Traversal is print.c's explicit-stack DFS: for a cons, push the CDR (unless
    /// nil) and continue into the CAR; for a vector-like, push every element and
    /// take them left to right. An object met again is neither renumbered nor
    /// re-descended, so a cycle terminates.
    ///
    /// The table doubles as print.c's status field: `0` is `Qt` ("seen once, no
    /// label"), `-N` is "label N assigned, not yet printed", `N` is "already
    /// printed as `#N=`".
    ///
    /// Candidates are what `PRINT_CIRCLE_CANDIDATE_P` accepts: cons, vector,
    /// record, char-table, closure, hash-table — and STRING, which print.c lists
    /// first (`STRINGP (obj) || CONSP (obj) || ...`). The containers are also what
    /// makes a cycle safe under `print-circle` t: the depth ceiling does NOT run
    /// in that mode (Emacs prints a 250-deep nest fine), so termination rests on
    /// every container that can close a cycle being labellable. A string closes
    /// nothing, but it is shareable, and since shard format v10 made it an arena
    /// object (`Obj::Str`) it has the identity the label table needs:
    ///
    /// ```text
    ///   (let ((print-circle t) (s "ab")) (prin1-to-string (list s s)))
    ///   emacs => "(#1=\"ab\" #1#)"
    ///   elisp => "(\"ab\" \"ab\")"   [before]
    /// ```
    ///
    /// which the fuzzer reached through an error datum:
    /// `(rassoc "!" (append (make-list 3 "foo10") 2))` signals with a list whose
    /// three elements are one string object.
    fn print_preprocess(&self, v: &Value) {
        let mut stack: Vec<Value> = Vec::new();
        let mut obj = v.clone();
        loop {
            if let Value::Obj(id) = obj {
                // The marker a char-table pushes after the slots of the sub-table
                // its `ascii` slot shares with the tree: reaching it is the SECOND
                // encounter, which is when print.c numbers an object.
                if id & CT_ASCII_LABEL != 0 {
                    let mut labels = self.print_labels.borrow_mut();
                    if let std::collections::hash_map::Entry::Vacant(e) = labels.entry(id) {
                        let n = self.print_next_label.get();
                        self.print_next_label.set(n + 1);
                        e.insert(-(n as i64));
                    }
                    drop(labels);
                    match stack.pop() {
                        Some(next) => {
                            obj = next;
                            continue;
                        }
                        None => break,
                    }
                }
                // Children in print order; `None` for a non-candidate.
                let children: Option<Vec<Value>> = match self.arena.get(id as usize) {
                    Some(Obj::Cons(car, cdr)) => {
                        // print.c: `if (!NILP (XCDR (obj))) push (XCDR (obj));
                        //           obj = XCAR (obj); continue;`
                        let mut kids = vec![car.clone()];
                        if el_truthy(cdr) {
                            kids.push(cdr.clone());
                        }
                        Some(kids)
                    }
                    // A zero-length string or vector is never labelled: Emacs
                    // shares one `zero_vector` / empty string, and prints
                    // `(let ((v (vector))) (list v v))` as `([] [])`, not
                    // `(#1=[] #1#)` (measured, 31.1; same for `""`).
                    Some(Obj::Vector(items)) if items.is_empty() => None,
                    Some(Obj::Str(a)) if a.is_empty() => None,
                    Some(Obj::Vector(items)) | Some(Obj::Record(items)) => Some(items.clone()),
                    // print.c:1431-1436 — "A string may have text properties,
                    // which can be circular": the children are the plists of the
                    // string's text-property INTERVALS, reached through
                    // `traverse_intervals_noorder`.
                    //
                    // Emacs walks intervals; this heap stores one plist per
                    // CHARACTER, so the run grouping has to be reconstructed with
                    // exactly the test `string_prop_intervals` prints with, or the
                    // counts disagree with Emacs's. Visiting per character instead
                    // makes every value inside a multi-character run look shared and
                    // earns it a `#N=` label Emacs does not print:
                    // `(put-text-property 0 3 'p '(1) (copy-sequence "abc"))`
                    // printed `#("abc" 0 3 (p #1=(1)))` against Emacs's
                    // `#("abc" 0 3 (p (1)))`.
                    //
                    // Without this arm at all, a cycle THROUGH a text property —
                    // which `#1=#("x" 0 1 (p #1#))` reads and `put-text-property`
                    // builds — was never labelled and the printer recursed into it
                    // until the stack overflowed.
                    Some(Obj::Str(a)) => {
                        let kids: Vec<Value> = self
                            .string_intervals(a)
                            .into_iter()
                            .filter(|(_, _, p)| el_truthy(p))
                            .map(|(_, _, p)| p)
                            .collect();
                        Some(kids)
                    }
                    // print.c walks a char-table as a vector: defalt, parent,
                    // purpose, the cached ASCII slot, the 64 contents slots,
                    // then the extras. A sub-char-table is not a heap object,
                    // but the depth-3 table `ascii` caches is the SAME object
                    // as the tree's `[0][0][0]`, so it is met twice and gets a
                    // label under `print-circle`, keyed by a synthetic id.
                    Some(Obj::CharTable(t)) => {
                        let mut kids = vec![t.default.clone(), t.parent.clone(), t.subtype.clone()];
                        let shared = matches!(t.ascii, CtAscii::Tree);
                        match &t.ascii {
                            CtAscii::Val(v) => kids.push(v.clone()),
                            CtAscii::Tree => {
                                if let Some(sub) = t.ascii_table() {
                                    sub.leaf_values(&mut kids);
                                }
                                // The shared table is met a second time on the way
                                // down the tree, after its own slots: a marker object
                                // numbers it at that point in the walk.
                                kids.push(Value::Obj(id | CT_ASCII_LABEL));
                            }
                        }
                        for slot in &t.contents {
                            slot.leaf_values(&mut kids, shared);
                        }
                        kids.extend(t.extra.iter().cloned());
                        Some(kids)
                    }
                    Some(Obj::Closure { src, .. }) => {
                        let mut kids = vec![src.arglist.clone()];
                        kids.extend(src.body.iter().cloned());
                        Some(kids)
                    }
                    Some(Obj::HashTable(t)) => {
                        let mut kids = Vec::with_capacity(t.count() * 2);
                        for (k, val) in t.pairs() {
                            kids.push(k.clone());
                            kids.push(val.clone());
                        }
                        Some(kids)
                    }
                    // `(! NILP (Vprint_gensym) && SYMBOLP (obj) && !SYMBOL_INTERNED_P
                    // (obj))`: a shared gensym gets a label, so `(list s s)` prints
                    // `(#1=#:x #1#)`. A leaf — it has no children to descend into.
                    Some(Obj::Symbol(_))
                        if self.print_gensym_on.get() && !self.interned_in_standard_obarray(id) =>
                    {
                        Some(Vec::new())
                    }
                    _ => None,
                };
                if let Some(kids) = children {
                    let mut labels = self.print_labels.borrow_mut();
                    match labels.get(&id).copied() {
                        // `Qt`: OBJ appears more than once. Number it now.
                        Some(0) => {
                            let n = self.print_next_label.get();
                            self.print_next_label.set(n + 1);
                            labels.insert(id, -(n as i64));
                        }
                        // Already numbered — print.c's `if (SYMBOLP (num))` is false,
                        // so no new index and no descent.
                        Some(_) => {}
                        None => {
                            labels.insert(id, 0);
                            drop(labels);
                            // Pushed in reverse so `pop` yields them left to right,
                            // which is what print.c's array entry does; anything a
                            // child pushes lands above its siblings, so each subtree
                            // completes before the next sibling — a plain DFS.
                            stack.extend(kids.into_iter().rev());
                        }
                    }
                }
            }
            match stack.pop() {
                Some(next) => obj = next,
                None => break,
            }
        }
    }

    /// The `#N=` / `#N#` prefix for OBJ, or None when it needs no label — print.c
    /// `print_object`'s `PRINT_CIRCLE_CANDIDATE_P` arm.
    ///
    /// Returns `Some(Err(text))` when the object was already printed — the caller
    /// emits `text` (`#N#`) INSTEAD of the object — and `Some(Ok(text))` on the
    /// first visit, where `text` (`#N=`) is a prefix and the object still prints
    /// in full. A `0` slot is print.c's `Qt`: a candidate that turned out not to be
    /// shared, which prints with no label at all.
    #[allow(clippy::result_large_err)]
    fn circle_label(&self, v: &Value) -> Option<Result<String, String>> {
        let Value::Obj(id) = v else { return None };
        let mut labels = self.print_labels.borrow_mut();
        let slot = labels.get_mut(id)?;
        match (*slot).cmp(&0) {
            std::cmp::Ordering::Equal => None,
            // Negative: "hasn't been printed yet" — emit `#N=` and flip the sign.
            std::cmp::Ordering::Less => {
                let n = -*slot;
                *slot = n;
                Some(Ok(format!("#{n}=")))
            }
            std::cmp::Ordering::Greater => Some(Err(format!("#{slot}#"))),
        }
    }

    /// Like `print`, but returns Emacs's `error "Apparently circular structure
    /// being printed"` when the value nested `PRINT_CIRCLE` deep (matching
    /// print.c: with `print-circle` nil, that depth signals rather than prints).
    pub fn print_checked(&self, v: &Value, readable: bool) -> Result<String, String> {
        let s = self.print(v, readable);
        if self.print_overflow.get() {
            return Err("Apparently circular structure being printed".to_string());
        }
        Ok(s)
    }

    /// Read a non-negative integer dynamic var (`print-length`/`print-level`) for
    /// the printer; None when unset/nil/negative (i.e. no limit).
    fn print_limit(&self, name: &str) -> Option<usize> {
        let id = *self.obarray.get(name)?;
        match self.arena.get(id as usize)? {
            Obj::Symbol(s) => match s.value.as_ref()? {
                Value::Int(n) if *n >= 0 => Some(*n as usize),
                _ => None,
            },
            _ => None,
        }
    }

    /// print.c `float_to_string` for a finite F: `float-output-format`, when it
    /// is a string Emacs accepts (`%.` then at most `DBL_DIG` digits, zero only
    /// for `f`, then one of `e` `f` `g`), and the shortest round-trip form
    /// otherwise. A result that would not read back as a float gets `.0`, except
    /// under `%.0f`.
    fn float_to_string(&self, f: f64) -> String {
        let spec = self
            .obarray
            .get("float-output-format")
            .and_then(|id| match self.arena.get(*id as usize) {
                Some(Obj::Symbol(s)) => s.value.clone(),
                _ => None,
            })
            .and_then(|v| self.str_text(&v).map(str::to_string));
        let Some((prec, conv)) = spec.as_deref().and_then(parse_float_output_format) else {
            return format_float(f);
        };
        let s = match conv {
            'f' => format!("{f:.prec$}", prec = prec.unwrap_or(0)),
            'e' => {
                let e_form = format!("{:.*e}", prec.unwrap_or(0), f);
                let (mantissa, exp) = e_form.rsplit_once('e').unwrap_or((&e_form, "0"));
                let exp: i32 = exp.parse().unwrap_or(0);
                let sign = if exp < 0 { '-' } else { '+' };
                format!("{mantissa}e{sign}{:02}", exp.abs())
            }
            _ => format_g(f, prec.unwrap_or(0)),
        };
        if prec == Some(0) {
            return s;
        }
        // The first character that is not a digit or `-` must be a `.` with a
        // digit after it, or an exponent.
        match s.find(|c: char| !c.is_ascii_digit() && c != '-') {
            None => format!("{s}.0"),
            Some(i) if i + 1 == s.len() && s.ends_with('.') => format!("{s}0"),
            _ => s,
        }
    }

    /// The body of a string under `prin1`, a port of print.c's string loop.
    ///
    /// `"` and `\` are backslashed; `print-escape-newlines` writes newline and
    /// formfeed as `\n` / `\f`; `print-escape-control-characters` writes the
    /// other control characters through `octalout`; and
    /// `print-escape-multibyte` writes every non-ASCII character as `\xXXXX`
    /// (at least four hex digits), following it with `\ ` when the next
    /// character is a hex digit that would otherwise extend the escape.
    fn escape_string_body(&self, s: &str) -> String {
        let esc_newlines = self.print_flag("print-escape-newlines");
        let esc_control = self.print_flag("print-escape-control-characters");
        let esc_multibyte = self.print_flag("print-escape-multibyte");
        let chars: Vec<char> = s.chars().collect();
        let mut out = String::with_capacity(s.len() + 2);
        let mut need_nonhex = false;
        for (i, &c) in chars.iter().enumerate() {
            if esc_multibyte && !c.is_ascii() {
                out.push_str(&format!("\\x{:04x}", c as u32));
                need_nonhex = true;
                continue;
            }
            if need_nonhex && c.is_ascii_hexdigit() {
                out.push_str("\\ ");
            }
            need_nonhex = false;
            match c {
                '\n' if esc_newlines => out.push_str("\\n"),
                '\u{c}' if esc_newlines => out.push_str("\\f"),
                '"' | '\\' => {
                    out.push('\\');
                    out.push(c);
                }
                c if esc_control && c.is_ascii_control() => {
                    // `octalout`: three digits when C needs them or when the
                    // next character is an octal digit, else as few as fit.
                    let next_octal = chars.get(i + 1).is_some_and(|n| ('0'..='7').contains(n));
                    let c = c as u32;
                    let digits = if c > 0o77 || next_octal {
                        3
                    } else if c > 0o7 {
                        2
                    } else {
                        1
                    };
                    out.push_str(&format!("\\{c:0digits$o}"));
                }
                _ => out.push(c),
            }
        }
        out
    }

    /// `print-integers-as-characters`: print.c writes a fixnum as `?C` when it is
    /// a character that reads back as itself -- a printable ASCII character, one
    /// of `\b \t \n \f \r`, or a non-ASCII letter, number, punctuation, symbol
    /// or private-use character.  Marks, separators, format and control
    /// characters stay numbers.  `"'();[]{}` and the backslash are backslashed.
    fn int_as_character(&self, n: i64) -> Option<String> {
        use std::sync::OnceLock;
        static GRAPHIC: OnceLock<fancy_regex::Regex> = OnceLock::new();
        if !self.print_flag("print-integers-as-characters") {
            return None;
        }
        let c = char::from_u32(u32::try_from(n).ok()?)?;
        let body = match c {
            '\u{8}' => "\\b".to_string(),
            '\t' => "\\t".to_string(),
            '\n' => "\\n".to_string(),
            '\u{c}' => "\\f".to_string(),
            '\r' => "\\r".to_string(),
            ' ' => "\\s".to_string(),
            '"' | '\'' | '(' | ')' | ';' | '[' | '\\' | ']' | '{' | '}' => format!("\\{c}"),
            ' '..='~' => c.to_string(),
            c if c.is_ascii() => return None,
            c => {
                let graphic = GRAPHIC.get_or_init(|| {
                    fancy_regex::Regex::new(r"^[\p{L}\p{N}\p{P}\p{S}\p{Co}]$")
                        .expect("static regex")
                });
                if !graphic.is_match(&c.to_string()).unwrap_or(false) {
                    return None;
                }
                c.to_string()
            }
        };
        Some(format!("?{body}"))
    }

    /// True if a printer flag dynamic var (e.g. `print-escape-newlines`) is non-nil.
    fn print_flag(&self, name: &str) -> bool {
        self.print_flag_or(name, false)
    }

    /// Like `print_flag` but uses DEFAULT when the variable is unbound (e.g.
    /// `print-quoted` defaults to t).
    fn print_flag_or(&self, name: &str, default: bool) -> bool {
        match self
            .obarray
            .get(name)
            .and_then(|id| self.arena.get(*id as usize))
        {
            Some(Obj::Symbol(s)) => s.value.as_ref().map(el_truthy).unwrap_or(default),
            _ => default,
        }
    }

    /// Print a sequence's elements honoring `print-length` (truncate with `...`).
    fn print_seq(&self, items: &[Value], readable: bool, depth: usize) -> Vec<String> {
        let limit = self.print_limit("print-length");
        let mut parts = Vec::new();
        for (i, e) in items.iter().enumerate() {
            if limit.is_some_and(|lim| i >= lim) {
                parts.push("...".to_string());
                break;
            }
            parts.push(self.print_inner(e, readable, depth));
        }
        parts
    }

    /// One nesting level of the printer is a few Rust frames, and with
    /// `print-circle` non-nil there is no `PRINT_CIRCLE` ceiling at all, so a
    /// deep-but-finite nest recurses as deep as the data. Grow the stack on
    /// demand on the same thread, as `reader.rs`'s `read_form` and
    /// `run_closure` do, so a caller on a default-sized thread (an embedder, a
    /// libtest worker) prints what the `elisp` binary's interpreter thread prints.
    fn print_inner(&self, v: &Value, readable: bool, depth: usize) -> String {
        stacker::maybe_grow(128 * 1024, 8 * 1024 * 1024, || {
            self.print_inner_frame(v, readable, depth)
        })
    }

    fn print_ct_slot(&self, slot: &CtSlot, key: u32, readable: bool, depth: usize) -> String {
        match slot {
            CtSlot::Val(v) => self.print_inner(v, readable, depth),
            CtSlot::Sub(s) => self.print_sub_char_table(s, key, readable, depth),
        }
    }

    /// A sub-char-table. The one at `[0][0][0]` is the object `ascii` caches, so
    /// under `print-circle` it prints as `#N=` the first time and `#N#` after.
    fn print_sub_char_table(
        &self,
        sub: &SubCharTable,
        key: u32,
        readable: bool,
        depth: usize,
    ) -> String {
        if sub.depth == 3 && sub.min_char == 0 && self.print_circle_on.get() {
            let mut labels = self.print_labels.borrow_mut();
            if let Some(slot) = labels.get_mut(&key) {
                if *slot > 0 {
                    return format!("#{slot}#");
                }
                let n = -*slot;
                *slot = n;
                drop(labels);
                return format!("#{n}={}", self.print_sub_body(sub, key, readable, depth));
            }
        }
        self.print_sub_body(sub, key, readable, depth)
    }

    fn print_sub_body(&self, sub: &SubCharTable, key: u32, readable: bool, depth: usize) -> String {
        let mut parts = vec![sub.depth.to_string(), sub.min_char.to_string()];
        for slot in &sub.contents {
            parts.push(self.print_ct_slot(slot, key, readable, depth));
        }
        format!("#^^[{}]", parts.join(" "))
    }

    fn print_inner_frame(&self, v: &Value, readable: bool, depth: usize) -> String {
        // print.c `print_object`'s prologue, in its own order: the whole
        // `being_printed` mechanism (and the `PRINT_CIRCLE` ceiling that guards it)
        // is the `NILP (Vprint_circle)` arm, and the `#N=`/`#N#` label table is the
        // other. They are alternatives, never both.
        if self.print_circle_on.get() {
            match self.circle_label(v) {
                // Already printed once: emit the back-reference INSTEAD of
                // re-printing (this is what terminates a circular structure).
                Some(Err(backref)) => return backref,
                Some(Ok(prefix)) => {
                    return format!("{prefix}{}", self.print_body(v, readable, depth))
                }
                None => {}
            }
        } else {
            // `if (print_depth >= PRINT_CIRCLE) error ("Apparently circular
            // structure being printed");` — stop recursing (both to match Emacs and
            // to keep the Rust call stack bounded) and flag it for `print_checked`.
            if depth >= PRINT_CIRCLE {
                self.print_overflow.set(true);
                return String::new();
            }
            // `for (int i = 0; i < print_depth; i++) if (BASE_EQ (obj,
            // being_printed[i])) → "#i"`. An object that is its own ancestor prints
            // as the index of the enclosing copy rather than recursing forever.
            let id = match v {
                Value::Obj(id) => Some(*id),
                _ => None,
            };
            if id.is_some() {
                let being = self.print_being.borrow();
                for (i, slot) in being.iter().take(depth).enumerate() {
                    if *slot == id {
                        return format!("#{i}");
                    }
                }
            }
            // `being_printed[print_depth] = obj;`
            let mut being = self.print_being.borrow_mut();
            if being.len() <= depth {
                being.resize(depth + 1, None);
            }
            being[depth] = id;
        }
        self.print_body(v, readable, depth)
    }

    /// `print_inner` minus the depth guard and the `print-circle` labelling — the
    /// actual per-type rendering. Split out so a labelled object can emit its
    /// `#N=` prefix and then print its body without re-entering the label check
    /// (which would see the label already assigned and emit `#N#` forever).
    fn print_body(&self, v: &Value, readable: bool, depth: usize) -> String {
        // A string OBJECT renders through the `Value::Str` arm below on a view of
        // its current text. The view shares the cell's `Arc`, which is what the
        // `#("abc" 0 3 (p 1))` propertized form looks its intervals up under.
        let view;
        let v = match self.obj(v) {
            Some(Obj::Str(s)) => {
                view = Value::Str(Arc::clone(s));
                &view
            }
            _ => v,
        };
        match v {
            Value::Undef => "nil".to_string(),
            Value::Bool(true) => "t".to_string(),
            Value::Bool(false) => "nil".to_string(),
            Value::Int(n) => self.int_as_character(*n).unwrap_or_else(|| n.to_string()),
            Value::Float(f) => {
                // Emacs's read syntax for the non-finite floats.
                if f.is_nan() {
                    // print.c prints the NaN's significand, not a fixed 0:
                    // `(read "3.7e+NaN")' prints back as `3.0e+NaN'. See
                    // `reader::NAN_PAYLOAD_MASK'.
                    let payload = f.to_bits() & crate::reader::NAN_PAYLOAD_MASK;
                    let sign = if f.is_sign_negative() { "-" } else { "" };
                    format!("{sign}{payload}.0e+NaN")
                } else if f.is_infinite() {
                    if *f < 0.0 { "-1.0e+INF" } else { "1.0e+INF" }.to_string()
                } else {
                    self.float_to_string(*f)
                }
            }
            Value::Str(s) => {
                if readable {
                    let t = self.escape_string_body(s);
                    // A propertized string prints as `#("text" START END (plist) …)`.
                    let intervals = self.string_prop_intervals(s, depth);
                    if intervals.is_empty() {
                        format!("\"{t}\"")
                    } else {
                        format!("#(\"{t}\"{intervals})")
                    }
                } else {
                    s.to_string()
                }
            }
            Value::Obj(id) => match self.arena.get(*id as usize) {
                // Unreachable: `print_body` replaced a string object with a view
                // of its text before this match. Here for exhaustiveness.
                Some(Obj::Str(s)) => self.print_body(&Value::Str(Arc::clone(s)), readable, depth),
                Some(Obj::Symbol(s)) => {
                    if readable {
                        // print.c: `if (escapeflag && print_gensym &&
                        // !SYMBOL_INTERNED_IN_INITIAL_OBARRAY_P (obj))` prints `#:`
                        // and then the name — with no `##` for an empty one.
                        if self.print_gensym_on.get() && !self.interned_in_standard_obarray(*id) {
                            let name = if s.name.is_empty() {
                                String::new()
                            } else {
                                print_symbol_readable(&s.name)
                            };
                            return format!("#:{name}");
                        }
                        print_symbol_readable(&s.name)
                    } else {
                        s.name.clone()
                    }
                }
                Some(Obj::Cons(..)) => self.print_list(v, readable, depth),
                Some(Obj::Vector(items)) => {
                    // NO `print-level` check: print.c tests `Vprint_level` in exactly
                    // one place — `case Lisp_Cons` — so only a LIST is ever replaced
                    // by `...`. A vector still costs a level (`print_depth++` runs
                    // for every object), it just cannot be truncated itself:
                    // `(let ((print-level 2)) [[[[1]]]])` prints in full, while the
                    // list one level down in `(([[(1)]]))` becomes `...`.
                    let parts = self.print_seq(items, readable, depth + 1);
                    format!("[{}]", parts.join(" "))
                }
                Some(Obj::Record(items)) => {
                    // No `print-level` check, for the same reason as `Obj::Vector`
                    // above: print.c truncates only conses.
                    // Emacs record syntax `#s(SLOT0 SLOT1 …)` — slot 0 is the type
                    // symbol, printed like any other slot (so a cl-defstruct
                    // instance reads back as `#s(NAME …)`).
                    let parts = self.print_seq(items, readable, depth + 1);
                    format!("#s({})", parts.join(" "))
                }
                Some(Obj::BoolVector(bits)) => {
                    // Emacs prints a bool-vector as `#&LEN"PACKED"`, where PACKED is
                    // the bits LSB-first in `ceil(LEN/8)` bytes. The byte string
                    // uses print.c's rules: `"`/`\` are backslash-escaped, bytes
                    // >= 128 are `\OOO` octal, all others (incl. controls) are raw.
                    let nbytes = bits.len().div_ceil(8);
                    let mut packed = vec![0u8; nbytes];
                    for (i, &b) in bits.iter().enumerate() {
                        if b {
                            packed[i / 8] |= 1 << (i % 8);
                        }
                    }
                    // The packed bytes go through print.c's string rules, which
                    // include `print-escape-control-characters`: with it set a
                    // zero byte prints as `\0` rather than as a raw NUL, so
                    // `(prin1-to-string (make-bool-vector 4 nil))` is
                    // `"#&4\"\\0\""` under the flag and `"#&4\"^@\""` without it.
                    let esc_ctl = self.print_flag("print-escape-control-characters");
                    let mut inner = String::new();
                    for &byte in &packed {
                        match byte {
                            b'"' => inner.push_str("\\\""),
                            b'\\' => inner.push_str("\\\\"),
                            0..=0x1f | 0x7f if esc_ctl => inner.push_str(&format!("\\{byte:o}")),
                            0..=127 => inner.push(byte as char),
                            _ => inner.push_str(&format!("\\{byte:o}")),
                        }
                    }
                    format!("#&{}\"{}\"", bits.len(), inner)
                }
                // `#^[DEFALT PARENT PURPOSE ASCII CONTENTS×64 EXTRAS…]`, a
                // sub-char-table as `#^^[DEPTH MIN-CHAR SLOTS…]`: print.c prints
                // both as vectors of their raw slots.
                Some(Obj::CharTable(t)) => {
                    let key = match v {
                        Value::Obj(id) => *id | CT_ASCII_LABEL,
                        _ => 0,
                    };
                    let mut parts = vec![
                        self.print_inner(&t.default, readable, depth + 1),
                        self.print_inner(&t.parent, readable, depth + 1),
                        self.print_inner(&t.subtype, readable, depth + 1),
                    ];
                    parts.push(match &t.ascii {
                        CtAscii::Val(a) => self.print_inner(a, readable, depth + 1),
                        CtAscii::Tree => match t.ascii_table() {
                            Some(sub) => self.print_sub_char_table(sub, key, readable, depth + 1),
                            None => "nil".to_string(),
                        },
                    });
                    for slot in &t.contents {
                        parts.push(self.print_ct_slot(slot, key, readable, depth + 1));
                    }
                    for e in &t.extra {
                        parts.push(self.print_inner(e, readable, depth + 1));
                    }
                    format!("#^[{}]", parts.join(" "))
                }
                // A bignum prints exactly like a fixnum — same type in elisp.
                Some(Obj::Bignum(b)) => b.to_string(),
                Some(Obj::Buffer(idx)) => {
                    match self.buffers.get(*idx).and_then(|b| b.name.as_ref()) {
                        Some(name) => format!("#<buffer {name}>"),
                        None => "#<killed buffer>".to_string(),
                    }
                }
                Some(Obj::Marker(m)) => {
                    let md = m.borrow();
                    let moves = if md.insertion_type {
                        "(moves after insertion) "
                    } else {
                        ""
                    };
                    match md
                        .buffer
                        .and_then(|bi| self.buffers.get(bi).and_then(|b| b.name.as_ref()))
                    {
                        Some(name) => format!("#<marker {moves}at {} in {}>", md.pos, name),
                        None => format!("#<marker {moves}in no buffer>"),
                    }
                }
                Some(Obj::Window(w)) => crate::window::print_window(self, *w),
                Some(Obj::Frame(f)) => crate::window::print_frame(self, *f),
                Some(Obj::WindowConfig(_)) => "#<window-configuration>".to_string(),
                Some(Obj::Overlay(o)) => {
                    let od = o.borrow();
                    match od
                        .buffer
                        .and_then(|bi| self.buffers.get(bi).and_then(|b| b.name.as_ref()))
                    {
                        Some(name) => {
                            format!("#<overlay from {} to {} in {}>", od.start, od.end, name)
                        }
                        None => "#<overlay in no buffer>".to_string(),
                    }
                }
                Some(Obj::Obarray(d)) => {
                    let n = if d.global {
                        self.obarray.len()
                    } else {
                        d.symbols.len()
                    };
                    format!("#<obarray n={n}>")
                }
                Some(Obj::Subr { name, .. }) => format!("#<subr {name}>"),
                Some(Obj::Closure {
                    is_macro,
                    env,
                    src,
                    dynamic,
                    ..
                }) => {
                    // Emacs: `#[ARGLIST BODY ENV]` for an interpreted closure, where
                    // ENV is the captured lexical alist — newest binding first — or
                    // `(t)` when nothing is captured. A macro is that, consed onto
                    // `macro`. A dynamically-bound function captures nothing at all
                    // and prints `nil` there — `(eval '(let ((x 1)) (lambda (y) x))
                    // nil)` is `#[(y) (x) nil]`, never `#[(y) (x) (t)]`.
                    let arglist = self.print_inner(&src.arglist, readable, depth + 1);
                    // eval.c `make-interpreted-closure`: the docstring and the
                    // interactive spec are slots 4 and 5, not body forms, and
                    // the vector is only as long as the last one present.
                    let slots = src.slots(self);
                    let body: Vec<String> = slots
                        .body
                        .iter()
                        .map(|f| self.print_inner(f, readable, depth + 1))
                        .collect();
                    let captures = if *dynamic {
                        "nil".to_string()
                    } else {
                        self.captured_alist(env, readable, depth + 1)
                    };
                    let mut extra = String::new();
                    if slots.doc.is_some() || slots.iform.is_some() {
                        let doc = slots.doc.clone().unwrap_or(Value::Undef);
                        extra = format!(" nil {}", self.print_inner(&doc, readable, depth + 1));
                    }
                    if let Some(iform) = &slots.iform {
                        // `ifcdr = CDR (iform)`: one element is the spec itself,
                        // more become the vector [SPEC MODES].
                        let spec = self.list_vec(iform).unwrap_or_default();
                        let shown = match spec.len() {
                            0..=2 => {
                                let v = spec.get(1).cloned().unwrap_or(Value::Undef);
                                self.print_inner(&v, readable, depth + 1)
                            }
                            _ => {
                                let modes: Vec<String> = spec[2..]
                                    .iter()
                                    .map(|m| self.print_inner(m, readable, depth + 1))
                                    .collect();
                                format!(
                                    "[{} ({})]",
                                    self.print_inner(&spec[1], readable, depth + 1),
                                    modes.join(" ")
                                )
                            }
                        };
                        extra.push(' ');
                        extra.push_str(&shown);
                    }
                    let closure = format!("#[{arglist} ({}) {captures}{extra}]", body.join(" "));
                    if *is_macro {
                        format!("(macro . {closure})")
                    } else {
                        closure
                    }
                }
                Some(Obj::HashTable(tbl)) => {
                    let (test, entries) = (&tbl.test, tbl.pairs().collect::<Vec<_>>());
                    // Emacs-30 syntax: omit `test` when eql (the default), and
                    // `data` when empty — `#s(hash-table test equal data (k v …))`.
                    let mut s = String::from("#s(hash-table");
                    // print.c: `test` unless eql (a `define-hash-table-test`
                    // table prints its NAME), then `weakness` unless nil.
                    match (&tbl.user_test, test) {
                        (Some((name, _, _)), _) => {
                            s.push_str(" test ");
                            s.push_str(&self.print_inner(name, readable, depth + 1));
                        }
                        (None, 0) => s.push_str(" test eq"),
                        (None, 2) => s.push_str(" test equal"),
                        _ => {}
                    }
                    if !el_nil(&tbl.weakness) {
                        s.push_str(" weakness ");
                        s.push_str(&self.print_inner(&tbl.weakness, readable, depth + 1));
                    }
                    if !entries.is_empty() {
                        s.push_str(" data (");
                        for (i, (k, v)) in entries.iter().enumerate() {
                            if i > 0 {
                                s.push(' ');
                            }
                            s.push_str(&self.print_inner(k, readable, depth + 1));
                            s.push(' ');
                            s.push_str(&self.print_inner(v, readable, depth + 1));
                        }
                        s.push(')');
                    }
                    s.push(')');
                    s
                }
                None => "#<dangling>".to_string(),
            },
            other => other.as_str_cow().into_owned(),
        }
    }
    fn print_list(&self, v: &Value, readable: bool, depth: usize) -> String {
        // print-level: a list one level too deep prints as `...`.
        if self
            .print_limit("print-level")
            .is_some_and(|lvl| depth + 1 > lvl)
        {
            return "...".to_string();
        }
        let nd = depth + 1;
        // Emacs abbreviates the two-element forms `(quote X)`/`(function X)`/`` (` X) ``
        // as `'X`/`#'X`/`` `X ``; longer lists with those heads print in full.
        // `(\, X)` / `(\,@ X)` abbreviate to `,X` / `,@X` only inside a
        // backquote, and each one uses up a level of it (print.c
        // `new_backquote_output`). Honored only when `print-quoted` is non-nil
        // (its default).
        if let Some(Obj::Cons(head, tail)) = self.obj(v) {
            let depth_now = self.print_backquote_depth.get();
            let prefix = if self.print_flag_or("print-quoted", true) {
                match self.obj(head) {
                    Some(Obj::Symbol(s)) => match s.name.as_str() {
                        "quote" => Some(("'", depth_now)),
                        "function" => Some(("#'", depth_now)),
                        "`" => Some(("`", depth_now + 1)),
                        "," if depth_now > 0 => Some((",", depth_now - 1)),
                        ",@" if depth_now > 0 => Some((",@", depth_now - 1)),
                        _ => None,
                    },
                    _ => None,
                }
            } else {
                None
            };
            if let Some((prefix, inner_depth)) = prefix {
                if let Some(Obj::Cons(arg, rest)) = self.obj(tail) {
                    if !el_truthy(rest) {
                        self.print_backquote_depth.set(inner_depth);
                        let body = self.print_inner(arg, readable, nd);
                        self.print_backquote_depth.set(depth_now);
                        return format!("{prefix}{body}");
                    }
                }
            }
        }
        // print.c pushes a `PE_list` continuation carrying `last`, `maxlen` and a
        // BRENT cycle detector (`tortoise`, step countdown `n`, step period `m`,
        // `tortoise_idx`), then prints the head's car and re-enters the loop. The
        // state is per-list, so a nested list gets its own detector, exactly as a
        // separate stack entry does in C.
        let print_length = self.print_limit("print-length");
        // `if (print_length == 0) print_c_string ("...)")` — before the car.
        if print_length == Some(0) {
            return "(...)".to_string();
        }
        let mut maxlen: i64 = print_length.map_or(i64::MAX, |n| n as i64);
        let mut out = String::from("(");
        let Some(Obj::Cons(car0, _)) = self.obj(v) else {
            return "()".to_string();
        };
        out.push_str(&self.print_inner(car0, readable, nd));
        let mut last = v.clone();
        let mut tortoise = match v {
            Value::Obj(id) => *id,
            _ => return "()".to_string(),
        };
        let (mut n, mut m, mut tortoise_idx): (i64, i64, i64) = (2, 2, 0);
        // `Lisp_Object next = XCDR (e->u.list.last);` — `last` always holds the
        // cons whose cdr the continuation is about to inspect.
        while let Some(Obj::Cons(_, cdr)) = self.obj(&last) {
            let next = cdr.clone();
            match &next {
                // Both nil representations end the list (a `(1 . nil)` cdr is the
                // one-element list `(1)`, never a dotted pair).
                Value::Undef | Value::Bool(false) => break,
                Value::Obj(id) if matches!(self.arena.get(*id as usize), Some(Obj::Cons(..))) => {
                    // A shared/circular tail prints as a dotted `#N#` back-reference
                    // (`#1=(1 2 . #1#)`) — the tail is a labelled object, so it must
                    // go through `print_inner` rather than continuing this loop.
                    // print.c checks this BEFORE the space, and before the tortoise.
                    // print.c: `if (!(NILP (num) || EQ (num, Qt)))` — only a
                    // NUMBERED tail takes the dotted branch. A `0` slot is `Qt`, a
                    // candidate that turned out unshared, and continues the list.
                    if self.print_circle_on.get()
                        && self
                            .print_labels
                            .borrow()
                            .get(id)
                            .is_some_and(|slot| *slot != 0)
                    {
                        out.push_str(" . ");
                        out.push_str(&self.print_inner(&next, readable, nd));
                        break;
                    }
                    out.push(' ');
                    maxlen -= 1;
                    if maxlen <= 0 {
                        out.push_str("...");
                        break;
                    }
                    last = next.clone();
                    n -= 1;
                    if n == 0 {
                        // "Double tortoise update period and teleport it." The
                        // teleport TAKES PRECEDENCE over the equality test, which is
                        // why the reported index only ever takes the values
                        // 0, 2, 6, 14, 30, … (2^k - 2) — it is the tortoise's
                        // position at the last teleport, not the cycle's period.
                        tortoise_idx += m;
                        m <<= 1;
                        n = m;
                        tortoise = *id;
                    } else if tortoise == *id {
                        // print.c's own comment: "This #N tail index is somewhat
                        // ambiguous; see bug#55395." The `)` is part of C's format
                        // string; here the shared `out.push(')')` below supplies it.
                        out.push_str(". #");
                        out.push_str(&tortoise_idx.to_string());
                        break;
                    }
                    let Some(Obj::Cons(a, _)) = self.obj(&last) else {
                        break;
                    };
                    out.push_str(&self.print_inner(a, readable, nd));
                }
                _ => {
                    out.push_str(" . ");
                    out.push_str(&self.print_inner(&next, readable, nd));
                    break;
                }
            }
        }
        out.push(')');
        out
    }

    pub fn take_error(&mut self) -> Option<String> {
        self.error.take()
    }

    /// Write `s` to stdout, or to the capture buffer when one is on.
    pub fn write_stdout(&mut self, s: &str) {
        use std::io::Write;
        match &mut self.capture {
            Some(buf) => buf.push_str(s),
            None => {
                print!("{s}");
                let _ = std::io::stdout().flush();
            }
        }
    }

    /// Write program output to stdout (a PRINTCHARFUN of t in batch).
    pub fn emit(&mut self, s: &str) {
        self.write_stdout(s);
        if let Some(c) = s.chars().last() {
            self.stdout_last = c;
        }
        // print.c `printchar` / `strout`: every batch write to stdout sets
        // `noninteractive_need_newline = 1`, and the next `message` flushes
        // it as a newline on *stderr* so the two streams do not collide on
        // one line.
        self.need_newline = true;
    }

    /// The current editing buffer.
    pub fn cur_buf(&mut self) -> &mut EditBuffer {
        &mut self.buffers[self.current]
    }
    /// The current editing buffer (shared).
    pub fn cur_buf_ref(&self) -> &EditBuffer {
        &self.buffers[self.current]
    }

    // ── buffer registry ──────────────────────────────────────────────────────
    /// The current buffer's object handle (`current-buffer`).
    pub fn current_buffer(&self) -> Value {
        self.buffers[self.current].self_obj.clone()
    }
    /// Resolve a buffer-or-name to a live buffer index. A buffer object resolves
    /// to its slot (even if killed → `None`); a string is looked up by name.
    pub fn resolve_buffer(&self, v: &Value) -> Option<usize> {
        match self.obj(v) {
            Some(Obj::Buffer(idx)) => {
                let idx = *idx;
                self.buffers.get(idx).filter(|b| b.name.is_some())?;
                Some(idx)
            }
            _ => self
                .str_text(v)
                .and_then(|name| self.find_buffer_by_name(name)),
        }
    }
    /// The slot a buffer *object* names, live or killed. `resolve_buffer` filters
    /// killed slots out; the three callers that follow Emacs's `Fget_buffer`
    /// (`get-buffer`, `set-buffer`, `buffer-name`) must be able to see them,
    /// because a killed buffer object stays a buffer object in Emacs and only
    /// `BUFFER_LIVE_P` distinguishes it.
    pub(crate) fn buffer_slot(&self, v: &Value) -> Option<usize> {
        match self.obj(v) {
            Some(Obj::Buffer(idx)) if *idx < self.buffers.len() => Some(*idx),
            _ => None,
        }
    }
    /// Port of `Fget_buffer` (`src/buffer.c`):
    ///
    /// ```c
    ///   if (BUFFERP (buffer_or_name)) return buffer_or_name;
    ///   CHECK_STRING (buffer_or_name);
    ///   return Fcdr (Fassoc (buffer_or_name, Vbuffer_alist, Qnil));
    /// ```
    ///
    /// A buffer object is returned unchanged whether or not it is live — only
    /// the name lookup can answer nil — and anything that is neither a buffer
    /// nor a string signals `(wrong-type-argument stringp X)` before any lookup
    /// happens. `Ok(None)` is Emacs's nil.
    pub fn get_buffer(&self, v: &Value) -> Result<Option<usize>, String> {
        if let Some(idx) = self.buffer_slot(v) {
            return Ok(Some(idx));
        }
        match self.str_text(v) {
            Some(name) => Ok(self.find_buffer_by_name(name)),
            None => Err(format!(
                "wrong-type-argument: stringp {}",
                self.print(v, true)
            )),
        }
    }
    /// Port of `nsberror` (`src/buffer.c`) — the "no such buffer" signal shared
    /// by every buffer-taking subr:
    ///
    /// ```c
    ///   if (STRINGP (spec)) error ("No buffer named %s", SDATA (spec));
    ///   error ("Invalid buffer argument");
    /// ```
    ///
    /// The name goes in unquoted (`SDATA`, not `prin1`).
    pub fn nsberror(&self, v: &Value) -> String {
        match self.str_text(v) {
            Some(name) => format!("error: No buffer named {name}"),
            None => "error: Invalid buffer argument".to_string(),
        }
    }
    /// Index of the live buffer named `name`, if any.
    pub fn find_buffer_by_name(&self, name: &str) -> Option<usize> {
        self.buffers
            .iter()
            .position(|b| b.name.as_deref() == Some(name))
    }
    /// Allocate a fresh buffer slot named `name` and return its `Obj::Buffer`
    /// handle. The caller guarantees `name` is not already taken.
    fn new_buffer(&mut self, name: String) -> Value {
        let idx = self.buffers.len();
        let locals = self.initial_slots(&name);
        self.buffers.push(EditBuffer {
            overlays: Vec::new(),
            name: Some(name),
            self_obj: Value::Undef,
            text: Vec::new(),
            props: Vec::new(),
            prop_bounds: Vec::new(),
            markers: Vec::new(),
            point: 1,
            begv: 1,
            zv: 1,
            mark: Value::Undef,
            se_markers: Vec::new(),
            restrict_stack: Vec::new(),
            locals,
            local_map: Value::Undef,
            mods: ModCounts::default(),
            has_intervals: false,
            list_order: 0,
            inhibit_hooks: false,
        });
        self.buffer_order_seq += 1;
        self.buffers[idx].list_order = self.buffer_order_seq;
        let handle = self.alloc(Obj::Buffer(idx));
        self.buffers[idx].self_obj = handle.clone();
        handle
    }
    /// `(get-buffer-create NAME)` — the live buffer named NAME, creating it if
    /// absent. Returns its buffer object.
    pub fn get_buffer_create(&mut self, name: &str) -> Value {
        match self.find_buffer_by_name(name) {
            Some(idx) => self.buffers[idx].self_obj.clone(),
            None => self.new_buffer(name.to_string()),
        }
    }
    /// `(generate-new-buffer-name NAME &optional IGNORE)`. Port of
    /// `Fgenerate_new_buffer_name` (`src/buffer.c`):
    ///
    /// ```c
    ///   if ((!NILP (ignore) && !NILP (Fstring_equal (name, ignore)))
    ///       || NILP (Fget_buffer (name)))
    ///     return name;
    ///
    ///   if (SREF (name, 0) != ' ') /* See bug#1229.  */
    ///     genbase = name;
    ///   else
    ///     {
    ///       int i = get_random () % 1000000;
    ///       sprintf (number, "-%d", i);
    ///       genbase = concat2 (name, lnumber);
    ///       if (NILP (Fget_buffer (genbase)))
    ///         return genbase;
    ///     }
    ///
    ///   for (ptrdiff_t count = 2; ; count++)
    ///     {
    ///       sprintf (number, "<%"pD"d>", count);
    ///       Lisp_Object gentemp = concat2 (genbase, lnumber);
    ///       if (!NILP (Fstring_equal (gentemp, ignore))
    ///           || NILP (Fget_buffer (gentemp)))
    ///         return gentemp;
    ///     }
    /// ```
    ///
    /// Two behaviors that a plain `NAME<N>` counter gets wrong:
    ///
    /// - a **hidden** name (leading space, e.g. ` *load*` / ` *temp*`) that is
    ///   taken gets a random `-NNNNNN` suffix *first*, so nested `with-temp-buffer`
    ///   / `load` do not walk a `<2>`, `<3>`, … chain. This is observable:
    ///   `(buffer-name (generate-new-buffer " *load*"))` under a load is
    ///   ` *load*-711551` in Emacs 30.2, not ` *load*<2>`.
    /// - IGNORE names a buffer that may be reused even though it exists — the
    ///   check applies both to NAME itself and to every `<N>` candidate, which is
    ///   what lets `rename-buffer` accept the current buffer's own name.
    pub fn generate_new_buffer_name(&self, name: &str, ignore: Option<&str>) -> String {
        if ignore == Some(name) || self.find_buffer_by_name(name).is_none() {
            return name.to_string();
        }
        let genbase = if !name.starts_with(' ') {
            name.to_string()
        } else {
            let cand = format!("{name}-{}", crate::builtins::rng_next() % 1_000_000);
            if self.find_buffer_by_name(&cand).is_none() {
                return cand;
            }
            cand
        };
        let mut count = 2;
        loop {
            let cand = format!("{genbase}<{count}>");
            if ignore == Some(cand.as_str()) || self.find_buffer_by_name(&cand).is_none() {
                return cand;
            }
            count += 1;
        }
    }
    /// `(set-buffer BUFFER-OR-NAME)` — make it current, returning its object.
    /// Port of `Fset_buffer` (`src/buffer.c`):
    ///
    /// ```c
    ///   buffer = Fget_buffer (buffer_or_name);
    ///   if (NILP (buffer)) nsberror (buffer_or_name);
    ///   if (!BUFFER_LIVE_P (XBUFFER (buffer))) error ("Selecting deleted buffer");
    ///   set_buffer_internal (XBUFFER (buffer));
    /// ```
    ///
    /// The three failures are distinct and were one message here before: a
    /// non-string non-buffer is `(wrong-type-argument stringp X)` from
    /// `get_buffer`, an unknown *name* is `No buffer named NAME`, and a killed
    /// buffer *object* is `Selecting deleted buffer`.
    pub fn set_buffer(&mut self, v: &Value) -> Result<Value, String> {
        let idx = self.get_buffer(v)?.ok_or_else(|| self.nsberror(v))?;
        if self.buffers[idx].name.is_none() {
            return Err("error: Selecting deleted buffer".to_string());
        }
        self.current = idx;
        Ok(self.buffers[idx].self_obj.clone())
    }
    /// `(kill-buffer &optional BUFFER)` — mark BUFFER (default current) dead.
    /// Returns t if a live buffer was killed, nil otherwise.
    pub fn kill_buffer(&mut self, v: Option<&Value>) -> Value {
        let idx = match v {
            Some(v) if el_truthy(v) => match self.resolve_buffer(v) {
                Some(i) => i,
                None => return Value::Undef,
            },
            _ => self.current,
        };
        if self.buffers[idx].name.is_none() {
            return Value::Undef;
        }
        // Clear the slot's contents but keep it so the object stays resolvable
        // (as a killed buffer). If the current buffer is killed, fall back to the
        // first live buffer (Emacs would switch to another buffer).
        let b = &mut self.buffers[idx];
        b.name = None;
        b.text.clear();
        b.props.clear();
        b.prop_bounds.clear();
        b.has_intervals = false;
        b.locals.clear();
        b.se_markers.clear();
        b.restrict_stack.clear();
        // The text is gone, so every position field has to go back to BEG with
        // it — `reset_buffer` does exactly this in Emacs:
        //
        // ```c
        //   b->pt = BEG;  b->begv = BEG;  b->zv = BEG;
        // ```
        //
        // Leaving them stale broke `EditBuffer::point`'s documented invariant
        // ("always kept within `[begv, zv]`"): after `(insert "hello")
        // (kill-buffer)` point was 6 in a zero-length buffer, and the next
        // `buffer-substring` sliced `text[..5]` and aborted the process.
        b.point = 1;
        b.begv = 1;
        b.zv = 1;
        // Detach every marker that pointed into the killed buffer.
        for mk in b.markers.drain(..) {
            let mut md = mk.borrow_mut();
            md.buffer = None;
            md.pos = 0;
        }
        // `replace_buffer_in_windows`, then `Fset_buffer (Fother_buffer (…))`
        // when the killed buffer was current; `other-buffer` ends in
        // `get-scratch-buffer-create`, so a killed buffer never stays current.
        let fallback = |h: &mut Self| match crate::window::other_buffer(h, Some(idx), false) {
            Some(b) => b,
            None => {
                let handle = h.new_buffer("*scratch*".to_string());
                h.buffer_slot(&handle).expect("fresh buffer slot")
            }
        };
        if self.windows.iter().any(|w| w.buffer == Some(idx)) {
            let replacement = fallback(self);
            crate::window::replace_buffer_in_windows(self, idx, replacement);
        }
        if self.current == idx {
            self.current = fallback(self);
        }
        let f = self.selected_frame;
        self.frames[f].buffer_list.retain(|&x| x != idx);
        Value::Bool(true)
    }
    /// `(rename-buffer NEWNAME &optional UNIQUE)` — rename the current buffer.
    /// Returns the name actually given. Port of `Frename_buffer` (`src/buffer.c`):
    ///
    /// ```c
    ///   if (SCHARS (newname) == 0)
    ///     error ("Empty string is invalid as a buffer name");
    ///   tem = Fget_buffer (newname);
    ///   if (!NILP (tem))
    ///     {
    ///       if (NILP (unique) && XBUFFER (tem) == current_buffer)
    ///         return BVAR (current_buffer, name);
    ///       if (!NILP (unique))
    ///         newname = Fgenerate_new_buffer_name (newname,
    ///                                              BVAR (current_buffer, name));
    ///       else
    ///         error ("Buffer name `%s' is in use", SDATA (newname));
    ///     }
    /// ```
    ///
    /// UNIQUE is not decoration: `(rename-buffer NAME t)` on a taken NAME is the
    /// documented way to free NAME up, and it stays meaningful even when the
    /// current buffer *already* holds NAME (IGNORE is the current name, so the
    /// `<N>` loop can hand it straight back — hence `(rename-buffer "s2" t)`
    /// answering `"s2"`, not `"s2<2>"`).
    pub fn rename_buffer(&mut self, newname: &str, unique: bool) -> Result<Value, String> {
        if newname.is_empty() {
            return Err("error: Empty string is invalid as a buffer name".to_string());
        }
        let mut newname = newname.to_string();
        if let Some(other) = self.find_buffer_by_name(&newname) {
            if unique {
                let ignore = self.buffers[self.current].name.clone();
                newname = self.generate_new_buffer_name(&newname, ignore.as_deref());
            } else if other == self.current {
                return Ok(self.new_string(newname));
            } else {
                // The C is `error ("Buffer name `%s' is in use", …)`, and `error`
                // runs its template through `format-message`, so Emacs 30.2 (default
                // `text-quoting-style' of `curve') reports curved quotes here.
                return Err(format!(
                    "error: Buffer name \u{2018}{newname}\u{2019} is in use"
                ));
            }
        }
        self.buffers[self.current].name = Some(newname.clone());
        Ok(self.new_string(newname))
    }
    /// Open the buffer `load` reads a file through, and make it the *only* live
    /// ` *load*`-family buffer for this load.
    ///
    /// `load-with-code-conversion` (mule.el) does `(generate-new-buffer " *load*")`,
    /// `insert-file-contents` into it, evaluates the file with the *original*
    /// buffer current, then kills it in an `unwind-protect`. `top_level` selects
    /// between the two callers:
    ///
    /// - `true` (the `elisp FILE` entry point) reuses the reserved slot, so the
    ///   name is exactly ` *load*` and no arena object is allocated — the cache-hit
    ///   and cache-miss paths must agree on every handle.
    /// - `false` (a nested `(load …)`) allocates a fresh buffer, so its name goes
    ///   through `generate_new_buffer_name`, which for a hidden name already taken
    ///   answers ` *load*-NNNNNN`, exactly as Emacs does.
    ///
    /// Point stays at 1 (where `insert-file-contents` leaves it). Emacs's ` *load*`
    /// point is the reader's *current* position, which elisprs cannot reproduce:
    /// it reads every top-level form before running any of them, so there is no
    /// meaningful "read is here" position while the file's own code observes it.
    pub fn open_load_buffer(&mut self, src: &str, top_level: bool) -> usize {
        let idx = if top_level {
            let idx = self.load_buf;
            self.buffers[idx].name = Some(" *load*".to_string());
            self.buffer_order_seq += 1;
            self.buffers[idx].list_order = self.buffer_order_seq;
            idx
        } else {
            let name = self.generate_new_buffer_name(" *load*", None);
            let handle = self.get_buffer_create(&name);
            self.buffer_slot(&handle).expect("fresh load buffer slot")
        };
        let text: Vec<char> = src.chars().collect();
        let len = text.len();
        let b = &mut self.buffers[idx];
        b.props = vec![Value::Undef; len];
        b.prop_bounds.clear();
        b.text = text;
        b.point = 1;
        b.begv = 1;
        b.zv = len + 1;
        idx
    }
    /// The top-level ` *load*` buffer's object (see `open_load_buffer`).
    pub fn load_buffer_object(&self) -> Value {
        self.buffers[self.load_buf].self_obj.clone()
    }
    /// The buffer object for slot `idx` (used to kill a load buffer afterward).
    pub fn buffer_object(&self, idx: usize) -> Value {
        self.buffers[idx].self_obj.clone()
    }
    /// The live buffer slots in `(buffer-list)` order (`Vbuffer_alist`).
    pub fn buffer_order(&self) -> Vec<usize> {
        let mut live: Vec<usize> = (0..self.buffers.len())
            .filter(|&i| self.buffers[i].name.is_some())
            .collect();
        live.sort_by_key(|&i| self.buffers[i].list_order);
        live
    }
    /// `(buffer-list)` — live buffer objects, most recently recorded first.
    pub fn buffer_list(&mut self) -> Value {
        let items: Vec<Value> = self
            .buffer_order()
            .into_iter()
            .map(|i| self.buffers[i].self_obj.clone())
            .collect();
        self.list_from(items)
    }

    // ── text mutation (marker-adjusting) ─────────────────────────────────────
    /// Apply an insertion of `len` chars at 1-based `pos` in the current buffer to
    /// every marker-like position (begv/zv/mark and the save stacks). Point is
    /// handled by the caller.
    fn adjust_for_insert(&mut self, pos: usize, len: usize) {
        let cur = self.current;
        for w in self.windows.iter_mut().filter(|w| w.buffer == Some(cur)) {
            adj_ins(&mut w.pointm, pos, len, false);
            adj_ins(&mut w.old_pointm, pos, len, false);
            adj_ins(&mut w.start, pos, len, false);
        }
        let b = &mut self.buffers[self.current];
        adj_ins(&mut b.begv, pos, len, false);
        adj_ins(&mut b.zv, pos, len, true);
        for m in b.se_markers.iter_mut() {
            adj_ins(m, pos, len, false);
        }
        for (lo, hi) in b.restrict_stack.iter_mut() {
            adj_ins(lo, pos, len, false);
            adj_ins(hi, pos, len, true);
        }
        for mk in b.markers.iter() {
            let mut md = mk.borrow_mut();
            let ins_type = md.insertion_type;
            adj_ins(&mut md.pos, pos, len, ins_type);
        }
        // An overlay's two ends advance independently: FRONT-ADVANCE decides
        // whether text inserted at the start lands outside it, REAR-ADVANCE
        // whether text inserted at the end lands inside it.
        for ov in b.overlays.iter() {
            let mut od = ov.borrow_mut();
            let (fa, ra) = (od.front_advance, od.rear_advance);
            adj_ins(&mut od.start, pos, len, fa);
            adj_ins(&mut od.end, pos, len, ra);
        }
    }
    /// Apply a deletion of `[from, to)` in the current buffer to every marker-like
    /// position, including point.
    fn adjust_for_delete(&mut self, from: usize, to: usize) {
        let cur = self.current;
        for w in self.windows.iter_mut().filter(|w| w.buffer == Some(cur)) {
            adj_del(&mut w.pointm, from, to);
            adj_del(&mut w.old_pointm, from, to);
            adj_del(&mut w.start, from, to);
        }
        let b = &mut self.buffers[self.current];
        adj_del(&mut b.point, from, to);
        adj_del(&mut b.begv, from, to);
        adj_del(&mut b.zv, from, to);
        for m in b.se_markers.iter_mut() {
            adj_del(m, from, to);
        }
        for (lo, hi) in b.restrict_stack.iter_mut() {
            adj_del(lo, from, to);
            adj_del(hi, from, to);
        }
        for mk in b.markers.iter() {
            adj_del(&mut mk.borrow_mut().pos, from, to);
        }
        for ov in b.overlays.iter() {
            let mut od = ov.borrow_mut();
            adj_del(&mut od.start, from, to);
            adj_del(&mut od.end, from, to);
        }
    }
    /// buffer.c `Fbarf_if_buffer_read_only`, as insdel.c
    /// `prepare_to_modify_buffer_1` calls it before every change: a non-nil
    /// `buffer-read-only` with `inhibit-read-only` nil signals
    /// `(buffer-read-only BUFFER)`. Callers check only when the change is
    /// non-empty, because Emacs returns before preparing an empty one.
    pub fn barf_if_read_only(&mut self) -> Result<(), String> {
        let set = |h: &Self, name: &str| {
            h.find_symbol(name)
                .and_then(|s| h.get_value(&s).ok())
                .is_some_and(|v| el_truthy(&v))
        };
        if !set(self, "buffer-read-only") || set(self, "inhibit-read-only") {
            return Ok(());
        }
        let buf = self.current_buffer();
        let msg = format!("buffer-read-only: {}", self.print(&buf, true));
        let sym = self.intern("buffer-read-only");
        let data = self.list_from(vec![buf]);
        let obj = self.cons(sym, data);
        self.set_pending_error(&msg, obj);
        Err(msg)
    }
    /// Count a change to LEN characters of the current buffer's text
    /// (`insert_1_both` / `del_range_2`: `modiff_incr`, then `CHARS_MODIFF = MODIFF`).
    pub fn note_text_change(&mut self, len: usize) {
        let m = &mut self.buffers[self.current].mods;
        m.incr(len);
        m.chars_modiff = m.modiff;
    }
    /// Count a text-property change in buffer BI (`modify_text_properties`:
    /// `MODIFF` advances by one, `CHARS_MODIFF` stays).
    pub fn note_prop_change(&mut self, bi: usize) {
        self.buffers[bi].mods.incr(1);
    }
    // ── undo (undo.c) ────────────────────────────────────────────────────────
    /// The current buffer's `buffer-undo-list`.
    fn undo_list(&mut self) -> Value {
        let sym = self.intern("buffer-undo-list");
        self.get_value(&sym).unwrap_or(Value::Undef)
    }
    fn set_undo_list(&mut self, v: Value) {
        let sym = self.intern("buffer-undo-list");
        let _ = self.set_value(&sym, v);
    }
    /// Whether undo is recorded in the current buffer (`undo_list` is not t).
    fn undo_enabled(&mut self) -> bool {
        !matches!(self.undo_list(), Value::Bool(true))
    }
    fn push_undo(&mut self, entry: Value) {
        let list = self.undo_list();
        let list = self.cons(entry, list);
        self.set_undo_list(list);
    }
    /// `record_first_change`: `(t . VISITED-MODTIME)`; a buffer visiting no
    /// file has modtime 0.
    /// `record_first_change` when undo is recorded in the current buffer.
    pub(crate) fn record_first_change_if_undo(&mut self) {
        if self.undo_enabled() {
            self.record_first_change();
        }
    }
    pub(crate) fn record_first_change(&mut self) {
        let t = Value::Bool(true);
        let entry = self.cons(t, Value::Int(0));
        self.push_undo(entry);
    }
    /// `record_point` for a change that will leave point at BEG.
    fn record_point(&mut self, beg: usize) {
        let inhibit = self.intern("undo-inhibit-record-point");
        if el_truthy(&self.get_value(&inhibit).unwrap_or(Value::Undef)) {
            return;
        }
        let list = self.undo_list();
        let at_boundary = match self.obj(&list) {
            Some(Obj::Cons(car, _)) => el_nil(car),
            _ => true,
        };
        let m = &self.buffers[self.current].mods;
        if m.modiff <= m.save_modiff {
            self.record_first_change();
        }
        if at_boundary
            && self.buffer_before_last_command_or_undo == Some(self.current)
            && self.point_before_last_command_or_undo != Some(beg)
        {
            if let Some(p) = self.point_before_last_command_or_undo {
                self.push_undo(Value::Int(p as i64));
            }
        }
    }
    /// `record_insert`: LEN characters about to be inserted at BEG, merged into
    /// an immediately preceding `(BEG . END)` entry that ends at BEG.
    pub fn record_insert(&mut self, beg: usize, len: usize) {
        if !self.undo_enabled() {
            return;
        }
        self.record_point(beg);
        let list = self.undo_list();
        if let Some(Obj::Cons(elt, _)) = self.obj(&list) {
            let elt = elt.clone();
            if let Some(Obj::Cons(Value::Int(_), Value::Int(end))) = self.obj(&elt) {
                if *end == beg as i64 {
                    if let Value::Obj(id) = elt {
                        if let Some(Obj::Cons(_, cdr)) = self.arena.get_mut(id as usize) {
                            *cdr = Value::Int((beg + len) as i64);
                        }
                    }
                    return;
                }
            }
        }
        let entry = self.cons(Value::Int(beg as i64), Value::Int((beg + len) as i64));
        self.push_undo(entry);
    }
    /// The text `[from, to)` of the current buffer as a string carrying its
    /// text properties (`make_buffer_string` with PROPS).
    fn buffer_string_with_props(&mut self, from: usize, to: usize) -> Value {
        let text: String = self.buffers[self.current].text[from - 1..to - 1]
            .iter()
            .collect();
        let plists: Vec<Value> = self.buffers[self.current].props[from - 1..to - 1].to_vec();
        let (out, arc) = self.new_string_keyed(text);
        if plists.iter().any(el_truthy) {
            let plists = self.copy_plist_runs(plists);
            self.string_set_props_vec(&arc, plists);
        }
        out
    }
    /// `record_delete` of the text `[from, to)`, about to be deleted, with the
    /// marker adjustments primitive-undo needs to restore markers inside it.
    pub fn record_delete(&mut self, from: usize, to: usize, record_markers: bool) {
        if !self.undo_enabled() {
            return;
        }
        let string = self.buffer_string_with_props(from, to);
        self.record_point(from);
        let pt = self.buffers[self.current].point;
        let sbeg = if pt == to {
            -(from as i64)
        } else {
            from as i64
        };
        if record_markers {
            // `BUF_MARKERS` is newest first.
            let markers: Vec<(Value, usize, bool)> = self.buffers[self.current]
                .markers
                .iter()
                .rev()
                .filter_map(|m| {
                    let md = m.borrow();
                    (from <= md.pos && md.pos <= to).then(|| (m.clone(), md.pos, md.insertion_type))
                })
                .filter_map(|(m, pos, itype)| self.marker_object_of(&m).map(|o| (o, pos, itype)))
                .collect();
            for (marker, pos, itype) in markers {
                let adjustment = (if itype { to } else { from }) as i64 - pos as i64;
                if adjustment != 0 {
                    let entry = self.cons(marker, Value::Int(adjustment));
                    self.push_undo(entry);
                }
            }
        }
        let entry = self.cons(string, Value::Int(sbeg));
        self.push_undo(entry);
    }
    /// `record_change`: LEN characters at BEG about to be replaced by as many.
    pub fn record_change(&mut self, beg: usize, len: usize) {
        self.record_delete(beg, beg + len, false);
        self.record_insert(beg, len);
    }
    /// `record_property_change`: PROP's old VALUE over LEN characters at BEG
    /// of buffer BI.
    pub fn record_property_change(
        &mut self,
        bi: usize,
        beg: usize,
        len: usize,
        prop: Value,
        value: Value,
    ) {
        let saved = self.current;
        self.current = bi;
        if self.undo_enabled() {
            let m = &self.buffers[bi].mods;
            if m.modiff <= m.save_modiff {
                self.record_first_change();
            }
            let tail = self.cons(Value::Int(beg as i64), Value::Int((beg + len) as i64));
            let tail = self.cons(value, tail);
            let tail = self.cons(prop, tail);
            let entry = self.cons(Value::Undef, tail);
            self.push_undo(entry);
        }
        self.current = saved;
    }
    /// `Fundo_boundary`.
    pub fn undo_boundary(&mut self) {
        if !self.undo_enabled() {
            return;
        }
        let list = self.undo_list();
        let head_nil = match self.obj(&list) {
            Some(Obj::Cons(car, _)) => el_nil(car),
            _ => true,
        };
        if !head_nil {
            let list = self.cons(Value::Undef, list);
            self.set_undo_list(list);
        }
        let cause = self.intern("undo-auto--last-boundary-cause");
        let explicit = self.intern("explicit");
        let _ = self.set_value(&cause, explicit);
        self.point_before_last_command_or_undo = Some(self.buffers[self.current].point);
        self.buffer_before_last_command_or_undo = Some(self.current);
    }

    /// Insert `chars` at point in the current buffer. `leave_after` puts point
    /// after the inserted text (the `insert` default); otherwise point is left at
    /// the start (`insert-file-contents`). Markers are adjusted per Emacs rules.
    pub fn cur_insert(&mut self, chars: Vec<char>, leave_after: bool) {
        let pos = self.buffers[self.current].point;
        let len = chars.len();
        if len == 0 {
            return;
        }
        self.record_insert(pos, len);
        self.note_text_change(len);
        let b = &mut self.buffers[self.current];
        b.text.splice((pos - 1)..(pos - 1), chars);
        // Plain insert gives the new characters nil properties (no inheritance).
        b.props
            .splice((pos - 1)..(pos - 1), std::iter::repeat_n(Value::Undef, len));
        self.shift_prop_bounds_for_insert(pos - 1, len);
        self.adjust_for_insert(pos, len);
        self.buffers[self.current].point = if leave_after { pos + len } else { pos };
    }
    /// `insert-before-markers`: like `cur_insert` (leaving point after), but every
    /// marker sitting exactly at the insertion point is relocated *after* the new
    /// text regardless of its insertion type (Emacs `insert_before_markers`).
    pub fn cur_insert_before_markers(&mut self, chars: Vec<char>) {
        let pos = self.buffers[self.current].point;
        let len = chars.len();
        if len == 0 {
            return;
        }
        self.record_insert(pos, len);
        self.note_text_change(len);
        let b = &mut self.buffers[self.current];
        b.text.splice((pos - 1)..(pos - 1), chars);
        b.props
            .splice((pos - 1)..(pos - 1), std::iter::repeat_n(Value::Undef, len));
        self.shift_prop_bounds_for_insert(pos - 1, len);
        self.adjust_for_insert(pos, len);
        // Bump any live marker that ended up exactly at the insertion point.
        for mk in self.buffers[self.current].markers.iter() {
            let mut md = mk.borrow_mut();
            if md.pos == pos {
                md.pos = pos + len;
            }
        }
        self.buffers[self.current].point = pos + len;
    }
    /// Delete the region `[from, to)` (1-based, `from <= to`) from the current
    /// buffer, adjusting point and all markers.
    pub fn cur_delete(&mut self, from: usize, to: usize) {
        if from >= to {
            return;
        }
        self.record_delete(from, to, true);
        self.note_text_change(to - from);
        if to - from == self.buffers[self.current].text.len() {
            self.buffers[self.current].has_intervals = false;
        }
        let b = &mut self.buffers[self.current];
        b.text.drain((from - 1)..(to - 1));
        b.props.drain((from - 1)..(to - 1));
        let (lo, hi) = ((from - 1) as u32, (to - 1) as u32);
        b.prop_bounds.retain(|&p| p <= lo || p >= hi);
        for p in &mut b.prop_bounds {
            if *p >= hi {
                *p -= hi - lo;
            }
        }
        self.adjust_for_delete(from, to);
    }
    /// `(narrow-to-region BEG END)` on the current buffer: clamp `begv`/`zv` to the
    /// region and pull point inside it.
    pub fn narrow(&mut self, beg: usize, end: usize) {
        let (lo, hi) = if beg <= end { (beg, end) } else { (end, beg) };
        let b = &mut self.buffers[self.current];
        let maxzv = b.text.len() + 1;
        b.begv = lo.clamp(1, maxzv);
        b.zv = hi.clamp(1, maxzv);
        b.point = b.point.clamp(b.begv, b.zv);
    }
    /// `(widen)` — remove any narrowing on the current buffer.
    pub fn widen(&mut self) {
        let b = &mut self.buffers[self.current];
        b.begv = 1;
        b.zv = b.text.len() + 1;
    }

    // ── markers ──────────────────────────────────────────────────────────────
    /// `(mark-marker)`: the current buffer's mark, one marker object for the
    /// buffer's lifetime.
    pub fn mark_marker(&mut self) -> Value {
        let cur = self.current;
        if !self.is_marker(&self.buffers[cur].mark) {
            let m = self.alloc_marker(None, 0, false);
            self.buffers[cur].mark = m;
        }
        self.buffers[cur].mark.clone()
    }
    /// The position of the current buffer's mark, or `None` when it is unset.
    pub fn mark_pos(&self) -> Option<usize> {
        self.marker_position(&self.buffers[self.current].mark)
    }
    /// Allocate an `Obj::Marker`; when it points into a buffer, register it in
    /// that buffer's live-marker list so edits keep it up to date.
    pub fn alloc_marker(&mut self, buffer: Option<usize>, pos: usize, itype: bool) -> Value {
        let md = Rc::new(RefCell::new(MarkerData {
            buffer,
            pos,
            insertion_type: itype,
        }));
        if let Some(bi) = buffer {
            self.buffers[bi].markers.push(md.clone());
        }
        self.alloc(Obj::Marker(md))
    }
    /// The marker object whose cell is M (a scan of the heap: markers keep no
    /// back-pointer to their object).
    fn marker_object_of(&self, m: &Rc<RefCell<MarkerData>>) -> Option<Value> {
        self.arena
            .iter()
            .position(|o| matches!(o, Obj::Marker(x) if Rc::ptr_eq(x, m)))
            .map(|i| Value::Obj(i as u32))
    }
    /// The shared marker cell behind V, if V is a marker.
    fn marker_rc(&self, v: &Value) -> Option<Rc<RefCell<MarkerData>>> {
        match self.obj(v) {
            Some(Obj::Marker(m)) => Some(m.clone()),
            _ => None,
        }
    }
    /// `(markerp V)`.
    pub fn is_marker(&self, v: &Value) -> bool {
        matches!(self.obj(v), Some(Obj::Marker(_)))
    }
    /// `(marker-position M)` — 1-based position, or `None` for a detached marker.
    pub fn marker_position(&self, v: &Value) -> Option<usize> {
        let m = self.marker_rc(v)?;
        let md = m.borrow();
        md.buffer.map(|_| md.pos)
    }
    /// `(marker-buffer M)` — the buffer's object handle, or `None` when detached.
    pub fn marker_buffer(&self, v: &Value) -> Option<Value> {
        let m = self.marker_rc(v)?;
        let bi = m.borrow().buffer?;
        Some(self.buffers[bi].self_obj.clone())
    }
    /// `(marker-insertion-type M)`.
    pub fn marker_insertion_type(&self, v: &Value) -> Option<bool> {
        Some(self.marker_rc(v)?.borrow().insertion_type)
    }
    /// `(set-marker-insertion-type M TYPE)`.
    pub fn set_marker_insertion_type(&mut self, v: &Value, itype: bool) {
        if let Some(m) = self.marker_rc(v) {
            m.borrow_mut().insertion_type = itype;
        }
    }
    /// Coerce a value to a buffer position: an integer/float is itself; a marker
    /// yields its position (`None` when detached); anything else `None`.
    pub fn as_position(&self, v: &Value) -> Option<i64> {
        match v {
            Value::Int(n) => Some(*n),
            Value::Float(f) => Some(*f as i64),
            _ => self.marker_position(v).map(|p| p as i64),
        }
    }
    /// Point MARKER at `(buffer, pos)` — or detach it when `buffer` is `None` —
    /// moving it between buffer registries. `pos` is clamped to `[1, size+1]`.
    pub fn set_marker_to(
        &mut self,
        marker: &Value,
        buffer: Option<usize>,
        pos: usize,
    ) -> Result<(), String> {
        let m = self.marker_rc(marker).ok_or("set-marker: not a marker")?;
        let old_buf = m.borrow().buffer;
        if let Some(ob) = old_buf {
            if let Some(b) = self.buffers.get_mut(ob) {
                b.markers.retain(|x| !Rc::ptr_eq(x, &m));
            }
        }
        match buffer {
            None => {
                let mut md = m.borrow_mut();
                md.buffer = None;
                md.pos = 0;
            }
            Some(bi) => {
                let size = self.buffers[bi].text.len();
                let p = pos.clamp(1, size + 1);
                {
                    let mut md = m.borrow_mut();
                    md.buffer = Some(bi);
                    md.pos = p;
                }
                self.buffers[bi].markers.push(m.clone());
            }
        }
        Ok(())
    }
    /// Two markers are `equal` when they share a buffer and position (Emacs
    /// `Fequal` on markers).
    pub fn markers_equal(&self, a: &Value, b: &Value) -> bool {
        match (self.marker_rc(a), self.marker_rc(b)) {
            (Some(x), Some(y)) => {
                let (xa, xb) = (x.borrow(), y.borrow());
                xa.buffer == xb.buffer && xa.pos == xb.pos
            }
            _ => false,
        }
    }

    // ── text properties ──────────────────────────────────────────────────────
    /// `plist-get` with `eq` key comparison (the `get-text-property` default).
    pub fn plist_get_eq(&self, plist: &Value, prop: &Value) -> Value {
        let mut cur = plist.clone();
        while let Some(Obj::Cons(k, d)) = self.obj(&cur) {
            let k = k.clone();
            let rest = d.clone();
            let (val, rest2) = match self.obj(&rest) {
                Some(Obj::Cons(v, d2)) => (v.clone(), d2.clone()),
                _ => return Value::Undef,
            };
            if self.values_eq(&k, prop) {
                return val;
            }
            cur = rest2;
        }
        Value::Undef
    }
    /// The property plist at absolute char index `idx0` in the current buffer.
    pub fn buffer_plist_at(&self, idx0: usize) -> Value {
        self.cur_buf_ref()
            .props
            .get(idx0)
            .cloned()
            .unwrap_or(Value::Undef)
    }
    /// Overwrite the property plist at absolute char index `idx0` in the current
    /// buffer (used by `insert` to carry an inserted string's text properties).
    pub fn buffer_set_plist_at(&mut self, idx0: usize, plist: Value) {
        if el_truthy(&plist) {
            self.buffers[self.current].has_intervals = true;
        }
        if let Some(slot) = self.buffers[self.current].props.get_mut(idx0) {
            *slot = plist;
        }
    }
    /// The property plist at absolute char index `idx0` in buffer `bi`.
    pub fn buffer_plist_at_idx(&self, bi: usize, idx0: usize) -> Value {
        self.buffers[bi]
            .props
            .get(idx0)
            .cloned()
            .unwrap_or(Value::Undef)
    }
    /// The `(point-min, point-max)` bounds of buffer `bi`.
    pub fn buffer_begv_zv(&self, bi: usize) -> (usize, usize) {
        let b = &self.buffers[bi];
        (b.begv, b.zv)
    }
    /// After `len` characters were spliced into the buffer's plists at char index
    /// `at`: boundaries past it move up, and — as `graft_intervals_into_buffer`
    /// does for text with no intervals of its own — the new text becomes an
    /// interval of its own when the buffer has intervals at all.
    fn shift_prop_bounds_for_insert(&mut self, at: usize, len: usize) {
        let has = self.buffers[self.current].has_intervals;
        let b = &mut self.buffers[self.current];
        for p in &mut b.prop_bounds {
            if *p as usize > at {
                *p += len as u32;
            }
        }
        if has {
            let total = b.props.len();
            for edge in [at, at + len] {
                if edge > 0 && edge < total {
                    let e = edge as u32;
                    if let Err(i) = b.prop_bounds.binary_search(&e) {
                        b.prop_bounds.insert(i, e);
                    }
                }
            }
        }
    }
    /// Run an interval operation over buffer BI's plists and boundaries.
    pub(crate) fn buffer_tp<T>(
        &mut self,
        bi: usize,
        f: impl FnOnce(&mut Self, &mut Vec<Value>, &mut Vec<u32>) -> T,
    ) -> T {
        let mut props = std::mem::take(&mut self.buffers[bi].props);
        let mut bounds = std::mem::take(&mut self.buffers[bi].prop_bounds);
        let r = f(self, &mut props, &mut bounds);
        self.buffers[bi].props = props;
        self.buffers[bi].prop_bounds = bounds;
        r
    }
    /// `add-text-properties` on the current buffer over char indices `[s0, e0)`.
    pub fn buffer_add_props(
        &mut self,
        s0: usize,
        e0: usize,
        pairs: &[(Value, Value)],
        set_type: crate::textprop::SetType,
    ) -> bool {
        let bi = self.current;
        self.buffers[bi].has_intervals |= s0 < e0;
        self.buffer_tp(bi, |h, props, bounds| {
            let end = e0.min(props.len());
            h.tp_add(props, bounds, s0, end, pairs, set_type)
        })
    }
    /// `put-text-property` on the current buffer over char indices `[s0, e0)`.
    pub fn buffer_put_prop(&mut self, s0: usize, e0: usize, prop: &Value, val: &Value) {
        self.buffer_add_props(
            s0,
            e0,
            &[(prop.clone(), val.clone())],
            crate::textprop::SetType::Replace,
        );
    }
    /// `set-text-properties` on the current buffer: `[s0, e0)` becomes one
    /// interval holding a copy of PLIST.
    pub fn buffer_set_props(&mut self, s0: usize, e0: usize, plist: &Value) {
        let bi = self.current;
        self.buffers[bi].has_intervals |= s0 < e0;
        self.buffer_tp(bi, |h, props, bounds| {
            let end = e0.min(props.len());
            h.tp_set(props, bounds, s0, end, plist);
        });
    }
    /// `remove-text-properties` on the current buffer.
    pub fn buffer_remove_props(&mut self, s0: usize, e0: usize, names: &[Value]) -> bool {
        let bi = self.current;
        self.buffer_tp(bi, |h, props, bounds| {
            let end = e0.min(props.len());
            h.tp_remove(props, bounds, s0, end, names)
        })
    }
    /// `remove-text-properties` of one property on the current buffer.
    pub fn buffer_remove_prop(&mut self, s0: usize, e0: usize, prop: &Value) {
        self.buffer_remove_props(s0, e0, std::slice::from_ref(prop));
    }

    /// The per-char property plists registered for string S, or `None` when it has
    /// none (or a stale/reused pointer — the `Weak` guard rejects that).
    pub fn string_props_vec(&self, s: &Arc<String>) -> Option<Vec<Value>> {
        let key = Arc::as_ptr(s) as usize;
        let (weak, props, _) = self.string_props.get(&key)?;
        weak.upgrade().filter(|a| Arc::as_ptr(a) as usize == key)?;
        Some(props.clone())
    }
    /// The recorded interval boundaries of string S (see [`crate::textprop`]).
    pub fn string_bounds_vec(&self, s: &Arc<String>) -> Vec<u32> {
        let key = Arc::as_ptr(s) as usize;
        match self.string_props.get(&key) {
            Some((weak, _, bounds))
                if weak
                    .upgrade()
                    .is_some_and(|a| Arc::as_ptr(&a) as usize == key) =>
            {
                bounds.clone()
            }
            _ => Vec::new(),
        }
    }
    /// S's intervals as `(START, END, PLIST)`, nil-plist runs included.
    pub fn string_intervals(&self, s: &Arc<String>) -> Vec<(usize, usize, Value)> {
        let Some(props) = self.string_props_vec(s) else {
            return Vec::new();
        };
        let bounds = self.string_bounds_vec(s);
        self.tp_runs(&props, &bounds)
            .into_iter()
            .map(|(a, b)| (a, b, props[a].clone()))
            .collect()
    }
    /// The property plist at char index `idx0` of string S.
    pub fn string_plist_at(&self, s: &Arc<String>, idx0: usize) -> Value {
        self.string_props_vec(s)
            .and_then(|v| v.get(idx0).cloned())
            .unwrap_or(Value::Undef)
    }
    /// Drop any per-char plists registered for string S, making it a plain
    /// unpropertized string — what `substring-no-properties` returns.
    pub fn string_clear_props(&mut self, s: &Arc<String>) {
        self.string_props.remove(&(Arc::as_ptr(s) as usize));
    }
    /// Install (replacing any existing) the per-char plists for string S.
    pub fn string_set_props_vec(&mut self, s: &Arc<String>, vec: Vec<Value>) {
        let key = Arc::as_ptr(s) as usize;
        self.string_props
            .insert(key, (Arc::downgrade(s), vec, Vec::new()));
    }
    /// Install the plists and the interval boundaries of string S.
    pub fn string_set_props_bounded(&mut self, s: &Arc<String>, vec: Vec<Value>, bounds: Vec<u32>) {
        let key = Arc::as_ptr(s) as usize;
        self.string_props
            .insert(key, (Arc::downgrade(s), vec, bounds));
    }
    /// The property vec for S, creating an all-nil one of the right length if the
    /// string has none registered yet.
    fn string_props_or_new(&self, s: &Arc<String>) -> Vec<Value> {
        self.string_props_vec(s)
            .unwrap_or_else(|| vec![Value::Undef; s.chars().count()])
    }
    /// intervals.c `copy_properties`: text copied into a new string or between
    /// a buffer and a string takes a fresh copy (`Fcopy_sequence`) of each
    /// interval's plist, so the result never shares a plist with its source. A
    /// run of characters holding the same plist is one interval and shares one
    /// copy.
    pub fn copy_plist_runs(&mut self, plists: Vec<Value>) -> Vec<Value> {
        let mut out: Vec<Value> = Vec::with_capacity(plists.len());
        for (i, p) in plists.iter().enumerate() {
            if !el_truthy(p) {
                out.push(Value::Undef);
            } else if i > 0 && self.values_eq(&plists[i - 1], p) {
                out.push(out[i - 1].clone());
            } else {
                let items = self.list_vec(p).unwrap_or_default();
                out.push(self.list_from(items));
            }
        }
        out
    }
    /// Carry text properties onto a freshly-built string.
    ///
    /// `pieces` names, for each run of the result in order, the source string it
    /// came from and the char index it starts at inside that source. A run whose
    /// source has no properties contributes nils, and a result with no propertized
    /// piece at all registers nothing — an unpropertized string must stay one, or
    /// every `concat` would allocate a plist vector.
    ///
    /// This is what makes `(concat (propertize "a" 'face 'bold) "b")` keep the
    /// face on its first character, the way Emacs's interval trees do: the
    /// properties are per-character, so they follow the characters wherever a
    /// builtin copies them.
    pub fn string_carry_props(
        &mut self,
        out: &Arc<String>,
        pieces: &[(Option<Arc<String>>, usize, usize)],
    ) {
        self.string_carry_props_ordered(out, pieces, false);
    }

    /// `copy_text_properties` as `substring` and `concat` call it: each source
    /// interval's plist reaches the new string with its PAIRS in reverse order
    /// (measured, GNU Emacs 31.1: `(substring (propertize "abc" 'a 1 'b 2) 0)`
    /// prints `(b 2 a 1)`). `copy-sequence` and `upcase` copy the interval tree
    /// and keep the order, so they stay on `string_carry_props`.
    pub fn string_copy_props(
        &mut self,
        out: &Arc<String>,
        pieces: &[(Option<Arc<String>>, usize, usize)],
    ) {
        self.string_carry_props_ordered(out, pieces, true);
    }

    fn string_carry_props_ordered(
        &mut self,
        out: &Arc<String>,
        pieces: &[(Option<Arc<String>>, usize, usize)],
        reverse_pairs: bool,
    ) {
        let total: usize = pieces.iter().map(|p| p.2).sum();
        let mut vec: Vec<Value> = vec![Value::Undef; total];
        let mut bounds: Vec<u32> = Vec::new();
        let mut any = false;
        let mut at = 0;
        for (src, start, len) in pieces {
            if let Some(s) = src {
                if let Some(props) = self.string_props_vec(s) {
                    let sb = self.string_bounds_vec(s);
                    // One fresh copy of the plist per source interval, shared
                    // by every character of it (`copy_properties`).
                    for (rs, re) in self.tp_runs(&props, &sb) {
                        if re <= *start || rs >= start + len || !el_truthy(&props[rs]) {
                            continue;
                        }
                        any = true;
                        let mut items = self.list_vec(&props[rs]).unwrap_or_default();
                        if reverse_pairs {
                            items = items.chunks(2).rev().flatten().cloned().collect();
                        }
                        let copy = self.list_from(items);
                        let a = rs.max(*start) - start + at;
                        let b = re.min(start + len) - start + at;
                        for slot in &mut vec[a..b] {
                            *slot = copy.clone();
                        }
                    }
                    self.tp_clip(&props, &sb, (*start, *len, at, total), &mut bounds);
                }
            }
            at += len;
        }
        if any {
            self.string_set_props_bounded(out, vec, bounds);
        }
    }

    /// The whole of `src` as one piece, for a builtin that transforms a string
    /// character-for-character (`upcase`, `capitalize`) or copies it entire.
    pub fn string_carry_all(&mut self, out: &Arc<String>, src: &Arc<String>) {
        let len = src.chars().count();
        self.string_carry_props(out, &[(Some(Arc::clone(src)), 0, len)]);
    }

    /// `put-text-property` on string S over char indices `[s0, e0)`.
    pub fn string_put_prop(
        &mut self,
        s: &Arc<String>,
        s0: usize,
        e0: usize,
        prop: &Value,
        val: &Value,
    ) {
        self.string_add_props(
            s,
            s0,
            e0,
            &[(prop.clone(), val.clone())],
            crate::textprop::SetType::Replace,
        );
    }
    /// `add-text-properties` (and `add-face-text-property`, by SET_TYPE) on
    /// string S over `[s0, e0)`; true when a property changed.
    pub fn string_add_props(
        &mut self,
        s: &Arc<String>,
        s0: usize,
        e0: usize,
        pairs: &[(Value, Value)],
        set_type: crate::textprop::SetType,
    ) -> bool {
        let mut vec = self.string_props_or_new(s);
        let mut bounds = self.string_bounds_vec(s);
        let end = e0.min(vec.len());
        let changed = self.tp_add(&mut vec, &mut bounds, s0, end, pairs, set_type);
        self.string_set_props_bounded(s, vec, bounds);
        changed
    }
    /// `set-text-properties` on string S over `[s0, e0)`: one interval holding
    /// PLIST, or no intervals at all when PLIST is nil and the range is the
    /// whole string.
    pub fn string_set_props(&mut self, s: &Arc<String>, s0: usize, e0: usize, plist: &Value) {
        let len = s.chars().count();
        if !el_truthy(plist) && s0 == 0 && e0 >= len {
            self.string_clear_props(s);
            return;
        }
        let mut vec = self.string_props_or_new(s);
        let mut bounds = self.string_bounds_vec(s);
        let end = e0.min(vec.len());
        self.tp_set(&mut vec, &mut bounds, s0, end, plist);
        self.string_set_props_bounded(s, vec, bounds);
    }
    /// `remove-text-properties` / `remove-list-of-text-properties` on string S
    /// over `[s0, e0)`; true when a property was removed.
    pub fn string_remove_props(
        &mut self,
        s: &Arc<String>,
        s0: usize,
        e0: usize,
        names: &[Value],
    ) -> bool {
        // A string with no intervals is left alone (`validate_interval_range`
        // is soft for removal).
        let Some(mut vec) = self.string_props_vec(s) else {
            return false;
        };
        let mut bounds = self.string_bounds_vec(s);
        let end = e0.min(vec.len());
        let changed = self.tp_remove(&mut vec, &mut bounds, s0, end, names);
        self.string_set_props_bounded(s, vec, bounds);
        changed
    }
    /// `remove-text-properties` of one property on string S over `[s0, e0)`.
    pub fn string_remove_prop(&mut self, s: &Arc<String>, s0: usize, e0: usize, prop: &Value) {
        self.string_remove_props(s, s0, e0, std::slice::from_ref(prop));
    }
    /// Value comparison for merging text-property intervals: `eq` semantics, but
    /// strings also compare by content (adjacent cells that were given an
    /// `equal`-string property merge, matching Emacs's shared-string intervals).
    fn merge_val_eq(&self, a: &Value, b: &Value) -> bool {
        match (self.str_text(a), self.str_text(b)) {
            (Some(x), Some(y)) => x == y,
            _ => self.values_eq(a, b),
        }
    }
    /// True if PLIST A ⊆ PLIST B: every `(key value)` of A has an equal value in B
    /// (a nil value counts as absent). Used only for interval merging on print.
    fn plist_subset(&self, a: &Value, b: &Value) -> bool {
        let mut cur = a.clone();
        while let Some(Obj::Cons(k, d)) = self.obj(&cur) {
            let k = k.clone();
            let (v, rest2) = match self.obj(d) {
                Some(Obj::Cons(v, d2)) => (v.clone(), d2.clone()),
                _ => break,
            };
            let bv = self.plist_get_eq(b, &k);
            if !self.merge_val_eq(&bv, &v) {
                return false;
            }
            cur = rest2;
        }
        true
    }
    /// Structural plist equality (same key→value set, `eq` on values) — used to
    /// merge adjacent text-property intervals when printing a propertized string.
    pub(crate) fn plist_struct_eq(&self, a: &Value, b: &Value) -> bool {
        // An empty plist is not the same interval as one that names a property
        // whose value happens to be nil: `(propertize "ab" 'p nil)` followed by
        // an unpropertized character prints as two runs, not one. The subset
        // walk cannot see the difference — a key absent from a plist reads as
        // nil — so the emptiness is compared first.
        if el_truthy(a) != el_truthy(b) {
            return false;
        }
        self.plist_subset(a, b) && self.plist_subset(b, a)
    }
    /// The `#(...)` interval tail for a propertized string: maximal runs of chars
    /// sharing a (non-nil) property list, as ` START END (plist)` segments. Empty
    /// when the string carries no properties.
    fn string_prop_intervals(&self, s: &Arc<String>, depth: usize) -> String {
        let mut out = String::new();
        for (i, j, plist) in self.string_intervals(s) {
            if el_truthy(&plist) {
                out.push_str(&format!(
                    " {} {} {}",
                    i,
                    j,
                    self.print_inner(&plist, true, depth + 1)
                ));
            }
        }
        out
    }

    /// Resolve char `c` in char-table `ct` with Emacs `char_table_ref` fallback:
    /// the table's own char value; if nil, its `default`; if that is also nil and
    /// `parent` is a char-table, recurse into the parent. `ct` must be a
    /// `Value::Obj` pointing at an `Obj::CharTable`.
    pub fn char_table_ref(&self, ct: &Value, c: u32) -> Value {
        let mut cur = ct.clone();
        // Iterate the parent chain instead of recursing.
        loop {
            let Some(Obj::CharTable(t)) = self.obj(&cur) else {
                return Value::Undef;
            };
            let v = t.raw_get(c);
            if el_truthy(&v) {
                return v;
            }
            if el_truthy(&t.default) {
                return t.default.clone();
            }
            if matches!(self.obj(&t.parent), Some(Obj::CharTable(_))) {
                cur = t.parent.clone();
            } else {
                return Value::Undef;
            }
        }
    }

    /// The designator characters of the syntax codes, in code order — Emacs's
    /// `syntax_code_spec` (`src/syntax.c`) and the prelude's
    /// `--syntax-code-spec--`, which must stay the same string.
    const SYNTAX_CODE_SPEC: &'static [u8] = b" .w_()'\"$\\/<>@!|";

    /// The syntax table `(syntax-table)` would return: the current buffer's, or
    /// the standard one when the buffer has none. Read straight out of the two
    /// prelude variables rather than by calling elisp, because the caller is a
    /// regexp compile that can happen underneath any evaluation.
    fn current_syntax_table(&self) -> Value {
        let local = self
            .find_symbol("--current-syntax-table--")
            .and_then(|s| self.get_value(&s).ok());
        match local {
            Some(v) if el_truthy(&v) => v,
            _ => self
                .find_symbol("--standard-syntax-table--")
                .and_then(|s| self.get_value(&s).ok())
                .unwrap_or(Value::Undef),
        }
    }

    /// `SYNTAX (c)` in the current syntax table, as its designator character.
    pub fn syntax_class_of(&self, c: char) -> char {
        self.syntax_class_in(&self.current_syntax_table(), c as u32)
    }

    /// `SYNTAX (c)` in TABLE; an entry that is not a `(CODE . MATCH)` cons is
    /// class 0 (whitespace).
    fn syntax_class_in(&self, table: &Value, c: u32) -> char {
        let v = self.char_table_ref(table, c);
        let code = match self.obj(&v) {
            Some(Obj::Cons(Value::Int(n), _)) => (*n as u64 & 0xFFFF) as usize,
            _ => 0,
        };
        *Self::SYNTAX_CODE_SPEC.get(code).unwrap_or(&b' ') as char
    }

    /// A hash of everything `syntax_class_ranges` reads: which table is current
    /// and, down its parent chain, every table's runs, default and parent.  A
    /// compiled regexp that consulted the syntax table stays valid exactly while
    /// this value is unchanged, so the regexp cache can keep it instead of
    /// recompiling on every call.
    pub fn syntax_fingerprint(&self) -> u64 {
        use std::hash::{Hash, Hasher};
        let code_of = |v: &Value| match self.obj(v) {
            Some(Obj::Cons(Value::Int(n), m)) => (*n, if let Value::Int(m) = m { *m } else { -1 }),
            _ => (-1, -1),
        };
        let mut hasher = std::collections::hash_map::DefaultHasher::new();
        let mut cur = self.current_syntax_table();
        for _ in 0..64 {
            let Some(Obj::CharTable(t)) = self.obj(&cur) else {
                break;
            };
            if let Value::Obj(id) = cur {
                id.hash(&mut hasher);
            }
            code_of(&t.default).hash(&mut hasher);
            for (start, v) in t.runs() {
                start.hash(&mut hasher);
                code_of(&v).hash(&mut hasher);
            }
            cur = t.parent.clone();
        }
        hasher.finish()
    }

    /// Every character range whose syntax class in the current table is `class`
    /// (a `modify-syntax-entry` designator: `w`, `_`, `.`, `<`, `>`, …).
    ///
    /// This is what `\sC` needs. Emacs's regexp engine asks `SYNTAX (c) ==
    /// class` per character as it matches; elisprs translates to a `fancy_regex`
    /// pattern up front, so the same question has to be answered for the whole
    /// character space at compile time. That is cheap here because a `CharTable`
    /// stores a block tree (see [`CharTable`]), not 4M slots: the breakpoints
    /// of the table and of every table in its parent chain bound every place the
    /// answer can change.
    ///
    /// An entry that is not a `(CODE . MATCH)` cons counts as class 0
    /// (whitespace), which is what `SYNTAX` yields for an unset slot.
    pub fn syntax_class_ranges(&self, class: char) -> Vec<(u32, u32)> {
        let table = self.current_syntax_table();
        let mut breaks: Vec<u32> = vec![0];
        let mut cur = table.clone();
        for _ in 0..64 {
            let Some(Obj::CharTable(t)) = self.obj(&cur) else {
                break;
            };
            breaks.extend(t.runs().iter().map(|(s, _)| *s));
            cur = t.parent.clone();
        }
        breaks.sort_unstable();
        breaks.dedup();

        let class_at = |c: u32| self.syntax_class_in(&table, c);

        let mut out: Vec<(u32, u32)> = Vec::new();
        for (i, &lo) in breaks.iter().enumerate() {
            let hi = breaks.get(i + 1).map_or(MAX_CHAR, |n| n - 1);
            if class_at(lo) != class {
                continue;
            }
            // Runs are produced in ascending order, so a run abutting the
            // previous kept one just extends it.
            match out.last_mut() {
                Some(last) if last.1 + 1 == lo => last.1 = hi,
                _ => out.push((lo, hi)),
            }
        }
        out
    }

    /// The current buffer's category table (category.c `BVAR (current_buffer,
    /// category_table)`): the buffer-local `--current-category-table--`, else
    /// the standard table. Both are maintained by src/lisp/category-c.el.
    fn current_category_table(&self) -> Value {
        let local = self
            .find_symbol("--current-category-table--")
            .and_then(|s| self.get_value(&s).ok());
        match local {
            Some(v) if el_truthy(&v) => v,
            _ => self
                .find_symbol("--standard-category-table--")
                .and_then(|s| self.get_value(&s).ok())
                .unwrap_or(Value::Undef),
        }
    }

    /// Whether category set SET (a 128-element bool-vector) has CATEGORY —
    /// category.h `CATEGORY_MEMBER`.
    fn category_member(&self, set: &Value, category: u8) -> bool {
        matches!(self.obj(set), Some(Obj::BoolVector(bits))
                 if bits.get(category as usize).copied().unwrap_or(false))
    }

    /// Every character range whose category set in the current category table
    /// contains CATEGORY. This is what `\cC` needs, for the same reason
    /// [`Self::syntax_class_ranges`] exists: regex-emacs.c asks
    /// `CHAR_HAS_CATEGORY (c, cat)` per character while matching, and the
    /// translation has to answer for the whole character space up front.
    pub fn category_ranges(&self, category: u8) -> Vec<(u32, u32)> {
        let table = self.current_category_table();
        let Some(Obj::CharTable(t)) = self.obj(&table) else {
            return Vec::new();
        };
        let runs = t.runs();
        let mut out: Vec<(u32, u32)> = Vec::new();
        for (i, (lo, val)) in runs.iter().enumerate() {
            let hi = runs.get(i + 1).map_or(MAX_CHAR, |(n, _)| n - 1);
            // An unset run reads as the table's default (CHAR_TABLE_REF).
            let set = if el_truthy(val) { val } else { &t.default };
            if !self.category_member(set, category) {
                continue;
            }
            match out.last_mut() {
                Some(last) if last.1 + 1 == *lo => last.1 = hi,
                _ => out.push((*lo, hi)),
            }
        }
        out
    }

    /// A hash of everything [`Self::category_ranges`] reads: which category
    /// table is current, its runs and the bits of every category set in it. A
    /// compiled `\cC` regexp stays valid exactly while this is unchanged.
    pub fn category_fingerprint(&self) -> u64 {
        use std::hash::{Hash, Hasher};
        let mut hasher = std::collections::hash_map::DefaultHasher::new();
        let table = self.current_category_table();
        if let Value::Obj(id) = table {
            id.hash(&mut hasher);
        }
        let bits_of = |v: &Value| match self.obj(v) {
            Some(Obj::BoolVector(bits)) => bits.clone(),
            _ => Vec::new(),
        };
        if let Some(Obj::CharTable(t)) = self.obj(&table) {
            bits_of(&t.default).hash(&mut hasher);
            for (start, v) in t.runs() {
                start.hash(&mut hasher);
                bits_of(&v).hash(&mut hasher);
            }
        }
        hasher.finish()
    }

    /// `eq`-style identity comparison (used for `catch`/`throw` tags).
    pub fn values_eq(&self, a: &Value, b: &Value) -> bool {
        if !el_truthy(a) && !el_truthy(b) {
            return true;
        }
        match (a, b) {
            (Value::Int(x), Value::Int(y)) => x == y,
            (Value::Float(x), Value::Float(y)) => x.to_bits() == y.to_bits(),
            (Value::Obj(x), Value::Obj(y)) => x == y,
            (Value::Bool(true), Value::Bool(true)) => true,
            _ => false,
        }
    }

    /// Build the `(error-symbol "message")` object a `condition-case` handler
    /// binds its variable to, from a rendered "symbol: message" error string.
    /// Detach the current lexical scope chain, returning it. Used by `eval`,
    /// whose FORM runs in the environment its LEXICAL argument names rather than
    /// in the caller's.
    pub fn take_lex(&mut self) -> Lex {
        self.lex.take()
    }

    /// Restore a scope chain taken by [`Self::take_lex`].
    pub fn restore_lex(&mut self, lex: Lex) {
        self.lex = lex;
    }

    /// The OClosure side table, flattened for the cache: `(closure-handle, type,
    /// slot-handles)`.
    ///
    /// It is NOT reconstructible from the heap image: `oclosure--fix-type` runs
    /// when the *prelude* runs (`oclosure--accessor-prototype` is a prelude
    /// `defconst`), and a cache hit skips the prelude. Without it, every prelude
    /// OClosure came back as a plain closure and `oclosure--copy` answered
    /// "not an OClosure" on the second run of any script.
    pub fn export_oclosure_meta(&self) -> Vec<(u32, u32, Vec<u32>)> {
        self.oclosure_meta
            .iter()
            .map(|(id, m)| (*id, m.ty, m.slots.clone()))
            .collect()
    }

    /// Restore the table exported by [`Self::export_oclosure_meta`]. Handles line
    /// up because the image is imported into a host whose arena is at exactly the
    /// length it had when the image was taken.
    pub fn import_oclosure_meta(&mut self, meta: Vec<(u32, u32, Vec<u32>)>) {
        for (id, ty, slots) in meta {
            self.oclosure_meta.insert(id, OClosureMeta { ty, slots });
        }
    }

    /// A sequence's elements, or Emacs's error for what it actually is.
    ///
    /// An improper list names its offending TAIL (`(reverse (cons 1 2))` is
    /// `(wrong-type-argument listp 2)`), while a non-sequence names itself.
    pub fn seq_vec_checked(&mut self, v: &Value) -> Result<Vec<Value>, String> {
        // A cons is walked with `FOR_EACH_TAIL` FIRST, because that walk is the
        // only one that terminates on a circular list. `Fmapconcat`, `Fmapcar`
        // and `Fmapc` all begin with `Flength (sequence)` for exactly this
        // reason, and this is the gate they reach it through here; without it
        // `(mapconcat #'identity CIRCULAR ",")` ran forever where Emacs signals
        // `(circular-list …)`.
        if matches!(self.obj(v), Some(Obj::Cons(..))) {
            let mut out = Vec::new();
            let mut w = crate::builtins::TailWalk::new(v);
            while let Some((car, cdr)) = w.cons(self) {
                out.push(car);
                if w.step(cdr) {
                    let tail = w.tail.clone();
                    return Err(self.signal_circular_list(&tail));
                }
            }
            if !el_nil(&w.tail) {
                // `CHECK_LIST_END`: an improper list names its TAIL here, not the
                // whole list — `(mapconcat #'identity (cons "a" 9))` is
                // `(wrong-type-argument listp 9)`.
                return Err(format!(
                    "wrong-type-argument: listp {}",
                    self.print(&w.tail, true)
                ));
            }
            return Ok(out);
        }
        if let Some(items) = self.seq_vec(v) {
            return Ok(items);
        }
        Err(format!(
            "wrong-type-argument: sequencep {}",
            self.print(v, true)
        ))
    }

    /// The function a designator names: a symbol resolves through its function
    /// cell (following aliases), anything else is already a function.
    ///
    /// `funcall`/`apply` resolve before calling, which is why Emacs's arity error
    /// from them names `#<subr char-to-string>` where a direct `(char-to-string)`
    /// names the symbol.
    /// Whether a function cell holds a macro: a macro closure, or a
    /// `(macro . FN)` cons.
    fn is_macro_cell(&self, cell: &Value) -> bool {
        match self.obj(cell) {
            Some(Obj::Closure { is_macro, .. }) => *is_macro,
            Some(Obj::Cons(car, _)) => self.sym_name(car).as_deref() == Some("macro"),
            _ => false,
        }
    }
    pub fn function_designator(&mut self, f: &Value) -> Value {
        let mut cur = f.clone();
        for _ in 0..16 {
            match self.obj(&cur) {
                Some(Obj::Symbol(s)) => match s.function.clone() {
                    // An autoload object cannot be called as a value: keep the
                    // symbol so `call_function' loads the file and retries.
                    Some(_) if self.indirect_autoload(&cur).is_some() => return cur,
                    // A macro cannot be funcalled, and `funcall_general` names
                    // the designator as passed in its `invalid-function` signal,
                    // so keep it rather than the `(macro . FN)` it leads to.
                    Some(next) if self.is_macro_cell(&next) => return f.clone(),
                    Some(next) => cur = next,
                    None => return cur,
                },
                _ => return cur,
            }
        }
        cur
    }

    /// Signal Emacs's `(wrong-number-of-arguments FUNCTION COUNT)`.
    ///
    /// The data holds the function *object*. Rendering it into the message and
    /// re-reading it (which is how the other error helpers build their data) cannot
    /// work here: a closure prints as `#[(x) (x) (t)]`, and no reader can turn that
    /// back into the closure it came from.
    ///
    /// FUNCTION is the object only for a C subr and an interpreted closure. A
    /// *byte-compiled* function never reaches `funcall_lambda`'s signal at all:
    /// its integral arglist sends it straight to `exec_byte_code`, which checks
    /// the arity itself and reports the packed template instead of the callee
    /// (bytecode.c:519-529 on emacs-30):
    ///
    /// ```text
    ///   bool rest      = (args_template & 128) != 0;
    ///   int  mandatory =  args_template & 127;
    ///   ptrdiff_t nonrest = args_template >> 8;
    ///   if (! (mandatory <= nargs && (rest || nargs <= nonrest)))
    ///     Fsignal (Qwrong_number_of_arguments,
    ///              list2 (Fcons (make_fixnum (mandatory), make_fixnum (nonrest)),
    ///                     make_fixnum (nargs)));
    /// ```
    ///
    /// so the datum is `(MANDATORY . NONREST)` — NONREST counts the non-`&rest`
    /// formals, which is why `error`, whose `&rest` makes `func-arity` say
    /// `(1 . many)`, still reports `(1 . 1)`. See `lisp_level_arity` for why
    /// elisprs has to know which of its subrs Emacs implements this way.
    /// `funcall_lambda` / `exec_byte_code` for a macro's expander: a user macro is
    /// an interpreted closure, named itself (the cdr of `(macro . FN)`); a prelude
    /// macro stands for byte-compiled Lisp and reports `(MANDATORY . NONREST)`,
    /// as `(macroexpand '(push 1))` does in Emacs: `(2 . 2) 1`.
    pub fn signal_macro_wrong_nargs(
        &mut self,
        macro_obj: &Value,
        params: &Params,
        argc: usize,
    ) -> String {
        let prelude = self.is_prelude_object(macro_obj);
        // A macro closure prints as `(macro . FN)`; the datum is FN.
        let fun = match self.obj(macro_obj) {
            Some(Obj::Closure {
                params,
                body,
                env,
                dynamic,
                src,
                ..
            }) => {
                let c = Obj::Closure {
                    params: params.clone(),
                    body: body.clone(),
                    is_macro: false,
                    env: env.clone(),
                    dynamic: *dynamic,
                    src: src.clone(),
                };
                if prelude {
                    macro_obj.clone()
                } else {
                    self.alloc(c)
                }
            }
            _ => macro_obj.clone(),
        };
        let subject = if prelude {
            let mandatory = params.required.len() as i64;
            let nonrest = mandatory + params.optional.len() as i64;
            self.cons(Value::Int(mandatory), Value::Int(nonrest))
        } else {
            fun
        };
        let sym = self.intern("wrong-number-of-arguments");
        let data = self.list_from(vec![subject.clone(), Value::Int(argc as i64)]);
        let msg = format!(
            "wrong-number-of-arguments: {} {argc}",
            self.print(&subject, true)
        );
        let obj = self.cons(sym, data);
        self.set_pending_error(&msg, obj);
        msg
    }

    /// `(when)` / `(unless)`: the byte-compiled `(cond &rest body)` expander
    /// rejects a missing COND with its arity template, `((1 . 1) 0)`.
    pub fn signal_intrinsic_macro_wrong_nargs(&mut self) -> String {
        let sym = self.intern("wrong-number-of-arguments");
        let template = self.cons(Value::Int(1), Value::Int(1));
        let data = self.list_from(vec![template, Value::Int(0)]);
        let obj = self.cons(sym, data);
        let msg = "wrong-number-of-arguments: (1 . 1) 0".to_string();
        self.set_pending_error(&msg, obj);
        msg
    }

    /// The `wrong-number-of-arguments` of a call to a prelude or user CLOSURE.
    ///
    /// A closure the prelude defined models Emacs's preloaded or autoloaded Lisp,
    /// which ships byte-compiled: `exec_byte_code` signals the packed
    /// `(MANDATORY . NONREST)` template, not the function (NONREST counts the
    /// formals before `&rest`). The exception is a name that is a C subr in Emacs
    /// (`PRELUDE_C_SUBR_NAMES`), which names the callee as written. A closure
    /// the program defined is interpreted in Emacs too and names the closure.
    pub fn signal_closure_wrong_nargs(
        &mut self,
        callee: &Value,
        object: &Value,
        argc: usize,
    ) -> String {
        if self.is_prelude_object(object) {
            let named_subr = self
                .sym_name(callee)
                .is_some_and(|n| PRELUDE_C_SUBR_NAMES.binary_search(&n.as_str()).is_ok());
            if named_subr {
                return self.signal_wrong_nargs_subject(callee.clone(), argc);
            }
            if let Some(Obj::Closure { params, .. }) = self.obj(object) {
                let mandatory = params.required.len() as i64;
                let nonrest = mandatory + params.optional.len() as i64;
                let template = self.cons(Value::Int(mandatory), Value::Int(nonrest));
                return self.signal_wrong_nargs_subject(template, argc);
            }
        }
        self.signal_wrong_nargs(object, argc)
    }

    pub fn signal_wrong_nargs_subject(&mut self, subject: Value, argc: usize) -> String {
        let sym = self.intern("wrong-number-of-arguments");
        let data = self.list_from(vec![subject.clone(), Value::Int(argc as i64)]);
        let display = format!("{} {}", self.print(&subject, true), argc);
        let obj = self.cons(sym, data);
        let msg = format!("wrong-number-of-arguments: {display}");
        self.set_pending_error(&msg, obj);
        msg
    }

    pub fn signal_wrong_nargs(&mut self, callee: &Value, argc: usize) -> String {
        let sym = self.intern("wrong-number-of-arguments");
        let count = Value::Int(argc as i64);
        let subject = match self.byte_compiled_arity_template(callee) {
            Some((mandatory, nonrest)) => {
                self.cons(Value::Int(mandatory as i64), Value::Int(nonrest as i64))
            }
            None => callee.clone(),
        };
        let data = self.list_from(vec![subject.clone(), count]);
        let display = format!("{} {}", self.print(&subject, true), argc);
        let obj = self.cons(sym, data);
        let msg = format!("wrong-number-of-arguments: {display}");
        self.set_pending_error(&msg, obj);
        msg
    }

    /// The `(MANDATORY . NONREST)` template `exec_byte_code` would report for
    /// `callee`, or `None` when Emacs reaches this call through a path that
    /// names the callee itself (a C subr, an interpreted closure).
    ///
    /// Only a subr designator can qualify: a closure elisprs built from a
    /// `defun` is the interpreted shape in Emacs too, and `funcall_lambda`
    /// names it.
    fn byte_compiled_arity_template(&self, callee: &Value) -> Option<(u16, u16)> {
        let mut cur = callee.clone();
        for _ in 0..64 {
            match self.obj(&cur) {
                Some(Obj::Subr { name, .. }) => return lisp_level_arity(name),
                Some(Obj::Symbol(s)) => cur = s.function.clone()?,
                _ => return None,
            }
        }
        None
    }

    /// lisp.h `circular_list (list)` — `xsignal1 (Qcircular_list, list)`, the
    /// signal `FOR_EACH_TAIL` raises when the hare catches the tortoise.
    ///
    /// The datum is the tail the walk was standing on, carried as the object so
    /// `condition-case` binds the real list. The MESSAGE deliberately does not
    /// render it: this printer walks the cdr chain, and the only reason the
    /// signal exists is that the chain has no end. `length` states the same
    /// limitation from the other direction.
    pub fn signal_circular_list(&mut self, list: &Value) -> String {
        let sym = self.intern("circular-list");
        let data = self.list_from(vec![list.clone()]);
        let obj = self.cons(sym, data);
        let msg = "circular-list: circular list".to_string();
        self.set_pending_error(&msg, obj);
        msg
    }

    /// `(wrong-type-argument PRED VALUE)` with VALUE carried as the *object*.
    ///
    /// The usual path renders the value into the message and re-reads it, which
    /// only works for values that have read syntax. A marker, a buffer or a
    /// closure prints as `#<…>` / `#[…]`, which the reader rejects — so the datum
    /// was silently dropped and the condition came back as `(wrong-type-argument
    /// PRED)` with no offender at all.
    pub fn signal_wrong_type(&mut self, pred: &str, value: &Value) -> String {
        let msg = format!("wrong-type-argument: {pred} {}", self.print(value, true));
        let sym = self.intern("wrong-type-argument");
        let p = self.intern(pred);
        let data = self.list_from(vec![p, value.clone()]);
        let obj = self.cons(sym, data);
        self.set_pending_error(&msg, obj);
        msg
    }

    /// Signal Emacs's `(error "MESSAGE" DATUM)` — `xsignal2 (Qerror,
    /// build_string (MESSAGE), DATUM)`, the shape `secure_hash` and `tzlookup`
    /// use.
    ///
    /// The message-only path renders DATUM into the message text and re-reads it,
    /// which for a plain `error` produces the one-element data `("MESSAGE DATUM")`
    /// — the datum fused into the message string rather than standing beside it.
    pub fn signal_error_with(&mut self, message: &str, datum: &Value) -> String {
        let msg = format!("error: {message} {}", self.print(datum, true));
        let sym = self.intern("error");
        let m = self.new_string(message);
        let data = self.list_from(vec![m, datum.clone()]);
        let obj = self.cons(sym, data);
        self.set_pending_error(&msg, obj);
        msg
    }

    /// Signal Emacs's `signal_error (S, ARG)` (eval.c:2000-2007, emacs-30.2):
    ///
    /// ```text
    ///   if (NILP (Fproper_list_p (arg)))
    ///     arg = list1 (arg);
    ///   xsignal (Qerror, Fcons (build_string (s), arg));
    /// ```
    ///
    /// so the error data is `("S" . ARG)`, and ARG is SPLICED when it is already
    /// a proper list rather than nested inside one. That is not the same shape as
    /// [`Self::signal_error_with`], which ports `xsignal2` and always nests: for
    /// a symbol or a number the two agree, for a list they do not, and for nil
    /// this one produces the message alone. C code reaches for whichever it
    /// means, so both exist here.
    pub fn signal_error_arg(&mut self, message: &str, arg: &Value) -> String {
        let msg = format!("error: {message} {}", self.print(arg, true));
        let sym = self.intern("error");
        let m = self.new_string(message);
        let mut items = vec![m];
        match self.list_vec(arg) {
            Some(tail) => items.extend(tail),
            None => items.push(arg.clone()),
        }
        let data = self.list_from(items);
        let obj = self.cons(sym, data);
        self.set_pending_error(&msg, obj);
        msg
    }

    /// Record the error object that belongs to `msg` (the string the failing call
    /// returns as its `Err`). See [`Self::take_pending_error`].
    pub fn set_pending_error(&mut self, msg: &str, obj: Value) {
        self.pending_error = Some((msg.to_string(), obj));
    }

    /// The error object recorded for `msg`, if any. An object recorded for a
    /// *different* message belongs to an error that has already been dealt with —
    /// it must not stand in for this one.
    pub fn take_pending_error(&mut self, msg: &str) -> Option<Value> {
        match &self.pending_error {
            Some((m, _)) if m == msg => self.pending_error.take().map(|(_, v)| v),
            _ => None,
        }
    }

    pub fn make_error_object(&mut self, e: &str) -> Value {
        // Conditions Emacs signals with an empty DATA list: the condition object
        // is just `(SYMBOL)` with no message datum (`arith-error`, `end-of-file`,
        // `beginning-of-buffer`, `end-of-buffer`). Their human-readable text lives
        // in the symbol's `error-message`, not in the data, so drop it here. The
        // generic `error`/`user-error` symbols keep the message as data.
        const NIL_DATA_ERRORS: &[&str] = &[
            "arith-error",
            "overflow-error",
            "end-of-file",
            "beginning-of-buffer",
            "end-of-buffer",
        ];
        let trimmed = e.trim();
        let sym_candidate = trimmed.split_once(':').map_or(trimmed, |(s, _)| s.trim());
        if NIL_DATA_ERRORS.contains(&sym_candidate) {
            let s = self.intern(sym_candidate);
            // `end-of-file` read from a string is bare too (lread.c
            // `end_of_file_error`); the readers of a buffer or a file being
            // loaded attach their source themselves.
            return self.list_from(vec![s]);
        }
        let (sym, msg) = match e.split_once(':') {
            Some((s, m)) => (s.trim().to_string(), m.trim().to_string()),
            None => ("error".to_string(), e.to_string()),
        };
        // These conditions carry a list of *values* as DATA in Emacs, not a
        // message string: `(wrong-type-argument PREDICATE VALUE)`,
        // `(args-out-of-range ARRAY START END)`, `(void-variable SYM)`,
        // `(void-function SYM)`. The Rust helpers render those values in
        // readable form, so re-read them into separate elements.
        if matches!(
            sym.as_str(),
            "wrong-type-argument"
                | "args-out-of-range"
                | "void-variable"
                | "void-function"
                | "wrong-number-of-arguments"
                | "wrong-length-argument"
                | "invalid-function"
                // `(excessive-lisp-nesting DEPTH)` — DEPTH is the integer, not "1601".
                | "excessive-lisp-nesting"
                // `(setting-constant SYM)` — the rejected symbol itself.
                | "setting-constant"
                // `(cl-assertion-failed (FORM ARGS…))` — the failed form, as a
                // form, never its printed text.
                | "cl-assertion-failed"
                // `(cyclic-variable-indirection SYM)` — the symbol, not its name.
                | "cyclic-variable-indirection"
        ) {
            if let Some(data) = self.read_all_forms(&msg) {
                let s = self.intern(&sym);
                return self.cons(s, data);
            }
        }
        let s = self.intern(&sym);
        let m = self.new_string(msg);
        self.list_from(vec![s, m])
    }

    /// Read every form in `src` into a proper list (used to reconstruct error
    /// DATA from a rendered message). None if nothing parses.
    fn read_all_forms(&mut self, src: &str) -> Option<Value> {
        let len = src.chars().count();
        let mut forms = Vec::new();
        let mut pos = 0;
        while pos < len {
            match crate::reader::read_one(self, src, pos) {
                Ok((v, next)) if next > pos => {
                    forms.push(v);
                    pos = next;
                }
                _ => break,
            }
        }
        if forms.is_empty() {
            None
        } else {
            Some(self.list_from(forms))
        }
    }
}

/// The `(PRECISION, CONVERSION)` of a `float-output-format` that print.c's
/// `float_to_string` accepts, or `None` for one it ignores. PRECISION is
/// `None` when no digits follow the `.`.
fn parse_float_output_format(spec: &str) -> Option<(Option<usize>, char)> {
    let rest = spec.strip_prefix("%.")?;
    let digits: String = rest.chars().take_while(char::is_ascii_digit).collect();
    let conv_rest = &rest[digits.len()..];
    let mut it = conv_rest.chars();
    let conv = it.next()?;
    if !matches!(conv, 'e' | 'f' | 'g') || it.next().is_some() {
        return None;
    }
    if digits.is_empty() {
        return Some((None, conv));
    }
    // `DBL_DIG < width` loses on the first digit past 15.
    let prec: usize = digits.parse().ok().filter(|&p| p <= 15)?;
    if prec == 0 && conv != 'f' {
        return None;
    }
    Some((Some(prec), conv))
}

/// Print a finite float the way Emacs does: the shortest round-tripping form,
/// choosing exponential notation when the decimal exponent is ≤ -5, or ≥ 15 and
/// the exponential string is shorter (so `1e15` => `1e+15` but
/// `1234567890123456.0` stays decimal). Integer-valued floats keep a `.0`.
pub fn format_float(f: f64) -> String {
    // Emacs prints a float as the shortest string that reads back as the same
    // float (`float_to_string` → gnulib `dtoastr`), formatted like C's `%g`: it
    // tries precision 15, 16, then 17 and takes the first that round-trips. That
    // is why `(float most-positive-fixnum)` prints as `2.305843009213694e+18`
    // rather than `2305843009213694000.0` — %g goes exponential once the decimal
    // exponent reaches the precision.
    // gnulib's `ftoastr` starts at precision 1 for a subnormal (where a single
    // significant digit already round-trips: 5e-324) and at DBL_DIG = 15
    // otherwise (so 1e10 prints as 10000000000.0, not 1e+10).
    let start = if f != 0.0 && f.abs() < f64::MIN_POSITIVE {
        1
    } else {
        15
    };
    for prec in start..=17 {
        let s = format_g(f, prec);
        if s.parse::<f64>() == Ok(f) {
            return ensure_float_syntax(s);
        }
    }
    ensure_float_syntax(format_g(f, 17))
}

/// C's `%g` with the given precision: fixed notation while the decimal exponent
/// is in `-4..PREC`, exponential outside it, trailing zeros trimmed either way.
fn format_g(x: f64, prec: usize) -> String {
    let prec = prec.max(1);
    let e_form = format!("{:.*e}", prec - 1, x);
    let (mantissa, exp_str) = e_form.rsplit_once('e').unwrap_or((e_form.as_str(), "0"));
    let exp: i32 = exp_str.parse().unwrap_or(0);
    if exp < -4 || exp >= prec as i32 {
        let sign = if exp < 0 { '-' } else { '+' };
        // C pads the exponent to at least two digits: `1e-10`, `1e+300`.
        format!("{}e{}{:02}", trim_zeros(mantissa), sign, exp.abs())
    } else {
        let decimals = (prec as i32 - 1 - exp).max(0) as usize;
        trim_zeros(&format!("{x:.decimals$}"))
    }
}

/// Drop a fraction's trailing zeros (and a bare trailing point), as `%g` does.
fn trim_zeros(s: &str) -> String {
    if !s.contains('.') {
        return s.to_string();
    }
    let t = s.trim_end_matches('0');
    t.strip_suffix('.').unwrap_or(t).to_string()
}

/// A printed float must read back as a float: Emacs appends `.0` when neither a
/// decimal point nor an exponent is present (`100` → `100.0`).
fn ensure_float_syntax(s: String) -> String {
    if s.contains('.') || s.contains('e') || s.contains("INF") || s.contains("NaN") {
        s
    } else {
        format!("{s}.0")
    }
}

/// True when V is elisp `nil`.
///
/// `nil` has two spellings on the VM. A literal `nil` compiles to fusevm
/// `Undef`, but every op that answers a boolean — `Op::NumLt` and the rest of
/// the comparisons the compiler lowers `<`/`=`/`>` to — answers
/// `Value::Bool(false)`. Both are elisp's one `nil`, so every place that accepts
/// `nil` has to accept both spellings: `(length (= 5 42))` is `0` in Emacs, and
/// treating only `Undef` as the empty list made it `(wrong-type-argument
/// sequencep nil)` — an error naming the very value it refused to recognise.
pub fn el_nil(v: &Value) -> bool {
    matches!(v, Value::Undef | Value::Bool(false))
}

/// elisp truthiness: only `nil` is false.
pub fn el_truthy(v: &Value) -> bool {
    !el_nil(v)
}

/// Render a symbol name the way `prin1` does: with `\` escapes so it reads back
/// as the same symbol. The empty symbol prints as `##`.
fn print_symbol_readable(name: &str) -> String {
    if name.is_empty() {
        return "##".to_string();
    }
    // A name that would read as a number, or that starts with `?`, needs a
    // leading escape so it reads back as a symbol rather than a number or a
    // character literal.
    //
    // A leading `.` needs one only when the WHOLE name is dots: `.` is the
    // dotted-pair separator and `..` is reserved, but `.a` reads back as
    // itself — which matters because `let-alist` binds exactly those names, and
    // `(let-alist ALIST '.a)` printed the escaped form.
    let numeric = crate::reader::token_is_number(name);
    let all_dots = name.chars().all(|c| c == '.');
    let mut out = String::new();
    for (i, c) in name.chars().enumerate() {
        let needs_escape = matches!(
            c,
            '"' | '\\' | '\'' | ';' | '#' | '(' | ')' | ',' | '`' | '[' | ']'
        ) || (c as u32) <= 0x20
            || (i == 0 && (numeric || c == '?' || (c == '.' && all_dots)));
        if needs_escape {
            out.push('\\');
        }
        out.push(c);
    }
    out
}

// ── thread-local host ────────────────────────────────────────────────────────

thread_local! {
    static HOST: RefCell<ElispHost> = RefCell::new(ElispHost::new());
    static PRELUDE_LOADED: Cell<bool> = const { Cell::new(false) };
    /// On only while the prelude source is being lowered. Emacs's preloaded Lisp
    /// is byte-compiled, and the byte compiler turns a call to one of ~80
    /// primitives into an opcode that never consults the symbol's function cell;
    /// this flag is what tells the compiler it is lowering that same layer.
    static PRELUDE_COMPILING: Cell<bool> = const { Cell::new(false) };
    /// DAP debug execution: when on, the compiler emits `DBG_LINE` statement
    /// markers and `run_chunk` skips the tracing JIT so every marker fires
    /// through the interpreter. Off = zero overhead (no markers emitted at all).
    static DEBUG_MODE: Cell<bool> = const { Cell::new(false) };
    /// The host exactly as the prelude left it, kept so a later `reset_host` +
    /// `load_prelude` on this thread can restore that state by copy instead of
    /// rebuilding it. See [`restore_prelude_snapshot`].
    static PRELUDE_SNAPSHOT: RefCell<Option<ElispHost>> = const { RefCell::new(None) };
    /// Off disables the snapshot entirely, so `load_prelude` rebuilds from
    /// source. The equivalence test flips this to produce a cold reference to
    /// compare a restored host against.
    static PRELUDE_SNAPSHOT_ON: Cell<bool> = const { Cell::new(true) };
}

/// Enable/disable the post-prelude snapshot (default on). Turning it off also
/// drops any snapshot already held, so the next `load_prelude` rebuilds.
pub fn set_prelude_snapshot_enabled(on: bool) {
    PRELUDE_SNAPSHOT_ON.with(|c| c.set(on));
    if !on {
        PRELUDE_SNAPSHOT.with(|s| *s.borrow_mut() = None);
    }
}

/// Copy the post-prelude host back over the live host, skipping the rebuild.
///
/// Loading the prelude means reading, macro-expanding, lowering and running
/// ~every preloaded-Lisp form; measured at 7-8s per call in a debug build,
/// which is what made a test that evaluates five expressions cost 40s. The
/// state that work produces is just the `ElispHost` value, so it is taken once
/// per thread and restored by clone thereafter.
///
/// The copy is sound because nothing in the arena is written through a shared
/// handle: `Obj::Str` is replaced wholesale by
/// [`ElispHost::set_string_text`] (a fresh `Arc`, never `Arc::make_mut`), and
/// no `Rc`/`Arc` in `src/` is ever `get_mut`/`make_mut`'d — so two hosts may
/// share a payload allocation and neither can observe the other's writes.
///
/// Returns whether a snapshot was available.
pub fn restore_prelude_snapshot() -> bool {
    if !PRELUDE_SNAPSHOT_ON.with(|c| c.get()) {
        return false;
    }
    let Some(snap) = PRELUDE_SNAPSHOT.with(|s| s.borrow().clone()) else {
        return false;
    };
    HOST.with(|h| *h.borrow_mut() = snap);
    PRELUDE_LOADED.with(|c| c.set(true));
    true
}

/// Record the live host as the post-prelude snapshot. Called once per thread,
/// right after the prelude finishes loading on a cold path.
///
/// The copy is taken EAGERLY, on the first load, rather than being deferred
/// until a reload proves it will be read. Deferring was measured and is the
/// worse trade: a process that loads the prelude exactly once (`elisp FILE`,
/// `elisp -e`) saves ~0.020s of CPU — inside the 0.030s A/A band of the same
/// binary against itself, so not a number worth claiming — while libtest gives
/// every test its own thread, so deferring costs each of them a SECOND full
/// prelude rebuild. Across 196 tests that is ~94s of CPU to buy back a
/// difference that does not clear its own noise floor.
pub fn save_prelude_snapshot() {
    if !PRELUDE_SNAPSHOT_ON.with(|c| c.get()) {
        return;
    }
    let copy = HOST.with(|h| h.borrow().clone());
    PRELUDE_SNAPSHOT.with(|s| *s.borrow_mut() = Some(copy));
}

/// Enable/disable DAP debug execution (statement markers + JIT-off). Set by the
/// `--dap` server around the program compile+run; a single `Cell` load per
/// `run_chunk` when off.
pub fn set_debug_mode(on: bool) {
    DEBUG_MODE.with(|d| d.set(on));
}
/// Is DAP debug execution active? Read by the compiler (marker emission) and
/// `run_chunk` (JIT gating).
pub fn debug_mode() -> bool {
    DEBUG_MODE.with(|d| d.get())
}

pub fn with_host<R>(f: impl FnOnce(&mut ElispHost) -> R) -> R {
    HOST.with(|h| f(&mut h.borrow_mut()))
}
pub fn reset_host() {
    HOST.with(|h| *h.borrow_mut() = ElispHost::new());
    PRELUDE_LOADED.with(|c| c.set(false));
    PRELUDE_COMPILING.with(|c| c.set(false));
    // The pooled VMs hold chunks whose constants are arena handles into the host
    // just replaced; keeping them would resolve a stale handle in the new arena.
    clear_vm_pool();
    // Cached regexps were translated against the old host's syntax table.
    crate::builtins::clear_regexp_cache();
}
pub fn prelude_loaded() -> bool {
    PRELUDE_LOADED.with(|c| c.get())
}
pub fn set_prelude_loaded(b: bool) {
    PRELUDE_LOADED.with(|c| c.set(b));
}
pub fn prelude_compiling() -> bool {
    PRELUDE_COMPILING.with(|c| c.get())
}
pub fn set_prelude_compiling(b: bool) {
    PRELUDE_COMPILING.with(|c| c.set(b));
}

/// `(kill-emacs &optional ARG RESTART)` as batch Emacs runs it (emacs.c
/// `Fkill_emacs`): run `kill-emacs-hook` with each function's error reported on
/// stderr and skipped (`safe_run_hooks`), then exit with ARG when it is an
/// integer (the OS keeps its low 8 bits) and 0 otherwise. Nothing unwinds:
/// `unwind-protect` cleanups and `condition-case` handlers do not run. Inside
/// [`crate::embed::run_program`] the run ends instead of the process.
fn kill_emacs(args: &[Value]) -> Result<Value, String> {
    for f in hook_functions("kill-emacs-hook")? {
        if let Err(e) = call_function(&f, &[]) {
            let report = with_host(|h| {
                let obj = h
                    .take_pending_error(&e)
                    .unwrap_or_else(|| h.make_error_object(&e));
                let (f, obj) = (h.print(&f, true), h.print(&obj, true));
                format!("Error in kill-emacs-hook ({f}): {obj}")
            });
            eprintln!("{report}");
        }
    }
    let code = match args.first() {
        Some(Value::Int(n)) => (*n & 0xff) as i32,
        _ => 0,
    };
    if with_host(|h| h.capture.is_some()) {
        std::panic::resume_unwind(Box::new(crate::embed::ExitNow(code)));
    }
    use std::io::Write;
    let _ = std::io::stdout().flush();
    std::process::exit(code);
}

/// The functions a hook variable runs (eval.c `run_hook_with_args`): none when
/// it is void or nil, the value itself when it is a single function, else the
/// list's elements (`t`, the "run the global value too" marker, is skipped).
fn hook_functions(hook: &str) -> Result<Vec<Value>, String> {
    let (boundp, symbol_value, functionp, sym) = with_host(|h| {
        (
            h.intern("boundp"),
            h.intern("symbol-value"),
            h.intern("functionp"),
            h.intern(hook),
        )
    });
    if el_nil(&call_function(&boundp, std::slice::from_ref(&sym))?) {
        return Ok(Vec::new());
    }
    let value = call_function(&symbol_value, &[sym])?;
    if el_nil(&value) {
        return Ok(Vec::new());
    }
    if el_truthy(&call_function(&functionp, std::slice::from_ref(&value))?) {
        return Ok(vec![value]);
    }
    let fns = with_host(|h| h.list_vec(&value)).unwrap_or_default();
    Ok(fns
        .into_iter()
        .filter(|f| !matches!(f, Value::Bool(true)))
        .collect())
}

/// Call a function designator with already-evaluated args. The single
/// re-entrant entry point: it never holds the host borrow across a callee, so a
/// closure body (run on a nested fusevm VM) can re-borrow the host freely.
/// `(wrong-number-of-arguments FUNCTION NARGS)` for the re-entrant intrinsics.
///
/// They are dispatched by NAME at the top of [`call_function`], above the
/// `Resolved::Subr` arity gate that every other subr is checked by, so each has
/// to raise its own. They used to do it by building a message string, which the
/// reader turned back into data with the designator collapsed to a bare symbol
/// — and, for the `ok_or` sites, with no argument count at all:
///
/// ```text
///   (funcall #'mapcar)          emacs (wrong-number-of-arguments #<subr mapcar> 0)
///                               was   (wrong-number-of-arguments mapcar 0)
///   (funcall #'macroexpand-1)   emacs (wrong-number-of-arguments (1 . 2) 0)
///                               was   (wrong-number-of-arguments macroexpand-1)
/// ```
///
/// `signal_wrong_nargs` carries the designator as an object, so it reports the
/// symbol for `(mapcar)` and the subr for `(funcall #'mapcar)` exactly as Emacs
/// does, and applies the byte-compiled arity template where one is due.
/// Whether a head with no function cell is genuinely void: the symbols
/// `call_function` answers by NAME (its `--catch--` family, `intercept-proceed`,
/// `__rust-compile`) and the `rust { }` FFI exports have no cell yet are callable.
fn is_void_function_head(h: &ElispHost, head: &Value) -> bool {
    if h.special_form_object(head).is_some() {
        return false;
    }
    match h.sym_name(head).as_deref() {
        Some(
            "--catch--" | "--unwind--" | "--condition-case--" | "intercept-proceed"
            | "__rust-compile",
        ) => false,
        Some(name) => !fusevm::ffi::is_registered(name),
        None => true,
    }
}

fn intrinsic_wrong_nargs(f: &Value, argc: usize) -> String {
    with_host(|h| h.signal_wrong_nargs(f, argc))
}

/// The file-name arguments a Rust file subr receives already expanded.
///
/// Each of these C functions (fileio.c, dired.c) starts with
/// `Fexpand_file_name (FILENAME, Qnil)`, so a relative name resolves against
/// `default-directory` and every error reports the absolute name:
/// `(insert-file-contents "x")` signals `(file-missing "Opening input file"
/// "No such file or directory" "<default-directory>x")`. `expand-file-name` is
/// prelude Lisp, which a subr cannot call from inside the host borrow, so the
/// expansion happens here, on the way in. `file-attributes` answers nil for a
/// name that cannot be expanded, so a non-string reaches it unexpanded.
const FILE_NAME_ARGS: &[(&str, &[usize])] = &[
    ("insert-file-contents", &[0]),
    ("write-region", &[2]),
    ("delete-file-internal", &[0]),
    ("delete-directory-internal", &[0]),
    ("make-directory-internal", &[0]),
    ("rename-file", &[0, 1]),
    ("copy-file", &[0, 1]),
    ("--directory-files--", &[0]),
    ("file-exists-p", &[0]),
    ("file-directory-p", &[0]),
    ("file-regular-p", &[0]),
    ("file-readable-p", &[0]),
    ("file-writable-p", &[0]),
    ("file-executable-p", &[0]),
    ("file-symlink-p", &[0]),
    ("file-attributes", &[0]),
    ("file-modes", &[0]),
    ("set-file-modes", &[0]),
    ("file-newer-than-file-p", &[0, 1]),
    ("file-accessible-directory-p", &[0]),
    ("make-symbolic-link", &[1]),
    ("add-name-to-file", &[0, 1]),
];

/// ARGS with the [`FILE_NAME_ARGS`] positions expanded when F resolves to one
/// of those subrs; None otherwise (including when the user redefined it). A
/// non-string is left alone for the subr's own `stringp` check.
fn expand_file_name_args(f: &Value, args: &[Value]) -> Result<Option<Vec<Value>>, String> {
    // This runs on every call, so the name is compared in place (no clone),
    // and the function cell is resolved only for one of the listed names.
    let positions = with_host(|h| {
        let name = match h.obj(f) {
            Some(Obj::Symbol(s)) => s.name.as_str(),
            Some(Obj::Subr { name, .. }) => name.as_str(),
            _ => return None,
        };
        let (listed, positions) = FILE_NAME_ARGS.iter().find(|(n, _)| *n == name)?;
        match h.resolve_function(f) {
            Ok(Resolved::Subr { name, .. }) if name == *listed => Some(*positions),
            _ => None,
        }
    });
    let Some(positions) = positions else {
        return Ok(None);
    };
    let expand = with_host(|h| h.intern("expand-file-name"));
    let mut out = args.to_vec();
    for &i in positions {
        if out.get(i).is_some_and(|v| with_host(|h| h.is_string(v))) {
            out[i] = call_function(&expand, &out[i..=i])?;
        }
    }
    Ok(Some(out))
}

pub fn call_function(f: &Value, args: &[Value]) -> Result<Value, String> {
    let expanded_args;
    let args = match expand_file_name_args(f, args)? {
        Some(v) => {
            expanded_args = v;
            &expanded_args[..]
        }
        None => args,
    };
    // A special form is fbound but not callable. Emacs's `funcall` sees a subr
    // with `max_args == UNEVALLED` and signals `(invalid-function #<subr if>)`
    // before looking at the arguments at all, so `(funcall 'if 1 2)` and
    // `(apply 'quote '(1))` both land here rather than reporting the form as
    // undefined.
    if let Some(subr) = with_host(|h| h.special_form_object(f)) {
        return Err(with_host(|h| h.signal_invalid_function(&subr)));
    }
    // Higher-order primitives are intercepted here so they don't run inside a
    // host borrow (which would deadlock the nested call).
    //
    // The designator may be the *subr object* rather than the symbol — that is
    // what `(funcall (symbol-function 'mapcar) …)` passes, and what any code
    // that went through `indirect-function` first passes — so the name is read
    // from either. A subr that is not in the match below falls through to the
    // ordinary path exactly as before.
    if let Some(name) = with_host(|h| {
        h.sym_name(f).or_else(|| match h.obj(f) {
            Some(Obj::Subr { name, .. }) => Some(name.clone()),
            _ => None,
        })
    }) {
        match name.as_str() {
            "kill-emacs" => return kill_emacs(args),
            "funcall" => {
                // `(funcall)` with no function designator: Emacs signals
                // `(wrong-number-of-arguments funcall 0)`, not a panic.
                if args.is_empty() {
                    return Err(intrinsic_wrong_nargs(f, 0));
                }
                let f = with_host(|h| h.function_designator(&args[0]));
                return call_function(&f, &args[1..]);
            }
            "apply" => {
                if args.is_empty() {
                    return Err(intrinsic_wrong_nargs(f, 0));
                }
                // apply spreads its LAST argument, which must be a list; with a
                // single argument that last IS `args[0]` (so `(apply '+)` fails
                // with `(wrong-type-argument listp +)`, matching Emacs).
                let spread = args.last().unwrap();
                let tail = with_host(|h| h.list_vec(spread)).ok_or_else(|| {
                    // Fapply sizes SPREAD with `list_length`, whose
                    // CHECK_LIST_END names the loop variable: the improper
                    // TAIL of a dotted list -- (apply #'+ '(1 . 2)) =>
                    // (wrong-type-argument listp 2) -- or SPREAD itself when
                    // it is not a cons at all.
                    with_host(|h| {
                        let mut t = spread.clone();
                        while let Some(Obj::Cons(_, cdr)) = h.obj(&t) {
                            t = cdr.clone();
                        }
                        format!("wrong-type-argument: listp {}", h.print(&t, true))
                    })
                })?;
                let mut a: Vec<Value> = if args.len() >= 2 {
                    args[1..args.len() - 1].to_vec()
                } else {
                    Vec::new()
                };
                a.extend(tail);
                let f = with_host(|h| h.function_designator(&args[0]));
                return call_function(&f, &a);
            }
            "mapcar" => {
                if args.len() < 2 {
                    return Err(intrinsic_wrong_nargs(f, args.len()));
                }
                // An improper list names its tail; a non-sequence names itself.
                let seq = with_host(|h| h.seq_vec_checked(&args[1]))?;
                let f = with_host(|h| h.function_designator(&args[0]));
                let mut out = Vec::with_capacity(seq.len());
                for e in seq {
                    out.push(call_function(&f, &[e])?);
                }
                return Ok(with_host(|h| h.list_from(out)));
            }
            "assoc" => {
                // fns.c `Fassoc`. TESTFN is called back into elisp, so the walk
                // cannot live inside a subr body's host borrow — but the walk
                // itself is `FOR_EACH_TAIL` exactly as `assq`/`member` use it,
                // driven here one cons at a time.
                if args.len() < 2 || args.len() > 3 {
                    return Err(intrinsic_wrong_nargs(f, args.len()));
                }
                let key = args[0].clone();
                let alist = args[1].clone();
                let testfn = args.get(2).cloned().unwrap_or(Value::Undef);
                // `if (eq_comparable_value (key) && NILP (testfn)) return Fassq`.
                if !el_truthy(&testfn) && with_host(|h| crate::builtins::eq_comparable(h, &key)) {
                    return with_host(|h| crate::builtins::assq(h, &[key, alist]));
                }
                let mut w = crate::builtins::TailWalk::new(&alist);
                while let Some((car, cdr)) = with_host(|h| w.cons(h)) {
                    // `if (!CONSP (car)) continue;`
                    if let Some((elt_key, _)) = with_host(|h| match h.obj(&car) {
                        Some(Obj::Cons(k, v)) => Some((k.clone(), v.clone())),
                        _ => None,
                    }) {
                        let hit = if el_truthy(&testfn) {
                            let tf = with_host(|h| h.function_designator(&testfn));
                            el_truthy(&call_function(&tf, &[elt_key, key.clone()])?)
                        } else {
                            with_host(|h| crate::builtins::equal_or_eq(h, &elt_key, &key))
                        };
                        if hit {
                            return Ok(car);
                        }
                    }
                    if w.step(cdr) {
                        return Err(with_host(|h| h.signal_circular_list(&w.tail)));
                    }
                }
                let tail = w.tail.clone();
                with_host(|h| crate::builtins::check_end(h, &tail, &alist))?;
                return Ok(Value::Undef);
            }
            "mapconcat" => {
                // fns.c `Fmapconcat`: `Flength` first (which is what signals on a
                // circular or non-sequence SEQUENCE), then `mapcar1`, then
                // `Fconcat` over the results interleaved with SEPARATOR. A nil or
                // empty SEPARATOR drops the interleave entirely rather than
                // concatenating empty strings, which is the same answer.
                if args.len() < 2 || args.len() > 3 {
                    return Err(intrinsic_wrong_nargs(f, args.len()));
                }
                let seq = with_host(|h| h.seq_vec_checked(&args[1]))?;
                let fun = with_host(|h| h.function_designator(&args[0]));
                let mut parts: Vec<Value> = Vec::with_capacity(2 * seq.len());
                let sep = args.get(2).cloned().unwrap_or(Value::Undef);
                let sep_empty = !el_truthy(&sep)
                    || with_host(|h| h.str_text(&sep).map(|s| s.is_empty()).unwrap_or(false));
                for (i, e) in seq.into_iter().enumerate() {
                    if i > 0 && !sep_empty {
                        parts.push(sep.clone());
                    }
                    parts.push(call_function(&fun, &[e])?);
                }
                return with_host(|h| crate::builtins::concat(h, &parts));
            }
            "mapc" => {
                if args.len() < 2 {
                    return Err(intrinsic_wrong_nargs(f, args.len()));
                }
                let seq = with_host(|h| h.seq_vec_checked(&args[1]))?;
                let f = with_host(|h| h.function_designator(&args[0]));
                for e in seq {
                    call_function(&f, &[e])?;
                }
                return Ok(args[1].clone());
            }
            "sort" => {
                // Stable sort of a list/vector. Supports the classic
                // (sort SEQ PRED), the Emacs-30 keyword form
                // (sort SEQ &key :lessp :key :reverse), and (sort SEQ) which
                // falls back to the default `value<` ordering. Re-enters elisp
                // for PRED/:key so it lives here, not as a plain subr.
                if args.is_empty() {
                    return Err(intrinsic_wrong_nargs(f, 0));
                }
                // fns.c `Fsort`: two arguments are the old `(sort SEQ PRED)` call
                // (in place, whatever PRED is); any other even count is
                // "Invalid argument list"; otherwise the rest are KEYWORD VALUE
                // pairs, and an unknown keyword is `(error "Invalid keyword
                // argument" KW)`. All of that is decided before SEQ is looked at.
                let mut pred: Option<Value> = None;
                let mut key: Option<Value> = None;
                let mut reverse = false;
                let mut in_place = false;
                if args.len() == 2 {
                    // A nil PRED takes the `value<` default.
                    if el_truthy(&args[1]) {
                        pred = Some(with_host(|h| h.function_designator(&args[1])));
                    }
                    in_place = true;
                } else if args.len() % 2 == 0 {
                    return Err("error: Invalid argument list".to_string());
                } else {
                    for pair in args[1..].chunks(2) {
                        let kw = with_host(|h| h.sym_name(&pair[0])).unwrap_or_default();
                        let val = &pair[1];
                        let truthy = el_truthy(val);
                        match kw.as_str() {
                            ":key" => key = truthy.then(|| val.clone()),
                            ":lessp" => {
                                pred = truthy.then(|| with_host(|h| h.function_designator(val)))
                            }
                            ":in-place" => in_place = truthy,
                            ":reverse" => reverse = truthy,
                            _ => {
                                let bad = pair[0].clone();
                                return Err(with_host(|h| {
                                    h.signal_error_arg("Invalid keyword argument", &bad)
                                }));
                            }
                        }
                    }
                }
                let (items, was_vec) = match with_host(|h| match h.obj(&args[0]) {
                    Some(Obj::Vector(v)) => Some((v.clone(), true)),
                    _ => h.list_vec(&args[0]).map(|l| (l, false)),
                }) {
                    Some(pair) => pair,
                    // A cons that is not a proper list: Emacs's list walk names the
                    // offending tail. Anything else is not a sortable container at
                    // all.
                    None if with_host(|h| matches!(h.obj(&args[0]), Some(Obj::Cons(..)))) => {
                        return Err(with_host(|h| h.seq_vec_checked(&args[0]))
                            .expect_err("a cons that is not a proper list must fail"))
                    }
                    None => {
                        return Err(format!(
                            "wrong-type-argument: list-or-vector-p {}",
                            with_host(|h| h.print(&args[0], true))
                        ))
                    }
                };
                let mut pairs: Vec<(Value, Value)> = Vec::with_capacity(items.len());
                for it in &items {
                    let k = match &key {
                        Some(kf) => call_function(kf, std::slice::from_ref(it))?,
                        None => it.clone(),
                    };
                    pairs.push((k, it.clone()));
                }
                // `:reverse` sorts the reversed input and reverses the result, so
                // elements that compare equal keep their original order.
                if reverse {
                    pairs.reverse();
                }
                merge_sort_by(&mut pairs, pred.as_ref())?;
                let mut sorted: Vec<Value> = pairs.into_iter().map(|(_, it)| it).collect();
                if reverse {
                    sorted.reverse();
                }
                // In-place forms write the sorted values back into the original
                // sequence and return it; otherwise build a fresh one.
                return Ok(with_host(|h| {
                    if !in_place {
                        return if was_vec {
                            h.alloc(Obj::Vector(sorted))
                        } else {
                            h.list_from(sorted)
                        };
                    }
                    if was_vec {
                        if let Value::Obj(id) = &args[0] {
                            if let Some(Obj::Vector(v)) = h.arena.get_mut(*id as usize) {
                                *v = sorted;
                                return args[0].clone();
                            }
                        }
                        h.alloc(Obj::Vector(sorted))
                    } else {
                        let mut cur = args[0].clone();
                        for val in sorted {
                            let next = match h.obj(&cur) {
                                Some(Obj::Cons(_, cdr)) => cdr.clone(),
                                _ => break,
                            };
                            if let Value::Obj(id) = cur {
                                if let Some(Obj::Cons(car, _)) = h.arena.get_mut(id as usize) {
                                    *car = val;
                                }
                            }
                            cur = next;
                        }
                        args[0].clone()
                    }
                }));
            }
            "maphash" => {
                if args.len() < 2 {
                    return Err(intrinsic_wrong_nargs(f, args.len()));
                }
                let entries = with_host(|h| match h.obj(&args[1]) {
                    Some(Obj::HashTable(t)) => Some(t.pairs().cloned().collect::<Vec<_>>()),
                    _ => None,
                })
                .ok_or("maphash: not a hash table")?;
                for (k, v) in entries {
                    call_function(&args[0], &[k, v])?;
                }
                return Ok(Value::Undef);
            }
            // A hash table whose test came from `define-hash-table-test` has
            // elisp for its test and hash functions, so a lookup on one has to
            // call elisp — which cannot happen inside the host borrow a subr
            // body runs in. The built-in tests take the ordinary path in one
            // borrow; only a user test re-enters.
            "gethash" | "puthash" | "remhash" => {
                let table_at = if name == "puthash" { 2 } else { 1 };
                let Some(table) = args.get(table_at) else {
                    return Err(intrinsic_wrong_nargs(f, args.len()));
                };
                if let Some(t) = crate::builtins::ht_user_test(table) {
                    return match name.as_str() {
                        "gethash" => crate::builtins::gethash_user(args, &t),
                        "puthash" => crate::builtins::puthash_user(args, &t),
                        _ => crate::builtins::remhash_user(args, &t),
                    };
                }
                return with_host(|h| match name.as_str() {
                    "gethash" => crate::builtins::gethash(h, args),
                    "puthash" => crate::builtins::puthash(h, args),
                    _ => crate::builtins::remhash(h, args),
                })
                .map(|v| with_host(|h| h.promote_string(v)));
            }
            // `make-hash-table` resolves a `define-hash-table-test` name by
            // reading the symbol's `hash-table-test` property, which is an
            // elisp plist — so the lookup happens here, outside the borrow, and
            // the resolved functions are handed to the table's constructor.
            "make-hash-table" => {
                // The argument-list checks run before any test lookup, in
                // `Fmake_hash_table's order (odd count, invalid keyword, then
                // the TEST value: it must be a symbol).
                let named = with_host(|h| -> Result<Option<(Value, String)>, String> {
                    let kw = crate::builtins::hash_table_keywords(h, args)?;
                    let Some(t) = kw.test else { return Ok(None) };
                    match h.sym_name(&t) {
                        Some(n) if !matches!(n.as_str(), "eq" | "eql" | "equal" | "nil") => {
                            Ok(Some((t, n)))
                        }
                        Some(_) => Ok(None),
                        None => Err(format!(
                            "wrong-type-argument: symbolp {}",
                            h.print(&t, true)
                        )),
                    }
                })?;
                let user = match named {
                    None => None,
                    Some((sym, _)) => {
                        let getf = with_host(|h| h.intern("get"));
                        let prop = with_host(|h| h.intern("hash-table-test"));
                        let spec = call_function(&getf, &[sym.clone(), prop])?;
                        match with_host(|h| h.list_vec(&spec)) {
                            Some(fns) if fns.len() >= 2 => {
                                Some((sym, fns[0].clone(), fns[1].clone()))
                            }
                            // `Fmake_hash_table` signals when the name was never
                            // declared: (error "Invalid hash table test" NAME).
                            _ => {
                                return Err(with_host(|h| {
                                    h.signal_error_with("Invalid hash table test", &sym)
                                }))
                            }
                        }
                    }
                };
                return with_host(|h| crate::builtins::make_hash_table_with(h, args, user));
            }
            // A function PRINTCHARFUN is called once per output character
            // (print.c `printchar`), which re-enters elisp, so that path runs
            // here; stdout, buffer and marker destinations fall through to
            // the subr. An arity the subr rejects also falls through.
            "princ" | "prin1" | "print" | "terpri" | "write-char" => {
                let (min, pcf) = if name == "terpri" { (0, 0) } else { (1, 1) };
                let ensure = name == "terpri" && args.get(1).is_some_and(el_truthy);
                if (min..=2).contains(&args.len()) && !ensure {
                    let dest = with_host(|h| crate::builtins::print_dest(h, args.get(pcf)))?;
                    if let crate::builtins::PrintDest::Function(pf) = dest {
                        if let Some(text) =
                            with_host(|h| crate::builtins::print_text(h, &name, args))?
                        {
                            let pf = with_host(|h| h.function_designator(&pf));
                            for c in text.chars() {
                                call_function(&pf, &[Value::Int(c as i64)])?;
                            }
                            return Ok(if name == "terpri" {
                                Value::Bool(true)
                            } else {
                                args[0].clone()
                            });
                        }
                    }
                }
            }
            "mapatoms" => {
                if args.is_empty() {
                    return Err(intrinsic_wrong_nargs(f, args.len()));
                }
                // The obarray defaults to the global one (the `obarray` variable).
                let ob = match args.get(1) {
                    Some(v) if !matches!(v, Value::Undef | Value::Bool(false)) => v.clone(),
                    _ => with_host(|h| {
                        let sym = h.find_symbol("obarray").unwrap_or(Value::Undef);
                        h.get_value(&sym).unwrap_or(Value::Undef)
                    }),
                };
                let syms = with_host(|h| h.obarray_symbols(&ob));
                for s in syms {
                    call_function(&args[0], &[s])?;
                }
                return Ok(Value::Undef);
            }
            // `load` reads a file's forms and evaluates them in the live host —
            // re-entrant (nested VM per form) and it dynamically rebinds
            // `load-file-name` &c, so it lives here, outside any host borrow.
            "load" => return intrinsic_load(f, args),
            // `eval` macroexpands, compiles, and runs a form — re-entrant, so it
            // lives here (outside any host borrow), like the other intrinsics.
            "eval" => {
                let form = args
                    .first()
                    .ok_or_else(|| intrinsic_wrong_nargs(f, args.len()))?;
                // `t` is a self-evaluating constant symbol (Emacs `eval_sub`:
                // its value slot holds itself).  It is represented as
                // `Value::Bool(true)`, which `compile_top` would lower to the
                // integer 1, so short-circuit it here to return `t` itself.
                if matches!(form, Value::Bool(true)) {
                    return Ok(form.clone());
                }
                // FORM is evaluated in the lexical environment given by LEXICAL —
                // NOT in the caller's. `(let ((x 5)) (eval 'x t))` signals
                // `void-variable x` in Emacs: `t` means "lexical binding, empty
                // environment". Running the chunk in the live scope chain instead
                // leaked every binding the caller happened to hold, and any closure
                // FORM created captured (and printed) them.
                //
                // A nil (or omitted) LEXICAL selects *dynamic* binding for FORM:
                // `let` binds value cells, and a `lambda` captures nothing, so
                // `(eval '(funcall (let ((x 1)) (lambda () x))) nil)` is
                // `void-variable x` — the binding is gone by the time it is called.
                let lexical = args.get(1).is_some_and(el_truthy);
                let saved = with_host(|h| h.take_lex());
                let prev_mode = with_host(|h| std::mem::replace(&mut h.dynamic_binding, !lexical));
                let out = eval_in_place(form);
                with_host(|h| {
                    h.restore_lex(saved);
                    h.dynamic_binding = prev_mode;
                });
                return out;
            }
            // The macro-expansion functions run macro expanders (re-entrant).
            "macroexpand-1" => {
                let form = args
                    .first()
                    .ok_or_else(|| intrinsic_wrong_nargs(f, args.len()))?;
                let env = args.get(1).cloned().unwrap_or(Value::Undef);
                match env_expand(form, &env)? {
                    EnvHit::Expanded(e) => return Ok(e),
                    EnvHit::Shadowed => return Ok(form.clone()),
                    EnvHit::Miss => {}
                }
                // A user macro (if any) wins; otherwise fall back to the intrinsic
                // `when`/`unless` expansions the compiler lowers as special forms.
                if let Some(e) = macroexpand_1(form)? {
                    return Ok(e);
                }
                return Ok(expand_intrinsic_macro(form)?.unwrap_or_else(|| form.clone()));
            }
            "macroexpand" => {
                // Expand the head to a fixpoint; don't recurse into sub-forms.
                let mut f = args
                    .first()
                    .ok_or_else(|| intrinsic_wrong_nargs(f, args.len()))?
                    .clone();
                let env = args.get(1).cloned().unwrap_or(Value::Undef);
                loop {
                    match env_expand(&f, &env)? {
                        EnvHit::Expanded(e) => {
                            // eval.c `Fmacroexpand': an expander that answers its
                            // own form ends the loop.
                            let same = with_host(|h| h.values_eq(&e, &f));
                            f = e;
                            if same {
                                break;
                            }
                            continue;
                        }
                        EnvHit::Shadowed => break,
                        EnvHit::Miss => {}
                    }
                    if let Some(e) = macroexpand_1(&f)? {
                        f = e;
                        continue;
                    }
                    if let Some(e) = expand_intrinsic_macro(&f)? {
                        f = e;
                        continue;
                    }
                    break;
                }
                return Ok(f);
            }
            "macroexpand-all" => {
                return macroexpand_all_builtin(
                    args.first()
                        .ok_or_else(|| intrinsic_wrong_nargs(f, args.len()))?,
                    args.get(1).unwrap_or(&Value::Undef),
                )
            }
            // (`replace-regexp-in-string` needs no interception: it is a Lisp
            // function here as in Emacs — the prelude port funcalls a function
            // REP itself.)
            // Nonlocal-exit intrinsics (the compiler rewrites catch/unwind-protect/
            // condition-case into these, passing lambda thunks).
            "--catch--" => return intrinsic_catch(args),
            "--unwind--" => return intrinsic_unwind(args),
            "--condition-case--" => return intrinsic_condition_case(args),
            // AOP pattern-intercept proceed protocol (elisprs extension). Runs the
            // original command from inside an `around` advice — re-entrant, so it
            // lives here (outside any host borrow), like the other intrinsics.
            "intercept-proceed" => return crate::intercepts::intrinsic_intercept_proceed(),
            // Inline Rust FFI: the `rust { ... }` desugar (src/rust_ffi.rs) emits
            // `(__rust-compile B64 LINE)`; compile the block to a cached cdylib
            // and register its `pub extern "C"` exports (which become callable by
            // bareword). Shells out to rustc, so it must run outside any host
            // borrow — hence here with the other intrinsics. Returns nil.
            "__rust-compile" => {
                let b64 = with_host(|h| {
                    args.first()
                        .and_then(|v| h.str_text(v).map(str::to_string))
                        .unwrap_or_default()
                });
                return fusevm::ffi::compile_and_register(&b64).map(|_| Value::Undef);
            }
            _ => {}
        }
    }

    // ── zshrs-original AOP pattern-intercept layer (elisprs extension) ──
    // Distinct from elisp nadvice (`advice-add`, per-symbol): this fires on a
    // GLOB/pattern match across many symbol names at once (`"forward-*"`, `"_*"`,
    // `"all"`) with before/after/around advice + a timing/proceed protocol. Only a
    // named (symbol) callee participates — an anonymous closure has no name to
    // match. The zero-intercept common case is a single cheap bool load; the
    // `intercept_active` guard makes advice bodies (and the proceeded original)
    // dispatch normally without re-triggering (recursion guard). See
    // [`crate::intercepts`].
    if with_host(|h| !h.intercepts.is_empty() && !h.intercept_active) {
        if let Some(name) = with_host(|h| h.sym_name(f)) {
            if let Some(result) = crate::intercepts::run_intercepts(f, &name, args)? {
                return Ok(result);
            }
        }
    }

    // The callee as written by the caller — a symbol, or the function object when
    // applied. It goes into the `wrong-number-of-arguments` data, so keep it
    // before the match binds `f` to the resolved fn pointer.
    let callee = f.clone();
    let resolved = match with_host(|h| h.resolve_function(f)) {
        Ok(r) => r,
        Err(e) => {
            // eval.c `funcall_general`: a list whose car is `lambda` is called by
            // `funcall_lambda` with an empty lexical environment, i.e. under
            // dynamic binding — `(funcall '(lambda (x) x) 4)` is 4.
            if let Some(fun) = with_host(|h| h.indirect_lambda_list(f)) {
                return call_lambda_list(&fun, args);
            }
            // A symbol whose function cell is an `autoload` object: load its
            // file (`autoload-do-load` signals if the file does not define the
            // function) and call again, as `funcall_general` does.
            if matches!(f, Value::Obj(_)) {
                if let Some(fundef) = with_host(|h| h.indirect_autoload(f)) {
                    let loader = with_host(|h| h.intern("autoload-do-load"));
                    call_function(&loader, &[fundef, f.clone()])?;
                    return call_function(f, args);
                }
            }
            // Inline Rust FFI fallback: a `rust { ... }` exported function is
            // callable by bareword when no elisp function shadows it. A user
            // `defun` still wins — it resolves above; only a `void-function` miss
            // (no function cell) reaches here, and the cheap membership check
            // keeps this off the hot path. elisp Values ARE fusevm Values, so the
            // args (ints/floats/strings) marshal straight through `try_call`.
            if let Some(r) = try_rust_ffi(f, args) {
                return r;
            }
            // eval.c `funcall_general`: a cell that is not callable is
            // `(invalid-function ORIGINAL-FUN)`, naming the designator as the
            // caller passed it. A compiler intrinsic (`when`, `defun`, `lambda`)
            // has no real function cell here, only its `(macro . FN)` stand-in,
            // and Emacs refuses that macro the same way.
            let intrinsic_macro = with_host(|h| {
                h.function_cell(f).is_none() && h.introspect_function_cell(f).is_some()
            });
            if intrinsic_macro || e.starts_with("invalid-function: ") {
                return Err(with_host(|h| h.signal_invalid_function(&callee)));
            }
            return Err(e);
        }
    };
    match resolved {
        Resolved::Subr { f, min, max, name } => {
            if args.len() < min || max.is_some_and(|m| args.len() > m) {
                let _ = &name;
                // Emacs's error data is (FUNC N): the callee as the caller wrote
                // it (a symbol, or the subr object when applied) and the argument
                // count it was given.
                return Err(with_host(|h| h.signal_wrong_nargs(&callee, args.len())));
            }
            // An alias of an intercepted primitive — `(defalias 'my-map
            // 'mapcar)`, or cl-lib's `(defalias 'cl-multiple-value-call
            // #'apply)` — resolves here to that primitive's placeholder body,
            // because the intercept above matched on the ALIAS's name. Arity
            // was checked against the alias, which is what eval_sub names;
            // dispatch the call itself through the primitive's own name.
            if std::ptr::fn_addr_eq(f, crate::builtins::intercepted_subr as SubrFn) {
                let target = with_host(|h| h.intern(&name));
                return call_function(&target, args);
            }
            // The change hooks, field constraints and property inheritance the
            // C runs Lisp for, outside the host borrow (see `crate::modhooks`).
            if let Some(r) = crate::modhooks::around(&name, f, args) {
                return r.map(|v| with_host(|h| h.promote_string(v)));
            }
            // Promote a string a subr built as a bare `Value::Str` transient
            // into a string CELL before it can be stored anywhere: an elisp
            // value that reaches a variable, a cons, or a hash table has to be
            // the mutable object, or `aset` on it would signal `arrayp`.
            with_host(|h| f(h, args).map(|v| h.promote_string(v)))
        }
        Resolved::Closure {
            params,
            body,
            is_macro,
            env,
            dynamic,
            object,
        } => {
            // eval.c `funcall_general`: a `(macro . FN)` cell is not callable,
            // and the signal names the designator the caller passed.
            if is_macro {
                return Err(with_host(|h| h.signal_invalid_function(&callee)));
            }
            // `funcall_lambda`'s signal names the resolved closure, not the
            // designator: `xsignal2 (Qwrong_number_of_arguments, … fun, …)`.
            // Passing `callee` here made `(f1 1 2)` report `f1` where Emacs
            // reports `#[(a) (a) (t)]`, and `defalias`ing a second name onto the
            // same function reported that second name.
            let max = params.required.len() + params.optional.len();
            if args.len() < params.required.len() || (params.rest.is_none() && args.len() > max) {
                return Err(with_host(|h| {
                    h.signal_closure_wrong_nargs(&callee, &object, args.len())
                }));
            }
            // The one place a user function body is entered: every compiled
            // `CALL`, `funcall` and `apply` funnels through here, so the DAP
            // function-breakpoint check is hooked once rather than per caller.
            crate::dap::enter_function(&callee);
            run_closure(&params, &body, env, dynamic, args)
        }
    }
}

/// eval.c `funcall_lambda` for a `(lambda ARGLIST . BODY)` list: `eval` of
/// `(function FUN)` under dynamic binding builds the closure Emacs interprets
/// the list as. The list itself is what an arity error names, and a list whose
/// cdr is not a cons is `invalid-function`.
fn call_lambda_list(fun: &Value, args: &[Value]) -> Result<Value, String> {
    let (eval_sym, form, well_formed) = with_host(|h| {
        let well_formed = matches!(h.obj(fun), Some(Obj::Cons(_, rest)) if matches!(h.obj(rest), Some(Obj::Cons(..))));
        let fsym = h.intern("function");
        (
            h.intern("eval"),
            h.list_from(vec![fsym, fun.clone()]),
            well_formed,
        )
    });
    if !well_formed {
        return Err(with_host(|h| h.signal_invalid_function(fun)));
    }
    let closure = call_function(&eval_sym, &[form, Value::Undef])?;
    if let Ok(Resolved::Closure { params, .. }) = with_host(|h| h.resolve_function(&closure)) {
        let max = params.required.len() + params.optional.len();
        if args.len() < params.required.len() || (params.rest.is_none() && args.len() > max) {
            return Err(with_host(|h| h.signal_wrong_nargs(fun, args.len())));
        }
    }
    call_function(&closure, args)
}

/// The inline-Rust FFI fallback, kept OUT of [`call_function`]'s frame.
///
/// `call_function` is on the elisp recursion path — every nested elisp call
/// stacks one of its frames — and it is a large function already. Its locals are
/// stack slots whether or not the branch holding them runs, so an argument
/// vector declared inline here would widen every frame of a deep recursion for a
/// path that fires only on a `void-function` miss. `#[inline(never)]` keeps it a
/// call away.
#[inline(never)]
fn try_rust_ffi(f: &Value, args: &[Value]) -> Option<Result<Value, String>> {
    let name = with_host(|h| h.sym_name(f))?;
    if !fusevm::ffi::is_registered(&name) {
        return None;
    }
    // A string argument travels as an arena HANDLE, which means nothing to a
    // `pub extern "C" fn(*const c_char)`. Hand the marshaller a view of the text
    // instead; the callee copies it either way, so flattening loses no identity.
    let flat: Vec<Value> = with_host(|h| args.iter().map(|v| h.str_view(v)).collect());
    let r = fusevm::ffi::try_call(&name, &flat)?;
    Some(r.map(|v| with_host(|h| h.promote_string(v))))
}

/// Stable merge sort driven by an elisp less-than predicate. `pred` is called as
/// `(pred a b)`; a non-nil result means `a` precedes `b`. Equal elements keep
/// their input order (the merge takes from the left run on ties).
fn num_f(v: &Value) -> Option<f64> {
    match v {
        Value::Int(n) => Some(*n as f64),
        Value::Float(f) => Some(*f),
        _ => None,
    }
}

/// Default `value<` ordering used by `(sort SEQ)` with no predicate: numbers
/// compare numerically, strings and symbol names lexically.
fn value_lt(a: &Value, b: &Value) -> Result<bool, String> {
    if let (Some(x), Some(y)) = (num_f(a), num_f(b)) {
        return Ok(x < y);
    }
    if let (Some(x), Some(y)) = with_host(|h| {
        (
            h.str_text(a).map(str::to_string),
            h.str_text(b).map(str::to_string),
        )
    }) {
        return Ok(x < y);
    }
    match (with_host(|h| h.sym_name(a)), with_host(|h| h.sym_name(b))) {
        (Some(x), Some(y)) => Ok(x < y),
        // Everything else — lists, vectors, and every cross-type pair — is the
        // prelude's `value<`, which already carries Emacs 30's class rules and
        // its `(type-mismatch A B)` signal. Duplicating them here would be a
        // second implementation of the same order, and it was the reason a
        // default-predicate `sort` reported "value<: unsupported comparison"
        // where Emacs signals `(type-mismatch "010" t)`.
        _ => {
            let f = with_host(|h| h.intern("value<"));
            Ok(el_truthy(&call_function(&f, &[a.clone(), b.clone()])?))
        }
    }
}

/// Stable merge sort of `(key, item)` pairs by `key`. With `pred` it re-enters
/// elisp `(pred key_j key_i)`; without, it falls back to `value_lt`.
fn merge_sort_by(items: &mut Vec<(Value, Value)>, pred: Option<&Value>) -> Result<(), String> {
    let n = items.len();
    if n < 2 {
        return Ok(());
    }
    let lt = |x: &Value, y: &Value| -> Result<bool, String> {
        match pred {
            Some(p) => {
                let r = call_function(p, &[x.clone(), y.clone()])?;
                Ok(!matches!(r, Value::Undef | Value::Bool(false)))
            }
            None => value_lt(x, y),
        }
    };
    // Emacs 30 sorts with `tim_sort` (src/sort.c, the CPython listsort port),
    // and its COMPARISON ORDER is observable through a side-effecting or
    // throwing predicate: `count_run` first calls pred(a[1], a[0]) — so
    // (sort '(t 1.0 nil) #'string-to-number) dies on 1.0, not nil. For inputs
    // shorter than MAX_MINRUN (64) — every list differential fuzzing produces —
    // tim_sort is exactly count_run + binary insertion, reproduced verbatim
    // here. Longer inputs keep the stable merge sort below (same result;
    // Emacs's merge machinery would call the predicate in a different order).
    if n < 64 {
        // count_run: pred(a[1], a[0]) picks ascending (extend while NOT less)
        // vs strictly-descending (extend while less, then reverse — strictness
        // is what keeps the reversal stable).
        let mut run = 2;
        if lt(&items[1].0, &items[0].0)? {
            while run < n && lt(&items[run].0, &items[run - 1].0)? {
                run += 1;
            }
            items[..run].reverse();
        } else {
            while run < n && !lt(&items[run].0, &items[run - 1].0)? {
                run += 1;
            }
        }
        // binarysort: insert a[start] into the sorted prefix a[0..start],
        // probing pred(pivot, a[mid]) and landing AFTER equals (stable).
        for start in run..n {
            let (mut l, mut r) = (0usize, start);
            while l < r {
                let p = l + ((r - l) >> 1);
                if lt(&items[start].0, &items[p].0)? {
                    r = p;
                } else {
                    l = p + 1;
                }
            }
            items[l..=start].rotate_right(1);
        }
        return Ok(());
    }
    let mid = n / 2;
    let mut right = items.split_off(mid);
    merge_sort_by(items, pred)?;
    merge_sort_by(&mut right, pred)?;
    let left = std::mem::take(items);
    let (mut i, mut j) = (0, 0);
    items.reserve(left.len() + right.len());
    while i < left.len() && j < right.len() {
        // Take from the right only when right[j] strictly precedes left[i].
        let rhs_first = match pred {
            Some(p) => {
                let r = call_function(p, &[right[j].0.clone(), left[i].0.clone()])?;
                !matches!(r, Value::Undef | Value::Bool(false))
            }
            None => value_lt(&right[j].0, &left[i].0)?,
        };
        if rhs_first {
            items.push(right[j].clone());
            j += 1;
        } else {
            items.push(left[i].clone());
            i += 1;
        }
    }
    items.extend_from_slice(&left[i..]);
    items.extend_from_slice(&right[j..]);
    Ok(())
}

/// Open a lexical scope (child of the closure's captured `env`), bind `args` to
/// the params, run the body on a nested fusevm VM, then close the scope. Used by
/// both function application and macro expansion (where `args` are the
/// unevaluated argument forms). Holds no host borrow across the nested run.
/// Call a closure: open a scope over its captured environment, bind the
/// parameters, run the body, then unwind.
///
/// `dynamic` is the closure's binding mode ([`Obj::Closure::dynamic`]). It is
/// installed for the duration of the call, so a function made under
/// `lexical-binding` nil binds its parameters — and every `let` its body runs —
/// on the specstack, and any `lambda` that body creates is dynamic in turn. The
/// previous mode is restored on every exit path, including a signalled error.
fn run_closure(
    params: &Rc<Params>,
    body: &Rc<Chunk>,
    env: Lex,
    dynamic: bool,
    args: &[Value],
) -> Result<Value, String> {
    // One nested elisp call is several Rust frames deep — `run_closure`, the
    // nested `VM::run`, its dispatch loop, `ext_dispatch`, `call_function` —
    // and elisp recursion is bounded by `max-lisp-eval-depth` (default 1600),
    // not by the OS stack. On a thread with the platform default stack that
    // limit is unreachable: the process aborts on a hardware stack overflow
    // first, which is not a signal any `condition-case` can catch. The reader
    // already grows the stack on demand for exactly this reason
    // (`reader.rs`'s `read_form`); doing it here makes
    // `excessive-lisp-nesting` the thing that fires, on any thread, rather
    // than the stack guard page.
    //
    // `maybe_grow` is a stack-pointer comparison when there is headroom, so
    // the ordinary call pays a compare and a branch.
    stacker::maybe_grow(256 * 1024, 8 * 1024 * 1024, || {
        run_closure_inner(params, body, env, dynamic, args)
    })
}

fn run_closure_inner(
    params: &Rc<Params>,
    body: &Rc<Chunk>,
    env: Lex,
    dynamic: bool,
    args: &[Value],
) -> Result<Value, String> {
    with_host(|h| h.enter_eval_frame())?;
    let entry = with_host(|h| h.scope_depth());
    let prev_mode = with_host(|h| std::mem::replace(&mut h.dynamic_binding, dynamic));
    let setup = with_host(|h| {
        h.open_scope_in(env.clone());
        h.bind_params_into_scope(params, args)
    });
    if let Err(e) = setup {
        with_host(|h| {
            h.unwind_scopes_to(entry);
            h.dynamic_binding = prev_mode;
            h.leave_eval_frame();
        });
        return Err(e);
    }
    let result = run_body(body);
    // Unwind to the entry depth (not just one scope): a `throw`/error out of an
    // inner `let` inside the body leaks scopes that this restores.
    with_host(|h| {
        h.unwind_scopes_to(entry);
        h.dynamic_binding = prev_mode;
        h.leave_eval_frame();
    });
    result
}

/// What a macro ENVIRONMENT says about a form's head (macroexp.el
/// `macroexpand-1`): `(assq HEAD ENVIRONMENT)` found nothing, found an entry
/// whose cdr is nil (the name is shadowed as a non-macro, so expansion stops
/// there), or found an expander, which has been applied to the form's
/// arguments.
pub(crate) enum EnvHit {
    Miss,
    Shadowed,
    Expanded(Value),
}

/// Consult ENV for FORM's head, applying the expander when there is one.
pub(crate) fn env_expand(form: &Value, env: &Value) -> Result<EnvHit, String> {
    let entry = with_host(|h| {
        let Some(Obj::Cons(head, rest)) = h.obj(form) else {
            return None;
        };
        let (head, rest) = (head.clone(), rest.clone());
        let mut e = env.clone();
        while let Some(Obj::Cons(item, next)) = h.obj(&e) {
            if let Some(Obj::Cons(k, v)) = h.obj(item) {
                if h.values_eq(k, &head) {
                    return Some((v.clone(), rest));
                }
            }
            e = next.clone();
        }
        None
    });
    match entry {
        None => Ok(EnvHit::Miss),
        Some((expander, _)) if !el_truthy(&expander) => Ok(EnvHit::Shadowed),
        Some((expander, rest)) => {
            let args = with_host(|h| h.list_vec(&rest)).unwrap_or_default();
            let f = with_host(|h| h.function_designator(&expander));
            Ok(EnvHit::Expanded(call_function(&f, &args)?))
        }
    }
}

/// One step of macro expansion: if `form` is `(macro-name . arg-forms)`, run the
/// macro on the *unevaluated* arg forms and return the expansion. Else `None`.
pub fn macroexpand_1(form: &Value) -> Result<Option<Value>, String> {
    // eval.c `Fmacroexpand': a head whose definition is a MACRO autoload (TYPE `t'
    // or `macro') is loaded first, then expanded as the macro it defined.
    let pending = with_host(|h| {
        let head = h.list_vec(form)?.into_iter().next()?;
        let fundef = h.indirect_autoload(&head)?;
        let ty = h.list_vec(&fundef)?.get(4).cloned()?;
        el_truthy(&ty).then_some((head, fundef))
    });
    if let Some((head, fundef)) = pending {
        let loader = with_host(|h| h.intern("autoload-do-load"));
        let macro_only = with_host(|h| h.intern("macro"));
        call_function(&loader, &[fundef, head, macro_only])?;
    }
    let info = with_host(|h| {
        let elems = h.list_vec(form)?;
        if elems.is_empty() {
            return None;
        }
        match h.resolve_function(&elems[0]) {
            Ok(Resolved::Closure {
                params,
                body,
                is_macro: true,
                env,
                dynamic,
                object,
            }) => Some((params, body, env, dynamic, object, elems[1..].to_vec())),
            _ => None,
        }
    });
    match info {
        Some((params, body, env, dynamic, object, args)) => {
            // `funcall_lambda`'s arity check names the expander itself: an
            // uncaught `(m 1)` for `(defmacro m (a b) a)` is
            // `(wrong-number-of-arguments #[(a b) (a) (t)] 1)`.
            let max = params.required.len() + params.optional.len();
            if args.len() < params.required.len() || (params.rest.is_none() && args.len() > max) {
                return Err(with_host(|h| {
                    h.signal_macro_wrong_nargs(&object, &params, args.len())
                }));
            }
            Ok(Some(run_closure(&params, &body, env, dynamic, &args)?))
        }
        None => Ok(None),
    }
}

/// Faithful `subr.el` expansions for the two intrinsic macros elisprs lowers as
/// compiler special forms (`when`/`unless`). Because the compiler intercepts
/// them by name they have no closure for [`macroexpand_1`] to find, so the
/// `macroexpand`/`macroexpand-1`/`macroexpand-all` builtins consult this to
/// reproduce Emacs's macro output. Returns `None` for any other head, and for a
/// head the user has shadowed with a real macro (that closure wins in the
/// callers, which try [`macroexpand_1`] first).
///
/// Emacs 30.2 `subr.el`:
/// ```elisp
/// (defmacro when   (cond &rest body) (list 'if cond (cons 'progn body)))
/// (defmacro unless (cond &rest body) (cons 'if (cons cond (cons nil body))))
/// ```
pub fn expand_intrinsic_macro(form: &Value) -> Result<Option<Value>, String> {
    with_host(|h| {
        let Some(elems) = h.list_vec(form) else {
            return Ok(None);
        };
        if elems.is_empty() {
            return Ok(None);
        }
        let Some(name) = h.sym_name(&elems[0]) else {
            return Ok(None);
        };
        // Both lambda lists are `(cond &rest body)`, so a call with no COND
        // is rejected by the byte-compiled expander before it runs:
        // `(wrong-number-of-arguments (1 . 1) 0)`.
        if elems.len() == 1 && matches!(name.as_str(), "when" | "unless") {
            return Err(h.signal_intrinsic_macro_wrong_nargs());
        }
        let body = &elems[2.min(elems.len())..];
        let cond = elems.get(1).cloned().unwrap_or(Value::Undef);
        // An EMPTY body is a different expansion in both macros. subr.el:
        //
        //   (if body (list 'if cond (cons 'progn body))
        //     (macroexp-warn-and-return … (list 'progn cond nil) …))
        //
        // so `(macroexpand '(when x))` is `(progn x nil)`, not `(if x (progn))`,
        // and `(macroexpand '(unless x))` is `(progn x nil)`, not `(if x nil)`.
        // The value is the same either way — the point is that COND is still
        // evaluated and the form answers nil — but the expansion is observable
        // through `macroexpand`, and the warning is what tells a reader the
        // empty body was a mistake. (The warning itself is not emitted here:
        // `macroexp-warn-and-return` needs the byte-compiler's diagnostic
        // channel, which this tree does not model.)
        let empty_body = body.is_empty();
        Ok(match name.as_str() {
            // subr.el: (defmacro lambda (&rest cdr) (list 'function (cons 'lambda cdr)))
            "lambda" => {
                let function_sym = h.intern("function");
                Some(h.list_from(vec![function_sym, form.clone()]))
            }
            // (if COND (progn BODY...)), or (progn COND nil) with no body.
            "when" => {
                if empty_body {
                    let progn_sym = h.intern("progn");
                    return Ok(Some(h.list_from(vec![progn_sym, cond, Value::Undef])));
                }
                let if_sym = h.intern("if");
                let mut progn = vec![h.intern("progn")];
                progn.extend_from_slice(body);
                let progn = h.list_from(progn);
                Some(h.list_from(vec![if_sym, cond, progn]))
            }
            // (if COND nil BODY...) — nil is `Value::Undef`.
            "unless" => {
                if empty_body {
                    let progn_sym = h.intern("progn");
                    return Ok(Some(h.list_from(vec![progn_sym, cond, Value::Undef])));
                }
                let mut out = vec![h.intern("if"), cond, Value::Undef];
                out.extend_from_slice(body);
                Some(h.list_from(out))
            }
            _ => None,
        })
    })
}

/// Fully expand macros in `form` (top-level to fixpoint, then recursively into
/// sub-forms), without descending into quoted data or into positions that are
/// not expression forms. Run before lowering.
///
/// Special forms with irregular shapes are handled explicitly so their
/// non-expression subparts are never mistaken for macro calls: a `let` binding
/// `(VAR INIT)` must not have `VAR` expanded, which matters because a symbol can
/// be *both* a special variable and a macro (e.g. `delay-mode-hooks`) — expanding
/// the binding head there loops forever.
pub fn macroexpand_all(form: &Value) -> Result<Value, String> {
    macroexpand_all_impl(form, Walk::Load, &Value::Undef)
}

/// Which of Emacs's three macro walks [`macroexpand_all_impl`] performs.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Walk {
    /// `load`'s eager `internal-macroexpand-for-load`, i.e. `macroexpand-all`
    /// ahead of lowering: compiler macros apply and `when`/`unless` unfold,
    /// so a closure's printed body is the expanded one
    /// (`#[(x) ((if x (progn y))) ((y . 1))]`). A COND-less `(when)` is left
    /// for the compiler, which signals its arity error only if it runs.
    Load,
    /// eval.c `eval_sub` under the `eval` builtin: no compiler macros, no
    /// `when`/`unless` unfolding, and an expander's failure is deferred to
    /// the point the call is reached.
    Eval,
    /// The `macroexpand-all` builtin: everything unfolds, and every failure
    /// signals at once.
    Builtin,
}

/// [`macroexpand_all`] for the `eval` builtin, which does NOT apply compiler
/// macros.
///
/// Emacs's `eval` walks the form itself; only `macroexpand-all` — and so
/// `load`, through `internal-macroexpand-for-load` — runs
/// `macroexp--compiler-macro`. The difference is observable, and it is the
/// whole reason `add-to-list` works on a lexical variable in a loaded file and
/// not through `eval`:
///
/// ```text
/// (eval '(let ((l nil)) (add-to-list 'l 1) l) t)   ; (void-variable l)
/// ```
pub fn macroexpand_all_for_eval(form: &Value) -> Result<Value, String> {
    macroexpand_all_impl(form, Walk::Eval, &Value::Undef)
}

/// `macroexpand-all` as the elisp builtin exposes it: identical to
/// [`macroexpand_all`] except that a COND-less `(when)` / `(unless)` signals
/// its arity error during the walk, as the expander does in Emacs, instead of
/// being left for the compiler to signal when the form runs.
pub fn macroexpand_all_builtin(form: &Value, env: &Value) -> Result<Value, String> {
    // macroexp.el binds `macroexpand-all-environment' around the walk, so an
    // expander that expands its own body (`cl-tagbody', `cl-macrolet') sees
    // the environment it was called under.
    let depth = with_host(|h| {
        let d = h.specdepth();
        let sym = h.intern("macroexpand-all-environment");
        let _ = h.specbind(&sym, env.clone());
        d
    });
    let out = macroexpand_all_impl(form, Walk::Builtin, env);
    with_host(|h| h.unbind_to(depth));
    out
}

/// macroexp.el `internal-macroexpand-for-load`, which `load` runs over each
/// top-level form before evaluating it: the whole form is `macroexpand-all`ed
/// up front, and an error raised by an expander becomes
/// `(error "Eager macro-expansion failure: %S" ERR)` — signalled before any of
/// the form runs, so a `condition-case` inside the form does not see it. A
/// `throw` is not an error and passes through.
pub fn macroexpand_for_load(form: &Value) -> Result<Value, String> {
    macroexpand_all_builtin(form, &Value::Undef).map_err(|err| {
        if err == "--throw--" {
            return err;
        }
        with_host(|h| {
            let obj = h
                .take_pending_error(&err)
                .unwrap_or_else(|| h.make_error_object(&err));
            let text = format!("Eager macro-expansion failure: {}", h.print(&obj, true));
            let msg = format!("error: {text}");
            let sym = h.intern("error");
            let s = h.new_string(&text);
            let data = h.list_from(vec![s]);
            let obj = h.cons(sym, data);
            h.set_pending_error(&msg, obj);
            msg
        })
    })
}

/// `v`'s elements when it is a `(lambda ARGLIST . BODY)` form, else None.
fn lambda_parts(v: Option<&Value>) -> Option<Vec<Value>> {
    let v = v?;
    with_host(|h| {
        let parts = h.list_vec(v)?;
        (parts.len() >= 2 && h.sym_name(parts.first()?).as_deref() == Some("lambda"))
            .then_some(parts)
    })
}

/// Expand a `(lambda ARGLIST . BODY)` form's BODY, keeping the bare `lambda`
/// head. The ARGLIST is a parameter list, not code — a parameter named after a
/// macro (e.g. `rx`) must NOT be macroexpanded — and the `function` wrapper is
/// added by whichever caller wants it, so this never double-wraps.
fn expand_lambda_bare(elems: &[Value], walk: Walk, env: &Value) -> Result<Value, String> {
    let mut out = Vec::with_capacity(elems.len());
    out.push(elems[0].clone());
    out.push(elems[1].clone()); // ARGLIST, untouched
    for e in &elems[2..] {
        out.push(macroexpand_all_impl(e, walk, env)?);
    }
    let lam = with_host(|h| h.list_from(out));
    if let (Walk::Eval, Value::Obj(id)) = (walk, &lam) {
        with_host(|h| h.eval_lambda_raw.insert(*id, elems[2..].to_vec()));
    }
    Ok(lam)
}

/// Apply the head symbol's COMPILER MACRO, if it has one.
///
/// A compiler macro is a rewrite a function may declare for its own call sites
/// (`(declare (compiler-macro …))`, stored as the symbol's `compiler-macro`
/// function property). Emacs applies them in `macroexp--expand-all`, which is
/// why the same form answers differently through `load` and through plain
/// `eval`:
///
/// ```text
/// (eval '(let ((l nil)) (add-to-list 'l 1) l) t)   ; (void-variable l)
/// (macroexpand-all '(let ((l nil)) (add-to-list 'l 1) l))
///   ; => (let ((l nil)) (if (member 1 l) l (setq l (cons 1 l))) l)
/// ```
///
/// The handler is called as `(HANDLER FORM . ARGS)` and may answer FORM itself
/// to decline, which is how `add-to-list`'s handler passes a dynamic variable
/// through to the ordinary function.
fn apply_compiler_macro(form: &Value) -> Result<Option<Value>, String> {
    let handler = with_host(|h| {
        let elems = h.list_vec(form)?;
        let head = elems.first()?;
        // Only a symbol head can carry the property, and a macro has already
        // been expanded by the time this runs. `compiler_macros` is the cheap
        // pre-filter that keeps the elisp lookup off every call form.
        let id = match head {
            Value::Obj(id) if h.compiler_macros.contains(id) => *id,
            _ => return None,
        };
        let _ = id;
        // During the early prelude `function-get` is interned but not yet
        // fbound; there are no compiler macros to find then either.
        let getter = h.find_symbol("function-get")?;
        h.resolve_function(&getter).ok()?;
        Some((getter, head.clone(), elems[1..].to_vec()))
    });
    let Some((getter, head, args)) = handler else {
        return Ok(None);
    };
    let prop = with_host(|h| h.intern("compiler-macro"));
    let Ok(cm) = call_function(&getter, &[head, prop]) else {
        return Ok(None);
    };
    if !el_truthy(&cm) {
        return Ok(None);
    }
    let mut call = vec![form.clone()];
    call.extend(args);
    // `macroexp--compiler-macro` catches a handler's error and keeps the
    // original form; a broken handler must not take the whole expansion down.
    let Ok(out) = call_function(&cm, &call) else {
        return Ok(None);
    };
    // A handler that answers its own argument declined.
    if with_host(|h| h.values_eq(&out, form)) {
        return Ok(None);
    }
    Ok(Some(out))
}

/// The form that replays a macro expander's failure at the point the macro
/// call is evaluated, for the lazy `eval` walk (see [`macroexpand_all_impl`]).
///
/// An error becomes `(signal 'SYMBOL 'DATA)` with the expander's own error
/// object, so a handler sees the same DATA. A `throw` becomes `(throw 'TAG
/// 'VALUE)`: one aimed at a `catch` already active when the walk ran is still
/// aimed at it, and one that found no `catch` then (`no-catch`) is thrown again
/// at run time, where a `catch` inside the evaluated form can now receive it —
/// `(eval '(catch 'x (list 1 (THROWING-MACRO))))` is the thrown value in Emacs.
/// With no `catch` at run time either, `throw` signals the same `no-catch`.
fn deferred_expansion_failure(err: String) -> Value {
    with_host(|h| {
        let quote = h.intern("quote");
        let thrown = if err == "--throw--" {
            h.pending_throw.take()
        } else {
            None
        };
        let (head, a, b) = match thrown {
            Some((tag, val)) => (h.intern("throw"), tag, val),
            None => {
                let obj = h
                    .take_pending_error(&err)
                    .unwrap_or_else(|| h.make_error_object(&err));
                let (sym, data) = match h.obj(&obj) {
                    Some(Obj::Cons(a, d)) => (a.clone(), d.clone()),
                    _ => (h.intern("error"), Value::Undef),
                };
                let no_catch = h.sym_name(&sym).as_deref() == Some("no-catch");
                match h.list_vec(&data) {
                    Some(d) if no_catch && d.len() == 2 => {
                        (h.intern("throw"), d[0].clone(), d[1].clone())
                    }
                    _ => (h.intern("signal"), sym, data),
                }
            }
        };
        let qa = h.list_from(vec![quote.clone(), a]);
        let qb = h.list_from(vec![quote, b]);
        h.list_from(vec![head, qa, qb])
    })
}

/// `(when)` / `(unless)` with no COND: the form the compiler lowers to its
/// run-time arity signal, so the [`Walk::Load`] walk leaves it as written.
fn is_condless_when(form: &Value) -> bool {
    with_host(|h| {
        h.list_vec(form).is_some_and(|v| {
            v.len() == 1 && matches!(h.sym_name(&v[0]).as_deref(), Some("when" | "unless"))
        })
    })
}

fn macroexpand_all_impl(form: &Value, walk: Walk, env: &Value) -> Result<Value, String> {
    let mut f = form.clone();
    loop {
        match env_expand(&f, env)? {
            EnvHit::Expanded(e) => {
                let same = with_host(|h| h.values_eq(&e, &f));
                f = e;
                if same {
                    break;
                }
                continue;
            }
            EnvHit::Shadowed => break,
            EnvHit::Miss => {}
        }
        match macroexpand_1(&f) {
            Ok(Some(e)) => {
                f = e;
                continue;
            }
            Ok(None) => {}
            // The `eval` walk (the only caller that skips compiler macros) is
            // eval.c `eval_sub`, which expands a macro call only when the call
            // is REACHED: `(eval '(if nil (BROKEN-MACRO) 'ok))` is `ok`, and a
            // `condition-case` in the same form catches the expander's error.
            Err(e) if walk == Walk::Eval => return Ok(deferred_expansion_failure(e)),
            Err(e) => return Err(e),
        }
        let unfold_intrinsics = match walk {
            Walk::Eval => false,
            Walk::Load => !is_condless_when(&f),
            Walk::Builtin => true,
        };
        if unfold_intrinsics {
            if let Some(e) = expand_intrinsic_macro(&f)? {
                f = e;
                continue;
            }
        }
        if walk != Walk::Eval {
            if let Some(e) = apply_compiler_macro(&f)? {
                f = e;
                continue;
            }
        }
        break;
    }
    let elems = with_host(|h| {
        if matches!(h.obj(&f), Some(Obj::Cons(..))) {
            h.list_vec(&f)
        } else {
            None
        }
    });
    let Some(elems) = elems else { return Ok(f) };
    if elems.is_empty() {
        return Ok(f);
    }
    let head = with_host(|h| h.sym_name(&elems[0]));
    // A special form whose argument count its `DEFUN` rejects is left exactly
    // as written, so the compiler still sees the count it must signal on.
    //
    // Expanding it is not merely pointless, it is unsound: each arm below reads
    // the positions the form is DECLARED to have, and `(let)` has none of them
    // — the `let` arm sliced `elems[2..]` of a one-element list and panicked the
    // interpreter thread outright ("range start index 2 out of range for slice
    // of length 1"). Normalizing instead of skipping would be worse than the
    // panic: it would manufacture the missing arguments and hide the count that
    // `(wrong-number-of-arguments let 0)` has to report.
    if let Some(n) = head.as_deref() {
        if crate::compiler::special_form_arity_error(n, elems.len() - 1).is_some() {
            return Ok(f);
        }
    }
    match head.as_deref() {
        // Quoted data is never expanded.
        Some("quote") => Ok(f),
        // `#'(lambda ...)` is not quoted data: the body is code and Emacs's
        // `macroexp--expand-all` expands it (`(macroexpand-all '#'(lambda ()
        // (when 1 2)))` is `#'(lambda nil (if 1 (progn 2)))`). `#'SYMBOL` is.
        Some("function") => {
            let Some(inner) = lambda_parts(elems.get(1)) else {
                return Ok(f);
            };
            // Expand the lambda BARE — `expand_lambda_bare` does not re-add the
            // wrapper, so `#'(lambda ...)` cannot come back as
            // `#'#'(lambda ...)`.
            let lam = expand_lambda_bare(&inner, walk, env)?;
            Ok(with_host(|h| h.list_from(vec![elems[0].clone(), lam])))
        }
        // Binding forms: expand each binding's INIT (never the VAR, which may name
        // a macro) and the body forms; keep the head and the binding names as-is.
        Some(kw @ ("let" | "let*")) => {
            let bindings = with_host(|h| h.list_vec(elems.get(1).unwrap_or(&Value::Undef)));
            let new_bindings = match bindings {
                Some(bs) => {
                    let mut out = Vec::with_capacity(bs.len());
                    for bd in &bs {
                        // A bare symbol binding stays as-is; a `(VAR INIT...)`
                        // list has only its INIT expressions expanded.
                        let parts = with_host(|h| {
                            if matches!(h.obj(bd), Some(Obj::Cons(..))) {
                                h.list_vec(bd)
                            } else {
                                None
                            }
                        });
                        match parts {
                            Some(parts) if !parts.is_empty() => {
                                let mut np = Vec::with_capacity(parts.len());
                                np.push(parts[0].clone()); // VAR, untouched
                                for p in &parts[1..] {
                                    np.push(macroexpand_all_impl(p, walk, env)?);
                                }
                                out.push(with_host(|h| h.list_from(np)));
                            }
                            _ => out.push(bd.clone()),
                        }
                    }
                    with_host(|h| h.list_from(out))
                }
                None => elems.get(1).cloned().unwrap_or(Value::Undef),
            };
            let mut out = Vec::with_capacity(elems.len());
            out.push(elems[0].clone());
            out.push(new_bindings);
            for e in &elems[2..] {
                out.push(macroexpand_all_impl(e, walk, env)?);
            }
            let _ = kw;
            Ok(with_host(|h| h.list_from(out)))
        }
        // `(lambda ARGLIST . BODY)`: the ARGLIST is a parameter list, not code —
        // a parameter named after a macro (e.g. `rx`) must NOT be macroexpanded.
        // Keep head + ARGLIST verbatim; expand only the body forms.
        //
        // `lambda` is a MACRO in Emacs (subr.el: `(list 'function (cons 'lambda
        // cdr))`), so expansion also wraps it: `(macroexpand-all '(list (lambda
        // () n)))` is `(list #'(lambda nil n))`. That wrapper is observable —
        // `cconv-make-interpreted-closure` stores the expanded body, so a
        // closure whose body contains a nested `lambda` PRINTS the `#'`.
        Some("lambda") if elems.len() >= 2 => {
            let lam = expand_lambda_bare(&elems, walk, env)?;
            Ok(with_host(|h| {
                let fsym = h.intern("function");
                h.list_from(vec![fsym, lam])
            }))
        }
        // `(defun|defmacro NAME ARGLIST . BODY)`: same protection for the ARGLIST
        // (and NAME); only the body forms are expression positions.
        Some(construct @ ("defun" | "defmacro")) if elems.len() >= 3 => {
            // Faithful byte-run.el `declare' handling: `defun'/`defmacro' are
            // macros in Emacs that process the `(declare ...)' specs (registering
            // gv-setters, obsolete/indent/doc-string props, …).  elisprs keeps
            // them as compiler special forms, so we delegate to the prelude bridge
            // `elisprs--expand-defun-declarations', which returns a rewritten
            // definition threading each spec's runtime side-effect form after it.
            // Guarded on fboundp so early-prelude defuns (compiled before the
            // bridge is defined) keep the pre-bridge behavior — no bootstrap cycle.
            let bridge_ready = with_host(|h| {
                let s = h.intern("elisprs--expand-defun-declarations");
                h.is_fbound(&s)
            });
            if bridge_ready {
                let (bridge, cons_sym, name, arglist, body_list) = with_host(|h| {
                    let bridge = h.intern("elisprs--expand-defun-declarations");
                    let cons_sym = h.intern(construct);
                    let body_list = h.list_from(elems[3..].to_vec());
                    (
                        bridge,
                        cons_sym,
                        elems[1].clone(),
                        elems[2].clone(),
                        body_list,
                    )
                });
                let replaced = call_function(&bridge, &[cons_sym, name, arglist, body_list])?;
                // Non-nil ⇒ BODY had a `declare'; expand the rewritten form (its
                // inner defun has the `declare' stripped, so this does not recurse).
                if el_truthy(&replaced) {
                    return macroexpand_all_impl(&replaced, walk, env);
                }
            }
            // Too early for the bridge: keep the form so the prelude can replay
            // its `declare` (indent, doc-string, gv-setter, …) once the handlers
            // exist, and drop the `declare` from the body as byte-run.el's
            // `defun`/`defmacro` do. It can only follow the optional docstring,
            // so the first two body forms are all that matter.
            let early_declare = if bridge_ready {
                None
            } else {
                with_host(|h| {
                    let declare = h.intern("declare");
                    let at = (3..elems.len().min(5)).find(|&i| {
                        h.list_vec(&elems[i])
                            .and_then(|l| l.first().cloned())
                            .is_some_and(|head| head == declare)
                    });
                    if at.is_some() {
                        h.early_declarations.push(f.clone());
                    }
                    at
                })
            };
            let mut out = Vec::with_capacity(elems.len());
            out.push(elems[0].clone());
            out.push(elems[1].clone()); // NAME, untouched
            out.push(elems[2].clone()); // ARGLIST, untouched
            for (i, e) in elems.iter().enumerate().skip(3) {
                if Some(i) != early_declare {
                    out.push(macroexpand_all_impl(e, walk, env)?);
                }
            }
            // byte-run.el: a body left empty (or only a docstring) by removing
            // the `declare` becomes `(nil)`.
            if early_declare.is_some() {
                let doc = out.len() > 3 && with_host(|h| h.is_string(&out[3]));
                if out.len() == 3 + doc as usize {
                    out.push(Value::Undef);
                }
            }
            let def = with_host(|h| h.list_from(out));
            if let (Walk::Eval, Value::Obj(id)) = (walk, &def) {
                with_host(|h| h.eval_lambda_raw.insert(*id, elems[3..].to_vec()));
            }
            Ok(def)
        }
        // macroexp.el: `(cond . ,clauses)` expands every element of every clause
        // as a form (`macroexp--all-clauses`), the condition included, so a
        // `(lambda ...)` condition becomes `#'(lambda ...)`. A non-list clause
        // is kept as it is.
        Some("cond") => {
            let mut out = Vec::with_capacity(elems.len());
            out.push(elems[0].clone());
            for clause in &elems[1..] {
                match with_host(|h| h.list_vec(clause)) {
                    Some(forms) if !forms.is_empty() => {
                        let mut nc = Vec::with_capacity(forms.len());
                        for f in &forms {
                            nc.push(macroexpand_all_impl(f, walk, env)?);
                        }
                        out.push(with_host(|h| h.list_from(nc)));
                    }
                    _ => out.push(clause.clone()),
                }
            }
            Ok(with_host(|h| h.list_from(out)))
        }
        _ => {
            let mut out = Vec::with_capacity(elems.len());
            for (i, e) in elems.iter().enumerate() {
                // A lambda in HEAD position keeps its bare `lambda` head:
                // `(macroexpand-all '((lambda (x) x) 5))` is
                // `((lambda (x) x) 5)` in Emacs, and `(#'(lambda (x) x) 5)`
                // would be `invalid-function` — `#'(lambda …)` is a form that
                // evaluates to a closure, not a closure.
                let expanded = match (i == 0).then(|| lambda_parts(Some(e))).flatten() {
                    Some(parts) => expand_lambda_bare(&parts, walk, env)?,
                    None => macroexpand_all_impl(e, walk, env)?,
                };
                // A `defmacro' among sibling forms has to take effect BEFORE its
                // siblings are expanded, or a macro defined and used in the same
                // enclosing form is unusable: expansion of `(progn (defmacro m …)
                // (m 1))' reached `(m 1)' while `m' still had no function cell, so
                // it compiled as a call and failed at run time with "macro called
                // as a function". Emacs's interpreter never sees this because it
                // evaluates `progn' forms one at a time, and its byte-compiler
                // evaluates `defmacro' at compile time for exactly this reason.
                //
                // The form is already fully expanded, so compiling it here cannot
                // re-enter expansion. Running it only writes the macro's function
                // cell — the enclosing form still contains the `defmacro', which
                // installs the identical definition again when it runs.
                if is_defmacro_form(e) {
                    if let Ok(chunk) = with_host(|h| crate::compiler::compile_top(h, &expanded)) {
                        let _ = run_chunk(chunk);
                    }
                }
                out.push(expanded);
            }
            Ok(with_host(|h| h.list_from(out)))
        }
    }
}

/// True when FORM is literally `(defmacro NAME ARGLIST …)`.
fn is_defmacro_form(form: &Value) -> bool {
    with_host(|h| {
        let Some(Obj::Cons(head, _)) = h.obj(form) else {
            return false;
        };
        let head = head.clone();
        h.sym_name(&head).as_deref() == Some("defmacro")
    })
}

/// lread.c `lisp_file_lexical_cookie` + `get_lexical_binding`: the value
/// `load` binds `lexical-binding` to while a file's forms run. The cookie is
/// the `lexical-binding:` variable of a `-*- … -*-` comment on the first line
/// (the second, after a `#!` line); any value but `nil` means t. A file
/// without one is evaluated with nil (Emacs 31 also warns, on stderr only).
///
/// The binding is `specbind`'s, so in `*scratch*` — where
/// `lisp-interaction-mode` made `lexical-binding` local — it is that local
/// value that changes, as when Emacs loads a file with `-l`.
pub(crate) fn file_lexical_cookie(src: &str) -> bool {
    let mut lines = src.lines();
    let mut first = lines.next().unwrap_or("");
    if first.starts_with("#!") {
        first = lines.next().unwrap_or("");
    }
    if !first.starts_with(';') {
        return false;
    }
    let Some(start) = first.find("-*-") else {
        return false;
    };
    let rest = &first[start + 3..];
    let vars = rest.find("-*-").map_or(rest, |end| &rest[..end]);
    vars.split(';')
        .filter_map(|pair| pair.split_once(':'))
        .find(|(var, _)| var.trim() == "lexical-binding")
        .is_some_and(|(_, val)| val.trim() != "nil")
}

/// `(catch TAG THUNK)` — run the thunk; if a `throw` to a matching tag unwinds
/// out of it, return the thrown value; otherwise re-propagate.
/// Resolve a load candidate to an absolute path string, expanding `~/` and
/// making relative paths absolute against the process cwd (which the elisp
/// `default-directory` mirrors). No path is required to exist here.
pub(crate) fn load_abspath(candidate: &str) -> std::path::PathBuf {
    if let Some(rest) = candidate.strip_prefix("~/") {
        if let Ok(home) = std::env::var("HOME") {
            return std::path::PathBuf::from(home).join(rest);
        }
    }
    let p = std::path::PathBuf::from(candidate);
    if p.is_absolute() {
        p
    } else {
        std::env::current_dir().map(|d| d.join(&p)).unwrap_or(p)
    }
}

/// `(load FILE &optional NOERROR NOMESSAGE NOSUFFIX MUST-SUFFIX)` — port of
/// Emacs's `Fload`/`openp` semantics (behavior, not line numbers; this repo has
/// no vendored C).
///
/// Resolution: if FILE has a directory component (or is absolute/`~`), it is
/// used as-is; otherwise each directory in `load-path` is tried (falling back to
/// cwd when `load-path` is empty). For each base, suffixes are tried in order:
/// `.el`, `.el.gz`, the exact name, then its `.gz` variant (Emacs would try `.elc`
/// first, but elisprs emits no bytecode so no `.elc` ever exists). The `.gz`
/// variants are jka-compr's `load-file-rep-suffixes`; a resolved `.gz` file is
/// gunzipped in memory. NOSUFFIX limits the search to the exact name (and its
/// `.gz`); MUST-SUFFIX requires a `load-suffixes` extension (`.el`/`.el.gz` here).
///
/// While the file's forms run, `load-file-name`, `load-true-file-name` and
/// `load-in-progress` are dynamically bound and restored afterward — even if a
/// form errors (the specstack is unwound to the pre-load depth).
fn intrinsic_load(f: &Value, args: &[Value]) -> Result<Value, String> {
    let file = match args
        .first()
        .map(|v| (v, with_host(|h| h.str_text(v).map(str::to_string))))
    {
        Some((_, Some(s))) => s,
        Some((other, None)) => {
            return Err(format!(
                "wrong-type-argument: stringp {}",
                other.as_str_cow()
            ))
        }
        // The designator is threaded in rather than re-interned: Emacs reports
        // `load' for a direct `(load)' and `#<subr load>' for `(funcall #'load)',
        // which is the difference between the symbol the caller wrote and the
        // object `funcall' resolved -- and only the caller knows which it was.
        None => return Err(intrinsic_wrong_nargs(f, args.len())),
    };
    let noerror = args.get(1).is_some_and(el_truthy);
    let nosuffix = args.get(3).is_some_and(el_truthy);
    let must_suffix = args.get(4).is_some_and(el_truthy);

    // Suffixes to append, in Emacs's search order. Each `load-suffixes` entry is
    // crossed with `load-file-rep-suffixes` = `("" ".gz")` (jka-compr's compressed
    // variant — the stock Emacs lisp tree ships as `*.el.gz`), then the bare
    // rep-suffixes are appended for the exact-name pass. `.elc` is skipped —
    // elisprs writes no bytecode files. NOSUFFIX drops the load-suffixes; MUST-SUFFIX
    // drops the bare exact-name pass. Mirrors `Fget_load_suffixes` + `openp` order.
    let suffixes: &[&str] = if nosuffix {
        &["", ".gz"]
    } else if must_suffix {
        &[".el", ".el.gz"]
    } else {
        &[".el", ".el.gz", "", ".gz"]
    };

    // Base names: FILE alone if it carries a directory component, else each
    // `load-path` entry joined with FILE (cwd when `load-path` is empty/unset).
    let has_dir = file.contains('/') || file.starts_with('~');
    let bases: Vec<String> = if has_dir {
        vec![file.clone()]
    } else {
        let lp = with_host(|h| {
            let sym = h.intern("load-path");
            h.get_value(&sym).ok().and_then(|v| h.list_vec(&v))
        });
        let dirs: Vec<String> = lp
            .unwrap_or_default()
            .iter()
            .filter_map(|v| with_host(|h| h.str_text(v).map(str::to_string)))
            .collect();
        if dirs.is_empty() {
            vec![format!("./{file}")]
        } else {
            dirs.iter()
                .map(|d| {
                    if d.ends_with('/') {
                        format!("{d}{file}")
                    } else {
                        format!("{d}/{file}")
                    }
                })
                .collect()
        }
    };

    // First existing (base + suffix) wins.
    let mut resolved: Option<std::path::PathBuf> = None;
    'search: for base in &bases {
        for suf in suffixes {
            let cand = load_abspath(&format!("{base}{suf}"));
            if cand.is_file() {
                resolved = Some(cand);
                break 'search;
            }
        }
    }

    // A library bundled from the Emacs tree answers when no file on
    // `load-path` does, as Emacs's own `lisp/` directory is its last entry.
    let bundled = if resolved.is_none() {
        crate::bundled::find(&file)
    } else {
        None
    };

    let (src, path_text) = match (resolved, bundled) {
        (Some(path), _) => {
            // Read the resolved file. A `.gz` target is decompressed in memory
            // (jka-compr does the same via `load` -> `insert-file-contents` ->
            // `jka-compr-insert`), so a stock `*.el.gz` library evaluates
            // identically to its `.el` form.
            let src = if path.extension().and_then(|e| e.to_str()) == Some("gz") {
                let bytes = std::fs::read(&path).map_err(|e| {
                    format!("file-error: Cannot open load file: {}: {e}", path.display())
                })?;
                let mut dec = flate2::read::GzDecoder::new(&bytes[..]);
                let mut s = String::new();
                std::io::Read::read_to_string(&mut dec, &mut s)
                    .map_err(|e| format!("file-error: uncompressing {}: {e}", path.display()))?;
                s
            } else {
                std::fs::read_to_string(&path).map_err(|e| {
                    format!("file-error: Cannot open load file: {}: {e}", path.display())
                })?
            };
            (src, path.to_string_lossy().into_owned())
        }
        (None, Some(lib)) => (lib.source.to_string(), crate::bundled::virtual_path(lib)),
        (None, None) => {
            if noerror {
                return Ok(Value::Undef);
            }
            // lread.c `Fload`: `report_file_error ("Cannot open load file",
            // file)` with errno ENOENT, FILE as given (not expanded).
            let enoent = std::io::Error::from_raw_os_error(libc::ENOENT);
            return Err(with_host(|h| {
                crate::builtins::report_file_errno(h, "Cannot open load file", &[&file], &enoent)
            }));
        }
    };
    let abs = with_host(|h| h.new_string(path_text));

    // Dynamically bind the load vars, remembering the pre-load specstack depth
    // so we can unwind them even if a form errors.
    let depth = with_host(|h| {
        let d = h.specdepth();
        let lfn = h.intern("load-file-name");
        let ltn = h.intern("load-true-file-name");
        let lip = h.intern("load-in-progress");
        let _ = h.specbind(&lfn, abs.clone());
        let _ = h.specbind(&ltn, abs.clone());
        let _ = h.specbind(&lip, Value::Bool(true));
        let lb = h.intern("lexical-binding");
        let _ = h.specbind(&lb, Value::Bool(file_lexical_cookie(&src)));
        d
    });

    // `load-with-code-conversion` reads the file through a buffer of its own and
    // kills it on the way out (`unwind-protect`), so a nested load is visible in
    // `(buffer-list)` while it runs and gone afterward.
    let load_buf = with_host(|h| h.open_load_buffer(&src, false));
    let load_obj = with_host(|h| h.buffer_object(load_buf));
    let result = crate::run_top_forms(&src, Some(load_obj));
    with_host(|h| {
        let obj = h.buffer_object(load_buf);
        h.kill_buffer(Some(&obj));
        h.unbind_to(depth);
    });

    result.map(|_| Value::Bool(true))
}

fn intrinsic_catch(args: &[Value]) -> Result<Value, String> {
    let tag = args.first().cloned().unwrap_or(Value::Undef);
    let thunk = args.get(1).cloned().unwrap_or(Value::Undef);
    with_host(|h| h.catch_tags.push(tag.clone()));
    let result = call_function(&thunk, &[]);
    with_host(|h| {
        h.catch_tags.pop();
    });
    match result {
        Ok(v) => Ok(v),
        Err(e) => {
            let pend = with_host(|h| h.pending_throw.clone());
            match pend {
                Some((ttag, tval)) if with_host(|h| h.values_eq(&ttag, &tag)) => {
                    with_host(|h| h.pending_throw = None);
                    Ok(tval)
                }
                _ => Err(e), // not our throw (or a real error): keep unwinding
            }
        }
    }
}

/// `(unwind-protect BODY-THUNK CLEANUP-THUNK)` — always run cleanup, preserving
/// an in-flight throw across it, then propagate the body's result.
fn intrinsic_unwind(args: &[Value]) -> Result<Value, String> {
    let body = args.first().cloned().unwrap_or(Value::Undef);
    let cleanup = args.get(1).cloned().unwrap_or(Value::Undef);
    let r = call_function(&body, &[]);
    let saved = with_host(|h| h.pending_throw.take());
    let cleanup_r = call_function(&cleanup, &[]);
    with_host(|h| {
        if h.pending_throw.is_none() {
            h.pending_throw = saved;
        }
    });
    // A cleanup that itself signals SUPERSEDES whatever the body was doing —
    // eval.c runs the unwind handler outside the body's protection, so its error
    // propagates and the body's in-flight error is dropped. Discarding it here
    // (`let _ =`) made `(condition-case e (unwind-protect (error "in")
    // (error "cleanup")) (error (cadr e)))` answer "in" where Emacs answers
    // "cleanup", and silently swallowed every failure inside a cleanup form.
    cleanup_r?;
    r
}

/// `(condition-case VAR BODY-THUNK HANDLERS)` where HANDLERS is a list of
/// `(CONDITION HANDLER-THUNK)`. Catches *errors* (not throws); binds VAR to the
/// error object while the matching handler runs.
fn intrinsic_condition_case(args: &[Value]) -> Result<Value, String> {
    let var = args.first().cloned().unwrap_or(Value::Undef);
    let body = args.get(1).cloned().unwrap_or(Value::Undef);
    let handlers = args.get(2).cloned().unwrap_or(Value::Undef);
    // Running the body forward: any leftover error object is stale.
    with_host(|h| h.pending_error = None);
    match call_function(&body, &[]) {
        Ok(v) => {
            // A `(:success BODY…)` handler runs on normal return, with VAR bound
            // to the body's value.
            let hlist = with_host(|h| h.list_vec(&handlers)).unwrap_or_default();
            for hp in hlist {
                let parts = with_host(|h| h.list_vec(&hp)).unwrap_or_default();
                if parts.len() < 2 {
                    continue;
                }
                let cname = with_host(|h| h.sym_name(&parts[0])).unwrap_or_default();
                if cname == ":success" {
                    let depth = with_host(|h| {
                        let d = h.specdepth();
                        if matches!(h.obj(&var), Some(Obj::Symbol(_))) {
                            let _ = h.specbind(&var, v.clone());
                        }
                        d
                    });
                    let hr = call_function(&parts[1], &[]);
                    with_host(|h| h.unbind_to(depth));
                    return hr;
                }
            }
            Ok(v)
        }
        Err(e) => {
            // A throw is not an error — let it keep unwinding to its catch.
            if with_host(|h| h.pending_throw.is_some()) {
                return Err(e);
            }
            // Prefer the structured error object's symbol over the message string.
            let esym: String = with_host(|h| {
                let obj = h
                    .pending_error
                    .as_ref()
                    .filter(|(m, _)| *m == e)
                    .map(|(_, eo)| eo.clone())?;
                match h.obj(&obj) {
                    Some(Obj::Cons(car, _)) => {
                        let car = car.clone();
                        h.sym_name(&car)
                    }
                    _ => None,
                }
            })
            .unwrap_or_else(|| e.split(':').next().unwrap_or("error").trim().to_string());
            let hlist = with_host(|h| h.list_vec(&handlers)).unwrap_or_default();
            // The signaled symbol's `error-conditions` (itself + parents, via
            // define-error); a handler matches any condition on this chain.
            let getfn = with_host(|h| h.intern("get"));
            let symv = with_host(|h| h.intern(&esym));
            let propv = with_host(|h| h.intern("error-conditions"));
            let mut signal_conditions: Vec<String> = call_function(&getfn, &[symv, propv])
                .ok()
                .and_then(|v| with_host(|h| h.list_vec(&v)))
                .map(|items| with_host(|h| items.iter().filter_map(|x| h.sym_name(x)).collect()))
                .unwrap_or_default();
            // `overflow-error`/`range-error` are signalled by float-rounding subrs
            // but their `define-error` chain lives in the elisp prelude, which may
            // not register them; supply Emacs's fixed parent chain so an
            // `arith-error`/`range-error` handler still catches an overflow.
            if signal_conditions.is_empty() {
                let chain: &[&str] = match esym.as_str() {
                    "overflow-error" => &["overflow-error", "range-error", "arith-error", "error"],
                    "range-error" => &["range-error", "arith-error", "error"],
                    _ => &[],
                };
                signal_conditions = chain.iter().map(|s| s.to_string()).collect();
            }
            for hp in hlist {
                let parts = with_host(|h| h.list_vec(&hp)).unwrap_or_default();
                if parts.len() < 2 {
                    continue;
                }
                // A handler condition is a symbol or a list of symbols; it matches
                // if any names `error`/`t`, the signaled condition, or a parent of
                // it (per the signal's error-conditions chain).
                let conds: Vec<String> = with_host(|h| match h.sym_name(&parts[0]) {
                    Some(name) => vec![name],
                    None => h
                        .list_vec(&parts[0])
                        .map(|items| items.iter().filter_map(|x| h.sym_name(x)).collect())
                        .unwrap_or_default(),
                });
                // An `error' handler is NOT a catch-all: it matches only signals
                // whose `error-conditions' chain actually contains `error'. `quit'
                // is the case that proves it — data.c seeds it with conditions
                // (quit), so `(condition-case nil (signal 'quit nil) (error 'c)
                // (t 'top))' answers `top' in Emacs. Treating `error' as
                // unconditional answered `c'. Only `t' is the real catch-all.
                //
                // When the chain is empty the signal came from an internal Rust
                // error string with no `define-error' registration; those are all
                // ordinary errors, so `error' still matches them.
                let derives_from_error =
                    signal_conditions.is_empty() || signal_conditions.iter().any(|c| c == "error");
                if conds.iter().any(|c| {
                    (c == "error" && derives_from_error)
                        || c == "t"
                        || *c == esym
                        || signal_conditions.contains(c)
                }) {
                    let depth = with_host(|h| {
                        let d = h.specdepth();
                        if matches!(h.obj(&var), Some(Obj::Symbol(_))) {
                            // Bind to the real (SYMBOL . DATA) object when we have
                            // it; otherwise reconstruct one from the message.
                            let eobj = h
                                .take_pending_error(&e)
                                .unwrap_or_else(|| h.make_error_object(&e));
                            let _ = h.specbind(&var, eobj);
                        }
                        d
                    });
                    let hr = call_function(&parts[1], &[]);
                    with_host(|h| h.unbind_to(depth));
                    return hr;
                }
            }
            Err(e)
        }
    }
}

/// fusevm extension handler. Non-capturing (satisfies `Send`); reaches the heap
/// through the thread-local host.
pub fn ext_dispatch(vm: &mut VM, id: u16, arg: u8) {
    match id {
        ops::TRUTHY => {
            let v = vm.pop();
            vm.push(Value::Bool(el_truthy(&v)));
        }
        ops::CALL => {
            let argc = arg as usize;
            let mut args = Vec::with_capacity(argc);
            for _ in 0..argc {
                args.push(vm.pop());
            }
            args.reverse();
            let symv = vm.pop();
            match call_function(&symv, &args) {
                Ok(v) => vm.push(v),
                Err(e) => abort(vm, e),
            }
        }
        ops::CHECK_ARITY => {
            // Emacs's `eval_sub` resolves the function cell BEFORE it evaluates
            // the argument forms, so `(car (setq x 1) (setq y 2))` signals
            // `(wrong-number-of-arguments car 2)` with x and y still 0. The
            // verdict is taken here rather than at compile time because
            // `fset`/`defalias` can retarget the symbol in between, and Emacs
            // honours the cell that is live at the call.
            let argc = arg as usize;
            let symv = vm.pop();
            let failure = with_host(|h| {
                // An AOP intercept fronts the callee, so the underlying subr's
                // arity is not the arity being called — leave those to `CALL`.
                if !h.intercepts.is_empty() {
                    return None;
                }
                // `eval_sub`: `if (NILP (fun)) xsignal1 (Qvoid_function,
                // original_fun)` — the ORIGINAL symbol, before any argument form
                // runs, even when the cell is an alias chain that dead-ends.
                let kind = h.fn_kind(&symv);
                if matches!(kind, FnKind::Vacant) && is_void_function_head(h, &symv) {
                    let sym = h.intern("void-function");
                    let msg = format!("void-function: {}", h.print(&symv, true));
                    let obj = h.list_from(vec![sym, symv.clone()]);
                    h.set_pending_error(&msg, obj);
                    return Some(msg);
                }
                kind.rejects_before_args(argc)
                    .then(|| h.signal_wrong_nargs(&symv, argc))
            });
            if let Some(e) = failure {
                abort(vm, e);
            }
        }
        ops::GETVAR => {
            let symv = vm.pop();
            match with_host(|h| h.get_value(&symv)) {
                Ok(v) => vm.push(v),
                Err(e) => abort(vm, e),
            }
        }
        ops::SETVAR => {
            let val = vm.pop();
            let symv = vm.pop();
            // The write can fail — `(setq nil 1)` is `setting-constant` — and a
            // discarded error would let the form quietly answer its own value.
            match with_host(|h| h.set_value(&symv, val.clone())) {
                Ok(()) => vm.push(val),
                Err(e) => abort(vm, e),
            }
        }
        ops::DEFVAR_INIT => {
            // `defvar`'s initializer runs only when the variable is void: after
            // `(setq zz 5)`, a later `(defvar zz 9)` leaves zz at 5. `defconst`
            // is the unconditional one and compiles to SETVAR instead. Keywords
            // are self-bound, which is why `(defvar :dv 1)` is a silent no-op
            // rather than `setting-constant`.
            let val = vm.pop();
            let symv = vm.pop();
            let bound = with_host(|h| h.default_boundp_raw(&symv));
            if bound {
                vm.push(val);
            } else {
                match with_host(|h| h.set_value(&symv, val.clone())) {
                    Ok(()) => vm.push(val),
                    Err(e) => abort(vm, e),
                }
            }
        }
        ops::FSET => {
            let def = vm.pop();
            let symv = vm.pop();
            match with_host(|h| h.set_function_value(&symv, def)) {
                Ok(()) => vm.push(symv),
                Err(e) => abort(vm, e),
            }
        }
        ops::SPECBIND => {
            // BIND1: bind into the current (already-open) scope; used by let*.
            let symv = vm.pop();
            let val = vm.pop();
            // `let*` binds each variable as it reaches it, so a constant in the
            // second binding still lets the first init run — which is Emacs's
            // order too.
            match with_host(|h| h.check_settable(&symv)) {
                Ok(()) => with_host(|h| h.bind_value(&symv, val)),
                Err(e) => abort(vm, e),
            }
        }
        ops::SCOPE_OPEN => {
            with_host(|h| h.open_scope());
        }
        ops::MAKE_CLOSURE => {
            let template = vm.pop();
            let clo = with_host(|h| h.instantiate_closure(&template));
            match eval_closure_source(&clo) {
                Ok(()) => vm.push(clo),
                Err(e) => abort(vm, e),
            }
        }
        ops::DBG_LINE => {
            // A DAP statement marker (emitted only in debug mode). The line rides
            // in the chunk's line table for this op; `vm.ip` has already advanced
            // past the marker, so the marker's slot is `ip - 1`. Stack-neutral.
            let line = *vm.chunk.lines.get(vm.ip.saturating_sub(1)).unwrap_or(&0);
            if line != 0 {
                crate::dap::check_line(line);
            }
        }
        _ => {}
    }
}

/// The body of `eval` once its environment is in place. eval.c `eval_sub`
/// interprets a `progn` one subform at a time, expanding each only when it is
/// reached, so a `cl-defstruct`, `defmacro` or `gv-define-setter` earlier in
/// the body is in effect for the forms after it (compiling the whole form
/// first expanded `(setf (S-x p) v)` before S existed). The subforms share one
/// environment, so a value-less `(defvar SYM)` among them reaches the rest.
fn eval_in_place(form: &Value) -> Result<Value, String> {
    let progn_body = with_host(|h| {
        h.list_vec(form)
            .filter(|v| !v.is_empty() && h.sym_name(&v[0]).as_deref() == Some("progn"))
    });
    if let Some(body) = progn_body {
        let mut last = Value::Undef;
        for sub in &body[1..] {
            last = eval_in_place(sub)?;
        }
        return Ok(last);
    }
    // `t` is a self-evaluating constant symbol (its value slot holds itself),
    // represented as `Value::Bool(true)`, which `compile_top` would lower to
    // the integer 1.
    if matches!(form, Value::Bool(true)) {
        return Ok(form.clone());
    }
    let expanded = macroexpand_all_for_eval(form)?;
    let chunk = with_host(|h| crate::compiler::compile_top(h, &expanded))?;
    run_chunk(chunk)
}

/// The printed source of a closure the `eval` walk built, settled when the
/// closure is made — cconv.el `cconv-make-interpreted-closure`, which eval.c
/// `Ffunction` calls with the lambda's body as written:
///
/// - with no lexical variable in scope (or under dynamic binding, where
///   `Ffunction` does not call it at all) the body is kept as written:
///   `(eval '(lambda () (push 1 z)) t)` is `#[nil ((push 1 z)) (t)]`;
/// - otherwise the body becomes its `macroexpand-all`, and an expander's error
///   is signalled here, at closure creation:
///   `(eval '(let ((y 1)) (lambda (x) (when x y))) t)` is
///   `#[(x) ((if x (progn y))) ((y . 1))]`.
///
/// The compiled body is the `eval` walk's in both cases; only the source a
/// closure prints (and compares by, under `equal`) is chosen here.
fn eval_closure_source(clo: &Value) -> Result<(), String> {
    let Some((arglist, raw, has_lexvars)) = with_host(|h| match h.obj(clo) {
        Some(Obj::Closure { src, dynamic, .. }) => {
            let raw = src.raw_body.clone()?;
            Some((
                src.arglist.clone(),
                raw,
                !*dynamic && h.lex.as_ref().is_some_and(|s| s.has_bindings()),
            ))
        }
        _ => None,
    }) else {
        return Ok(());
    };
    let body = if has_lexvars {
        let (form, env) = with_host(|h| {
            let mut lam = vec![h.intern("lambda"), arglist.clone()];
            lam.extend(raw.iter().cloned());
            let lam = h.list_from(lam);
            let function = h.intern("function");
            let env_sym = h.intern("macroexpand-all-environment");
            let env = h.get_value(&env_sym).unwrap_or(Value::Undef);
            (h.list_from(vec![function, lam]), env)
        });
        let expanded = macroexpand_all_builtin(&form, &env)?;
        // `(pcase expanded-form (`#'(lambda ,_args ,_iform . ,newbody) newbody)
        // (_ body))` — Emacs's pattern also binds the interactive form slot,
        // which elisprs keeps inside the body.
        with_host(|h| {
            let lam = h.list_vec(&expanded).and_then(|v| v.get(1).cloned());
            match lam.and_then(|l| h.list_vec(&l)) {
                Some(parts) if parts.len() >= 2 => parts[2..].to_vec(),
                _ => raw.clone(),
            }
        })
    } else {
        raw
    };
    with_host(|h| {
        let new_src = Rc::new(ClosureSrc {
            arglist,
            body: if body.is_empty() {
                vec![Value::Undef]
            } else {
                body
            },
            raw_body: None,
        });
        // cconv-fv runs on the EXPANDED form, so the captures are recomputed
        // from it: `(let ((y 2)) (lambda () (add-to-list 'y 3)))` closes over
        // y only once the compiler macro has turned the call into `(setq y ...)`.
        let new_env = has_lexvars.then(|| h.trim_lex(u32::MAX, &new_src));
        if let Value::Obj(id) = clo {
            if let Some(Obj::Closure { src, env, .. }) = h.arena.get_mut(*id as usize) {
                *src = new_src;
                if let Some(e) = new_env {
                    *env = e;
                }
            }
        }
    });
    Ok(())
}

/// Wide extension handler — for ops with a usize payload (LETBIND/UNBIND counts).
pub fn ext_dispatch_wide(vm: &mut VM, id: u16, n: usize) {
    match id {
        ops::LETBIND => {
            // stack: val1,sym1,...,valn,symn  (symn on top). Inits were evaluated
            // in the outer scope; now open a fresh scope and bind them in parallel.
            let mut pairs = Vec::with_capacity(n);
            for _ in 0..n {
                let sym = vm.pop();
                let val = vm.pop();
                pairs.push((sym, val));
            }
            pairs.reverse();
            // A constant in binding position is rejected here rather than at
            // compile time: the inits have already run, which is Emacs's order,
            // and the signal stays inside any enclosing `condition-case`. No
            // scope is opened on the failing path, so nothing needs unwinding.
            let rejected = with_host(|h| {
                pairs
                    .iter()
                    .find_map(|(sym, _)| h.check_settable(sym).err())
            });
            match rejected {
                Some(e) => abort(vm, e),
                None => with_host(|h| {
                    h.open_scope();
                    for (sym, val) in pairs {
                        h.bind_value(&sym, val);
                    }
                }),
            }
        }
        ops::UNBIND => {
            let _ = n;
            with_host(|h| h.close_scope());
        }
        _ => {}
    }
}

/// Abort the running chunk: record the error and halt the VM immediately (so
/// code after a failing/throwing call does not run). The loop guard
/// `ip < ops.len()` makes this safe.
fn abort(vm: &mut VM, e: String) {
    with_host(|h| h.error = Some(e));
    vm.ip = vm.chunk.ops.len();
}

/// Emacs `most-positive-fixnum` (2^61-1) and `most-negative-fixnum` (-2^61).
/// An integer outside this range is a bignum, even though it still fits an
/// `i64` — matching Emacs, where the two low bits are the type tag.
pub const MOST_POSITIVE_FIXNUM: i64 = 2305843009213693951;
/// See [`MOST_POSITIVE_FIXNUM`].
pub const MOST_NEGATIVE_FIXNUM: i64 = -2305843009213693952;

/// An elisp number in the one place elisp arithmetic has to be exact: an integer
/// is arbitrary-precision, a float is an `f64`. Mixed arithmetic is
/// float-contagious, as in Emacs.
pub enum Num {
    Int(BigInt),
    Float(f64),
}

impl Num {
    pub fn to_f64(&self) -> f64 {
        match self {
            Num::Int(i) => bigint_to_f64(i),
            Num::Float(f) => *f,
        }
    }
}

/// Order two elisp numbers the way Emacs's `arithcompare` (data.c) does: on
/// their *exact* values, never on `f64` images of them.
///
/// The mixed integer/float case is the one that matters. An `f64` has 53 bits of
/// mantissa, so converting a larger integer to compare it rounds — and the
/// rounded image is a *different number*. Measured against `emacs --batch` (GNU
/// Emacs 30.2), with `L` = `(expt 3 34)` = 16677181699666569 (a fixnum:
/// `most-positive-fixnum` is 2^61-1) and `F` = `(float L)` = 16677181699666568.0:
///
/// ```text
/// (= L F) => nil   (< L F) => nil   (> L F) => t
/// (= F L) => nil   (< F L) => t     (> F L) => nil
/// ```
///
/// Emacs answers on the exact values, so the integer is the larger. This is
/// Emacs's own rule, not the JVM languages' (Java/Scala/Groovy promote the
/// integer to `double` and accept the rounded answer) and not Go's (which
/// rejects the mixed pair outright).
///
/// A float is a dyadic rational, so it is exactly comparable to an integer of
/// any size: truncating it loses nothing, and its fractional part breaks a tie
/// on equal integer parts.
///
/// `None` means "incomparable" — a NaN operand, for which every elisp comparison
/// is false and `/=` is true.
pub fn num_cmp(a: &Num, b: &Num) -> Option<std::cmp::Ordering> {
    match (a, b) {
        (Num::Int(x), Num::Int(y)) => Some(x.cmp(y)),
        (Num::Int(x), Num::Float(y)) => cmp_int_f64(x, *y),
        (Num::Float(x), Num::Int(y)) => cmp_int_f64(y, *x).map(std::cmp::Ordering::reverse),
        (Num::Float(x), Num::Float(y)) => x.partial_cmp(y),
    }
}

/// Exact ordering of the integer `x` against the float `y`, `None` for a NaN.
/// An infinite `y` is beyond every integer, so it decides on its own.
fn cmp_int_f64(x: &BigInt, y: f64) -> Option<std::cmp::Ordering> {
    use num_traits::FromPrimitive;
    use std::cmp::Ordering;
    if y.is_nan() {
        return None;
    }
    if y == f64::INFINITY {
        return Some(Ordering::Less);
    }
    if y == f64::NEG_INFINITY {
        return Some(Ordering::Greater);
    }
    // `y` is finite, so `from_f64` — which truncates toward zero — is exact and
    // cannot fail.
    let t = y.trunc();
    let ti = BigInt::from_f64(t)?;
    Some(match x.cmp(&ti) {
        // Equal integer parts: the float's fraction decides. `y` above its own
        // truncation means `y` is the larger, so `x` is the smaller.
        Ordering::Equal => t.partial_cmp(&y)?,
        o => o,
    })
}

/// `BigInt` → `f64`, the conversion Emacs does when an integer meets a float.
/// Saturates to ±inf beyond `f64` range, which is what Emacs's `(float (expt 10
/// 400))` yields.
pub fn bigint_to_f64(i: &BigInt) -> f64 {
    use num_traits::ToPrimitive;
    i.to_f64()
        .unwrap_or(if i.sign() == num_bigint::Sign::Minus {
            f64::NEG_INFINITY
        } else {
            f64::INFINITY
        })
}

/// elisp's numeric semantics, installed into fusevm as a [`fusevm::NumericHook`].
///
/// fusevm's arithmetic ops are awk-flavoured by default — a non-numeric operand
/// coerces (`"a"` → `0.0`) and integer overflow wraps — and the compiler lowers
/// `+`/`-`/`*`/`1+`/`1-` and the numeric comparisons straight to them
/// (`compiler.rs`, `try_native_op`), which is what makes elisp arithmetic
/// JIT-compilable. Strict mode keeps that lowering and hands back only the cases
/// fusevm cannot compute natively:
///
/// - a non-number (string, cons, symbol, `t`, `nil`): Emacs signals
///   `(wrong-type-argument number-or-marker-p X)` — except for a marker, which is
///   its buffer position;
/// - a bignum operand, which rides through the VM as a `Value::Obj` handle;
/// - an integer result that overflowed `i64` *or* left elisp's fixnum range:
///   Emacs's integers are unbounded, so it becomes a bignum.
/// - a *comparison* of an integer with a float where reading the integer as an
///   `f64` would round it (`|int| > 2^53`). fusevm answers such a pair natively
///   up to and including 0.17.0 — on the rounded images, which is the wrong
///   answer for elisp — and delegates it from the release after 0.17.0, because
///   only the host knows its language's rule. Emacs's rule is exact comparison
///   (see [`num_cmp`]), so this hook answers on exact values.
///
/// Everything else — fixnum arithmetic in range, all float arithmetic, and every
/// comparison an `f64` can represent without rounding — never reaches here and
/// stays on the VM's (and the JIT's) fast path. The compiler only ever lowers
/// `+`/`-`/`*`/`1+`/`1-`/`(- X)` and the six comparisons to VM ops
/// (`compiler.rs`, `try_native_op`), so `Div`, `Pow` and `Mod` do not arrive
/// from compiled elisp at all.
pub(crate) fn numeric_hook(op: NumOp, a: &Value, b: &Value) -> Result<Value, String> {
    with_host(|h| {
        // `(+ 1 (point-marker))` — a marker is a number in arithmetic position.
        let coerce = |h: &ElispHost, v: &Value| -> Option<Num> {
            match v {
                Value::Int(n) => Some(Num::Int(BigInt::from(*n))),
                Value::Float(f) => Some(Num::Float(*f)),
                Value::Obj(_) => match h.obj(v) {
                    Some(Obj::Bignum(b)) => Some(Num::Int(b.clone())),
                    _ => h.marker_position(v).map(|p| Num::Int(BigInt::from(p))),
                },
                _ => None,
            }
        };
        let unary = matches!(op, NumOp::Neg);
        let an = coerce(h, a).ok_or_else(|| {
            format!(
                "wrong-type-argument: number-or-marker-p {}",
                h.print(a, true)
            )
        })?;
        let bn = if unary {
            Num::Int(BigInt::from(0))
        } else {
            coerce(h, b).ok_or_else(|| {
                format!(
                    "wrong-type-argument: number-or-marker-p {}",
                    h.print(b, true)
                )
            })?
        };
        h.apply_num_op(op, an, bn)
    })
}

/// Install the elisp execution contract on a VM: the extension dispatchers, the
/// strict numeric hook, the fixnum range and the tracing JIT.
///
/// `VM::reset` preserves every one of these, so a pooled VM is configured once
/// and reused.
fn configure_vm(vm: &mut VM) {
    vm.set_extension_handler(Box::new(ext_dispatch));
    vm.set_extension_wide_handler(Box::new(ext_dispatch_wide));
    // elisp is not awk: arithmetic signals on a non-number and promotes past
    // fixnum range instead of coercing and wrapping. The hook is what the VM
    // (and its JIT) call for the cases they cannot compute natively.
    vm.set_numeric_hook(std::sync::Arc::new(numeric_hook));
    vm.set_fixnum_range(MOST_NEGATIVE_FIXNUM, MOST_POSITIVE_FIXNUM);
    // Hot loops trace-compile through fusevm's Cranelift JIT; with the
    // `jit-disk-cache` feature, compiled native code is persisted across runs.
    // Under the DAP debugger the JIT is disabled so every `DBG_LINE` statement
    // marker fires through the interpreter (a JIT-compiled trace would elide the
    // extension-op callback and the debugger could never pause).
    if !debug_mode() {
        vm.enable_tracing_jit();
    }
}

/// Read a finished VM's outcome as an elisp result.
fn vm_outcome(vm: &VM, outcome: VMResult) -> Result<Value, String> {
    if let Some(e) = with_host(|h| h.take_error()) {
        return Err(e);
    }
    match outcome {
        VMResult::Ok(v) => Ok(v),
        VMResult::Halted => Ok(vm.stack.last().cloned().unwrap_or(Value::Undef)),
        VMResult::Error(e) => Err(e),
    }
}

/// Run a compiled chunk on a fresh fusevm VM, returning the elisp result.
///
/// Top-level entry point (one call per file / `eval` form). A CLOSURE body goes
/// through [`run_body`] instead, which pools its VM.
pub fn run_chunk(chunk: Chunk) -> Result<Value, String> {
    with_host(|h| h.error = None);
    let mut vm = VM::new(chunk);
    configure_vm(&mut vm);
    let outcome = vm.run();
    vm_outcome(&vm, outcome)
}

/// A closure body's pooled VMs, plus the `Rc` that owns the chunk they hold.
///
/// Keeping the `Rc` alive is what makes the key sound: the key is the `Rc`'s
/// address, and an address can only be handed to a second chunk after the first
/// is freed.
struct VmPoolEntry {
    _chunk: Rc<Chunk>,
    /// Boxed so the pooled VM never travels through a stack frame. A `VM` is a
    /// large struct (stack, frames, globals, JIT state), and elisp call frames
    /// nest one native frame per Lisp frame — holding an unboxed one on the
    /// frame alongside the live one cost enough stack to overflow a 2 MiB test
    /// thread (`cargo test --test eval` aborted with "has overflowed its
    /// stack"). `clippy::vec_box` reads the `Box` as redundant indirection,
    /// which it would be if the element never left the `Vec`; here it is what
    /// keeps the element off the call frame.
    #[allow(clippy::vec_box)]
    vms: Vec<Box<VM>>,
}

thread_local! {
    /// Pooled VMs keyed by closure body.
    ///
    /// `VM::new` allocates a JIT compiler, a 256-value stack, a frame vector and
    /// a globals vector, and the caller used to hand it a fresh DEEP COPY of the
    /// body `Chunk` — `ops`, `constants`, `lines`, and one `String` per entry in
    /// `names` — on EVERY elisp call. Profiling a 200 000-call loop
    /// (`sample`, macOS, debug build) put `_platform_memmove` at 141 of the
    /// interpreter thread's 978 samples, second only to `VM::exec_op` at 177.
    ///
    /// Keying by chunk is what removes the copy: a pooled VM already holds the
    /// chunk it ran last time, so [`run_body`] takes it back OUT of the VM
    /// (`std::mem::take`) and hands the same value to `VM::reset`. Nothing is
    /// cloned on a warm call, and the VM's JIT state — traces compiled for that
    /// exact chunk — survives with it.
    #[allow(clippy::type_complexity)]
    static VM_POOL: RefCell<HashMap<usize, VmPoolEntry, BuildPtrHasher>> =
        RefCell::new(HashMap::default());
}

/// A hasher for keys that are already well-distributed machine words (here, a
/// chunk's address). `HashMap`'s default SipHash is built to resist adversarial
/// keys, which a pointer this map never sees; on the call path it was pure
/// overhead. This is Fibonacci hashing — one multiply, no state.
#[derive(Default, Clone, Copy)]
pub struct PtrHasher(u64);

impl std::hash::Hasher for PtrHasher {
    fn finish(&self) -> u64 {
        self.0
    }
    fn write(&mut self, bytes: &[u8]) {
        for b in bytes {
            self.write_u64(u64::from(*b));
        }
    }
    fn write_usize(&mut self, n: usize) {
        self.write_u64(n as u64);
    }
    fn write_u64(&mut self, n: u64) {
        self.0 = (self.0 ^ n).wrapping_mul(0x9E37_79B9_7F4A_7C15);
    }
}

type BuildPtrHasher = std::hash::BuildHasherDefault<PtrHasher>;

/// Most VMs kept per chunk. Recursion needs one live VM per frame; past this
/// depth the extra VMs are dropped rather than held for the process's lifetime.
const VM_POOL_PER_CHUNK: usize = 16;

/// Run a closure body, reusing a pooled VM for that exact body when one is free.
///
/// Re-entrant: a recursive call finds the pool empty and builds its own VM, so
/// the pool holds at most one VM per live frame of that body.
pub fn run_body(body: &Rc<Chunk>) -> Result<Value, String> {
    with_host(|h| h.error = None);
    let key = Rc::as_ptr(body) as usize;
    let pooled = VM_POOL.with(|p| p.borrow_mut().get_mut(&key).and_then(|e| e.vms.pop()));
    let mut vm: Box<VM> = match pooled {
        Some(mut vm) => {
            // The VM already holds this chunk: move it out and straight back in,
            // so `reset` clears the run state without copying the program.
            let chunk = std::mem::take(&mut vm.chunk);
            vm.reset(chunk);
            vm
        }
        None => {
            let mut vm = Box::new(VM::new((**body).clone()));
            configure_vm(&mut vm);
            vm
        }
    };
    let outcome = vm.run();
    let result = vm_outcome(&vm, outcome);
    VM_POOL.with(|p| {
        let mut pool = p.borrow_mut();
        let entry = pool.entry(key).or_insert_with(|| VmPoolEntry {
            _chunk: Rc::clone(body),
            vms: Vec::new(),
        });
        if entry.vms.len() < VM_POOL_PER_CHUNK {
            entry.vms.push(vm);
        }
    });
    result
}

/// Drop every pooled VM. Called from `reset_host`: the pooled VMs hold chunks
/// whose constants are arena handles into the host being replaced.
pub fn clear_vm_pool() {
    VM_POOL.with(|p| p.borrow_mut().clear());
}

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

    /// `(expt 3 34)`: a fixnum (`most-positive-fixnum` is 2^61-1) far enough past
    /// 2^53 that its `f64` image is a *different* integer.
    const L: i64 = 16_677_181_699_666_569;
    /// `(float (expt 3 34))` — one less than `L`.
    const F: f64 = 16_677_181_699_666_568.0;

    fn hook(op: NumOp, a: Value, b: Value) -> Value {
        reset_host();
        numeric_hook(op, &a, &b).expect("numeric hook")
    }

    fn truthy(v: &Value) -> bool {
        matches!(v, Value::Bool(true))
    }

    /// The rounding the whole fix is about: `L` and `F` are different numbers
    /// that share an `f64` image, so any comparison routed through `f64` must
    /// call them equal.
    #[test]
    fn the_f64_image_of_l_is_not_l() {
        assert_eq!(L as f64, F);
        assert_ne!(L, F as i64);
        assert_eq!(F as i64, L - 1);
    }

    /// The hook compares a mixed integer/float pair on exact values, in both
    /// operand orders. Ground truth (`emacs --batch`, GNU Emacs 30.2), with
    /// `L` = `(expt 3 34)` and `F` = `(float L)`:
    ///
    /// ```text
    /// (=  L F) => nil   (/= L F) => t     (<  L F) => nil
    /// (>  L F) => t     (<= L F) => nil   (>= L F) => t
    /// (=  F L) => nil   (/= F L) => t     (<  F L) => t
    /// (>  F L) => nil   (<= F L) => t     (>= F L) => nil
    /// ```
    ///
    /// fusevm answers this pair natively through 0.17.0 — on the rounded images,
    /// so `=` came out `t` — and delegates it here from the next release, which
    /// is why the hook is exercised directly rather than through `run_chunk`.
    #[test]
    fn hook_compares_int_against_float_exactly() {
        // Integer first: L is the larger.
        for (op, want) in [
            (NumOp::Eq, false),
            (NumOp::Ne, true),
            (NumOp::Lt, false),
            (NumOp::Gt, true),
            (NumOp::Le, false),
            (NumOp::Ge, true),
        ] {
            let got = hook(op, Value::Int(L), Value::Float(F));
            assert_eq!(truthy(&got), want, "({op:?} L F) => {got:?}");
        }
        // Float first: the mirrored answers.
        for (op, want) in [
            (NumOp::Eq, false),
            (NumOp::Ne, true),
            (NumOp::Lt, true),
            (NumOp::Gt, false),
            (NumOp::Le, true),
            (NumOp::Ge, false),
        ] {
            let got = hook(op, Value::Float(F), Value::Int(L));
            assert_eq!(truthy(&got), want, "({op:?} F L) => {got:?}");
        }
    }

    /// Exactness must not cost the ordinary answers: a float that *is* the
    /// integer still compares equal, and a fractional float still orders.
    /// Ground truth: `(= 1 1.0)` => t, `(< 1 1.5)` => t, `(> 2 1.5)` => t,
    /// `(= 0 -0.0)` => t, `(= (expt 2 53) (float (expt 2 53)))` => t,
    /// `(> (1+ (expt 2 53)) (float (expt 2 53)))` => t.
    #[test]
    fn hook_keeps_the_representable_answers() {
        assert!(truthy(&hook(NumOp::Eq, Value::Int(1), Value::Float(1.0))));
        assert!(truthy(&hook(NumOp::Lt, Value::Int(1), Value::Float(1.5))));
        assert!(truthy(&hook(NumOp::Gt, Value::Int(2), Value::Float(1.5))));
        assert!(truthy(&hook(NumOp::Eq, Value::Int(0), Value::Float(-0.0))));
        let two53 = 1i64 << 53;
        let two53f = two53 as f64;
        assert!(truthy(&hook(
            NumOp::Eq,
            Value::Int(two53),
            Value::Float(two53f)
        )));
        assert!(truthy(&hook(
            NumOp::Gt,
            Value::Int(two53 + 1),
            Value::Float(two53f)
        )));
    }

    /// An infinity is beyond every integer and a NaN is incomparable, both ways
    /// round. Ground truth: `(< L 1.0e+INF)` => t, `(> L -1.0e+INF)` => t,
    /// and against `0.0e+NaN` every comparison is nil while `/=` is t.
    #[test]
    fn hook_handles_infinities_and_nan() {
        assert!(truthy(&hook(
            NumOp::Lt,
            Value::Int(L),
            Value::Float(f64::INFINITY)
        )));
        assert!(truthy(&hook(
            NumOp::Gt,
            Value::Int(L),
            Value::Float(f64::NEG_INFINITY)
        )));
        for op in [NumOp::Eq, NumOp::Lt, NumOp::Gt, NumOp::Le, NumOp::Ge] {
            assert!(!truthy(&hook(op, Value::Int(L), Value::Float(f64::NAN))));
            assert!(!truthy(&hook(op, Value::Float(f64::NAN), Value::Int(L))));
        }
        assert!(truthy(&hook(
            NumOp::Ne,
            Value::Int(L),
            Value::Float(f64::NAN)
        )));
    }

    /// Arithmetic is *not* exact and must not become so: Emacs is
    /// float-contagious, so a mixed pair rounds the integer to `f64` first.
    /// Ground truth: `(+ L 0.0)` => 16677181699666568.0, `(* L 2.0)` =>
    /// 33354363399333136.0, `(- 0.0 L)` => -16677181699666568.0.
    #[test]
    fn hook_arithmetic_stays_float_contagious() {
        assert_eq!(
            hook(NumOp::Add, Value::Int(L), Value::Float(0.0)),
            Value::Float(16_677_181_699_666_568.0)
        );
        assert_eq!(
            hook(NumOp::Mul, Value::Int(L), Value::Float(2.0)),
            Value::Float(33_354_363_399_333_136.0)
        );
        assert_eq!(
            hook(NumOp::Sub, Value::Float(0.0), Value::Int(L)),
            Value::Float(-16_677_181_699_666_568.0)
        );
    }

    /// A bignum rides through the VM as a heap handle, so the hook sees it as
    /// `Value::Obj` — and must compare it against a float just as exactly.
    /// Ground truth, with `B` = `(expt 3 100)`: `(= B (float B))` => nil,
    /// `(> B (float B))` => t, `(< (float B) B)` => t.
    #[test]
    fn hook_compares_bignum_against_float_exactly() {
        use num_traits::One;
        reset_host();
        let (big, bigf) = with_host(|h| {
            let mut n = BigInt::one();
            for _ in 0..100 {
                n *= 3;
            }
            let f = bigint_to_f64(&n);
            (h.make_integer(n), f)
        });
        assert!(matches!(big, Value::Obj(_)), "expected a heap bignum");
        assert!(!truthy(
            &numeric_hook(NumOp::Eq, &big, &Value::Float(bigf)).unwrap()
        ));
        assert!(truthy(
            &numeric_hook(NumOp::Gt, &big, &Value::Float(bigf)).unwrap()
        ));
        assert!(truthy(
            &numeric_hook(NumOp::Lt, &Value::Float(bigf), &big).unwrap()
        ));
    }
}

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

    /// `signal_closure_wrong_nargs` binary-searches the table, so an entry out of
    /// byte order is silently never found.
    #[test]
    fn prelude_c_subr_names_are_sorted_and_unique() {
        assert!(PRELUDE_C_SUBR_NAMES.windows(2).all(|w| w[0] < w[1]));
    }
}