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
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
//! Primitive subrs, written in Rust. Per the research inventory these are the
//! ~irreducible core; the large derived surface (caar.., seq-*, cl-*, alist
//! helpers) will be defined in an elisp prelude on top of these.

use crate::host::{
    bigint_to_f64, num_cmp, CharTable, CtAscii, CtSlot, ElHashTable, ElispHost, MatchData, Num,
    Obj, Resolved,
};
use fusevm::Value;
use num_bigint::BigInt;
use num_traits::ToPrimitive;
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;

type R = Result<Value, String>;

fn nil_or(b: bool) -> Value {
    if b {
        Value::Bool(true)
    } else {
        Value::Undef
    }
}
fn is_nil(v: &Value) -> bool {
    matches!(v, Value::Undef | Value::Bool(false))
}

// ── numeric helpers ──
/// Approximate numeric accessor: `(fixnum, as-f64, is-float)`.
///
/// Kept for the float-valued builtins (`sqrt`, `sin`, `log`, `ffloor`, the `%e`/
/// `%f`/`%g` format directives …), which read only the `f64`. Anything whose
/// result must be *exact* — arithmetic, comparison, the bit ops — uses
/// [`as_number`] instead: a bignum cannot fit the `i64` field, and above 2^53 the
/// `f64` field is lossy.
fn as_num(h: &ElispHost, v: &Value) -> Result<(i64, f64, bool), String> {
    match v {
        Value::Int(n) => Ok((*n, *n as f64, false)),
        Value::Float(f) => Ok((*f as i64, *f, true)),
        _ => {
            // A bignum is exact only in `f64` here — every caller of this
            // accessor produces a float anyway.
            if let Some(b) = h.as_bigint(v) {
                let f = bigint_to_f64(&b);
                return Ok((f as i64, f, false));
            }
            // A marker coerces to its (integer) buffer position in arithmetic.
            match h.marker_position(v) {
                Some(p) => Ok((p as i64, p as f64, false)),
                None => Err(format!(
                    "wrong-type-argument: number-or-marker-p {}",
                    h.print(v, true)
                )),
            }
        }
    }
}
fn as_int(h: &ElispHost, v: &Value) -> Result<i64, String> {
    match v {
        Value::Int(n) => Ok(*n),
        Value::Float(f) => Ok(*f as i64),
        _ => match h.marker_position(v) {
            Some(p) => Ok(p as i64),
            None => Err(format!(
                "wrong-type-argument: integerp {}",
                h.print(v, true)
            )),
        },
    }
}
/// The string value of `v`, or Emacs's `(wrong-type-argument stringp X)` — with
/// X printed as `prin1` would, never as the raw heap handle the value carries.
fn as_string(h: &ElispHost, v: &Value) -> Result<String, String> {
    match h.str_text(v) {
        Some(s) => Ok(s.to_string()),
        None => Err(format!("wrong-type-argument: stringp {}", h.print(v, true))),
    }
}
/// Strict integer accessor signalling `integerp` (for `ash`/`lsh`/`lognot`/`logcount`).
fn as_integer(h: &ElispHost, v: &Value) -> Result<i64, String> {
    match v {
        Value::Int(n) => Ok(*n),
        _ => Err(format!(
            "wrong-type-argument: integerp {}",
            h.print(v, true)
        )),
    }
}
/// Emacs `most-positive-fixnum` (2^61-1). Integers above this are bignums in
/// Emacs, and the fixed-size allocators (`make-vector`, `make-string`,
/// `make-record`) reject a bignum length as a non-wholenum.
const MOST_POSITIVE_FIXNUM: i64 = 2305843009213693951;
/// Rendered form of `Vmemory_signal_data`: the plain `error` Emacs signals when
/// an allocation request cannot be satisfied. `make_error_object` splits this
/// into `(error "Memory exhausted--use C-x s then exit and restart Emacs")`.
const MEMORY_EXHAUSTED: &str = "error: Memory exhausted--use C-x s then exit and restart Emacs";

/// [`check_array_len`] on an elisp value: a bignum length is out of fixnum range
/// by construction, so it is the `wholenump` rejection rather than a type error.
fn check_array_len_val(h: &ElispHost, v: &Value) -> Result<usize, String> {
    if h.is_bignum(v) {
        return Err(format!(
            "wrong-type-argument: wholenump {}",
            h.print(v, true)
        ));
    }
    check_array_len(as_num(h, v)?.0)
}

/// `CHECK_FIXNAT (V)`: V must be an integer in `[0, most-positive-fixnum]`, and
/// anything else — a negative fixnum, a float, a bignum, a string, nil — is
/// `wrong-type-argument wholenump V` naming the value itself.
///
/// [`check_array_len_val`] is the same test for a caller that goes on to
/// ALLOCATE the length; this one is for a caller that only counts with it.
fn check_fixnat(h: &ElispHost, v: &Value) -> Result<i64, String> {
    match v {
        Value::Int(n) if (0..=MOST_POSITIVE_FIXNUM).contains(n) => Ok(*n),
        _ => Err(format!(
            "wrong-type-argument: wholenump {}",
            h.print(v, true)
        )),
    }
}

/// Validate a requested array/string length the way Emacs's `CHECK_FIXNAT`
/// does: a negative value or one above `most-positive-fixnum` (a bignum) is not
/// a wholenum, so signal `wrong-type-argument wholenump N` rather than
/// attempting an allocation that would panic or abort the process.
fn check_array_len(n: i64) -> Result<usize, String> {
    if !(0..=MOST_POSITIVE_FIXNUM).contains(&n) {
        return Err(format!("wrong-type-argument: wholenump {n}"));
    }
    Ok(n as usize)
}

/// Character-code accessor: a valid character is an integer in [0, #x3FFFFF];
/// anything else signals `wrong-type-argument characterp VALUE` (a negative code
/// or one past the upper bound, as `char-to-string`/`make-string` do).
/// `CHECK_FIXNUM` under a caller-chosen predicate name: a float, a bignum, a
/// marker and a string are all rejected. `forward-char`/`backward-char` name
/// `fixnump`, where the shared `as_int` accessor would have said `integerp`.
fn as_fixnum_named(h: &mut ElispHost, v: &Value, pred: &str) -> Result<i64, String> {
    match v {
        Value::Int(n) => Ok(*n),
        _ => Err(h.signal_wrong_type(pred, v)),
    }
}

/// `CHECK_FIXNUM_COERCE_MARKER` under a caller-chosen predicate name: a fixnum
/// or a marker (which contributes its position), never a float or a bignum.
fn as_int_or_marker(h: &mut ElispHost, v: &Value, pred: &str) -> Result<i64, String> {
    match v {
        Value::Int(n) => Ok(*n),
        _ => match h.marker_position(v) {
            Some(p) => Ok(p as i64),
            None => Err(h.signal_wrong_type(pred, v)),
        },
    }
}

fn as_char(h: &mut ElispHost, v: &Value) -> Result<u32, String> {
    match v {
        Value::Int(n) if (0..=0x3F_FFFF).contains(n) => Ok(*n as u32),
        _ => Err(h.signal_wrong_type("characterp", v)),
    }
}

/// The exact value of an elisp number: an integer of any size, or a float.
///
/// This is the accessor every builtin whose result must be *exact* uses —
/// `+`, `*`, `-`, `/`, `expt`, `abs`, the comparisons. `as_num`'s `(i64, f64,
/// bool)` triple cannot represent a bignum, and comparing large integers as
/// `f64` (which it forces) calls 2^62 and 2^62+1 equal.
///
/// A marker coerces to its buffer position, as in Emacs. Anything that is not a
/// number signals with Emacs's predicate and its `prin1` form (never the raw
/// heap handle).
fn as_number(h: &ElispHost, v: &Value) -> Result<Num, String> {
    as_number_p(h, v, true)
}

/// [`as_number`], but choosing Emacs's predicate for the calling builtin.
///
/// `markers_ok` distinguishes the two families: the arithmetic ops accept a
/// marker (as its buffer position) and signal `number-or-marker-p`, while
/// `abs`/`floor`/`ceiling`/`round`/`truncate`/`float`/`expt`/`sqrt`/
/// `number-to-string` take strictly a number and signal `numberp`.
fn as_number_p(h: &ElispHost, v: &Value, markers_ok: bool) -> Result<Num, String> {
    match v {
        Value::Int(n) => Ok(Num::Int(BigInt::from(*n))),
        Value::Float(f) => Ok(Num::Float(*f)),
        _ => {
            if let Some(b) = h.as_bigint(v) {
                return Ok(Num::Int(b));
            }
            if markers_ok {
                if let Some(p) = h.marker_position(v) {
                    return Ok(Num::Int(BigInt::from(p)));
                }
            }
            Err(format!(
                "wrong-type-argument: {} {}",
                if markers_ok {
                    "number-or-marker-p"
                } else {
                    "numberp"
                },
                h.print(v, true)
            ))
        }
    }
}

/// Fold an n-ary exact arithmetic op (`+`, `*`, `-`) over its arguments.
/// Integer arithmetic stays exact and promotes to a bignum; a single float
/// operand makes the whole result a float, as in Emacs.
fn fold_arith(
    h: &mut ElispHost,
    a: &[Value],
    init: i64,
    int_op: fn(BigInt, BigInt) -> BigInt,
    float_op: fn(f64, f64) -> f64,
) -> R {
    // Seed from the FIRST argument, not from the identity — that is what Emacs's
    // `arith_driver' does, and it is observable on signed zero: `(+ -0.0)' is
    // -0.0 because the lone argument is returned (type-checked) rather than
    // added to 0, while `(+ -0.0 0)' really does add and gives 0.0. Only an
    // empty argument list falls back to the identity.
    let mut acc = match a.first() {
        Some(v) => as_number(h, v)?,
        None => Num::Int(BigInt::from(init)),
    };
    for v in a.iter().skip(1) {
        let n = as_number(h, v)?;
        acc = match (acc, n) {
            (Num::Int(x), Num::Int(y)) => Num::Int(int_op(x, y)),
            (x, y) => Num::Float(float_op(x.to_f64(), y.to_f64())),
        };
    }
    Ok(match acc {
        Num::Int(i) => h.make_integer(i),
        Num::Float(f) => Value::Float(f),
    })
}

fn add(h: &mut ElispHost, a: &[Value]) -> R {
    fold_arith(h, a, 0, |x, y| x + y, |x, y| x + y)
}
fn mul(h: &mut ElispHost, a: &[Value]) -> R {
    fold_arith(h, a, 1, |x, y| x * y, |x, y| x * y)
}
fn sub(h: &mut ElispHost, a: &[Value]) -> R {
    if a.is_empty() {
        return Ok(Value::Int(0));
    }
    // Unary `-` negates; n-ary subtracts the rest from the first.
    if a.len() == 1 {
        return Ok(match as_number(h, &a[0])? {
            Num::Int(x) => h.make_integer(-x),
            Num::Float(f) => Value::Float(-f),
        });
    }
    let mut acc = as_number(h, &a[0])?;
    for v in &a[1..] {
        let n = as_number(h, v)?;
        acc = match (acc, n) {
            (Num::Int(x), Num::Int(y)) => Num::Int(x - y),
            (x, y) => Num::Float(x.to_f64() - y.to_f64()),
        };
    }
    Ok(match acc {
        Num::Int(i) => h.make_integer(i),
        Num::Float(f) => Value::Float(f),
    })
}
fn div(h: &mut ElispHost, a: &[Value]) -> R {
    // Integer division truncates toward zero and stays exact (a bignum quotient is
    // a bignum); the first float operand makes the rest float division.
    let first = as_number(h, &a[0])?;
    // Unary `/` is `1/x` in Emacs — `(/ 4)` is 0 (integer division), `(/ 4.0)` is
    // 0.25 — not the argument itself.
    let (mut acc, rest): (Num, &[Value]) = if a.len() == 1 {
        (Num::Int(BigInt::from(1)), &a[0..1])
    } else {
        (first, &a[1..])
    };
    // Whether a NaN was *handed to* the division rather than produced by it.
    let mut nan_operand = matches!(acc, Num::Float(f) if f.is_nan());
    for v in rest {
        let n = as_number(h, v)?;
        nan_operand |= matches!(n, Num::Float(f) if f.is_nan());
        acc = match (acc, n) {
            (Num::Int(x), Num::Int(y)) => {
                if y == BigInt::from(0) {
                    return Err("arith-error: division by zero".to_string());
                }
                Num::Int(x / y)
            }
            (x, y) => Num::Float(x.to_f64() / y.to_f64()),
        };
    }
    Ok(match acc {
        Num::Int(i) => h.make_integer(i),
        Num::Float(mut f) => {
            // A NaN the division *invents* (`(/ 0.0 0.0)`) gets a
            // hardware-dependent sign: x86-64 yields a sign-negative NaN, ARM a
            // positive one. Emacs inherits that difference from the C division;
            // canonicalizing to positive keeps elisprs's output the same on both.
            //
            // A NaN that merely *passed through* is a different matter: IEEE
            // propagates an operand NaN unchanged on every ISA, so `(/ -0.0e+NaN
            // -1)' is -0.0e+NaN in Emacs everywhere. Flattening that one too made
            // the sign of an existing NaN unobservable through `/'.
            if f.is_nan() && !nan_operand {
                f = f.abs();
            }
            Value::Float(f)
        }
    })
}
fn modulo(h: &mut ElispHost, a: &[Value]) -> R {
    let x = as_int_exact(h, &a[0])?;
    let y = as_int_exact(h, &a[1])?;
    if y == BigInt::from(0) {
        return Err("arith-error: division by zero".to_string());
    }
    let r = x % y;
    Ok(h.make_integer(r))
}
// `mod` (vs `%`): the result takes the sign of the divisor, and either operand
// may be a float — (mod 13.5 4) => 1.5, (mod -1 3) => 2.
fn mod_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let xn = as_number(h, &a[0])?;
    let yn = as_number(h, &a[1])?;
    if matches!(xn, Num::Float(_)) || matches!(yn, Num::Float(_)) {
        let (xf, yf) = (xn.to_f64(), yn.to_f64());
        // Faithful port of Emacs `Fmod` (data.c): fmod, then fix the sign so the
        // result matches the divisor. `%` on f64 is fmod (the remainder keeps the
        // dividend's sign, so `(mod -0.0 5)` stays `-0.0`, as Emacs returns). A
        // zero float divisor yields NaN — Emacs does NOT signal arith-error for
        // float mod-by-zero (only integer mod-by-zero, handled below).
        let mut r = xf % yf;
        if if yf < 0.0 { r > 0.0 } else { r < 0.0 } {
            r += yf;
        }
        // Canonicalize only a NaN this computation invented — `(mod 5.0 0)` —
        // whose sign is hardware-dependent. An operand that was already a NaN
        // propagates unchanged on every ISA, so `(mod 0 -0.0e+NaN)' keeps its
        // sign in Emacs and must here too. Mirrors the `div` handling above.
        if r.is_nan() && !(xf.is_nan() || yf.is_nan()) {
            r = r.abs();
        }
        return Ok(Value::Float(r));
    }
    let x = as_int_exact(h, &a[0])?;
    let y = as_int_exact(h, &a[1])?;
    if y == BigInt::from(0) {
        return Err("arith-error: division by zero".to_string());
    }
    let zero = BigInt::from(0);
    let mut r = &x % &y;
    if r != zero && (r < zero) != (y < zero) {
        r += &y;
    }
    Ok(h.make_integer(r))
}
/// `(max NUM…)` / `(min NUM…)` — Emacs checks each argument in order, so the
/// error names the FIRST non-number, and both are subrs (which is what their
/// `wrong-number-of-arguments` and `#<subr min>` printing depend on).
///
/// Emacs picks the winner with `arithcompare`, so the comparison is exact
/// ([`num_cmp`]) and a mixed integer/float pair is decided on real values:
/// `(min (expt 3 34) (float (expt 3 34)))` is the *float*, because it is the
/// smaller number even though both round to the same `f64`.
/// data.c `minmax_driver`. Every argument goes through
/// `check_number_coerce_marker`, so a marker answers as its position (an
/// integer), never as the marker. A NaN that turns up AFTER the first argument
/// is returned on the spot, without type-checking the rest: `(max 1 0.0e+NaN
/// "x")` is NaN, while `(min 0.0e+NaN 'a)` still rejects `a`.
fn min_max(h: &mut ElispHost, a: &[Value], want_max: bool) -> R {
    let coerce = |h: &mut ElispHost, v: &Value| -> Result<(Num, Value), String> {
        let n = as_number(h, v)?;
        let v = match h.marker_position(v) {
            Some(p) => h.make_integer(BigInt::from(p)),
            None => v.clone(),
        };
        Ok((n, v))
    };
    let (mut best, mut best_v) = coerce(h, &a[0])?;
    for v in &a[1..] {
        let (n, v) = coerce(h, v)?;
        // `arithcompare (val, accum, comparison)`: false on a NaN pair.
        let better =
            num_cmp(&n, &best).is_some_and(|o| if want_max { o.is_gt() } else { o.is_lt() });
        if better {
            best = n;
            best_v = v;
        } else if matches!(n, Num::Float(f) if f.is_nan()) {
            return Ok(v);
        }
    }
    Ok(best_v)
}
fn max_fn(h: &mut ElispHost, a: &[Value]) -> R {
    min_max(h, a, true)
}
fn min_fn(h: &mut ElispHost, a: &[Value]) -> R {
    min_max(h, a, false)
}

fn one_plus(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(match as_number(h, &a[0])? {
        Num::Int(i) => h.make_integer(i + 1),
        Num::Float(f) => Value::Float(f + 1.0),
    })
}
fn one_minus(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(match as_number(h, &a[0])? {
        Num::Int(i) => h.make_integer(i - 1),
        Num::Float(f) => Value::Float(f - 1.0),
    })
}

/// Compare adjacent arguments with `pred`.
///
/// Every pair compares *exactly*, never through `f64` — see [`num_cmp`]. At 2^53
/// an `f64` runs out of mantissa, so a float-only comparison answered `t` to
/// `(= 2305843009213693950 2305843009213693951)` and, for a mixed integer/float
/// pair, `t` to `(= (expt 3 34) (float (expt 3 34)))` where Emacs answers nil.
fn cmp(h: &ElispHost, a: &[Value], pred: fn(std::cmp::Ordering) -> bool, nan_val: bool) -> R {
    for w in a.windows(2) {
        let (x, y) = (as_number(h, &w[0])?, as_number(h, &w[1])?);
        let ord = match num_cmp(&x, &y) {
            Some(o) => o,
            // A NaN operand: `=`/`<`/`>`/`<=`/`>=` are all false.
            None => {
                if nan_val {
                    continue;
                }
                return Ok(Value::Undef);
            }
        };
        if !pred(ord) {
            return Ok(Value::Undef);
        }
    }
    Ok(Value::Bool(true))
}
fn num_eq(h: &mut ElispHost, a: &[Value]) -> R {
    cmp(h, a, |o| o.is_eq(), false)
}
fn lt(h: &mut ElispHost, a: &[Value]) -> R {
    cmp(h, a, |o| o.is_lt(), false)
}
fn gt(h: &mut ElispHost, a: &[Value]) -> R {
    cmp(h, a, |o| o.is_gt(), false)
}
fn le(h: &mut ElispHost, a: &[Value]) -> R {
    cmp(h, a, |o| o.is_le(), false)
}
fn ge(h: &mut ElispHost, a: &[Value]) -> R {
    cmp(h, a, |o| o.is_ge(), false)
}

// ── equality ──
// `eq` is object identity. Fixnums and interned symbols/heap handles compare by
// value, but two distinct float *objects* are never `eq` (matching Emacs:
// `(eq 1.0 1.0)` => nil). `eql` adds by-value float comparison on top of `eq`.
pub(crate) fn el_eq(h: &ElispHost, a: &Value, b: &Value) -> bool {
    if is_nil(a) && is_nil(b) {
        return true;
    }
    match (a, b) {
        (Value::Int(x), Value::Int(y)) => x == y,
        (Value::Obj(x), Value::Obj(y)) => x == y,
        (Value::Bool(true), Value::Bool(true)) => true,
        // Strings are objects, and `eq` is object identity: two references to the
        // SAME string are `eq` even though two equal literals are not.
        // `Value::Str` is an `Arc<String>`, and every construction that Emacs
        // calls a fresh object (`copy-sequence`, `substring`, `concat`,
        // `make-string`, each literal read) allocates its own `Arc`, so pointer
        // identity IS the object identity Emacs compares. Without this
        // `(let ((s "abc")) (eq s s))` answered nil, and every identity-based
        // list op over strings — `memq`, `assq`, `delq`, `memql` — answered as
        // though the string were absent.
        //
        // The empty string keeps its own clause: Emacs shares ONE
        // `empty_unibyte_string` object (alloc.c), so every 0-length string is
        // `eq` to every other regardless of where it came from.
        (Value::Str(x), Value::Str(y)) => {
            std::sync::Arc::ptr_eq(x, y) || (x.is_empty() && y.is_empty())
        }
        _ => {
            let _ = h;
            false
        }
    }
}
fn el_eql(h: &ElispHost, a: &Value, b: &Value) -> bool {
    match (a, b) {
        (Value::Float(x), Value::Float(y)) => x.to_bits() == y.to_bits(),
        // Bignums compare by value, like every other number: Emacs's `eql` is
        // `eq` plus by-value comparison for the boxed numeric types.
        (Value::Obj(_), Value::Obj(_)) => match (h.obj(a), h.obj(b)) {
            (Some(Obj::Bignum(x)), Some(Obj::Bignum(y))) => x == y,
            _ => el_eq(h, a, b),
        },
        _ => el_eq(h, a, b),
    }
}
fn el_equal(h: &ElispHost, a: &Value, b: &Value) -> bool {
    if el_eql(h, a, b) {
        return true;
    }
    // Two strings are `equal` when their CURRENT text matches — read through
    // `str_text` so a string that `aset`/`store-substring` has rewritten
    // compares as what it now holds, not as what it was allocated with.
    if let (Some(x), Some(y)) = (h.str_text(a), h.str_text(b)) {
        return x == y;
    }
    match (a, b) {
        (Value::Obj(_), Value::Obj(_)) => match (h.obj(a), h.obj(b)) {
            (Some(Obj::Cons(a1, a2)), Some(Obj::Cons(b1, b2))) => {
                el_equal(h, a1, b1) && el_equal(h, a2, b2)
            }
            (Some(Obj::Vector(va)), Some(Obj::Vector(vb)))
            | (Some(Obj::Record(va)), Some(Obj::Record(vb))) => {
                va.len() == vb.len() && va.iter().zip(vb).all(|(x, y)| el_equal(h, x, y))
            }
            (Some(Obj::BoolVector(ba)), Some(Obj::BoolVector(bb))) => ba == bb,
            // A char-table is a pseudovector: `equal` compares every slot, a
            // sub-char-table included, as vectors.
            (Some(Obj::CharTable(ta)), Some(Obj::CharTable(tb))) => {
                el_equal(h, &ta.default, &tb.default)
                    && el_equal(h, &ta.parent, &tb.parent)
                    && el_equal(h, &ta.subtype, &tb.subtype)
                    && ta.extra.len() == tb.extra.len()
                    && ta
                        .extra
                        .iter()
                        .zip(&tb.extra)
                        .all(|(x, y)| el_equal(h, x, y))
                    && ct_slots_equal(h, &ta.contents, &tb.contents)
                    && match (&ta.ascii, &tb.ascii) {
                        (CtAscii::Val(x), CtAscii::Val(y)) => el_equal(h, x, y),
                        (CtAscii::Tree, CtAscii::Tree) => true,
                        _ => false,
                    }
            }
            // Two markers are `equal` when they share a buffer and position.
            (Some(Obj::Marker(_)), Some(Obj::Marker(_))) => h.markers_equal(a, b),
            // An interpreted closure is its `#[ARGLIST BODY ENV]` structure, and
            // `equal` descends into it: `(equal (lambda () 1) (lambda () 1))` is
            // t, `(equal (lambda (x) x) (lambda (y) y))` is nil. `remove-hook`
            // depends on it — it matches the function to drop with `member`, so
            // an anonymous hook function could not be removed without this.
            (Some(Obj::Closure { .. }), Some(Obj::Closure { .. })) => {
                match (h.closure_parts(a), h.closure_parts(b)) {
                    (Some((am, ad, aa, abody, aenv)), Some((bm, bd, ba, bbody, benv))) => {
                        am == bm
                            && ad == bd
                            && el_equal(h, &aa, &ba)
                            && abody.len() == bbody.len()
                            && abody.iter().zip(&bbody).all(|(x, y)| el_equal(h, x, y))
                            && aenv.len() == benv.len()
                            && aenv.iter().zip(&benv).all(|((s1, v1), (s2, v2))| {
                                s1 == s2
                                    && match (v1, v2) {
                                        (Some(v1), Some(v2)) => el_equal(h, v1, v2),
                                        (None, None) => true,
                                        _ => false,
                                    }
                            })
                    }
                    _ => false,
                }
            }
            _ => false,
        },
        _ => false,
    }
}
/// Slot-by-slot `equal` of two char-table (or sub-char-table) slot arrays.
fn ct_slots_equal(h: &ElispHost, a: &[CtSlot], b: &[CtSlot]) -> bool {
    a.len() == b.len()
        && a.iter().zip(b).all(|(x, y)| match (x, y) {
            (CtSlot::Val(x), CtSlot::Val(y)) => el_equal(h, x, y),
            (CtSlot::Sub(x), CtSlot::Sub(y)) => {
                x.depth == y.depth
                    && x.min_char == y.min_char
                    && ct_slots_equal(h, &x.contents, &y.contents)
            }
            _ => false,
        })
}

fn eq_fn(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(nil_or(el_eq(h, &a[0], &a[1])))
}
fn eql_fn(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(nil_or(el_eql(h, &a[0], &a[1])))
}
fn equal_fn(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(nil_or(el_equal(h, &a[0], &a[1])))
}

// ── lists ──
fn cons_fn(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(h.cons(a[0].clone(), a[1].clone()))
}
fn car(h: &mut ElispHost, a: &[Value]) -> R {
    match h.obj(&a[0]) {
        Some(Obj::Cons(x, _)) => Ok(x.clone()),
        _ if is_nil(&a[0]) => Ok(Value::Undef),
        _ => Err(format!(
            "wrong-type-argument: listp {}",
            h.print(&a[0], true)
        )),
    }
}
fn cdr(h: &mut ElispHost, a: &[Value]) -> R {
    match h.obj(&a[0]) {
        Some(Obj::Cons(_, y)) => Ok(y.clone()),
        _ if is_nil(&a[0]) => Ok(Value::Undef),
        _ => Err(format!(
            "wrong-type-argument: listp {}",
            h.print(&a[0], true)
        )),
    }
}
fn setcar(h: &mut ElispHost, a: &[Value]) -> R {
    if let Value::Obj(id) = &a[0] {
        if let Some(Obj::Cons(c, _)) = h.arena.get_mut(*id as usize) {
            *c = a[1].clone();
            return Ok(a[1].clone());
        }
    }
    Err(format!(
        "wrong-type-argument: consp {}",
        h.print(&a[0], true)
    ))
}
fn setcdr(h: &mut ElispHost, a: &[Value]) -> R {
    if let Value::Obj(id) = &a[0] {
        if let Some(Obj::Cons(_, d)) = h.arena.get_mut(*id as usize) {
            *d = a[1].clone();
            return Ok(a[1].clone());
        }
    }
    Err(format!(
        "wrong-type-argument: consp {}",
        h.print(&a[0], true)
    ))
}
fn list_fn(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(h.list_from(a.to_vec()))
}
fn append_fn(h: &mut ElispHost, a: &[Value]) -> R {
    if a.is_empty() {
        return Ok(Value::Undef);
    }
    // The final argument becomes the tail as-is (shared, any type) — so a
    // non-list last arg yields a dotted result: (append '(1 2) 3) => (1 2 . 3).
    // Every preceding argument must be a sequence and is flattened.
    let mut out = Vec::new();
    for v in &a[..a.len() - 1] {
        if is_nil(v) {
            continue;
        }
        match h.str_text(v) {
            Some(s) => out.extend(s.chars().map(|c| Value::Int(c as i64)).collect::<Vec<_>>()),
            None => match h.obj(v) {
                Some(Obj::Vector(items)) => out.extend(items.clone()),
                _ => out.extend(h.seq_vec_checked(v)?),
            },
        }
    }
    let mut tail = a[a.len() - 1].clone();
    for item in out.into_iter().rev() {
        tail = h.cons(item, tail);
    }
    Ok(tail)
}
fn reverse_fn(h: &mut ElispHost, a: &[Value]) -> R {
    // `reverse` works on any sequence: list, string, or vector.
    if let Some(s) = h.str_text(&a[0]) {
        let rev = s.chars().rev().collect::<String>();
        return Ok(h.new_string(rev));
    }
    // Reject an improper list (and a non-sequence) with Emacs's error before
    // falling through to the list path, which would otherwise silently ignore
    // the dotted tail.
    h.seq_vec_checked(&a[0])?;
    let vec_items = match h.obj(&a[0]) {
        Some(Obj::Vector(items)) => Some(items.clone()),
        _ => None,
    };
    if let Some(mut items) = vec_items {
        items.reverse();
        return Ok(h.alloc(Obj::Vector(items)));
    }
    let mut v = h
        .list_vec(&a[0])
        .ok_or_else(|| format!("wrong-type-argument: sequencep {}", h.print(&a[0], true)))?;
    v.reverse();
    Ok(h.list_from(v))
}
/// `(downcase OBJ)` / `(upcase OBJ)` — case-fold a string, or a single character
/// (an integer), returning the same kind. Unicode-aware via Rust's case mapping.
/// Single-character (simple) case mapping, matching Emacs's `upcase`/`downcase`
/// on a *character*. Rust's `char::to_uppercase`/`to_lowercase` are the Unicode
/// *full* mappings, which can expand to several chars (ß→"SS", fi→"FI"); Emacs's
/// char case folds to exactly one char. For the multi-expansion chars Emacs
/// returns the char unchanged, except this enumerated set where the simple /
/// titlecase mapping is a distinct single char (German sharp s and the Greek
/// iota-subscript forms). Verified against emacs 30.2 `upcase` over 0..#x110000.
fn simple_case(cp: i64, upper: bool) -> i64 {
    if upper {
        match cp {
            223 => return 7838,                                       // ß → ẞ
            8064..=8071 | 8080..=8087 | 8096..=8103 => return cp + 8, // ᾀ.. → ᾈ..
            8115 | 8131 | 8179 => return cp + 9,                      // ῃ ῳ ᾳ → titlecase
            _ => {}
        }
    }
    let Some(ch) = u32::try_from(cp).ok().and_then(char::from_u32) else {
        return cp;
    };
    let mut mapped: [char; 3] = ['\0'; 3];
    let mut n = 0;
    if upper {
        for m in ch.to_uppercase() {
            if n < 3 {
                mapped[n] = m;
            }
            n += 1;
        }
    } else {
        for m in ch.to_lowercase() {
            if n < 3 {
                mapped[n] = m;
            }
            n += 1;
        }
    }
    // A multi-char full mapping has no single-char simple mapping → unchanged.
    if n == 1 {
        mapped[0] as i64
    } else {
        cp
    }
}
fn case_fold(h: &mut ElispHost, a: &[Value], upper: bool) -> R {
    match &a[0] {
        // casefiddle.c: a negative fixnum is not a character (char-or-string-p),
        // but one above the character range is returned UNCHANGED — Emacs treats
        // the high bits as event modifiers, so (upcase 4194304) => 4194304.
        Value::Int(c) if *c < 0 => Err(h.signal_wrong_type("char-or-string-p", &a[0])),
        Value::Int(c) if *c > 0x3F_FFFF => Ok(Value::Int(*c)),
        Value::Int(c) => Ok(Value::Int(simple_case(*c, upper))),
        _ if h.is_string(&a[0]) => {
            // Case folding is character-for-character here, so the text
            // properties land on the same characters they were on.
            let src = h.str_arc(&a[0]).expect("checked stringp");
            let text = if upper {
                src.to_uppercase()
            } else {
                src.to_lowercase()
            };
            let same_len = text.chars().count() == src.chars().count();
            let (folded, out) = h.new_string_keyed(text);
            if same_len {
                h.string_carry_all(&out, &src);
            }
            Ok(folded)
        }
        // The datum has to travel as the *object*: a subr prints `#<subr +>` and
        // a closure `#[…]`, neither of which the reader can turn back into what
        // it came from, so rendering it into the message and re-reading it (which
        // is what the message-only path does) silently dropped it and left a bare
        // `(wrong-type-argument char-or-string-p)`.
        v => {
            let v = v.clone();
            Err(h.signal_wrong_type("char-or-string-p", &v))
        }
    }
}
/// `(--char-titlecase-- CHAR)` — the Unicode *title-case* mapping of CHAR, as a
/// string, because it is one-to-many for some characters (ß → "Ss", fi → "Fi")
/// and differs from upper case for the digraphs (dz → Dz, not DZ).
///
/// This is what `casefiddle.c` reaches for at a word start: `case_character_impl`
/// consults `special-titlecase` first, then the `titlecase` char-table, and only
/// then falls back to `upcase`. Not an Emacs function — `capitalize` and
/// `upcase-initials` in the prelude are its only callers.
fn char_titlecase(h: &mut ElispHost, a: &[Value]) -> R {
    match &a[0] {
        Value::Int(c) if (0..=0x3F_FFFF).contains(c) => match char::from_u32(*c as u32) {
            Some(ch) => Ok(h.new_string(titlecase_str(ch))),
            // A code point with no scalar value (a surrogate) has no case.
            None => Ok(h.new_string(String::new())),
        },
        v => Err(format!(
            "wrong-type-argument: characterp {}",
            h.print(v, true)
        )),
    }
}

/// The Unicode title-case mapping of `ch`, as a string.
///
/// `char::to_titlecase` is unstable, so this derives the same answer from the
/// stable uppercase mapping plus the two closed sets where title case is not
/// "upper-case the first, lower-case the rest":
///
/// * the four Latin digraph triples, whose title form is the *middle* code
///   point of the triple (dz/DZ title to Dz, not to DZ);
/// * Greek letters with ypogegrammeni, whose full uppercase is two characters
///   (ᾀ → "ἈΙ") but whose title case is the single precomposed capital
///   (ᾀ → ᾈ), laid out one block of eight below its lowercase run.
///
/// Everywhere else the rule holds exactly: ß → "SS" → "Ss", fi → "FI" → "Fi",
/// ffi → "FFI" → "Ffi". `titlecase_char_only` is the same mapping restricted to
/// the one-to-one cases, which is what a *character* argument gets.
fn titlecase_str(ch: char) -> String {
    if let Some(t) = titlecase_char_only(ch) {
        return t.to_string();
    }
    // Everything up to and including the first *cased* character of the
    // uppercase expansion stays as it is; the rest is lower-cased. Taking
    // "index 0" instead is wrong for ʼn (U+0149), whose uppercase is "ʼN": the
    // apostrophe carries no case, so the N is the letter that must stay
    // capital, and Emacs answers "ʼN" where "lower-case everything after the
    // first character" answers "ʼn".
    let mut out = String::new();
    let mut seen_cased = false;
    for u in ch.to_uppercase() {
        if seen_cased {
            // A non-initial capital iota in an uppercase expansion can only
            // have come from a ypogegrammeni, and its title form is the
            // COMBINING GREEK YPOGEGRAMMENI, not a lowercase iota: ᾲ title-cases
            // to "Ὰ" + U+0345, which is what Emacs answers.
            if u == '\u{0399}' {
                out.push('\u{0345}');
            } else {
                out.extend(u.to_lowercase());
            }
        } else {
            out.push(u);
            if u.to_lowercase().next() != Some(u) {
                seen_cased = true;
            }
        }
    }
    out
}

/// The one-to-one title-case mapping, when it differs from `to_uppercase` or
/// when `to_uppercase` is one-to-many but a single title character exists.
/// `None` means "no special case — derive it from the uppercase mapping".
fn titlecase_char_only(ch: char) -> Option<char> {
    let c = ch as u32;
    let t = match c {
        // Latin digraphs: DŽ/Dž/dž, LJ/Lj/lj, NJ/Nj/nj, DZ/Dz/dz.
        0x01C4..=0x01C6 => 0x01C5,
        0x01C7..=0x01C9 => 0x01C8,
        0x01CA..=0x01CC => 0x01CB,
        0x01F1..=0x01F3 => 0x01F2,
        // Greek with ypogegrammeni: three runs of sixteen, each a lowercase
        // eight followed by the capital eight that is also the title form.
        0x1F80..=0x1F87 => c + 8,
        0x1F90..=0x1F97 => c + 8,
        0x1FA0..=0x1FA7 => c + 8,
        0x1FB3 => 0x1FBC,
        0x1FC3 => 0x1FCC,
        0x1FF3 => 0x1FFC,
        // The capital halves of those runs are already the title forms, and
        // must stay put: their full *uppercase* is two characters (ᾈ → "ἈΙ"),
        // so deriving from it would decompose a character Emacs leaves alone.
        0x1F88..=0x1F8F | 0x1F98..=0x1F9F | 0x1FA8..=0x1FAF => c,
        0x1FBC | 0x1FCC | 0x1FFC => c,
        // Georgian Mkhedruli: Unicode gives these an uppercase (the Mtavruli
        // block) but no title case, so a word-initial ა stays ა even though
        // `(upcase ?ა)` is Ა. Deriving the title form from the uppercase one
        // would capitalize Georgian text that Emacs leaves alone.
        0x10D0..=0x10FA | 0x10FD..=0x10FF => c,
        _ => return None,
    };
    char::from_u32(t)
}
fn downcase_fn(h: &mut ElispHost, a: &[Value]) -> R {
    case_fold(h, a, false)
}
fn upcase_fn(h: &mut ElispHost, a: &[Value]) -> R {
    case_fold(h, a, true)
}
fn length_fn(h: &mut ElispHost, a: &[Value]) -> R {
    // nil is the empty list in either of its two VM spellings (`Undef` for a
    // literal, `Bool(false)` for a comparison that answered false).
    if is_nil(&a[0]) {
        return Ok(Value::Int(0));
    }
    // A closure is a pseudovector of 3, 5 or 6 slots.
    if let Some(slots) = h.closure_slots(&a[0]) {
        return Ok(Value::Int(slots.len() as i64));
    }
    if let Some(s) = h.str_text(&a[0]) {
        return Ok(Value::Int(s.chars().count() as i64));
    }
    match &a[0] {
        // A symbol, a number, t … are not sequences: Emacs signals rather than
        // answering 0. (`safe-length` is the one that answers 0.)
        Value::Bool(_) | Value::Int(_) | Value::Float(_) => Err(format!(
            "wrong-type-argument: sequencep {}",
            h.print(&a[0], true)
        )),
        Value::Obj(_) => match h.obj(&a[0]) {
            Some(Obj::Vector(items)) | Some(Obj::Record(items)) => {
                Ok(Value::Int(items.len() as i64))
            }
            Some(Obj::BoolVector(bits)) => Ok(Value::Int(bits.len() as i64)),
            Some(Obj::Cons(..)) => {
                // fns.c `list_length`, which is `Flength`'s cons arm:
                //
                //   ptrdiff_t i = 0;
                //   FOR_EACH_TAIL (list) i++;
                //   CHECK_LIST_END (list, list);
                //
                // Both signals name the LOOP VARIABLE, not the original argument:
                // an improper list reports its tail (`(length '(1 2 . 3))` signals
                // with 3) and a circular one reports the tail Brent's walk was
                // standing on when the hare caught the tortoise. A Floyd walk here
                // found the cycle but could not name that tail, and passed a
                // placeholder string as the datum instead:
                //
                //   (butlast (let ((c (list 9 3 2.5))) (setcdr (last c) (cdr c)) c))
                //   emacs => (circular-list #1=(2.5 3 . #1#))
                //   elisp => (circular-list "circular list")   [before]
                let mut n: i64 = 0;
                let mut w = TailWalk::new(&a[0]);
                while let Some((_, cdr)) = w.cons(h) {
                    n += 1;
                    if w.step(cdr) {
                        let tail = w.tail.clone();
                        return Err(h.signal_circular_list(&tail));
                    }
                }
                let tail = w.tail.clone();
                check_list_end(h, &tail, &tail)?;
                Ok(Value::Int(n))
            }
            // A bool-vector/char-table/record has a length; a symbol, a subr, a
            // buffer … do not — Emacs signals rather than answering 0.
            // `Flength` on a char-table is `MAX_CHAR + 1` (`chartab_chars[0]`
            // slots of 64 blocks).
            Some(Obj::CharTable(_)) => Ok(Value::Int(MAX_CHAR + 1)),
            _ => Err(h.signal_wrong_type("sequencep", &a[0])),
        },
        _ => Err(format!(
            "wrong-type-argument: sequencep {}",
            h.print(&a[0], true)
        )),
    }
}
/// fns.c `CHECK_LIST_END (x, y)`: `CHECK_TYPE (NILP (x), Qlistp, y)` — a nil tail
/// is a proper end, anything else names the WHOLE list under `listp`.
fn check_list_end(h: &mut ElispHost, tail: &Value, list: &Value) -> Result<(), String> {
    if is_nil(tail) {
        Ok(())
    } else {
        // The offender travels as the OBJECT. Rendering it into the message and
        // re-reading it — which is what this did — loses any list the reader
        // cannot reconstruct, and `print-circle` t makes that the common case:
        // the text becomes `(#1="foo10" #1# #1# . 2)`, the re-read fails, and the
        // condition came back as a bare `(wrong-type-argument listp)` with no
        // offender at all.
        Err(h.signal_wrong_type("listp", list))
    }
}

/// fns.c `Fnthcdr`, ported. Take cdr N times on LIST and return the result.
///
/// The two things a naive `while (> n 0)` loop gets wrong, both of which Emacs
/// handles here and both of which the fuzzer reached:
///
/// - **N may be a bignum.** `CHECK_INTEGER` accepts one, so
///   `(nth (floor 1.5e+300) '(a))` is `nil`, not `(wrong-type-argument integerp …)`.
///   A negative bignum returns LIST untouched; a positive one is walked with
///   `EMACS_INT_MAX` substituted, and the substitution error is undone below.
/// - **LIST may be circular.** Counting down 4611686018427387903 cdrs of a
///   three-element cycle never terminates. Emacs runs Brent's teleporting
///   tortoise, then reduces the remaining count modulo the distance the hare
///   travelled since the last teleport. That distance is always a MULTIPLE of the
///   true cycle period (both pointers sit on the same cell when they meet), so
///   reducing by it lands on the same cell the full walk would have — which is why
///   the answer does not depend on the tortoise's schedule.
fn nthcdr_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let list = a[1].clone();
    let mut tail = list.clone();
    // `CHECK_INTEGER (n)`: a bignum passes, a float does not — `(nthcdr 1.5 '(a))`
    // is `(wrong-type-argument integerp 1.5)` even though 1.5 has no fraction bits
    // to spare.
    if !h.is_integer(&a[0]) {
        return Err(format!(
            "wrong-type-argument: integerp {}",
            h.print(&a[0], true)
        ));
    }
    // "A huge but in-range EMACS_INT that can be substituted for a positive
    // bignum while counting down."
    const LARGE_NUM: i64 = i64::MAX;
    // fns.c `SMALL_LIST_LEN_MAX`: below this, skip circularity and quit checking.
    const SMALL_LIST_LEN_MAX: i64 = 127;
    let bignum: Option<BigInt> = match h.obj(&a[0]) {
        Some(Obj::Bignum(b)) => Some(b.clone()),
        _ => None,
    };
    let mut num: i64 = match (&a[0], &bignum) {
        (Value::Int(n), _) => {
            let mut num = *n;
            if num <= SMALL_LIST_LEN_MAX {
                while num > 0 {
                    match h.obj(&tail) {
                        Some(Obj::Cons(_, d)) => tail = d.clone(),
                        _ => {
                            check_list_end(h, &tail, &list)?;
                            return Ok(Value::Undef);
                        }
                    }
                    num -= 1;
                }
                return Ok(tail);
            }
            num
        }
        (_, Some(b)) => {
            if b.sign() == num_bigint::Sign::Minus {
                return Ok(tail);
            }
            LARGE_NUM
        }
        // `is_integer` already accepted it, so this arm is unreachable.
        _ => return Ok(tail),
    };

    // `FOR_EACH_TAIL_SAFE (tail)` with the body of Fnthcdr. The C two-level
    // countdown (an `unsigned short` q plus an `intptr_t` n, both refilled from a
    // doubling `max`) is one i64 counter here; it is the same total period.
    let mut tortoise = tail.clone();
    let mut tortoise_num = num;
    let mut saved_tail = tail.clone();
    let mut period: i64 = 2;
    let mut countdown: i64 = 2;
    while let Some(Obj::Cons(_, d)) = h.obj(&tail) {
        // "If the tortoise just jumped (which is rare), update TORTOISE_NUM."
        if value_eq_obj(&tail, &tortoise) {
            tortoise_num = num;
        }
        saved_tail = d.clone();
        num -= 1;
        if num == 0 {
            return Ok(saved_tail);
        }
        tail = saved_tail.clone();
        countdown -= 1;
        if countdown == 0 {
            // Teleport; no cycle test on the step that teleports.
            period <<= 1;
            countdown = period;
            tortoise = tail.clone();
        } else if value_eq_obj(&tail, &tortoise) {
            break;
        }
    }

    tail = saved_tail;
    if !matches!(h.obj(&tail), Some(Obj::Cons(..))) {
        check_list_end(h, &tail, &list)?;
        return Ok(Value::Undef);
    }

    // TAIL is part of a cycle. Reduce NUM modulo the cycle length.
    let cycle_length = tortoise_num - num;
    if let Some(b) = &bignum {
        // Undo the LARGE_NUM substitution: add (N - LARGE_NUM) mod CYCLE_LENGTH.
        let m = BigInt::from(cycle_length);
        let r = (b % &m).to_i64().unwrap_or(0);
        num += r;
        num += cycle_length - LARGE_NUM % cycle_length;
    }
    num = num.rem_euclid(cycle_length);
    while num > 0 {
        match h.obj(&tail) {
            Some(Obj::Cons(_, d)) => tail = d.clone(),
            _ => break,
        }
        num -= 1;
    }
    Ok(tail)
}

/// `BASE_EQ` for the two cases a list walk can produce: two heap handles, or two
/// identical immediates. Enough for cycle detection, where only conses can match.
fn value_eq_obj(a: &Value, b: &Value) -> bool {
    matches!((a, b), (Value::Obj(x), Value::Obj(y)) if x == y)
}

// ── fns.c list search (FOR_EACH_TAIL) ────────────────────────────────────────

/// lisp.h `struct for_each_tail_internal` plus the advance clause of
/// `FOR_EACH_TAIL_INTERNAL`, ported as a driver so a walk can be run from a subr
/// body (which holds the host borrow) and from `host::call_function` (which must
/// release it between elisp calls) with one implementation.
///
/// The C is Brent's teleporting tortoise-hare, and the schedule is not
/// incidental — it decides *which* tail the `circular-list` signal names:
///
/// ```text
///   for (struct for_each_tail_internal li = { tail, 2, 0, 2 };
///        CONSP (tail);
///        ((tail) = XCDR (tail),
///     ((--li.q != 0
///       || ((check_quit) ? maybe_quit () : (void) 0, 0 < --li.n)
///       || (li.q = li.n = li.max <<= 1, li.n >>= USHRT_WIDTH,
///           li.tortoise = (tail), false))
///      && BASE_EQ (tail, li.tortoise))
///     ? (cycle) : (void) 0))
/// ```
///
/// This replaces seven prelude `defun`s (`memq`, `memql`, `member`, `assq`,
/// `assoc`, `rassq`, `rassoc`) that walked with a bare `while (consp l)` and so
/// **did not terminate at all** on a circular list, where Emacs signals:
///
/// ```text
///   $ emacs -Q --batch -l circ.el    # (circular-list (3 1 2 3 1 . #2))
///   $ elisp circ.el                  # hangs
/// ```
pub struct TailWalk {
    /// The C loop variable: the current cons while walking, the terminating
    /// non-cons once the loop exits.
    pub tail: Value,
    tortoise: Value,
    max: i64,
    n: i64,
    q: u16,
}

impl TailWalk {
    pub fn new(list: &Value) -> Self {
        // `struct for_each_tail_internal li = { tail, 2, 0, 2 }`.
        Self {
            tail: list.clone(),
            tortoise: list.clone(),
            max: 2,
            n: 0,
            q: 2,
        }
    }

    /// The loop's `CONSP (tail)` test, returning `(car, cdr)` while it holds.
    pub fn cons(&self, h: &ElispHost) -> Option<(Value, Value)> {
        match h.obj(&self.tail) {
            Some(Obj::Cons(car, cdr)) => Some((car.clone(), cdr.clone())),
            _ => None,
        }
    }

    /// The `for` statement's third clause. `cdr` is `XCDR (tail)` read while the
    /// host was borrowed. Returns whether a cycle was just detected — the point
    /// at which `FOR_EACH_TAIL` evaluates `circular_list (tail)`.
    #[must_use]
    pub fn step(&mut self, cdr: Value) -> bool {
        self.tail = cdr;
        self.q = self.q.wrapping_sub(1);
        let advanced = if self.q != 0 {
            true
        } else {
            self.n -= 1;
            if self.n > 0 {
                true
            } else {
                // `li.q = li.n = li.max <<= 1, li.n >>= USHRT_WIDTH,
                //  li.tortoise = (tail), false` — the teleport, which yields
                // false so the `BASE_EQ` that follows is short-circuited away.
                self.max <<= 1;
                self.n = self.max;
                self.q = (self.n & 0xffff) as u16;
                self.n >>= 16;
                self.tortoise = self.tail.clone();
                false
            }
        };
        advanced && value_eq_obj(&self.tail, &self.tortoise)
    }
}

/// fns.c `eq_comparable_value`: `SYMBOLP (x) || FIXNUMP (x)`. `member`, `assoc`
/// and `rassoc` route to their `eq` siblings for such a key, which is why
/// `(member 1 L)` reports `memq`'s walk and not `equal`'s.
fn eq_comparable_value(h: &ElispHost, v: &Value) -> bool {
    match v {
        Value::Int(_) | Value::Bool(_) | Value::Undef => true,
        Value::Obj(_) => matches!(h.obj(v), Some(Obj::Symbol(_))),
        _ => false,
    }
}

/// Run a `FOR_EACH_TAIL` walk inside a single host borrow: `hit` decides, per
/// cons, whether this is the answer. Returns nil after `CHECK_LIST_END`.
fn for_each_tail(
    h: &mut ElispHost,
    list: &Value,
    mut hit: impl FnMut(&ElispHost, &Value, &Value) -> Option<Value>,
) -> R {
    let mut w = TailWalk::new(list);
    while let Some((car, cdr)) = w.cons(h) {
        if let Some(found) = hit(h, &car, &w.tail) {
            return Ok(found);
        }
        if w.step(cdr) {
            return Err(h.signal_circular_list(&w.tail));
        }
    }
    check_list_end(h, &w.tail, list)?;
    Ok(Value::Undef)
}

/// fns.c `Fmemq`.
fn memq_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let elt = a[0].clone();
    for_each_tail(h, &a[1], |h, car, tail| {
        el_eq(h, car, &elt).then(|| tail.clone())
    })
}

/// fns.c `Fmemql`. Only a float or a bignum takes the by-value path; every other
/// element type is `Fmemq`'s job, which is why `(memql "a" (list "a"))` is nil.
fn memql_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let elt = a[0].clone();
    let float = matches!(elt, Value::Float(_));
    let bignum = matches!(h.obj(&elt), Some(Obj::Bignum(_)));
    if !float && !bignum {
        return memq_fn(h, a);
    }
    for_each_tail(h, &a[1], |h, car, tail| {
        let same = if float {
            matches!(car, Value::Float(_)) && el_eql(h, &elt, car)
        } else {
            matches!(h.obj(car), Some(Obj::Bignum(_))) && el_eql(h, &elt, car)
        };
        same.then(|| tail.clone())
    })
}

/// fns.c `Fmember`.
fn member_fn(h: &mut ElispHost, a: &[Value]) -> R {
    if eq_comparable_value(h, &a[0]) {
        return memq_fn(h, a);
    }
    let elt = a[0].clone();
    for_each_tail(h, &a[1], |h, car, tail| {
        el_equal(h, &elt, car).then(|| tail.clone())
    })
}

/// fns.c `Fassq`. A non-cons element is skipped, not an error.
fn assq_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let key = a[0].clone();
    for_each_tail(h, &a[1], |h, car, _| match h.obj(car) {
        Some(Obj::Cons(k, _)) if el_eq(h, k, &key) => Some(car.clone()),
        _ => None,
    })
}

/// fns.c `Frassq`.
fn rassq_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let key = a[0].clone();
    for_each_tail(h, &a[1], |h, car, _| match h.obj(car) {
        Some(Obj::Cons(_, v)) if el_eq(h, v, &key) => Some(car.clone()),
        _ => None,
    })
}

// `assoc` and `mapconcat` call back into elisp (TESTFN, FUNCTION), so their
// bodies live in `host::call_function` rather than in a subr that would already
// hold the host borrow. These are the pieces of the fns.c ports they reuse.

/// fns.c `eq_comparable_value`, for the `Fassoc` fast path.
pub fn eq_comparable(h: &ElispHost, v: &Value) -> bool {
    eq_comparable_value(h, v)
}

/// fns.c `Fassq`, callable from the `assoc` intercept.
pub fn assq(h: &mut ElispHost, a: &[Value]) -> R {
    assq_fn(h, a)
}

/// `Fassoc`'s default test: `EQ (XCAR (car), key) || !NILP (Fequal (…))`.
pub fn equal_or_eq(h: &ElispHost, a: &Value, b: &Value) -> bool {
    el_eq(h, a, b) || el_equal(h, a, b)
}

/// fns.c `CHECK_LIST_END`, callable from the `assoc` intercept.
pub fn check_end(h: &mut ElispHost, tail: &Value, list: &Value) -> Result<(), String> {
    check_list_end(h, tail, list)
}

/// fns.c `Fconcat`, callable from the `mapconcat` intercept.
pub fn concat(h: &mut ElispHost, a: &[Value]) -> R {
    concat_fn(h, a)
}

/// fns.c `Frassoc`.
fn rassoc_fn(h: &mut ElispHost, a: &[Value]) -> R {
    if eq_comparable_value(h, &a[0]) {
        return rassq_fn(h, a);
    }
    let key = a[0].clone();
    for_each_tail(h, &a[1], |h, car, _| match h.obj(car) {
        Some(Obj::Cons(_, v)) if el_eq(h, v, &key) || el_equal(h, v, &key) => Some(car.clone()),
        _ => None,
    })
}

fn nth_fn(h: &mut ElispHost, a: &[Value]) -> R {
    // fns.c: `Fnth` is literally `Fcar (Fnthcdr (n, list))`.
    let cur = nthcdr_fn(h, a)?;
    match h.obj(&cur) {
        Some(Obj::Cons(car, _)) => Ok(car.clone()),
        _ if is_nil(&cur) => Ok(Value::Undef),
        _ => Err(format!(
            "wrong-type-argument: listp {}",
            h.print(&cur, true)
        )),
    }
}

// ── c[ad]+r combinators ──
// subr.el defines every two-, three- and four-letter composition as Lisp
// (`caddr` is `(car (cdr (cdr x)))`), so each one inherits car/cdr's edge
// semantics: car/cdr of nil yield nil (a short list answers nil), while car/cdr
// of a non-nil non-cons signals `wrong-type-argument listp` naming the value
// reached at that step. OPS is the letters between `c` and `r`, applied
// right-to-left: `cxr(h, a, "add")` is caddr. Every name is listed in
// `host::LISP_LEVEL_ARITY`, because a wrong argument count in Emacs is caught
// by exec_byte_code and reported as `(1 . 1)`, not as the function.
fn cxr(h: &mut ElispHost, a: &[Value], ops: &str) -> R {
    let mut v = a[0].clone();
    for op in ops.bytes().rev() {
        v = if op == b'a' {
            car(h, &[v])?
        } else {
            cdr(h, &[v])?
        };
    }
    Ok(v)
}
macro_rules! cxr_subrs {
    ($($f:ident $ops:literal),* $(,)?) => {
        $(fn $f(h: &mut ElispHost, a: &[Value]) -> R { cxr(h, a, $ops) })*
        /// Every c[ad]+r subr as `(NAME, FN)`, for `install`.
        const CXR_SUBRS: &[(&str, crate::host::SubrFn)] =
            &[$((concat!("c", $ops, "r"), $f)),*];
    };
}
cxr_subrs!(
    caar "aa", cadr "ad", cdar "da", cddr "dd",
    caaar "aaa", caadr "aad", cadar "ada", caddr "add",
    cdaar "daa", cdadr "dad", cddar "dda", cdddr "ddd",
    caaaar "aaaa", caaadr "aaad", caadar "aada", caaddr "aadd",
    cadaar "adaa", cadadr "adad", caddar "adda", cadddr "addd",
    cdaaar "daaa", cdaadr "daad", cdadar "dada", cdaddr "dadd",
    cddaar "ddaa", cddadr "ddad", cdddar "ddda", cddddr "dddd",
);

// ── predicates ──
fn null_fn(_h: &mut ElispHost, a: &[Value]) -> R {
    Ok(nil_or(is_nil(&a[0])))
}
fn consp(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(nil_or(matches!(h.obj(&a[0]), Some(Obj::Cons(..)))))
}
fn listp(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(nil_or(
        is_nil(&a[0]) || matches!(h.obj(&a[0]), Some(Obj::Cons(..))),
    ))
}
fn atom(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(nil_or(!matches!(h.obj(&a[0]), Some(Obj::Cons(..)))))
}
fn symbolp(h: &mut ElispHost, a: &[Value]) -> R {
    // `nil` travels as either `Undef` or `Bool(false)`; both are the symbol nil.
    Ok(nil_or(
        matches!(a[0], Value::Bool(_) | Value::Undef)
            || matches!(h.obj(&a[0]), Some(Obj::Symbol(_))),
    ))
}
fn stringp(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(nil_or(h.is_string(&a[0])))
}
/// `natnump` is a C subr in Emacs (data.c), so `#'natnump` must be — and print
/// as — `#<subr natnump>` (a prelude lambda would print its closure source in
/// e.g. a `wrong-number-of-arguments` error).
fn natnump_fn(h: &mut ElispHost, a: &[Value]) -> R {
    use num_traits::Signed;
    let ok = match &a[0] {
        Value::Int(n) => *n >= 0,
        v => h.as_bigint(v).is_some_and(|b| !b.is_negative()),
    };
    Ok(nil_or(ok))
}
/// `nlistp` is a C subr in Emacs (data.c) — same identity requirement as natnump.
fn nlistp_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let is_list = is_nil(&a[0]) || matches!(h.obj(&a[0]), Some(Obj::Cons(..)));
    Ok(nil_or(!is_list))
}
fn numberp(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(nil_or(h.is_number(&a[0])))
}
fn integerp(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(nil_or(h.is_integer(&a[0])))
}
/// `fixnump` — an integer small enough to need no heap cell. A bignum is an
/// integer, so `integerp` accepts it and this does not.
fn fixnump(_h: &mut ElispHost, a: &[Value]) -> R {
    Ok(nil_or(matches!(a[0], Value::Int(_))))
}
fn bignump(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(nil_or(h.is_bignum(&a[0])))
}
fn floatp(_h: &mut ElispHost, a: &[Value]) -> R {
    Ok(nil_or(matches!(a[0], Value::Float(_))))
}
fn vectorp(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(nil_or(matches!(h.obj(&a[0]), Some(Obj::Vector(_)))))
}

// ── vectors ──
fn vector_fn(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(h.alloc(Obj::Vector(a.to_vec())))
}
/// `(make-list LENGTH INIT)` — port of `Fmake_list` (alloc.c:2991-3005).
///
/// This was a prelude `defun` with the same semantics, which made every
/// observable that names the FUNCTION disagree: Emacs reports
/// `#<subr make-list>` and elisprs printed the whole closure, so
/// `(apply #'make-list nil)` differed in its error, and `subrp`, `subr-name`
/// and `type-of` all answered for an interpreted function. The values and the
/// `wholenump` rejections already matched; only the identity did not.
fn make_list(h: &mut ElispHost, a: &[Value]) -> R {
    let n = check_fixnat(h, &a[0])?;
    let mut val = Value::Undef;
    for _ in 0..n {
        val = h.cons(a[1].clone(), val);
    }
    Ok(val)
}

fn make_vector(h: &mut ElispHost, a: &[Value]) -> R {
    let n = check_array_len_val(h, &a[0])?;
    // Fallible allocation: a length that fits `most-positive-fixnum` can still
    // exceed available memory (or `isize::MAX` bytes). Emacs signals a plain
    // `error` there instead of aborting, so `try_reserve_exact` maps both the
    // capacity-overflow and out-of-memory cases to `MEMORY_EXHAUSTED`.
    let mut v: Vec<Value> = Vec::new();
    v.try_reserve_exact(n)
        .map_err(|_| MEMORY_EXHAUSTED.to_string())?;
    v.resize(n, a[1].clone());
    Ok(h.alloc(Obj::Vector(v)))
}

// ── records ──
/// `(record TYPE &rest SLOTS)` — a new record whose slot 0 is TYPE and whose
/// remaining slots are SLOTS (Emacs `Frecord`).
fn record_fn(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(h.alloc(Obj::Record(a.to_vec())))
}
/// `(make-record TYPE SLOTS INIT)` — a record with SLOTS non-type slots, each
/// INIT, and slot 0 = TYPE (Emacs `Fmake_record`). SLOTS must be a wholenum, and
/// the record is capped at `PSEUDOVECTOR_SIZE_MASK` (4095) total slots.
fn make_record(h: &mut ElispHost, a: &[Value]) -> R {
    let slots = match &a[1] {
        Value::Int(n) if *n >= 0 => *n as usize,
        _ => {
            return Err(format!(
                "wrong-type-argument: wholenump {}",
                h.print(&a[1], true)
            ))
        }
    };
    let total = slots + 1;
    if total > 4095 {
        return Err(format!(
            "Attempt to allocate a record of {total} slots; max is 4095"
        ));
    }
    let mut v: Vec<Value> = Vec::new();
    v.try_reserve_exact(total)
        .map_err(|_| MEMORY_EXHAUSTED.to_string())?;
    v.resize(total, a[2].clone());
    v[0] = a[0].clone();
    Ok(h.alloc(Obj::Record(v)))
}

// ── bool-vectors ──
/// Clone a bool-vector's bits, or signal `(wrong-type-argument bool-vector-p X)`.
fn as_bool_vector(h: &ElispHost, v: &Value) -> Result<Vec<bool>, String> {
    match h.obj(v) {
        Some(Obj::BoolVector(bits)) => Ok(bits.clone()),
        _ => Err(format!(
            "wrong-type-argument: bool-vector-p {}",
            h.print(v, true)
        )),
    }
}
/// `(make-bool-vector LENGTH INIT)` — a bool-vector of LENGTH elements, each `t`
/// if INIT is non-nil, else `nil` (Emacs `Fmake_bool_vector`).
fn make_bool_vector(h: &mut ElispHost, a: &[Value]) -> R {
    let n = check_array_len_val(h, &a[0])?;
    let bit = !is_nil(&a[1]);
    let mut v: Vec<bool> = Vec::new();
    v.try_reserve_exact(n)
        .map_err(|_| MEMORY_EXHAUSTED.to_string())?;
    v.resize(n, bit);
    Ok(h.alloc(Obj::BoolVector(v)))
}
/// `(bool-vector &rest OBJECTS)` — a bool-vector whose element I is `t` when
/// OBJECT I is non-nil (Emacs `Fbool_vector`).
fn bool_vector_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let bits: Vec<bool> = a.iter().map(|x| !is_nil(x)).collect();
    Ok(h.alloc(Obj::BoolVector(bits)))
}
fn bool_vector_p(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(nil_or(matches!(h.obj(&a[0]), Some(Obj::BoolVector(_)))))
}
/// `(bool-vector-count-population A)` — the number of `t` elements of A.
fn bool_vector_count_population(h: &mut ElispHost, a: &[Value]) -> R {
    let bits = as_bool_vector(h, &a[0])?;
    Ok(Value::Int(bits.iter().filter(|&&b| b).count() as i64))
}
/// `(bool-vector-subsetp A B)` — non-nil when every `t` bit of A is `t` in B. A
/// and B must have equal length, else `wrong-length-argument`.
fn bool_vector_subsetp(h: &mut ElispHost, a: &[Value]) -> R {
    let ba = as_bool_vector(h, &a[0])?;
    let bb = as_bool_vector(h, &a[1])?;
    if ba.len() != bb.len() {
        // Emacs's `Fbool_vector_subsetp` reports (len-A len-B len-B).
        return Err(format!(
            "wrong-length-argument: {} {} {}",
            ba.len(),
            bb.len(),
            bb.len()
        ));
    }
    Ok(nil_or(ba.iter().zip(&bb).all(|(&x, &y)| !x || y)))
}
/// data.c `bool_vector_binop_driver` for the four set operations: the result
/// goes into C when given (C must match A and B in length) and is returned
/// only if C changed, otherwise into a fresh bool vector.
fn bool_vector_binop(h: &mut ElispHost, a: &[Value], op: fn(bool, bool) -> bool) -> R {
    let ba = as_bool_vector(h, &a[0])?;
    let bb = as_bool_vector(h, &a[1])?;
    let dest = a.get(2).filter(|v| !is_nil(v)).cloned();
    let wrong_length = |extra: Option<usize>| match extra {
        Some(n) => format!("wrong-length-argument: {} {} {n}", ba.len(), bb.len()),
        None => format!("wrong-length-argument: {} {}", ba.len(), bb.len()),
    };
    if bb.len() != ba.len() {
        let extra = match &dest {
            Some(d) => Some(as_bool_vector(h, d)?.len()),
            None => None,
        };
        return Err(wrong_length(extra));
    }
    let out: Vec<bool> = ba.iter().zip(&bb).map(|(&x, &y)| op(x, y)).collect();
    let Some(dest) = dest else {
        return Ok(h.alloc(Obj::BoolVector(out)));
    };
    let bd = as_bool_vector(h, &dest)?;
    if bd.len() != ba.len() {
        return Err(wrong_length(Some(bd.len())));
    }
    if bd == out {
        return Ok(Value::Undef);
    }
    if let Value::Obj(id) = &dest {
        if let Some(Obj::BoolVector(bits)) = h.arena.get_mut(*id as usize) {
            *bits = out;
        }
    }
    Ok(dest)
}
fn bool_vector_exclusive_or(h: &mut ElispHost, a: &[Value]) -> R {
    bool_vector_binop(h, a, |x, y| x ^ y)
}
fn bool_vector_union(h: &mut ElispHost, a: &[Value]) -> R {
    bool_vector_binop(h, a, |x, y| x | y)
}
fn bool_vector_intersection(h: &mut ElispHost, a: &[Value]) -> R {
    bool_vector_binop(h, a, |x, y| x & y)
}
fn bool_vector_set_difference(h: &mut ElispHost, a: &[Value]) -> R {
    bool_vector_binop(h, a, |x, y| x & !y)
}
/// data.c `Fbool_vector_count_consecutive`: how many elements of A from I on
/// equal B; I may be one past the end.
fn bool_vector_count_consecutive(h: &mut ElispHost, a: &[Value]) -> R {
    let ba = as_bool_vector(h, &a[0])?;
    let i = match &a[2] {
        Value::Int(n) if *n >= 0 => *n as usize,
        v => return Err(h.signal_wrong_type("wholenump", v)),
    };
    if i > ba.len() {
        let (v, n) = (a[0].clone(), a[2].clone());
        let data = h.list_from(vec![v, n]);
        let sym = h.intern("args-out-of-range");
        let obj = h.cons(sym, data);
        let msg = format!("args-out-of-range: {}", h.print(&obj, true));
        h.set_pending_error(&msg, obj);
        return Err(msg);
    }
    let b = !is_nil(&a[1]);
    Ok(Value::Int(
        ba[i..].iter().take_while(|&&x| x == b).count() as i64
    ))
}
/// `(bool-vector-not A &optional B)` — store the complement of A into B (or a new
/// bool-vector) and return it. B, if given, must have A's length.
fn bool_vector_not(h: &mut ElispHost, a: &[Value]) -> R {
    let ba = as_bool_vector(h, &a[0])?;
    let out: Vec<bool> = ba.iter().map(|&x| !x).collect();
    if a.len() > 1 && !is_nil(&a[1]) {
        let bb = as_bool_vector(h, &a[1])?;
        if bb.len() != ba.len() {
            return Err(format!("wrong-length-argument: {} {}", ba.len(), bb.len()));
        }
        if let Value::Obj(id) = &a[1] {
            if let Some(Obj::BoolVector(bits)) = h.arena.get_mut(*id as usize) {
                bits.clear();
                bits.extend_from_slice(&out);
            }
        }
        return Ok(a[1].clone());
    }
    Ok(h.alloc(Obj::BoolVector(out)))
}
/// `(elt SEQUENCE N)` — port of `Felt` (fns.c).
///
/// ```c
///   if (CONSP (sequence) || NILP (sequence))
///     return Fnth (n, sequence);
///   else
///     {
///       CHECK_ARRAY (sequence, Qsequencep);
///       return Faref (sequence, n);
///     }
/// ```
///
/// It was an elisp `defun` in the prelude, which behaved the same but could not
/// name itself the way a C primitive does. Emacs reports the SUBR when a
/// function object is called with the wrong count, so
/// `(funcall #'elt)` is `(wrong-number-of-arguments #<subr elt> 0)`; the prelude
/// version answered with its own printed closure source instead — a
/// `#[(seq n) (…)]` blob in place of `#<subr elt>`.
///
/// The type checks are `Fnth`'s and `Faref`'s, exactly as the C delegates them:
/// the array path's index check is `Faref`'s `CHECK_FIXNUM`
/// (`(elt [1 2 3] 1.5)` is `(wrong-type-argument fixnump 1.5)`), and the list
/// path's is `Fnthcdr`'s, which accepts an integer only.
fn elt_fn(h: &mut ElispHost, a: &[Value]) -> R {
    // `CONSP (sequence) || NILP (sequence)` — a list, including the empty one.
    if is_nil(&a[0]) || matches!(h.obj(&a[0]), Some(Obj::Cons(..))) {
        // Fnth takes (N, LIST); elt takes (SEQUENCE, N).
        return nth_fn(h, &[a[1].clone(), a[0].clone()]);
    }
    // CHECK_ARRAY (sequence, Qsequencep): the TEST is `ARRAYP` but the
    // PREDICATE reported is `sequencep`, because a non-array reaching here is
    // not a sequence at all. `ARRAYP` is vector | string | bool-vector |
    // char-table — a RECORD is not one, even though `Faref` accepts it:
    //
    //   (elt (record 'a 1 2) 1)          => (wrong-type-argument sequencep #s(a 1 2))
    //   (elt (make-char-table 'test 7) ?a) => 7
    //   (arrayp (record 'a 1))           => nil
    if !matches!(
        h.obj(&a[0]),
        Some(Obj::Vector(_))
            | Some(Obj::Str(_))
            | Some(Obj::BoolVector(_))
            | Some(Obj::CharTable(_))
    ) {
        return Err(format!(
            "wrong-type-argument: sequencep {}",
            h.print(&a[0], true)
        ));
    }
    aref(h, a)
}

fn aref(h: &mut ElispHost, a: &[Value]) -> R {
    // A char-table indexes by character (0..=MAX_CHAR) with parent/default
    // fallback, unlike a plain vector's positional index.
    if matches!(h.obj(&a[0]), Some(Obj::CharTable(_))) {
        let c = as_char(h, &a[1])?;
        return Ok(h.char_table_ref(&a[0], c));
    }
    let idx = match &a[1] {
        Value::Int(n) => *n,
        v => return Err(format!("wrong-type-argument: fixnump {}", h.print(v, true))),
    };
    // Faref dispatches on the ARRAY's type before any bounds check, so a
    // non-array names itself even with a negative index: (aref 97 -7) =>
    // (wrong-type-argument arrayp 97), while (aref "ab" -1) is
    // args-out-of-range.
    let oor = |h: &ElispHost| format!("args-out-of-range: {} {idx}", h.print(&a[0], true));
    let get = |len: usize| -> Option<usize> { usize::try_from(idx).ok().filter(|i| *i < len) };
    // An interpreted closure is a pseudovector: `aref` reads its slots.
    if let Some(slots) = h.closure_slots(&a[0]) {
        return get(slots.len())
            .map(|i| slots[i].clone())
            .ok_or_else(|| oor(h));
    }
    match h.obj(&a[0]) {
        Some(Obj::Vector(items)) | Some(Obj::Record(items)) => get(items.len())
            .map(|i| items[i].clone())
            .ok_or_else(|| oor(h)),
        Some(Obj::BoolVector(bits)) => get(bits.len())
            .map(|i| nil_or(bits[i]))
            .ok_or_else(|| oor(h)),
        _ => match h.str_text(&a[0]) {
            Some(s) => get(s.chars().count())
                .and_then(|i| s.chars().nth(i))
                .map(|c| Value::Int(c as i64))
                .ok_or_else(|| oor(h)),
            None => Err(format!(
                "wrong-type-argument: arrayp {}",
                h.print(&a[0], true)
            )),
        },
    }
}
/// `(--note-compiler-macro SYMBOL)` — record that SYMBOL now carries a
/// `compiler-macro` property, so `macroexpand-all` knows to look it up. Called
/// from the prelude's `put` (so `function-put`, `define-symbol-prop` and
/// `cl-define-compiler-macro` all reach it); not an Emacs function.
fn note_compiler_macro(h: &mut ElispHost, a: &[Value]) -> R {
    if let Value::Obj(id) = &a[0] {
        h.compiler_macros.insert(*id);
    }
    Ok(a[0].clone())
}
fn aset(h: &mut ElispHost, a: &[Value]) -> R {
    // A char-table indexes by character; `aset` sets that single char.
    if matches!(h.obj(&a[0]), Some(Obj::CharTable(_))) {
        let c = as_char(h, &a[1])?;
        if let Value::Obj(id) = &a[0] {
            if let Some(Obj::CharTable(t)) = h.arena.get_mut(*id as usize) {
                t.set_range(c, c, a[2].clone());
            }
        }
        return Ok(a[2].clone());
    }
    let idx = as_num(h, &a[1])?.0;
    if idx < 0 {
        return Err(format!("args-out-of-range: {} {idx}", h.print(&a[0], true)));
    }
    let i = idx as usize;
    // A bool-vector stores `t`/`nil`: any non-nil VALUE is stored as `t`.
    let bit = !is_nil(&a[2]);
    if let Value::Obj(id) = &a[0] {
        match h.arena.get_mut(*id as usize) {
            // A record is aset-able exactly like a vector (including slot 0).
            Some(Obj::Vector(items)) | Some(Obj::Record(items)) => {
                if i < items.len() {
                    items[i] = a[2].clone();
                    return Ok(a[2].clone());
                }
                return Err(format!("args-out-of-range: {} {idx}", h.print(&a[0], true)));
            }
            Some(Obj::BoolVector(bits)) => {
                if i < bits.len() {
                    bits[i] = bit;
                    return Ok(a[2].clone());
                }
                return Err(format!("args-out-of-range: {} {idx}", h.print(&a[0], true)));
            }
            _ => {}
        }
    }
    // A STRING is mutable, and the write lands on the string OBJECT, so every
    // reference to it — an alias, a list element, a function's literal — sees
    // the new character. Emacs 30 removed pure space, so even a literal is
    // writable: `(progn (defun f () "ab") (aset (f) 0 ?z) (f))` is `"zb"`.
    //
    // `Faset` (data.c) checks the INDEX before the character: `(aset "ab" 5 'x)`
    // is `(args-out-of-range "ab" 5)`, not `(wrong-type-argument characterp x)`.
    if h.is_string(&a[0]) {
        let mut chars: Vec<char> = h
            .str_text(&a[0])
            .expect("checked stringp")
            .chars()
            .collect();
        if i >= chars.len() {
            return Err(format!("args-out-of-range: {} {idx}", h.print(&a[0], true)));
        }
        let c = as_char(h, &a[2])?;
        chars[i] = char::from_u32(c).unwrap_or('\u{fffd}');
        let text: String = chars.into_iter().collect();
        h.set_string_text(&a[0], text);
        return Ok(a[2].clone());
    }
    // Emacs names the offending object: `(aset 5 0 1)` is
    // `(wrong-type-argument arrayp 5)`, never a bare `(wrong-type-argument arrayp)`.
    Err(format!(
        "wrong-type-argument: arrayp {}",
        h.print(&a[0], true)
    ))
}
/// `(fillarray ARRAY ITEM)` — set every element of ARRAY to ITEM, in place.
/// ARRAY may be a vector or a string; for a string ITEM must be a character
/// (`(fillarray (copy-sequence "ab") ?z)` leaves `"zz"`).
fn fillarray(h: &mut ElispHost, a: &[Value]) -> R {
    if h.is_string(&a[0]) {
        let n = h.str_text(&a[0]).expect("checked stringp").chars().count();
        let c = as_char(h, &a[1])?;
        let ch = char::from_u32(c).unwrap_or('\u{fffd}');
        let text: String = std::iter::repeat_n(ch, n).collect();
        h.set_string_text(&a[0], text);
        return Ok(a[0].clone());
    }
    if let Value::Obj(id) = &a[0] {
        if let Some(Obj::Vector(items)) = h.arena.get_mut(*id as usize) {
            for x in items.iter_mut() {
                *x = a[1].clone();
            }
            return Ok(a[0].clone());
        }
    }
    Err(format!(
        "wrong-type-argument: arrayp {}",
        h.print(&a[0], true)
    ))
}

/// `(store-substring STRING IDX OBJ)` — port of `Fstore_substring` (editfns.c).
/// OBJ is a character or a string; its characters overwrite STRING starting at
/// IDX, and STRING itself is returned.
///
/// The bounds check is *per character*, not up front, so a too-long OBJ writes
/// what fits and only then signals — and the error names the PARTIALLY WRITTEN
/// string, because the datum is the string object:
///
/// ```text
/// (let ((s (copy-sequence "abc"))) (store-substring s 1 "XYZW"))
///   => (args-out-of-range "aXY" 3)
/// ```
fn store_substring(h: &mut ElispHost, a: &[Value]) -> R {
    if !h.is_string(&a[0]) {
        return Err(h.signal_wrong_type("stringp", &a[0]));
    }
    let mut chars: Vec<char> = h
        .str_text(&a[0])
        .expect("checked stringp")
        .chars()
        .collect();
    let idx = as_int(h, &a[1])?;
    let incoming: Vec<char> = match h.str_text(&a[2]) {
        Some(s) => s.chars().collect(),
        None => vec![char::from_u32(as_char(h, &a[2])?).unwrap_or('\u{fffd}')],
    };
    for (k, c) in incoming.into_iter().enumerate() {
        let pos = idx + k as i64;
        if pos < 0 || pos as usize >= chars.len() {
            // Flush what was written before naming the range, so the datum
            // shows the partial result exactly as Emacs's does.
            let text: String = chars.into_iter().collect();
            h.set_string_text(&a[0], text);
            return Err(format!("args-out-of-range: {} {pos}", h.print(&a[0], true)));
        }
        chars[pos as usize] = c;
    }
    let text: String = chars.into_iter().collect();
    h.set_string_text(&a[0], text);
    Ok(a[0].clone())
}

/// `(clear-string STRING)` — port of `Fclear_string` (fns.c): overwrite every
/// character of STRING with NUL, in place, and answer nil. The length is
/// unchanged (`(length (clear-string (copy-sequence "abc")))` reads 3 on the
/// string), which is what makes it useful for wiping a password buffer.
fn clear_string(h: &mut ElispHost, a: &[Value]) -> R {
    if !h.is_string(&a[0]) {
        return Err(h.signal_wrong_type("stringp", &a[0]));
    }
    let n = h.str_text(&a[0]).expect("checked stringp").chars().count();
    let text: String = std::iter::repeat_n('\0', n).collect();
    h.set_string_text(&a[0], text);
    Ok(Value::Undef)
}

// ── char-tables ──
/// `(make-char-table--new SUBTYPE INIT N-EXTRA)` — low-level allocator. The
/// public `make-char-table` (prelude) reads N-EXTRA from SUBTYPE's
/// `char-table-extra-slots' property before calling this. INIT fills every char
/// slot, and — as in `Fmake_char_table` — the default slot and the extras.
fn make_char_table_new(h: &mut ElispHost, a: &[Value]) -> R {
    let n = as_num(h, &a[2])?.0;
    let n = if n < 0 { 0 } else { n as usize };
    Ok(h.alloc(Obj::CharTable(CharTable::new(
        a[0].clone(),
        a[1].clone(),
        n,
    ))))
}
fn char_table_p(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(nil_or(matches!(h.obj(&a[0]), Some(Obj::CharTable(_)))))
}
fn char_table_subtype(h: &mut ElispHost, a: &[Value]) -> R {
    match h.obj(&a[0]) {
        Some(Obj::CharTable(t)) => Ok(t.subtype.clone()),
        _ => Err(wrong_char_table(h, &a[0])),
    }
}
fn char_table_parent(h: &mut ElispHost, a: &[Value]) -> R {
    match h.obj(&a[0]) {
        Some(Obj::CharTable(t)) => Ok(t.parent.clone()),
        _ => Err(wrong_char_table(h, &a[0])),
    }
}
fn set_char_table_parent(h: &mut ElispHost, a: &[Value]) -> R {
    if let Value::Obj(id) = &a[0] {
        if let Some(Obj::CharTable(t)) = h.arena.get_mut(*id as usize) {
            t.parent = a[1].clone();
            return Ok(a[1].clone());
        }
    }
    Err(wrong_char_table(h, &a[0]))
}
fn char_table_extra_slot(h: &mut ElispHost, a: &[Value]) -> R {
    let n = as_num(h, &a[1])?.0;
    match h.obj(&a[0]) {
        Some(Obj::CharTable(t)) => t
            .extra
            .get(n as usize)
            .filter(|_| n >= 0)
            .cloned()
            .ok_or_else(|| format!("args-out-of-range: {} {n}", h.print(&a[0], true))),
        _ => Err(wrong_char_table(h, &a[0])),
    }
}
fn set_char_table_extra_slot(h: &mut ElispHost, a: &[Value]) -> R {
    let n = as_num(h, &a[1])?.0;
    if let Value::Obj(id) = &a[0] {
        if let Some(Obj::CharTable(t)) = h.arena.get_mut(*id as usize) {
            if n >= 0 && (n as usize) < t.extra.len() {
                t.extra[n as usize] = a[2].clone();
                return Ok(a[2].clone());
            }
            return Err(format!("args-out-of-range: {} {n}", h.print(&a[0], true)));
        }
    }
    Err(wrong_char_table(h, &a[0]))
}
/// `(char-table-range CHAR-TABLE RANGE)` — RANGE is nil (the default slot), a
/// character, or a cons `(FROM . TO)` (value at FROM). `t` is invalid.
fn char_table_range(h: &mut ElispHost, a: &[Value]) -> R {
    if !matches!(h.obj(&a[0]), Some(Obj::CharTable(_))) {
        return Err(wrong_char_table(h, &a[0]));
    }
    match &a[1] {
        Value::Undef | Value::Bool(false) => match h.obj(&a[0]) {
            Some(Obj::CharTable(t)) => Ok(t.default.clone()),
            _ => unreachable!(),
        },
        Value::Bool(true) => {
            Err("Invalid RANGE argument to \u{2018}char-table-range\u{2019}".to_string())
        }
        Value::Int(_) => {
            let c = as_char(h, &a[1])?;
            Ok(h.char_table_ref(&a[0], c))
        }
        _ => {
            // A cons (FROM . TO): value at FROM (with fallback), like Emacs.
            if let Some(Obj::Cons(from, _)) = h.obj(&a[1]) {
                let from = from.clone();
                let c = as_char(h, &from)?;
                Ok(h.char_table_ref(&a[0], c))
            } else {
                Err("Invalid RANGE argument to \u{2018}char-table-range\u{2019}".to_string())
            }
        }
    }
}
/// `(--char-table-run-end-- TABLE FROM LIMIT)`: the last character, at most
/// LIMIT, of the run of characters starting at FROM that TABLE stores one value
/// for. This is the TO of chartab.c's `char_table_ref_and_range`, which
/// category.c's `modify-category-entry` walks a range with.
fn char_table_run_end(h: &mut ElispHost, a: &[Value]) -> R {
    let from = as_char(h, &a[1])?;
    let limit = as_char(h, &a[2])?;
    let Some(Obj::CharTable(t)) = h.obj(&a[0]) else {
        return Err(wrong_char_table(h, &a[0]));
    };
    let next = t
        .runs()
        .iter()
        .map(|(start, _)| *start)
        .find(|start| *start > from);
    let end = next.map_or(crate::host::MAX_CHAR, |n| n - 1).min(limit);
    Ok(Value::Int(end as i64))
}
/// `(set-char-table-range CHAR-TABLE RANGE VALUE)` — RANGE is nil (set default),
/// `t` (set every char), a character, or a cons `(FROM . TO)`.
fn set_char_table_range(h: &mut ElispHost, a: &[Value]) -> R {
    let id = match &a[0] {
        Value::Obj(id) if matches!(h.obj(&a[0]), Some(Obj::CharTable(_))) => *id,
        _ => return Err(wrong_char_table(h, &a[0])),
    };
    let val = a[2].clone();
    match &a[1] {
        Value::Undef | Value::Bool(false) => {
            if let Some(Obj::CharTable(t)) = h.arena.get_mut(id as usize) {
                t.default = val;
            }
        }
        Value::Bool(true) => {
            if let Some(Obj::CharTable(t)) = h.arena.get_mut(id as usize) {
                t.set_all(val);
            }
        }
        Value::Int(_) => {
            let c = as_char(h, &a[1])?;
            if let Some(Obj::CharTable(t)) = h.arena.get_mut(id as usize) {
                t.set_range(c, c, val);
            }
        }
        _ => {
            let (from, to) = match h.obj(&a[1]) {
                Some(Obj::Cons(f, t)) => (f.clone(), t.clone()),
                _ => {
                    return Err(
                        "Invalid RANGE argument to \u{2018}set-char-table-range\u{2019}"
                            .to_string(),
                    )
                }
            };
            let from = as_char(h, &from)?;
            let to = as_char(h, &to)?;
            if let Some(Obj::CharTable(t)) = h.arena.get_mut(id as usize) {
                if from <= to {
                    t.set_range(from, to, val);
                }
            }
        }
    }
    Ok(a[2].clone())
}
/// `(elisprs--copy-char-table TABLE)` — `copy_char_table`: a deep copy of the
/// sub-char-table tree and the extras; the parent is shared and the cached
/// ASCII slot is recomputed from the copy.
fn copy_char_table(h: &mut ElispHost, a: &[Value]) -> R {
    let copy = match h.obj(&a[0]) {
        Some(Obj::CharTable(t)) => t.copied(),
        _ => return Err(wrong_char_table(h, &a[0])),
    };
    Ok(h.alloc(Obj::CharTable(copy)))
}

/// `(elisprs--char-table-runs TABLE)` — the effective value of every character
/// as `((START . VALUE) …)`, runs of `eq` values merged: own value, else the
/// table's default, else the parent chain's — what `map_char_table` walks.
fn char_table_runs(h: &mut ElispHost, a: &[Value]) -> R {
    if !matches!(h.obj(&a[0]), Some(Obj::CharTable(_))) {
        return Err(wrong_char_table(h, &a[0]));
    }
    let mut breaks: Vec<u32> = vec![0];
    let mut cur = a[0].clone();
    while let Some(Obj::CharTable(t)) = h.obj(&cur) {
        breaks.extend(t.runs().iter().map(|(s, _)| *s));
        cur = t.parent.clone();
    }
    breaks.sort_unstable();
    breaks.dedup();
    let mut runs: Vec<(u32, Value)> = Vec::new();
    for b in breaks {
        let v = h.char_table_ref(&a[0], b);
        match runs.last() {
            Some((_, last)) if h.values_eq(last, &v) => {}
            _ => runs.push((b, v)),
        }
    }
    let items = runs
        .into_iter()
        .map(|(s, v)| h.cons(Value::Int(i64::from(s)), v))
        .collect();
    Ok(h.list_from(items))
}

/// `(optimize-char-table TABLE &optional TEST)` — collapse a sub-char-table
/// whose slots are all equal (by TEST: `equal` when nil, `eq` for `eq`) into one
/// value, then refresh the cached ASCII slot.
fn optimize_char_table(h: &mut ElispHost, a: &[Value]) -> R {
    let id = match &a[0] {
        Value::Obj(id) if matches!(h.obj(&a[0]), Some(Obj::CharTable(_))) => *id,
        _ => return Err(wrong_char_table(h, &a[0])),
    };
    let use_eq = a.get(1).and_then(|t| h.sym_name(t)).as_deref() == Some("eq");
    let mut table = match h.obj(&a[0]) {
        Some(Obj::CharTable(t)) => t.copied_exact(),
        _ => unreachable!(),
    };
    let same = |x: &Value, y: &Value| {
        if use_eq {
            h.values_eq(x, y)
        } else {
            el_equal(h, x, y)
        }
    };
    table.optimize(&same);
    if let Some(Obj::CharTable(t)) = h.arena.get_mut(id as usize) {
        *t = table;
    }
    Ok(Value::Undef)
}

fn wrong_char_table(h: &ElispHost, v: &Value) -> String {
    format!("wrong-type-argument: char-table-p {}", h.print(v, true))
}

// ── symbols / cells ──
fn symbol_name(h: &mut ElispHost, a: &[Value]) -> R {
    match h.sym_name(&a[0]) {
        Some(s) => Ok(h.new_string(s)),
        None => Err(format!(
            "wrong-type-argument: symbolp {}",
            h.print(&a[0], true)
        )),
    }
}
/// Classify the optional obarray argument shared by `intern`/`intern-soft`/
/// `unintern`: `None` (absent/nil → the global obarray), `Some(Some(id))` for a
/// private obarray, or an `obarrayp` type error. A non-nil, non-obarray value
/// signals `(wrong-type-argument obarrayp VALUE)`, matching Emacs's `CHECK_OBARRAY`.
fn obarray_arg(h: &ElispHost, v: Option<&Value>) -> Result<Option<u32>, String> {
    match v {
        None | Some(Value::Undef) | Some(Value::Bool(false)) => Ok(None),
        Some(ob) => match h.obj(ob) {
            Some(Obj::Obarray(d)) if d.global => Ok(None),
            Some(Obj::Obarray(_)) => match ob {
                Value::Obj(id) => Ok(Some(*id)),
                _ => Ok(None),
            },
            _ => Err(format!(
                "wrong-type-argument: obarrayp {}",
                h.print(ob, true)
            )),
        },
    }
}
fn intern_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let name = match h.str_text(&a[0]) {
        Some(s) => s.to_string(),
        None => {
            return Err(format!(
                "wrong-type-argument: stringp {}",
                h.print(&a[0], true)
            ))
        }
    };
    match obarray_arg(h, a.get(1))? {
        // `nil` and `t` are already in the global obarray in Emacs, so interning
        // their names hands back those very objects. elisprs represents them as
        // `Value::Undef`/`Value::Bool(true)` rather than heap symbols, and
        // creating a heap symbol *named* "nil" produced something that prints as
        // `nil`, is `symbolp`, and is not `eq` to nil — so `(and (intern "nil")
        // 1)` answered 1 where Emacs answers nil.
        None if name == "nil" => Ok(Value::Undef),
        None if name == "t" => Ok(Value::Bool(true)),
        None => Ok(h.intern(&name)),
        Some(id) => Ok(h.obarray_intern(id, &name)),
    }
}
/// `(obarray-make &optional SIZE)` — a fresh, empty private obarray. SIZE (a
/// vestigial capacity hint since Emacs 29's obarrays auto-grow) must be a
/// wholenum when supplied, matching Emacs's `CHECK_FIXNAT`.
fn obarray_make_fn(h: &mut ElispHost, a: &[Value]) -> R {
    if let Some(v) = a.first() {
        match v {
            Value::Int(n) if *n >= 0 => {}
            Value::Undef | Value::Bool(false) => {}
            _ => {
                return Err(format!(
                    "wrong-type-argument: wholenump {}",
                    h.print(v, true)
                ))
            }
        }
    }
    Ok(h.alloc(Obj::Obarray(crate::host::ObarrayData {
        symbols: std::collections::HashMap::new(),
        global: false,
    })))
}
/// `(obarrayp OBJECT)` — t iff OBJECT is an obarray. (Emacs 30 no longer accepts
/// a plain vector as an obarray, so neither do we.)
fn obarrayp_fn(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(nil_or(matches!(h.obj(&a[0]), Some(Obj::Obarray(_)))))
}
/// `(unintern NAME &optional OBARRAY)` — remove NAME (a symbol or string) from
/// OBARRAY, returning t if a symbol was removed, nil otherwise.
fn unintern_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let name = match h.str_text(&a[0]) {
        Some(s) => s.to_string(),
        None => h
            .sym_name(&a[0])
            .ok_or_else(|| format!("wrong-type-argument: stringp {}", h.print(&a[0], true)))?,
    };
    let removed = match obarray_arg(h, a.get(1))? {
        None => h.obarray_unintern_global(&name),
        Some(id) => h.obarray_unintern(id, &name),
    };
    Ok(nil_or(removed))
}
fn make_symbol_fn(h: &mut ElispHost, a: &[Value]) -> R {
    match h.str_text(&a[0]).map(str::to_string) {
        Some(s) => Ok(h.make_symbol(&s)),
        None => Err(format!(
            "wrong-type-argument: stringp {}",
            h.print(&a[0], true)
        )),
    }
}
fn set_fn(h: &mut ElispHost, a: &[Value]) -> R {
    h.set_dynamic_value(&a[0], a[1].clone())?;
    Ok(a[1].clone())
}
/// `(keywordp OBJECT)` — OBJECT is a symbol interned in the standard obarray
/// under a `:`-prefixed name.
///
/// Spelling alone is not the test: `(make-symbol ":u")` and
/// `(intern ":u" (obarray-make))` both read back as `:u` and are both non-keywords,
/// because `intern_driver` applies the keyword treatment only for the standard
/// obarray. Only the host knows which object the obarray holds, so this cannot
/// live in the prelude.
fn keywordp(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(Value::Bool(h.is_keyword(&a[0])))
}
/// `(symbol-value SYMBOL)` — SYMBOL's dynamic value.
///
/// A keyword is its own value, seeded into its value cell by `intern`. The
/// compiler already loads a keyword as a self-evaluating constant, so the only
/// way to reach this path with one is an indirect `(symbol-value SYM)`.
fn symbol_value(h: &mut ElispHost, a: &[Value]) -> R {
    if h.is_keyword(&a[0]) {
        return Ok(a[0].clone());
    }
    h.get_dynamic_value(&a[0])
}
/// `(makunbound SYMBOL)` — clear SYMBOL's value cell, returning SYMBOL.
fn makunbound(h: &mut ElispHost, a: &[Value]) -> R {
    h.unset_value(&a[0])?;
    Ok(a[0].clone())
}
/// `(fset SYMBOL DEFINITION)` — set SYMBOL's function cell, returning DEFINITION.
fn fset(h: &mut ElispHost, a: &[Value]) -> R {
    h.set_function_value(&a[0], a[1].clone())?;
    // A symbol pointed at a subr can be pointed at a *narrower* one before its
    // next call, so calls to it need the pre-argument arity guard from here on.
    h.note_subr_alias(&a[0], &a[1]);
    Ok(a[1].clone())
}
/// `(fmakunbound SYMBOL)` — data.c `Ffmakunbound`: empty SYMBOL's function cell
/// and return SYMBOL. `nil` and `t` are refused with `setting-constant`; a
/// keyword is not (only its value cell is constant).
fn fmakunbound(h: &mut ElispHost, a: &[Value]) -> R {
    if is_nil(&a[0]) || matches!(a[0], Value::Bool(true)) {
        let name = if is_nil(&a[0]) { "nil" } else { "t" };
        return Err(format!("setting-constant: {name}"));
    }
    h.set_function_value(&a[0], Value::Undef)?;
    Ok(a[0].clone())
}
/// `(fboundp SYMBOL)` — non-nil if SYMBOL has a function definition.
fn fboundp(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(nil_or(
        h.resolve_function(&a[0]).is_ok() || h.introspect_function_cell(&a[0]).is_some(),
    ))
}
/// `(indirect-function OBJECT)` — follow symbol→function-cell aliases to the final
/// function object (a subr/closure), or nil if undefined.
fn indirect_function(h: &mut ElispHost, a: &[Value]) -> R {
    let mut cur = a[0].clone();
    for _ in 0..64 {
        // `t` and `nil` ARE symbols in Emacs, with no function cell — so
        // `(indirect-function t)` is nil, not `t`. elisprs represents them as
        // `Value::Bool`/`Value::Undef` rather than heap symbols, so they miss the
        // symbol arm below and used to be returned unchanged, as if a non-symbol.
        if is_nil(&cur) || matches!(cur, Value::Bool(true)) {
            return Ok(Value::Undef);
        }
        match h.obj(&cur) {
            Some(Obj::Symbol(_)) => match h.introspect_function_cell(&cur) {
                Some(def) => cur = def,
                None => return Ok(Value::Undef),
            },
            _ => return Ok(cur),
        }
    }
    Ok(cur)
}
/// `(defvaralias NEW-ALIAS BASE-VARIABLE &optional DOCSTRING)` — make NEW-ALIAS a
/// variable alias for BASE-VARIABLE: value operations on either affect both. The
/// optional DOCSTRING is accepted and ignored (no interactive doc store). Returns
/// BASE-VARIABLE.
fn defvaralias(h: &mut ElispHost, a: &[Value]) -> R {
    h.defvaralias(&a[0], &a[1])
}
/// `(indirect-variable OBJECT)` — follow the `defvaralias` chain from OBJECT to the
/// base variable symbol, or return OBJECT unchanged when it is not a symbol.
fn indirect_variable(h: &mut ElispHost, a: &[Value]) -> R {
    match &a[0] {
        Value::Obj(id) => {
            let base = h.indirect_var(*id);
            Ok(Value::Obj(base))
        }
        _ => Ok(a[0].clone()),
    }
}
/// `(boundp SYMBOL)` — non-nil if SYMBOL currently has a value.
fn boundp(h: &mut ElispHost, a: &[Value]) -> R {
    check_symbol(h, &a[0])?;
    // nil and t are always bound; otherwise the value cell must resolve.
    let bound =
        is_nil(&a[0]) || matches!(a[0], Value::Bool(true)) || h.get_dynamic_value(&a[0]).is_ok();
    Ok(nil_or(bound))
}

// ── functional ──
// `funcall`/`apply`/`mapcar`/`mapc` are intercepted in `host::call_function`
// (they re-enter elisp, so they can't run inside a host borrow) — they are not
// plain subrs here.
fn identity(_h: &mut ElispHost, a: &[Value]) -> R {
    Ok(a[0].clone())
}
/// Where a print primitive's output goes: print.c `PRINTPREPARE`'s reading of
/// PRINTCHARFUN. nil means the value of `standard-output`; t is stdout in
/// batch; a buffer inserts at its point; a marker inserts at the marker and
/// moves it past the text; anything else is called once per character.
pub(crate) enum PrintDest {
    Stdout,
    Buffer(usize),
    Marker(Value),
    Function(Value),
}

/// Resolve PRINTCHARFUN (absent = nil) the way `PRINTPREPARE` does.
pub(crate) fn print_dest(h: &ElispHost, pcf: Option<&Value>) -> Result<PrintDest, String> {
    let mut v = pcf.cloned().unwrap_or(Value::Undef);
    if is_nil(&v) {
        v = h
            .find_symbol("standard-output")
            .and_then(|s| h.get_value(&s).ok())
            .unwrap_or(Value::Bool(true));
    }
    if is_nil(&v) {
        // `standard-output' itself nil: print.c then prints to the echo area,
        // which is stdout in batch.
        return Ok(PrintDest::Stdout);
    }
    if matches!(v, Value::Bool(true)) {
        return Ok(PrintDest::Stdout);
    }
    match h.obj(&v) {
        Some(Obj::Buffer(idx)) => {
            if h.buffers.get(*idx).is_none_or(|b| b.name.is_none()) {
                return Err("error: Selecting deleted buffer".to_string());
            }
            Ok(PrintDest::Buffer(*idx))
        }
        Some(Obj::Marker(m)) => {
            if m.borrow().buffer.is_none() {
                return Err("error: Marker does not point anywhere".to_string());
            }
            Ok(PrintDest::Marker(v.clone()))
        }
        _ => Ok(PrintDest::Function(v)),
    }
}

/// Send S to a non-function destination (`PRINTFINISH` for a buffer or a
/// marker: the text goes in at the insertion position, the marker ends after
/// it, the target buffer's point moves with the insertion, and the current
/// buffer is restored).
pub(crate) fn print_to(h: &mut ElispHost, dest: &PrintDest, s: &str) -> Result<(), String> {
    match dest {
        PrintDest::Stdout => h.emit(s),
        PrintDest::Buffer(idx) => {
            let old = h.current;
            h.current = *idx;
            h.cur_insert(s.chars().collect(), true);
            h.current = old;
        }
        PrintDest::Marker(mv) => {
            let Some(Obj::Marker(m)) = h.obj(mv) else {
                unreachable!("print_dest only yields markers here")
            };
            let m = m.clone();
            let (bi, pos) = {
                let md = m.borrow();
                (md.buffer.expect("checked in print_dest"), md.pos)
            };
            let old = h.current;
            h.current = bi;
            let (begv, zv, old_point) = {
                let b = h.cur_buf_ref();
                (b.begv, b.zv, b.point)
            };
            if pos < begv || pos > zv {
                h.current = old;
                return Err(
                    h.signal_error_arg("Marker is outside the accessible part of the buffer", mv)
                );
            }
            h.cur_buf().point = pos;
            let n = s.chars().count();
            h.cur_insert(s.chars().collect(), true);
            m.borrow_mut().pos = pos + n;
            h.cur_buf().point = if old_point >= pos {
                old_point + n
            } else {
                old_point
            };
            h.current = old;
        }
        PrintDest::Function(_) => {
            unreachable!("function destinations are driven by host::call_function")
        }
    }
    Ok(())
}

/// The text a print primitive produces, for the function-destination path in
/// `host::call_function`, which calls PRINTCHARFUN once per character outside
/// any host borrow. Returns None for an arity the subr itself must reject.
pub(crate) fn print_text(
    h: &mut ElispHost,
    name: &str,
    a: &[Value],
) -> Result<Option<String>, String> {
    Ok(Some(match name {
        "princ" if !a.is_empty() => h.print_checked(&a[0], false)?,
        "prin1" if !a.is_empty() => h.print_checked(&a[0], true)?,
        "print" if !a.is_empty() => format!("\n{}\n", h.print_checked(&a[0], true)?),
        "terpri" => "\n".to_string(),
        "write-char" if !a.is_empty() => {
            let c = write_char_code(h, &a[0])?;
            char::from_u32(c).unwrap_or('\u{fffd}').to_string()
        }
        _ => return Ok(None),
    }))
}

/// `(backquote-process S &optional LEVEL)` — backquote.el's expander; returns
/// `(TAG . CODE)`. See `crate::backquote`.
fn backquote_process_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let level = match a.get(1) {
        Some(Value::Int(n)) => *n,
        Some(v) if !is_nil(v) => return Err(h.signal_wrong_type("number-or-marker-p", v)),
        _ => 0,
    };
    let (tag, code) = crate::backquote::process(h, &a[0], level)?;
    Ok(h.cons(Value::Int(tag as i64), code))
}

/// print.c `Fwrite_char`: `CHECK_FIXNUM (character)`.
fn write_char_code(h: &mut ElispHost, v: &Value) -> Result<u32, String> {
    match v {
        Value::Int(n) => Ok(*n as u32),
        _ => Err(h.signal_wrong_type("fixnump", v)),
    }
}
/// `bolp` at POS (1-based) in TEXT whose accessible start is BEGV.
fn at_bol(text: &[char], begv: usize, pos: usize) -> bool {
    pos <= begv || text[pos - 2] == '\n'
}
/// `(terpri &optional PRINTCHARFUN ENSURE)`. With ENSURE, print.c writes the
/// newline only when the output is not already at the start of a line: for
/// stdout that is the last byte written there, for a buffer or marker it is
/// `bolp` at the insertion position, and a function destination is an error.
fn terpri(h: &mut ElispHost, a: &[Value]) -> R {
    let dest = print_dest(h, a.first())?;
    let ensure = a.get(1).is_some_and(|v| !is_nil(v));
    let needed = if !ensure {
        true
    } else {
        match &dest {
            PrintDest::Stdout => h.stdout_last != '\n',
            PrintDest::Buffer(idx) => {
                let b = &h.buffers[*idx];
                !at_bol(&b.text, b.begv, b.point)
            }
            PrintDest::Marker(mv) => match h.obj(mv) {
                Some(Obj::Marker(m)) => {
                    let md = m.borrow();
                    let b = &h.buffers[md.buffer.expect("checked in print_dest")];
                    !at_bol(&b.text, b.begv, md.pos)
                }
                _ => true,
            },
            PrintDest::Function(f) => {
                let f = f.clone();
                return Err(h.signal_error_arg("Unsupported function argument", &f));
            }
        }
    };
    if needed {
        print_to(h, &dest, "\n")?;
    }
    Ok(nil_or(needed))
}
/// `(print OBJECT &optional PRINTCHARFUN)` — `prin1` surrounded by newlines.
/// print.c writes a newline BEFORE the object as well as after ("Output a
/// newline, then OBJECT, then a newline"), which is what separates successive
/// `print` calls; emitting only the trailing one made
/// `(with-output-to-string (print 'a))` answer "a\n" instead of "\na\n".
fn print_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let dest = print_dest(h, a.get(1))?;
    let s = h.print_checked(&a[0], true)?;
    print_to(h, &dest, &format!("\n{s}\n"))?;
    Ok(a[0].clone())
}
/// `(write-char CHAR &optional PRINTCHARFUN)` — output one character; returns
/// CHAR. print.c checks CHAR with `CHECK_FIXNUM`, so a non-integer is
/// `(wrong-type-argument fixnump X)`.
fn write_char_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let c = write_char_code(h, &a[0])?;
    let dest = print_dest(h, a.get(1))?;
    print_to(
        h,
        &dest,
        &char::from_u32(c).unwrap_or('\u{fffd}').to_string(),
    )?;
    Ok(a[0].clone())
}
fn prin1_to_string(h: &mut ElispHost, a: &[Value]) -> R {
    // `(prin1-to-string OBJECT &optional NOESCAPE)` — a non-nil NOESCAPE prints
    // the way `princ` does (no quotes, no escapes).
    let readable = a.get(1).is_none_or(is_nil);
    Ok(h.new_string(h.print_checked(&a[0], readable)?))
}

// ── nonlocal exits ──
// `throw` records the (tag, value) and aborts via the error channel; `catch`
// (an intrinsic in host::call_function) intercepts it.
fn throw_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let tag = a[0].clone();
    let val = a.get(1).cloned().unwrap_or(Value::Undef);
    let tags = h.catch_tags.clone();
    if tags.iter().any(|t| h.values_eq(t, &tag)) {
        h.pending_throw = Some((tag, val));
        Err("--throw--".to_string())
    } else {
        // No matching catch on the stack: signal (no-catch TAG VALUE).
        let sym = h.intern("no-catch");
        let data = h.list_from(vec![tag, val]);
        let display = h.print(&data, true);
        let obj = h.cons(sym, data);
        let msg = format!("no-catch: {display}");
        h.set_pending_error(&msg, obj);
        Err(msg)
    }
}
/// Apply the default `text-quoting-style` (`curve`) to a format *template*:
/// a grave accent becomes a left single quotation mark and an apostrophe a right
/// one. This is the message half of `styled_format` (`src/editfns.c`), which
/// `Ferror`, `Fuser_error` and `Fmessage` all route through — `Ferror` is
/// literally `Fsignal (Qerror, list1 (Fformat_message (nargs, args)))`.
///
/// Only the template is translated, never a substituted argument: the scan
/// happens while walking the format string, and `%s` output is not re-scanned.
/// `\=` is NOT an escape here — that is `substitute-command-keys`, a different
/// function. Measured on GNU Emacs 30.2: `(error "a %s" "x `y'")` keeps the
/// argument's quotes, and `(error "a \\=`b c")` still curves the backtick.
fn curve_quotes(h: &ElispHost, fmt: &str) -> String {
    // doc.c `Ftext_quoting_style`: `grave` leaves both alone, `straight` turns a
    // grave accent into an apostrophe, nil or anything else is `curve`.
    let style = h
        .find_symbol("text-quoting-style")
        .and_then(|s| match h.obj(&s) {
            Some(Obj::Symbol(d)) => d.value.clone(),
            _ => None,
        })
        .and_then(|v| h.sym_name(&v));
    fmt.chars()
        .map(|c| match (c, style.as_deref()) {
            (_, Some("grave")) => c,
            ('`', Some("straight")) => '\'',
            (_, Some("straight")) => c,
            ('`', _) => '\u{2018}',
            ('\'', _) => '\u{2019}',
            _ => c,
        })
        .collect()
}

/// `el_format` with the format template curve-quoted (`format-message`).
fn el_format_message(h: &mut ElispHost, a: &[Value]) -> Result<String, String> {
    match a
        .first()
        .and_then(|v| h.str_text(v))
        .map(|t| curve_quotes(h, t))
    {
        Some(curved) => {
            let mut args = a.to_vec();
            args[0] = h.new_string(curved);
            el_format(h, &args)
        }
        // A non-string template is el_format's error to report, unchanged.
        None => el_format(h, a),
    }
}

fn error_fn(h: &mut ElispHost, a: &[Value]) -> R {
    // Error object: (error "MESSAGE"). Keep it for condition-case.
    let msg = el_format_message(h, a)?;
    let esym = h.intern("error");
    let mstr = h.new_string(msg.clone());
    let data = h.list_from(vec![mstr]);
    let obj = h.cons(esym, data);
    let full = format!("error: {msg}");
    h.set_pending_error(&full, obj);
    Err(full)
}
fn user_error_fn(h: &mut ElispHost, a: &[Value]) -> R {
    // Like `error`, but signals the `user-error` condition.
    let msg = el_format_message(h, a)?;
    let esym = h.intern("user-error");
    let mstr = h.new_string(msg.clone());
    let data = h.list_from(vec![mstr]);
    let obj = h.cons(esym, data);
    let full = format!("user-error: {msg}");
    h.set_pending_error(&full, obj);
    Err(full)
}
/// `(get SYM PROP)` read from Rust. Symbol plists live in the prelude's
/// `symbol-plist--table` (an `eq` table keyed by the symbol), so this is the
/// same lookup the prelude's `get` does, without a round trip through elisp.
fn symbol_get(h: &mut ElispHost, sym: &Value, prop: &str) -> Value {
    let table_sym = h.intern("symbol-plist--table");
    let Ok(table) = h.get_dynamic_value(&table_sym) else {
        return Value::Undef;
    };
    let plist = gethash(h, &[sym.clone(), table]).unwrap_or(Value::Undef);
    let prop = h.intern(prop);
    h.plist_get_eq(&plist, &prop)
}
/// `(signal ERROR-SYMBOL DATA)` — eval.c `Fsignal` / `signal_or_quit`, 31.1.
///
/// A nil ERROR-SYMBOL takes the symbol from `(car DATA)` (and the rest as
/// DATA); a nil or non-cons DATA makes it `error`. The symbol must be a symbol
/// (`wrong-type-argument symbolp`) and must have `error-conditions`, or the
/// signal becomes `(error "Invalid error symbol" SYM)`; a non-list conditions
/// property is `wrong-type-argument listp`.
fn signal_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let (mut symv, mut data) = (a[0].clone(), a.get(1).cloned().unwrap_or(Value::Undef));
    // Emacs 31 made DATA optional: `(signal ERR)` with ERR a whole error
    // object `(SYMBOL . DATA)` re-signals it, which is how files.el's
    // `files--ensure-directory` re-raises a caught error. With DATA given, a
    // cons ERROR-SYMBOL is still `(wrong-type-argument symbolp ...)`.
    let whole_error = match h.obj(&symv) {
        Some(Obj::Cons(car, cdr)) if is_nil(&data) => Some((car.clone(), cdr.clone())),
        _ => None,
    };
    if let Some((car, cdr)) = whole_error {
        symv = car;
        data = cdr;
    } else if is_nil(&symv) {
        match h.obj(&data) {
            Some(Obj::Cons(car, cdr)) => {
                let (car, cdr) = (car.clone(), cdr.clone());
                symv = car;
                data = cdr;
            }
            _ => symv = h.intern("error"),
        }
    }
    let is_symbol =
        matches!(symv, Value::Bool(true)) || matches!(h.obj(&symv), Some(Obj::Symbol(_)));
    if !is_symbol {
        return Err(format!(
            "wrong-type-argument: symbolp {}",
            h.print(&symv, true)
        ));
    }
    let conditions = symbol_get(h, &symv, "error-conditions");
    if is_nil(&conditions) {
        let msg = h.new_string("Invalid error symbol");
        let err = h.intern("error");
        let obj = h.list_from(vec![err, msg, symv.clone()]);
        let text = format!("error: Invalid error symbol: {}", h.print(&symv, true));
        h.set_pending_error(&text, obj);
        return Err(text);
    }
    if !matches!(h.obj(&conditions), Some(Obj::Cons(..))) {
        return Err(format!(
            "wrong-type-argument: listp {}",
            h.print(&conditions, true)
        ));
    }
    let sym = h.sym_name(&symv).unwrap_or_else(|| "error".to_string());
    let display = h.print(&data, true);
    let obj = h.cons(symv, data);
    let msg = format!("{sym}: {display}");
    h.set_pending_error(&msg, obj);
    Err(msg)
}

// ── strings / format / IO ──
fn concat_fn(h: &mut ElispHost, a: &[Value]) -> R {
    // Fconcat: each argument is a string, nil, or a list/vector of CHARACTERS.
    // Errors are per-argument, left to right: a non-char element signals
    // `characterp' naming it ((concat '(a)) => characterp a), a dotted list
    // names its tail ((concat '(1 . 2)) => listp 2), and a non-sequence names
    // itself ((concat t) => sequencep t).
    let mut out = String::new();
    // Where each argument's characters land in the result, so a string
    // argument's text properties follow them (`Fconcat` copies intervals the
    // same way). A `None` piece is that many property-less characters — the
    // char-list and vector arguments, which carry none.
    let mut pieces: Vec<(Option<std::sync::Arc<String>>, usize, usize)> = Vec::new();
    let mut carried = 0usize;
    // A char code Emacs accepts (characterp: 0..=#x3FFFFF); codes valid in
    // Emacs but unrepresentable as a Rust char (surrogates, > #x10FFFF)
    // degrade to U+FFFD rather than mis-signalling characterp.
    let push_char = |h: &ElispHost, out: &mut String, it: &Value| -> Result<(), String> {
        match it {
            Value::Int(c) if (0..=0x3F_FFFF).contains(c) => {
                out.push(char::from_u32(*c as u32).unwrap_or('\u{FFFD}'));
                Ok(())
            }
            _ => Err(format!(
                "wrong-type-argument: characterp {}",
                h.print(it, true)
            )),
        }
    };
    for v in a {
        if is_nil(v) {
            continue;
        }
        match h.str_arc(v) {
            Some(s) => {
                let n = s.chars().count();
                out.push_str(&s);
                pieces.push((Some(s), 0, n));
                carried += n;
            }
            None => match h.obj(v) {
                Some(Obj::Vector(items)) => {
                    for it in items.clone() {
                        push_char(h, &mut out, &it)?;
                    }
                }
                Some(Obj::Cons(..)) => {
                    // concat_to_string validates each list arg's STRUCTURE
                    // (list_length => listp on a dotted tail) before checking
                    // any element: (concat '(a . 2)) => listp 2, not
                    // characterp a. seq_vec_checked is exactly that walk.
                    for it in h.seq_vec_checked(v)? {
                        push_char(h, &mut out, &it)?;
                    }
                }
                _ => {
                    return Err(format!(
                        "wrong-type-argument: sequencep {}",
                        h.print(v, true)
                    ))
                }
            },
        }
        // Whatever this argument contributed that was not a string is that many
        // property-less characters, and the offsets after it depend on them.
        let so_far = out.chars().count();
        if so_far > carried {
            pieces.push((None, 0, so_far - carried));
            carried = so_far;
        }
    }
    let (out, key) = h.new_string_keyed(out);
    h.string_copy_props(&key, &pieces);
    Ok(out)
}
/// A parsed `%`-directive: `%[-][0][width][.prec]CONV`.
struct FmtSpec {
    left: bool,
    zero: bool,
    plus: bool,
    space: bool,
    alt: bool,
    width: usize,
    prec: Option<usize>,
    conv: char,
}

/// The integer argument of `%d`/`%i`/`%o`/`%x`/`%X`, as editfns.c
/// `styled_format` dispatches on it.
enum IntArg {
    /// A fixnum, or a float whose magnitude fits a `uintmax_t` under
    /// `%o`/`%x`/`%X`: formatted by `sprintf`.
    Fixnum(BigInt),
    /// A float under `%d`/`%i`: `sprintf ("%.0f", trunc (x))`.
    FloatD(f64),
    /// A bignum, or a float too large for `uintmax_t` under `%o`/`%x`/`%X`:
    /// formatted by `bignum_to_c_string`.
    Bignum(BigInt),
}

/// One integer conversion of editfns.c `styled_format`, padding included.
///
/// The text is built from the same pieces in the same order as the C:
/// leading padding, the sign and `0x` taken from the start of the `sprintf`
/// output, the prefix array (sign and `0x` of a bignum), the excess-precision
/// zeros, the rest of the `sprintf` output, trailing padding. A bignum's
/// precision counts its `-` sign (`(format "%.25d" (- (expt 2 70)))` has 25
/// characters), and a `0` flag is dropped when a precision is given.
fn format_integer(arg: IntArg, spec: &FmtSpec) -> String {
    use num_traits::{Signed, Zero};
    let conv = spec.conv;
    let sharp = spec.alt && !matches!(conv, 'd' | 'i');
    let plus = spec.plus;
    let space = spec.space && !plus;
    let zero_flag = spec.zero && !spec.left && spec.prec.is_none();
    let radix = match conv {
        'o' => 8,
        'x' | 'X' => 16,
        _ => 10,
    };
    let digits = |n: &BigInt| {
        let s = n.abs().to_str_radix(radix);
        if conv == 'X' {
            s.to_uppercase()
        } else {
            s
        }
    };
    let sign_char = |negative: bool| {
        if negative {
            "-"
        } else if plus {
            "+"
        } else if space {
            " "
        } else {
            ""
        }
    };
    // C printf's integer precision: at least PREC digits, none for a zero
    // value at precision 0.
    let printf_digits = |n: &BigInt| match spec.prec {
        Some(0) if n.is_zero() => String::new(),
        Some(p) => {
            let d = digits(n);
            format!("{}{d}", "0".repeat(p.saturating_sub(d.len())))
        }
        None => digits(n),
    };
    // P is the `sprintf` (or `bignum_to_c_string`) output, PREC the precision
    // it was given; EXCESS is what is left over for leading zeros.
    let mut prefix = String::new();
    let (p, excess) = match arg {
        IntArg::Fixnum(n) => {
            let mut d = printf_digits(&n);
            // printf's `#` with `o` raises the precision so the first digit is 0.
            if sharp && conv == 'o' && !d.starts_with('0') {
                d.insert(0, '0');
            }
            if sharp && radix == 16 && !n.is_zero() {
                d.insert_str(0, if conv == 'X' { "0X" } else { "0x" });
            }
            (format!("{}{d}", sign_char(n.is_negative())), 0)
        }
        IntArg::FloatD(x) => {
            let t = x.trunc();
            let n = <BigInt as num_traits::FromPrimitive>::from_f64(t).unwrap_or_default();
            let p = format!("{}{}", sign_char(n.is_negative()), digits(&n));
            let signedp = usize::from(!p.starts_with(|c: char| c.is_ascii_digit()));
            let len = p.len() - signedp;
            (p, spec.prec.map_or(0, |pr| pr.saturating_sub(len)))
        }
        IntArg::Bignum(n) => {
            let negative = n.is_negative();
            let p = format!("{}{}", if negative { "-" } else { "" }, digits(&n));
            if !negative && (plus || space) {
                prefix.push(if plus { '+' } else { ' ' });
            }
            if sharp && radix == 16 {
                prefix.push('0');
                prefix.push(conv);
            }
            let len = p.len();
            (p, spec.prec.map_or(0, |pr| pr.saturating_sub(len)))
        }
    };
    let pb = p.as_bytes();
    let mut leading_zeros = excess;
    let numwidth = prefix.len() + p.len() + excess;
    let mut padding = spec.width.saturating_sub(numwidth);
    let signedp = usize::from(matches!(pb.first(), Some(b'-' | b'+' | b' ')));
    let beglen = signedp
        + if pb.get(signedp) == Some(&b'0') && pb.get(signedp + 1) == Some(&(conv as u8)) {
            2
        } else {
            0
        };
    if zero_flag && pb.get(beglen).is_some_and(u8::is_ascii_hexdigit) {
        leading_zeros += padding;
        padding = 0;
    }
    if leading_zeros == 0 && sharp && conv == 'o' && pb.get(beglen) != Some(&b'0') {
        leading_zeros += 1;
        padding -= usize::from(padding != 0);
    }
    let (lead, trail) = if spec.left {
        (0, padding)
    } else {
        (padding, 0)
    };
    format!(
        "{}{}{prefix}{}{}{}",
        " ".repeat(lead),
        &p[..beglen],
        "0".repeat(leading_zeros),
        &p[beglen..],
        " ".repeat(trail)
    )
}

/// Rust's `core::fmt` stores a dynamic precision in a `u16`, so `format!` with
/// a precision >= 65536 panics ("Formatting argument out of range"). Emacs (via
/// C `printf`) accepts an arbitrary precision, padding past the value's exact
/// decimal expansion with zeros. `FMT_PREC_CAP` is the largest precision Rust's
/// formatter accepts; beyond it we render at the cap and append the remaining
/// zeros ourselves, reproducing Emacs's output without the panic.
const FMT_PREC_CAP: usize = 65535;

/// A finite `f64`'s exact decimal expansion has at most ~1074 fractional (767
/// significant) digits; past that every additional digit is `0`. `%g` trims
/// trailing zeros, so any precision at or above this cap yields the identical
/// trimmed string — clamping here keeps `format_g` under `FMT_PREC_CAP` without
/// changing its output.
const FMT_G_CAP: usize = 1100;

/// `%f` body: `v` with exactly `prec` fractional digits, avoiding Rust's
/// `u16`-precision panic for huge `prec` by rendering at `FMT_PREC_CAP` and
/// zero-padding the tail (which C `printf`/Emacs also emit as zeros).
fn format_fixed(v: f64, prec: usize) -> String {
    if prec <= FMT_PREC_CAP {
        format!("{:.*}", prec, v)
    } else {
        let mut s = format!("{:.*}", FMT_PREC_CAP, v);
        s.push_str(&"0".repeat(prec - FMT_PREC_CAP));
        s
    }
}

/// C-style `%e`: a `prec`-digit mantissa, then `e`, a sign, and a ≥2-digit
/// exponent (`1000.0` => `1.000000e+03`). Rust's `{:e}` omits the padding/sign.
/// C-printf `%g`: pick `%e` or `%f` by the decimal exponent, with PREC
/// significant digits; trailing zeros are trimmed unless `alt` (the `#` flag).
fn format_g(v: f64, prec: usize, alt: bool) -> String {
    let p = prec.clamp(1, FMT_G_CAP);
    let strip = |mant: &str| -> String {
        if mant.contains('.') {
            mant.trim_end_matches('0').trim_end_matches('.').to_string()
        } else {
            mant.to_string()
        }
    };
    // Decimal exponent X from an %e rendering (0 for a zero value).
    let x: i32 = if v == 0.0 {
        0
    } else {
        let es = format!("{:.*e}", p - 1, v);
        es[es.find('e').unwrap() + 1..].parse().unwrap_or(0)
    };
    if x >= -4 && x < p as i32 {
        let prec_f = (p as i32 - 1 - x).max(0) as usize;
        let s = format!("{:.*}", prec_f, v);
        if alt {
            s
        } else {
            strip(&s)
        }
    } else {
        let body = format_e(v, p - 1);
        if alt {
            body
        } else {
            match body.find('e') {
                Some(ep) => format!("{}{}", strip(&body[..ep]), &body[ep..]),
                None => strip(&body),
            }
        }
    }
}
/// Insert the decimal point printf's `#` flag guarantees: before the exponent of
/// an `e` form, else at the end, when S has none.
fn with_decimal_point(s: String) -> String {
    if s.contains('.') {
        return s;
    }
    match s.find('e') {
        Some(ep) => format!("{}.{}", &s[..ep], &s[ep..]),
        None => s + ".",
    }
}
fn format_e(v: f64, prec: usize) -> String {
    // Beyond FMT_PREC_CAP, render the mantissa at the cap and zero-pad the extra
    // fractional digits before the exponent (Rust's u16 precision would panic).
    let s = if prec <= FMT_PREC_CAP {
        format!("{:.*e}", prec, v)
    } else {
        let capped = format!("{:.*e}", FMT_PREC_CAP, v);
        match capped.find('e') {
            Some(epos) => {
                let mut m = capped[..epos].to_string();
                m.push_str(&"0".repeat(prec - FMT_PREC_CAP));
                m.push_str(&capped[epos..]);
                m
            }
            None => capped,
        }
    };
    match s.find('e') {
        Some(epos) => {
            let (mant, rest) = s.split_at(epos);
            let exp = &rest[1..];
            let (sign, digits) = match exp.strip_prefix('-') {
                Some(d) => ('-', d),
                None => ('+', exp.strip_prefix('+').unwrap_or(exp)),
            };
            format!("{mant}e{sign}{digits:0>2}")
        }
        None => s,
    }
}

/// Prefix an explicit sign on a non-negative numeric body per the `+`/space
/// flags (`+` wins over space). A leading `-` already carries the sign.
fn apply_sign(body: String, spec: &FmtSpec) -> String {
    if body.starts_with('-') {
        body
    } else if spec.plus {
        format!("+{body}")
    } else if spec.space {
        format!(" {body}")
    } else {
        body
    }
}

/// A character's width in display columns — Emacs's `char-width` (`indent.c`),
/// which reads `char-width-table` and the `ctl-arrow`/`tab-width` display model.
///
/// Measured against `emacs -Q --batch` (GNU Emacs 30.2):
/// `(list (char-width ?\t) (char-width ?\n) (char-width 7) (char-width 127)
/// (char-width 200) (char-width ?中))` => `(8 0 2 2 1 2)`. A TAB is a flat
/// `tab-width` here rather than a distance to the next tab stop, which
/// `(string-width "a\t")` => `9` confirms.
pub fn char_display_width(c: u32) -> usize {
    match c {
        0x0A => 0,                    // newline occupies no columns
        0x09 => 8,                    // tab-width
        0..=0x1F | 0x7F => 2,         // control chars display as `^X`
        0x0300..=0x036F => 0,         // combining diacriticals
        0x200B..=0x200F => 0,         // zero-width / directional marks
        0x1100..=0x115F               // Hangul Jamo
        | 0x2E80..=0x303E             // CJK radicals … symbols
        | 0x3041..=0x33FF             // Hiragana … CJK compatibility
        | 0x3400..=0x4DBF             // CJK ext A
        | 0x4E00..=0x9FFF             // CJK unified
        | 0xA000..=0xA4CF             // Yi
        | 0xAC00..=0xD7A3             // Hangul syllables
        | 0xF900..=0xFAFF             // CJK compatibility ideographs
        | 0xFF00..=0xFF60             // fullwidth forms
        | 0xFFE0..=0xFFE6
        | 0x1F300..=0x1F64F           // misc symbols & pictographs, emoticons
        | 0x1F900..=0x1F9FF           // supplemental symbols & pictographs
        | 0x1FA70..=0x1FAFF           // symbols & pictographs ext A
        | 0x20000..=0x3FFFD => 2,     // CJK ext B+
        _ => 1,
    }
}

/// A string's width in display columns (Emacs's `string-width`).
pub fn string_display_width(s: &str) -> usize {
    s.chars().map(|c| char_display_width(c as u32)).sum()
}

/// The longest prefix of `s` whose display width is at most `cols`.
///
/// `format`'s `%.Ns` precision is a column budget, not a character count, and a
/// character that would overflow the budget is dropped whole:
/// `(format "%.3s" "\tXY")` is `""` and `(format "%.3s" "中中")` is `"中"` in
/// Emacs 30.2.
fn truncate_to_columns(s: &str, cols: usize) -> String {
    let mut used = 0;
    let mut out = String::new();
    for c in s.chars() {
        let w = char_display_width(c as u32);
        if used + w > cols {
            break;
        }
        used += w;
        out.push(c);
    }
    out
}

/// Pad `body` to `spec.width` honoring the `-` (left) and `0` (zero-fill) flags.
/// Zero-fill only applies to right-justified numerics and goes after any sign.
///
/// The field width is a count of display *columns*, as every conversion shows:
/// `(format "%6s|" "中")` is `"    中|"`, `(format "%4c|" ?中)` is `"  中|"` and
/// `(format "%6S|" "中")` is `"  \"中\"|"` — each padded to six columns, not six
/// characters.
fn pad(body: String, spec: &FmtSpec) -> String {
    let body_cols = string_display_width(&body);
    if body_cols >= spec.width {
        return body;
    }
    let fill = spec.width - body_cols;
    if spec.left {
        format!("{body}{}", " ".repeat(fill))
    } else if spec.zero && matches!(spec.conv, 'd' | 'o' | 'x' | 'X' | 'e' | 'f' | 'g') {
        // Keep any leading sign (-, +, space) and `0x`/`0X` radix prefix ahead of
        // the zero fill: `%#010x` of 255 => `0x000000ff`.
        let mut p = 0;
        if matches!(body.chars().next(), Some('-' | '+' | ' ')) {
            p = 1;
        }
        if body[p..].starts_with("0x") || body[p..].starts_with("0X") {
            p += 2;
        }
        format!("{}{}{}", &body[..p], "0".repeat(fill), &body[p..])
    } else {
        format!("{}{body}", " ".repeat(fill))
    }
}

/// One directive of a format string and the output it produced: the format
/// characters `[fbeg, fend)`, the output characters `[out_start, out_end)`
/// (padding included), where the argument's own text starts, and — for `%s` of
/// a string — the string whose text properties belong on it.
struct FmtField {
    fbeg: usize,
    fend: usize,
    /// Where the directive's output begins, left padding included.
    fstart: usize,
    text_start: usize,
    out_end: usize,
    carries: Option<std::sync::Arc<String>>,
}

fn el_format(h: &ElispHost, a: &[Value]) -> Result<String, String> {
    el_format_pieces(h, a).map(|(s, _)| s)
}

/// `format`, also reporting where each run of the result came from so the
/// caller can carry text properties onto it. Emacs propagates two things: the
/// properties of the format string's own literal text, and those of a `%s`
/// argument, each onto the characters they produced. Padding carries none.
fn el_format_pieces(h: &ElispHost, a: &[Value]) -> Result<(String, Vec<FmtField>), String> {
    let fmt = match h.str_text(&a[0]) {
        Some(s) => s.to_string(),
        None => {
            return Err(format!(
                "wrong-type-argument: stringp {}",
                h.print(&a[0], true)
            ))
        }
    };
    // Every directive's span in the format string and in the result, for the
    // text-property transfer (`format_fn`).
    let mut fields: Vec<FmtField> = Vec::new();
    let fmt_len = fmt.chars().count();
    let mut out = String::new();
    let mut ai = 1;
    let mut chars = fmt.chars().peekable();
    while let Some(c) = chars.next() {
        if c != '%' {
            out.push(c);
            continue;
        }
        let fbeg = fmt_len - chars.clone().count() - 1;
        // %% is a literal percent and takes no flags/argument.
        if chars.peek() == Some(&'%') {
            chars.next();
            let at = out.chars().count();
            out.push('%');
            fields.push(FmtField {
                fbeg,
                fend: fbeg + 2,
                fstart: at,
                text_start: at,
                out_end: at + 1,
                carries: None,
            });
            continue;
        }
        // Optional argument field `N$` (N starts 1-9, so it can't be confused
        // with a `0` flag) — selects the Nth argument: `%2$s` uses arg 2.
        let mut field: Option<usize> = None;
        let mut width = 0usize;
        let mut width_done = false;
        if matches!(chars.peek(), Some('1'..='9')) {
            let mut num = 0usize;
            while let Some(&d) = chars.peek() {
                if d.is_ascii_digit() {
                    num = num * 10 + (d as usize - '0' as usize);
                    chars.next();
                } else {
                    break;
                }
            }
            if chars.peek() == Some(&'$') {
                chars.next();
                field = Some(num);
            } else {
                // Not a field — those digits were the width.
                width = num;
                width_done = true;
            }
        }
        // flags
        let (mut left, mut zero, mut plus, mut space, mut alt) =
            (false, false, false, false, false);
        if !width_done {
            while let Some(&f) = chars.peek() {
                match f {
                    '-' => left = true,
                    '0' => zero = true,
                    '+' => plus = true,
                    ' ' => space = true,
                    '#' => alt = true,
                    _ => break,
                }
                chars.next();
            }
        }
        // width
        if !width_done {
            while let Some(&d) = chars.peek() {
                if d.is_ascii_digit() {
                    width = width * 10 + (d as usize - '0' as usize);
                    chars.next();
                } else {
                    break;
                }
            }
        }
        // .precision
        let mut prec = None;
        if chars.peek() == Some(&'.') {
            chars.next();
            let mut p = 0usize;
            while let Some(&d) = chars.peek() {
                if d.is_ascii_digit() {
                    p = p * 10 + (d as usize - '0' as usize);
                    chars.next();
                } else {
                    break;
                }
            }
            prec = Some(p);
        }
        // A `%` with no conversion character after it is an error, not a literal
        // `%`: `(format "abc%")` signals in Emacs and answered "abc%" here.
        let Some(conv) = chars.next() else {
            return Err("Format string ends in middle of format specifier".to_string());
        };
        // editfns.c `styled_format`: a `%` conversion copies a `%` whatever the
        // flags, width and precision before it, and consumes no argument — but a
        // field number still repositions the argument counter.
        if conv == '%' {
            if let Some(f) = field {
                ai = f;
            }
            let at = out.chars().count();
            out.push('%');
            fields.push(FmtField {
                fbeg,
                fend: fmt_len - chars.clone().count(),
                fstart: at,
                text_start: at,
                out_end: at + 1,
                carries: None,
            });
            continue;
        }
        let mut spec = FmtSpec {
            left,
            zero,
            plus,
            space,
            alt,
            width,
            prec,
            conv,
        };
        // Emacs error messages for the argument step. The curly apostrophe in
        // BAD_TYPE matches `emacs -Q` (default text-quoting-style).
        const NOT_ENOUGH: &str = "Not enough arguments for format string";
        const BAD_TYPE: &str = "Format specifier doesn\u{2019}t match argument type";
        // A field number selects an explicit (1-based) argument; otherwise take
        // the next one in sequence.
        let idx = field.unwrap_or(ai);
        // The numeric/char conversions need a number-valued argument; a missing
        // one is "Not enough arguments", a non-number is a type mismatch.
        let numf = |idx: usize| -> Result<(i64, f64, bool), String> {
            let arg = a.get(idx).ok_or_else(|| NOT_ENOUGH.to_string())?;
            as_num(h, arg).map_err(|_| BAD_TYPE.to_string())
        };
        // The integer directives (%d/%o/%x/%X) print the *exact* value: a bignum
        // must not be truncated to an i64. A float argument truncates toward
        // zero, as in Emacs.
        let bigf = |idx: usize| -> Result<BigInt, String> {
            let arg = a.get(idx).ok_or_else(|| NOT_ENOUGH.to_string())?;
            match arg {
                Value::Float(f) => <BigInt as num_traits::FromPrimitive>::from_f64(f.trunc())
                    .ok_or_else(|| BAD_TYPE.to_string()),
                _ => as_int_exact(h, arg).map_err(|_| BAD_TYPE.to_string()),
            }
        };
        // How styled_format dispatches an integer conversion on its argument.
        let int_arg = |idx: usize| -> Result<IntArg, String> {
            let arg = a.get(idx).ok_or_else(|| NOT_ENOUGH.to_string())?;
            Ok(match arg {
                Value::Float(f) if matches!(conv, 'd' | 'i') => IntArg::FloatD(*f),
                // `abs_d < UINTMAX_MAX + 1.0`
                Value::Float(f) if f.abs() < 18446744073709551616.0 => IntArg::Fixnum(bigf(idx)?),
                Value::Float(_) => IntArg::Bignum(bigf(idx)?),
                _ if h.is_bignum(arg) => IntArg::Bignum(bigf(idx)?),
                _ => IntArg::Fixnum(bigf(idx)?),
            })
        };
        // A `%s` of a string argument reproduces that string's characters, so
        // its properties belong on them. Truncation by a precision drops the
        // tail but keeps the head's, which the offsets below already express.
        let carries: Option<std::sync::Arc<String>> = match conv {
            's' => a.get(idx).and_then(|v| h.str_arc(v)),
            _ => None,
        };
        let body = match conv {
            's' => {
                let arg = a.get(idx).ok_or_else(|| NOT_ENOUGH.to_string())?;
                let s = h.print_checked(arg, false)?;
                match spec.prec {
                    Some(p) => truncate_to_columns(&s, p),
                    None => s,
                }
            }
            'S' => {
                let arg = a.get(idx).ok_or_else(|| NOT_ENOUGH.to_string())?;
                let s = h.print_checked(arg, true)?;
                // `%S`'s precision truncates the *printed* representation, quote
                // marks included: `(format "%.3S" "中中中")` is `"\"中"` in
                // Emacs 30.2 — one column for the opening quote, two for 中.
                match spec.prec {
                    Some(p) => truncate_to_columns(&s, p),
                    None => s,
                }
            }
            // The `+`/space sign flags apply to the signed conversions (d/e/f/g).
            // `%i` is an accepted alias for `%d` (as in C printf).
            'd' | 'i' => match a.get(idx) {
                // A non-finite float renders as the word "nan"/"inf"/"-inf",
                // exactly like %e/%f/%g (editfns.c styled_format): precision and
                // the `0` flag are ignored (space-padded to width), and the
                // `+`/space sign flags apply to infinities but never to NaN.
                Some(Value::Float(f)) if !f.is_finite() => {
                    spec.zero = false;
                    if f.is_nan() {
                        "nan".to_string()
                    } else if *f < 0.0 {
                        "-inf".to_string()
                    } else {
                        apply_sign("inf".to_string(), &spec)
                    }
                }
                _ => format_integer(int_arg(idx)?, &spec),
            },
            // The unsigned radix conversions have no word rendering for a
            // non-finite float: Emacs signals `(overflow-error)` (a NaN/Inf has
            // no integer value to print).
            'o' | 'x' | 'X' => {
                if let Some(Value::Float(f)) = a.get(idx) {
                    if !f.is_finite() {
                        return Err("overflow-error".to_string());
                    }
                }
                format_integer(int_arg(idx)?, &spec)
            }
            'c' => {
                // %c takes a character: any float — even an integral one — is a
                // type mismatch in Emacs (`CHARACTERP` is integers only).
                let (i, _, is_float) = numf(idx)?;
                if is_float {
                    return Err(BAD_TYPE.to_string());
                }
                // Emacs applies `CHECK_CHARACTER` to the argument (editfns.c
                // `styled_format`), so an integer outside `0 … #x3FFFFF` signals
                // `(wrong-type-argument characterp N)` — it is not silently
                // dropped, and the error is `wrong-type-argument`, not the
                // "Format specifier doesn't match argument type" a float gets.
                if !(0..=0x3F_FFFF).contains(&i) {
                    return Err(format!("wrong-type-argument: characterp {i}"));
                }
                char::from_u32(i as u32)
                    .map(String::from)
                    .unwrap_or_default()
            }
            'e' | 'f' | 'g' => {
                let v = numf(idx)?.1;
                if v.is_finite() {
                    let raw = match conv {
                        'e' => format_e(v, spec.prec.unwrap_or(6)),
                        'f' => format_fixed(v, spec.prec.unwrap_or(6)),
                        _ => format_g(v, spec.prec.unwrap_or(6), spec.alt),
                    };
                    // printf's `#`: the result always has a decimal point, even
                    // with no digits after it (`%#.0f` of 1.0 is "1.").
                    let raw = if spec.alt {
                        with_decimal_point(raw)
                    } else {
                        raw
                    };
                    apply_sign(raw, &spec)
                } else {
                    // inf/nan: Emacs renders "inf"/"-inf"/"nan", ignoring precision
                    // and the `0` flag (space-padded to width). `+`/space signs
                    // apply to infinities but never to NaN.
                    spec.zero = false;
                    if v.is_nan() {
                        "nan".to_string()
                    } else if v < 0.0 {
                        "-inf".to_string()
                    } else {
                        apply_sign("inf".to_string(), &spec)
                    }
                }
            }
            other => {
                // Unknown conversion. Emacs still validates argument
                // availability first — `(format "%b")` is "Not enough
                // arguments", but `(format "%b" 1)` is "Invalid format
                // operation %b" — so check the arg before signalling.
                if a.get(idx).is_none() {
                    return Err(NOT_ENOUGH.to_string());
                }
                return Err(format!("Invalid format operation %{other}"));
            }
        };
        // A field number repositions the counter: `(format "%2$s %s" 1 2 3)` is "2 3".
        ai = idx + 1;
        let out_start = out.chars().count();
        let body_len = body.chars().count();
        let padded = pad(body, &spec);
        out.push_str(&padded);
        // `pad` adds spaces on one side. Padding that follows the argument is
        // inside its interval, so the argument's text starts after the padding
        // that precedes it.
        let pad_len = padded.chars().count() - body_len;
        let text_start = if spec.left {
            out_start
        } else {
            out_start + pad_len
        };
        fields.push(FmtField {
            fbeg,
            fend: fmt_len - chars.clone().count(),
            fstart: out_start,
            text_start,
            out_end: out_start + body_len + pad_len,
            carries: carries.clone(),
        });
    }
    Ok((out, fields))
}
/// Where format character position P lands in the result: literal characters
/// are one for one, a directive is a unit that the `%` at its start jumps over,
/// and `%%` produces a single character (editfns.c `styled_format`'s
/// property-translation walk).
fn format_position(fields: &[FmtField], p: usize) -> usize {
    let (mut out, mut fpos) = (0usize, 0usize);
    for f in fields {
        if p <= f.fbeg {
            return out + (p - fpos);
        }
        out = f.out_end;
        fpos = f.fend;
        if p < f.fend {
            return out;
        }
    }
    out + (p - fpos)
}

/// Put the text properties of the format string and of its `%s` string
/// arguments on the result.
fn apply_format_props(
    h: &mut ElispHost,
    key: &std::sync::Arc<String>,
    fmt: &Value,
    fields: &[FmtField],
) {
    let replace = crate::textprop::SetType::Replace;
    // With intervals on the FORMAT string, `styled_format` places an argument's
    // properties from the start of its field, left padding included, instead of
    // from its first character -- measured, GNU Emacs 31.1:
    //   (format "%5s" (concat "a" (propertize "b" 'p 1)))            => props 4 5
    //   (format (propertize "%5s" 'f 1) (concat "a" (propertize "b" 'p 1)))
    //                                                       => (p f) over 1 5
    let mut field_start = false;
    if let Some(farc) = h.str_arc(fmt) {
        let intervals = h.string_intervals(&farc);
        field_start = !intervals.is_empty();
        for (rs, re, plist) in intervals {
            if is_nil(&plist) {
                continue;
            }
            let (os, oe) = (format_position(fields, rs), format_position(fields, re));
            if oe > os {
                let pairs = each_prop_pair(h, &plist);
                h.string_add_props(key, os, oe, &pairs, replace);
            }
        }
    }
    for f in fields {
        let Some(src) = &f.carries else { continue };
        let len = src.chars().count();
        let start = if field_start { f.fstart } else { f.text_start };
        let new_len = f.out_end - start;
        for (rs, re, plist) in h.string_intervals(src) {
            if is_nil(&plist) || rs >= new_len {
                continue;
            }
            // `extend_property_ranges`: an interval ending at the old end
            // stretches over the padding; one past the new end is cut.
            let mut end = re;
            if (end == len && end != new_len) || end > new_len {
                end = new_len;
            }
            let pairs = each_prop_pair(h, &plist);
            h.string_add_props(key, start + rs, start + end, &pairs, replace);
        }
    }
}

fn format_fn(h: &mut ElispHost, a: &[Value]) -> R {
    // editfns.c `styled_format` hands back an existing string instead of building a
    // new one in two cases (measured, GNU Emacs 31.1): a format with no `%` at all
    // answers the format string itself, and a bare "%s" over a string argument
    // answers that argument itself (so its property order is not re-reversed).
    if let Some(fmt) = h.str_text(&a[0]) {
        if !fmt.contains('%') {
            return Ok(a[0].clone());
        }
        if fmt == "%s" && a.len() == 2 && h.str_text(&a[1]).is_some() {
            let plain = h
                .str_arc(&a[0])
                .is_none_or(|f| h.string_intervals(&f).is_empty());
            if plain {
                return Ok(a[1].clone());
            }
        }
    }
    let (s, fields) = el_format_pieces(h, a)?;
    let (out, key) = h.new_string_keyed(s);
    apply_format_props(h, &key, &a[0], &fields);
    Ok(out)
}
/// `(message FORMAT-STRING &rest ARGS)`. Port of `Fmessage` (`src/xdisp.c`) plus
/// the batch tail it reaches, `message_to_stderr`:
///
/// ```c
///   if (NILP (args[0]) || (STRINGP (args[0]) && SBYTES (args[0]) == 0))
///     { message1 (0); return args[0]; }
///   else { val = Fformat_message (nargs, args); message3 (val); return val; }
///
///   /* message_to_stderr (m) */
///   if (noninteractive_need_newline)
///     { noninteractive_need_newline = false; errputc ('\n'); }
///   if (STRINGP (m)) errwrite (SDATA (s), SBYTES (s));
///   if (STRINGP (m) || !cursor_in_echo_area) errputc ('\n');
/// ```
///
/// Three things that a bare `eprintln!("{}", format(...))` gets wrong:
///
/// - nil (and "") clear the echo area and answer the argument unchanged, so
///   `(message nil)` is nil, not `(wrong-type-argument stringp nil)`.
/// - the template is curve-quoted (`format-message`, not `format`).
/// - a pending `noninteractive_need_newline` — set by any batch write to stdout —
///   is flushed to stderr first, so a `princ` and a following `message` do not
///   share a line. `cursor_in_echo_area` is always false in batch, so the
///   trailing newline is unconditional and nil therefore emits *two*.
fn message_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let blank = match a.first() {
        Some(v) if is_nil(v) => true,
        Some(v) => h.str_text(v).is_some_and(str::is_empty),
        None => false,
    };
    let text = if blank {
        None
    } else {
        Some(el_format_message(h, a)?)
    };
    if h.need_newline {
        h.need_newline = false;
        eprintln!();
    }
    match text {
        Some(s) => {
            eprintln!("{s}");
            Ok(h.new_string(s))
        }
        None => {
            eprintln!();
            Ok(a.first().cloned().unwrap_or(Value::Undef))
        }
    }
}
fn princ_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let dest = print_dest(h, a.get(1))?;
    let s = h.print_checked(&a[0], false)?;
    print_to(h, &dest, &s)?;
    Ok(a[0].clone())
}
fn prin1_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let dest = print_dest(h, a.get(1))?;
    let s = h.print_checked(&a[0], true)?;
    print_to(h, &dest, &s)?;
    Ok(a[0].clone())
}
fn number_to_string(h: &mut ElispHost, a: &[Value]) -> R {
    as_number_p(h, &a[0], false)?;
    Ok(h.new_string(h.print(&a[0], false)))
}

// ── hash tables ──
fn hash_eq(h: &ElispHost, test: u8, a: &Value, b: &Value) -> bool {
    match test {
        // `equal` test: deep structural equality.
        2 => el_equal(h, a, b),
        // `eql` test (the make-hash-table default): like `eq` but equal floats and
        // equal bignums compare the same, so a float or bignum key put with
        // `puthash` is found again by `gethash`.
        1 => el_eql(h, a, b),
        // `eq` test: identity.
        _ => el_eq(h, a, b),
    }
}

/// How deep [`hash_key`] descends into an `equal`-test key.
///
/// The cap is what makes a circular key terminate. It only weakens the hash:
/// two keys that agree down to this depth land in one bucket and are then told
/// apart by `hash_eq`, so the answer stays exact.
const HASH_DEPTH_LIMIT: u32 = 8;

/// A hash of KEY consistent with [`hash_eq`] for TEST: keys the test calls equal
/// always hash alike. The converse is not required — a collision costs one extra
/// `hash_eq` call, never a wrong answer.
fn hash_key(h: &ElispHost, test: u8, v: &Value) -> u64 {
    use std::hash::Hasher;
    let mut st = std::collections::hash_map::DefaultHasher::new();
    hash_into(h, test, v, 0, &mut st);
    st.finish()
}

fn hash_into(h: &ElispHost, test: u8, v: &Value, depth: u32, st: &mut impl std::hash::Hasher) {
    use std::hash::Hash;
    if is_nil(v) {
        st.write_u8(0);
        return;
    }
    if depth > HASH_DEPTH_LIMIT {
        st.write_u8(0xFF);
        return;
    }
    match v {
        Value::Int(n) => {
            st.write_u8(1);
            st.write_i64(*n);
        }
        // A float is `eql`/`equal` by bit pattern, so hash the bits. Under `eq`
        // no two floats are equal at all, so any hash is consistent.
        Value::Float(f) => {
            st.write_u8(2);
            st.write_u64(f.to_bits());
        }
        Value::Bool(b) => {
            st.write_u8(3);
            st.write_u8(u8::from(*b));
        }
        // A string hashes by CONTENT under every test: `equal` requires it, and
        // under `eq`/`eql` the only pair that must agree is a string with
        // itself, which content also gives.
        Value::Str(txt) => {
            st.write_u8(4);
            txt.as_str().hash(st);
        }
        // A string CELL hashes as its text, not as its handle: `equal` compares
        // the text, so two distinct cells holding "ab" must share a bucket.
        Value::Obj(_) if h.is_string(v) => {
            st.write_u8(4);
            h.str_text(v).unwrap_or_default().hash(st);
        }
        Value::Obj(id) => match h.arena.get(*id as usize) {
            // A bignum is `eql` by VALUE, so its handle cannot be the hash.
            Some(Obj::Bignum(b)) => {
                st.write_u8(5);
                b.to_string().hash(st);
            }
            // Only the `equal` test looks inside a container; under `eq`/`eql`
            // two containers are equal only when they are the same object.
            Some(Obj::Cons(a, d)) if test == 2 => {
                st.write_u8(6);
                hash_into(h, test, a, depth + 1, st);
                hash_into(h, test, d, depth + 1, st);
            }
            Some(Obj::Vector(items)) | Some(Obj::Record(items)) if test == 2 => {
                st.write_u8(7);
                st.write_usize(items.len());
                for it in items.iter() {
                    hash_into(h, test, it, depth + 1, st);
                }
            }
            Some(Obj::BoolVector(bits)) if test == 2 => {
                st.write_u8(8);
                bits.hash(st);
            }
            // Two markers are `equal` when they share a buffer and a position,
            // which is not readable from here — put every marker in one bucket
            // and let `hash_eq` decide.
            Some(Obj::Marker(_)) if test == 2 => st.write_u8(9),
            // Two closures are `equal` when their arglist, body and captures
            // are, so the handle cannot be the hash under the `equal` test.
            Some(Obj::Closure { .. }) if test == 2 => {
                st.write_u8(12);
                if let Some((is_macro, dynamic, arglist, body, captures)) = h.closure_parts(v) {
                    st.write_u8(u8::from(is_macro));
                    st.write_u8(u8::from(dynamic));
                    hash_into(h, test, &arglist, depth + 1, st);
                    st.write_usize(body.len());
                    for form in &body {
                        hash_into(h, test, form, depth + 1, st);
                    }
                    st.write_usize(captures.len());
                    for (sym, val) in &captures {
                        st.write_u32(*sym);
                        if let Some(val) = val {
                            hash_into(h, test, val, depth + 1, st);
                        }
                    }
                }
            }
            _ => {
                st.write_u8(10);
                st.write_u32(*id);
            }
        },
        _ => st.write_u8(11),
    }
}

pub(crate) fn ht_ref<'a>(h: &'a ElispHost, v: &Value) -> Result<&'a ElHashTable, String> {
    match h.obj(v) {
        Some(Obj::HashTable(t)) => Ok(t),
        _ => Err(format!(
            "wrong-type-argument: hash-table-p {}",
            h.print(v, true)
        )),
    }
}

fn ht_mut<'a>(h: &'a mut ElispHost, v: &Value) -> Option<&'a mut ElHashTable> {
    match v {
        Value::Obj(id) => match h.arena.get_mut(*id as usize) {
            Some(Obj::HashTable(t)) => Some(t),
            _ => None,
        },
        _ => None,
    }
}

/// Fill a table's hash index if it arrived from a serialized image without one.
/// See [`ElHashTable::needs_index`].
fn ht_ensure_index(h: &mut ElispHost, v: &Value) -> Result<(), String> {
    let t = ht_ref(h, v)?;
    if !t.needs_index() {
        return Ok(());
    }
    let test = t.test;
    let keys: Vec<(u32, Value)> = t
        .slots
        .iter()
        .enumerate()
        .filter_map(|(i, slot)| slot.as_ref().map(|(k, _)| (i as u32, k.clone())))
        .collect();
    let hashes: Vec<(u32, u64)> = keys
        .iter()
        .map(|(i, k)| (*i, hash_key(h, test, k)))
        .collect();
    if let Some(t) = ht_mut(h, v) {
        t.reindex(&hashes);
    }
    Ok(())
}

/// The slot holding KEY, and KEY's hash — the shared front half of `gethash`,
/// `puthash` and `remhash`.
fn ht_find(h: &mut ElispHost, table: &Value, key: &Value) -> Result<(u64, Option<u32>), String> {
    ht_ensure_index(h, table)?;
    let t = ht_ref(h, table)?;
    let test = t.test;
    let hk = hash_key(h, test, key);
    let t = ht_ref(h, table)?;
    let slot = t
        .candidates(hk)
        .iter()
        .copied()
        .find(|&i| t.key_at(i).is_some_and(|k| hash_eq(h, test, key, k)));
    Ok((hk, slot))
}

/// `(make-hash-table &rest KEYWORD-ARGS)`.
///
/// `user` is the `(NAME TESTFN HASHFN)` of a `define-hash-table-test` test, when
/// the `:test` argument named one. Resolving that lives in
/// [`crate::host::call_function`] rather than here, because the declaration is
/// kept on the symbol's `hash-table-test` property — an elisp plist, so reading
/// it CALLS elisp, which cannot happen inside this host borrow.
/// The keyword arguments of `make-hash-table`, after the pairwise scan of
/// Emacs 31's `Fmake_hash_table` (fns.c).
pub(crate) struct HashTableKeywords {
    /// First `:test` value, if the keyword was given.
    pub test: Option<Value>,
    /// First `:size` value.
    pub size: Option<Value>,
    /// First `:weakness` value.
    pub weakness: Option<Value>,
}

/// The argument-list half of `Fmake_hash_table` (emacs-31.1): an odd count is
/// `(error "Odd number of arguments")`; otherwise the arguments are KEYWORD
/// VALUE pairs in which the FIRST occurrence of `:test`/`:size`/`:weakness`
/// wins, `:purecopy`/`:rehash-size`/`:rehash-threshold` are accepted and
/// ignored, and any other keyword (of any type) is remembered — the LAST one is
/// reported as `(error "Invalid keyword argument" KW)`, after the whole list was
/// scanned and before any value is validated.
pub(crate) fn hash_table_keywords(
    h: &mut ElispHost,
    a: &[Value],
) -> Result<HashTableKeywords, String> {
    if a.len() % 2 == 1 {
        return Err("error: Odd number of arguments".to_string());
    }
    let mut kw = HashTableKeywords {
        test: None,
        size: None,
        weakness: None,
    };
    let mut bad: Option<Value> = None;
    for pair in a.chunks(2) {
        let name = h.sym_name(&pair[0]);
        let slot = match name.as_deref() {
            Some(":test") => &mut kw.test,
            Some(":size") => &mut kw.size,
            Some(":weakness") => &mut kw.weakness,
            // Accepted and ignored: elisprs has no pure space, and the rehash
            // parameters are obsolete since Emacs 29.
            Some(":purecopy") | Some(":rehash-size") | Some(":rehash-threshold") => continue,
            _ => {
                bad = Some(pair[0].clone());
                continue;
            }
        };
        if slot.is_none() {
            *slot = Some(pair[1].clone());
        }
    }
    if let Some(k) = bad {
        return Err(h.signal_error_arg("Invalid keyword argument", &k));
    }
    Ok(kw)
}

pub(crate) fn make_hash_table_with(
    h: &mut ElispHost,
    a: &[Value],
    user: Option<(Value, Value, Value)>,
) -> R {
    let kw = hash_table_keywords(h, a)?;
    let test = match &kw.test {
        None => 1u8, // eql default
        Some(v) => match h.sym_name(v).as_deref() {
            Some("eq") => 0,
            Some("equal") => 2,
            // A name the caller resolved to a user test; anything else
            // is `eql` (including the `eql` spelling itself).
            Some(other) if other != "eql" && user.is_some() => 3,
            _ => 1,
        },
    };
    // `:size' is the initial allocation, reported back by `hash-table-size'
    // until the table outgrows it. `FIXNATP' rejects a negative or non-integer
    // size outright; nil selects the default, which is elisprs's 0.
    let size = match &kw.size {
        None => 0usize,
        Some(v) => match v {
            v if crate::host::el_nil(v) => 0,
            Value::Int(n) if *n >= 0 => *n as usize,
            v => {
                let v = v.clone();
                return Err(h.signal_error_arg("Invalid hash table size", &v));
            }
        },
    };
    let weakness = match &kw.weakness {
        None => Value::Undef,
        Some(w) => {
            let w = w.clone();
            hash_table_weakness_arg(h, &w)?
        }
    };
    let mut t = ElHashTable::new(test, size, weakness);
    if test == 3 {
        t.user_test = user;
    }
    Ok(h.alloc(Obj::HashTable(t)))
}
/// Validate a `:weakness` value the way `Fmake_hash_table` does: nil, `key`,
/// `value`, `key-or-value` and `key-and-value` are kept, `t` is the historical
/// spelling of `key-and-value` and is stored as that, anything else is
/// `(error "Invalid hash table weakness" W)`. The `#s(hash-table weakness W)`
/// reader goes through the same check.
pub(crate) fn hash_table_weakness_arg(h: &mut ElispHost, w: &Value) -> R {
    if matches!(w, Value::Bool(true)) {
        return Ok(h.intern("key-and-value"));
    }
    let named = h.sym_name(w);
    let ok = crate::host::el_nil(w)
        || matches!(
            named.as_deref(),
            Some("key") | Some("value") | Some("key-or-value") | Some("key-and-value")
        );
    if !ok {
        return Err(h.signal_error_arg("Invalid hash table weakness", w));
    }
    Ok(w.clone())
}

/// The `(NAME TESTFN HASHFN)` of TABLE's user-defined test, if it has one.
pub(crate) fn ht_user_test(table: &Value) -> Option<(Value, Value, Value)> {
    crate::host::with_host(|h| ht_ref(h, table).ok().and_then(|t| t.user_test.clone()))
}

/// [`ht_find`] for a table whose test is elisp.
///
/// This is the whole reason `gethash`/`puthash`/`remhash` are dispatched from
/// [`crate::host::call_function`]: HASHFN and TESTFN are elisp functions, and
/// calling one needs the host borrow released. So the walk takes the host in
/// short bursts — read the candidate slots out, drop the borrow, run the test —
/// rather than holding a `&mut ElispHost` across the probe.
///
/// Emacs (`hashfn_user_defined`, fns.c) hashes the value HASHFN *returns* with
/// the ordinary `equal` hash, so two keys HASHFN maps to `equal` values land in
/// one bucket and TESTFN then decides.
pub(crate) fn ht_find_user(
    table: &Value,
    key: &Value,
    testfn: &Value,
    hashfn: &Value,
) -> Result<(u64, Option<u32>), String> {
    use crate::host::{call_function, with_host};
    let hv = call_function(hashfn, std::slice::from_ref(key))?;
    let hk = with_host(|h| hash_key(h, 2, &hv));
    let cands: Vec<(u32, Value)> = with_host(|h| {
        let t = ht_ref(h, table)?;
        Ok::<_, String>(
            t.candidates(hk)
                .iter()
                .filter_map(|&i| t.key_at(i).map(|k| (i, k.clone())))
                .collect(),
        )
    })?;
    for (i, k) in cands {
        if crate::host::el_truthy(&call_function(testfn, &[key.clone(), k])?) {
            return Ok((hk, Some(i)));
        }
    }
    Ok((hk, None))
}

/// `gethash` on a user-test table (see [`ht_find_user`]).
pub(crate) fn gethash_user(a: &[Value], t: &(Value, Value, Value)) -> R {
    let (_, slot) = ht_find_user(&a[1], &a[0], &t.1, &t.2)?;
    crate::host::with_host(|h| match slot {
        Some(i) => Ok(ht_ref(h, &a[1])?
            .value_at(i)
            .cloned()
            .unwrap_or(Value::Undef)),
        None => Ok(a.get(2).cloned().unwrap_or(Value::Undef)),
    })
}

/// `puthash` on a user-test table. A key the test already matches keeps the
/// ORIGINAL key object and only its value is replaced, exactly as for the
/// built-in tests.
pub(crate) fn puthash_user(a: &[Value], t: &(Value, Value, Value)) -> R {
    let (hk, slot) = ht_find_user(&a[2], &a[0], &t.1, &t.2)?;
    crate::host::with_host(|h| {
        if let Some(tbl) = ht_mut(h, &a[2]) {
            match slot {
                Some(i) => tbl.set_value_at(i, a[1].clone()),
                None => tbl.insert(hk, a[0].clone(), a[1].clone()),
            }
        }
    });
    Ok(a[1].clone())
}

/// `remhash` on a user-test table.
pub(crate) fn remhash_user(a: &[Value], t: &(Value, Value, Value)) -> R {
    let (hk, slot) = ht_find_user(&a[1], &a[0], &t.1, &t.2)?;
    crate::host::with_host(|h| {
        if let (Some(i), Some(tbl)) = (slot, ht_mut(h, &a[1])) {
            tbl.remove(hk, i);
        }
    });
    Ok(Value::Undef)
}

pub(crate) fn gethash(h: &mut ElispHost, a: &[Value]) -> R {
    let (_, slot) = ht_find(h, &a[1], &a[0])?;
    match slot {
        Some(i) => Ok(ht_ref(h, &a[1])?
            .value_at(i)
            .cloned()
            .unwrap_or(Value::Undef)),
        None => Ok(a.get(2).cloned().unwrap_or(Value::Undef)),
    }
}
pub(crate) fn puthash(h: &mut ElispHost, a: &[Value]) -> R {
    let (hk, slot) = ht_find(h, &a[2], &a[0])?;
    if let Some(t) = ht_mut(h, &a[2]) {
        match slot {
            Some(i) => t.set_value_at(i, a[1].clone()),
            None => t.insert(hk, a[0].clone(), a[1].clone()),
        }
    }
    Ok(a[1].clone())
}
pub(crate) fn remhash(h: &mut ElispHost, a: &[Value]) -> R {
    let (hk, slot) = ht_find(h, &a[1], &a[0])?;
    if let (Some(i), Some(t)) = (slot, ht_mut(h, &a[1])) {
        t.remove(hk, i);
    }
    Ok(Value::Undef) // remhash always returns nil
}
fn clrhash(h: &mut ElispHost, a: &[Value]) -> R {
    if let Some(t) = ht_mut(h, &a[0]) {
        t.clear();
    }
    Ok(a[0].clone())
}
fn hash_table_count(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(Value::Int(ht_ref(h, &a[0])?.count() as i64))
}
fn hash_table_p(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(nil_or(matches!(h.obj(&a[0]), Some(Obj::HashTable(_)))))
}
/// `(hash-table-test TABLE)` — the symbol naming TABLE's comparison test.
fn hash_table_test(h: &mut ElispHost, a: &[Value]) -> R {
    let t = ht_ref(h, &a[0])?;
    // A `define-hash-table-test` table reports the NAME it was made with, not
    // one of the three built-in test symbols.
    if let Some((name, _, _)) = &t.user_test {
        return Ok(name.clone());
    }
    let name = match t.test {
        0 => "eq",
        1 => "eql",
        _ => "equal",
    };
    Ok(h.intern(name))
}
/// `(hash-table-size TABLE)` — the current ALLOCATION size, not the entry count.
fn hash_table_size(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(Value::Int(ht_ref(h, &a[0])?.size as i64))
}
/// `(hash-table-weakness TABLE)` — the `:weakness` argument as given.
fn hash_table_weakness(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(ht_ref(h, &a[0])?.weakness.clone())
}
/// subr-x's `hash-table-keys`/`hash-table-values` are a `maphash` that PUSHES
/// onto a list and never reverses it, so both come back in REVERSE slot order.
fn hash_table_keys(h: &mut ElispHost, a: &[Value]) -> R {
    let mut keys: Vec<Value> = ht_ref(h, &a[0])?.pairs().map(|(k, _)| k.clone()).collect();
    keys.reverse();
    Ok(h.list_from(keys))
}
fn hash_table_values(h: &mut ElispHost, a: &[Value]) -> R {
    let mut vals: Vec<Value> = ht_ref(h, &a[0])?.pairs().map(|(_, v)| v.clone()).collect();
    vals.reverse();
    Ok(h.list_from(vals))
}
fn copy_hash_table(h: &mut ElispHost, a: &[Value]) -> R {
    // `Fcopy_hash_table` copies the table structure as it stands: the test
    // (a `define-hash-table-test` one included), weakness, size, slot order,
    // free list and hashes. Rehashing here would need the user test's HASHFN,
    // which is elisp, and would compact the free list Emacs keeps.
    ht_ensure_index(h, &a[0])?;
    let copy = ht_ref(h, &a[0])?.clone();
    Ok(h.alloc(Obj::HashTable(copy)))
}

// ── strings ──
/// `(elisprs--copy-string STRING)` — `Fcopy_sequence` on a string: a fresh string whose
/// interval tree is copied as it stands, so each interval keeps its plist order
/// (`substring` and `concat` re-add the pairs and reverse them).
fn copy_string(h: &mut ElispHost, a: &[Value]) -> R {
    let Some(text) = h.str_text(&a[0]).map(str::to_string) else {
        return Err(format!(
            "wrong-type-argument: stringp {}",
            h.print(&a[0], true)
        ));
    };
    let src = h.str_arc(&a[0]);
    let (out, dst) = h.new_string_keyed(text);
    if let Some(src) = src {
        h.string_carry_all(&dst, &src);
    }
    Ok(out)
}
/// `(substring-no-properties STRING &optional FROM TO)` — a property-free copy.
/// A C subr in Emacs (editfns.c) that demands `stringp` (never a vector, unlike
/// `substring`); index handling is then identical to `substring`.
fn substring_no_properties_fn(h: &mut ElispHost, a: &[Value]) -> R {
    if !h.is_string(&a[0]) {
        return Err(format!(
            "wrong-type-argument: stringp {}",
            h.print(&a[0], true)
        ));
    }
    // `substring` carries the slice's text properties; this subr is exactly
    // that slice without them.
    let out = substring(h, a)?;
    if let Some(s) = h.str_arc(&out) {
        h.string_clear_props(&s);
    }
    Ok(out)
}
fn substring(h: &mut ElispHost, a: &[Value]) -> R {
    // Emacs `substring` works on both strings and vectors (arrays), and checks
    // the array BEFORE the indices: (substring -1 1.5) is `arrayp -1`.
    enum Seq {
        Str(Vec<char>),
        Vec(Vec<Value>),
    }
    let seq = match h.str_text(&a[0]) {
        Some(s) => Seq::Str(s.chars().collect()),
        None => match h.obj(&a[0]) {
            Some(Obj::Vector(items)) => Seq::Vec(items.clone()),
            _ => {
                return Err(format!(
                    "wrong-type-argument: arrayp {}",
                    h.print(&a[0], true)
                ));
            }
        },
    };
    // FROM/TO must be fixnums: Emacs signals `integerp` rather than truncating
    // a float — and a bignum index draws the same signal.
    for idx in a.iter().skip(1) {
        if !is_nil(idx) && !matches!(idx, Value::Int(_)) {
            return Err(format!(
                "wrong-type-argument: integerp {}",
                h.print(idx, true)
            ));
        }
    }
    let len = match &seq {
        Seq::Str(c) => c.len() as i64,
        Seq::Vec(v) => v.len() as i64,
    };
    // Negative indices count from the end; Emacs then bounds-checks rather than
    // clamping, signalling args-out-of-range for anything outside [0, len].
    let adj = |i: i64| -> i64 {
        if i < 0 {
            len + i
        } else {
            i
        }
    };
    let start = match a.get(1) {
        Some(v) if !is_nil(v) => adj(as_int(h, v)?),
        _ => 0,
    };
    let end = match a.get(2) {
        Some(v) if !is_nil(v) => adj(as_int(h, v)?),
        _ => len,
    };
    if start < 0 || end > len || start > end {
        // Emacs reports the *original* FROM/TO arguments (nil for an omitted
        // TO), not the negative-resolved or defaulted values.
        let from = a
            .get(1)
            .map(|v| h.print(v, true))
            .unwrap_or_else(|| "nil".to_string());
        let to = a
            .get(2)
            .map(|v| h.print(v, true))
            .unwrap_or_else(|| "nil".to_string());
        return Err(format!(
            "args-out-of-range: {} {from} {to}",
            h.print(&a[0], true)
        ));
    }
    match seq {
        Seq::Str(c) => {
            let text = c[start as usize..end as usize].iter().collect::<String>();
            let src = h.str_arc(&a[0]);
            let (out, dst) = h.new_string_keyed(text);
            // The slice's characters keep the properties they had in the
            // original, re-based to the new string's start.
            if let Some(src) = src {
                h.string_copy_props(&dst, &[(Some(src), start as usize, (end - start) as usize)]);
            }
            Ok(out)
        }
        Seq::Vec(v) => Ok(h.alloc(Obj::Vector(v[start as usize..end as usize].to_vec()))),
    }
}
/// subr.el `split-string-default-separators` — space, formfeed, tab, newline,
/// carriage return and vertical tab, and nothing else. Notably NOT "Unicode
/// whitespace": `(split-string "a\u{a0}b")` is `("a\u{a0}b")` in Emacs, one
/// element, because a no-break space is not in this class.
pub(crate) const SPLIT_STRING_DEFAULT_SEPARATORS: &str = "[ \u{c}\t\n\r\u{b}]+";

/// `(match-end 0)` right after a successful `string-match`.
fn match_end_0(h: &mut ElispHost) -> Result<i64, String> {
    let end = match_end(h, &[Value::Int(0)])?;
    as_int(h, &end)
}

/// subr.el `split-string` (emacs-31.1), ported statement for statement. 31.1
/// replaced the 30.x `push-one` walk with an index walk that advances `next` by
/// at least one past each search, so an empty-matching separator splits between
/// every character and a trailing empty match is kept under `keep-empty`.
///
/// Every step goes through the real `string-match` / `string-match-p` /
/// `substring` builtins, so the match data left behind, the argument checks and
/// their order (`length` of STRING, then `concat` of TRIM, then the first
/// `string-match`) are the Lisp definition's own.
fn split_string(h: &mut ElispHost, a: &[Value]) -> R {
    let nil = Value::Undef;
    let arg = |i: usize| a.get(i).cloned().unwrap_or(Value::Undef);
    let string = arg(0);
    let separators = arg(1);
    let trim = arg(3);
    let keep_empty = !is_nil(&separators) && is_nil(&arg(2));
    let len = emacs_length(h, &string)?;
    // `(trim-left-re (and trim (concat "\\`\\(?:" trim "\\)")))` and the right-
    // anchored twin: `concat` accepts any sequence of characters, not only a
    // string, and signals `sequencep` for anything else.
    let anchored = |h: &mut ElispHost, head: &str, tail: &str| -> R {
        concat_fn(
            h,
            &[
                Value::str(head.to_string()),
                trim.clone(),
                Value::str(tail.to_string()),
            ],
        )
    };
    let (trim_left_re, trim_right_re) = if is_nil(&trim) {
        (nil.clone(), nil.clone())
    } else {
        (
            anchored(h, "\\`\\(?:", "\\)")?,
            anchored(h, "\\(?:", "\\)\\'")?,
        )
    };
    let sep_re = if is_nil(&separators) {
        match h
            .find_symbol("split-string-default-separators")
            .and_then(|s| h.get_value(&s).ok())
        {
            Some(v) if !is_nil(&v) => v,
            _ => Value::str(SPLIT_STRING_DEFAULT_SEPARATORS.to_string()),
        }
    } else {
        separators
    };

    // Trim both ends of ITEM: `(string-match LEFT ITEM 0)` then `(match-end 0)`,
    // the right edge via `string-match-p`. Returns the (possibly shortened) item
    // and the final BEG and END, which `keep-empty` reads.
    let trim_item = |h: &mut ElispHost, item: Value| -> Result<(Value, i64, i64), String> {
        let hit = string_match(h, &[trim_left_re.clone(), item.clone(), Value::Int(0)])?;
        let beg = if is_nil(&hit) { 0 } else { match_end_0(h)? };
        let item_len = emacs_length(h, &item)?;
        let end = match string_match_p(h, &[trim_right_re.clone(), item.clone(), Value::Int(beg)])?
        {
            Value::Int(n) => n,
            _ => item_len,
        };
        if beg > 0 || end < item_len {
            let item = substring(h, &[item, Value::Int(beg), Value::Int(end)])?;
            return Ok((item, beg, end));
        }
        Ok((item, beg, end))
    };

    let mut acc: Vec<Value> = Vec::new();
    let (mut next, mut start) = (0i64, 0i64);
    loop {
        let sep = string_match(h, &[sep_re.clone(), string.clone(), Value::Int(next)])?;
        let Value::Int(sep) = sep else { break };
        let sep_end = match_end_0(h)?;
        if keep_empty || start < sep {
            let item = substring(h, &[string.clone(), Value::Int(start), Value::Int(sep)])?;
            if is_nil(&trim) {
                acc.push(item);
            } else {
                let (item, beg, end) = trim_item(h, item)?;
                if keep_empty || beg < end {
                    acc.push(item);
                }
            }
        }
        next = (next + 1).max(sep_end);
        start = sep_end;
        if start >= len {
            break;
        }
    }
    // The text after the last separator. `start` 0 means no separator matched,
    // and the whole STRING is the item as-is (the very same object).
    let mut item = if start == 0 {
        string
    } else {
        substring(h, &[string, Value::Int(start)])?
    };
    if !is_nil(&trim) {
        item = trim_item(h, item)?.0;
    }
    if keep_empty || !el_equal(h, &item, &Value::str(String::new())) {
        acc.push(item);
    }
    Ok(h.list_from(acc))
}

/// The `(length V)` the Lisp definitions of `string-prefix-p`/`string-suffix-p`
/// take before any string check — with `length`'s own `sequencep`/`listp`
/// signals for a non-sequence or an improper list.
fn emacs_length(h: &mut ElispHost, v: &Value) -> Result<i64, String> {
    match length_fn(h, std::slice::from_ref(v))? {
        Value::Int(n) => Ok(n),
        _ => Ok(0), // length_fn only ever returns an Int on success
    }
}
/// `compare-strings`' per-char case fold: simple one-char lowercasing.
fn cs_fold(ignore_case: bool) -> impl Fn(char) -> char {
    move |c| {
        if ignore_case {
            c.to_lowercase().next().unwrap_or(c)
        } else {
            c
        }
    }
}
fn string_prefix_p(h: &mut ElispHost, a: &[Value]) -> R {
    // subr.el: (if (> (length prefix) (length string)) nil
    //            (eq t (compare-strings prefix 0 prefix-length string 0 …)))
    // Both lengths are taken before any string check — so a non-sequence
    // signals `sequencep` (PREFIX first), a too-long PREFIX answers nil even
    // for a non-string STRING, and only then does `compare-strings` signal
    // `stringp` (again PREFIX first).
    let plen = emacs_length(h, &a[0])?;
    let slen = emacs_length(h, &a[1])?;
    if plen > slen {
        return Ok(Value::Undef);
    }
    let pre = as_string(h, &a[0])?;
    let s = as_string(h, &a[1])?;
    let fold = cs_fold(a.get(2).is_some_and(|v| !is_nil(v)));
    Ok(nil_or(
        pre.chars()
            .map(&fold)
            .eq(s.chars().take(plen as usize).map(&fold)),
    ))
}
fn string_suffix_p(h: &mut ElispHost, a: &[Value]) -> R {
    // subr.el: (let ((start-pos (- (length string) (length suffix))))
    //          (and (>= start-pos 0) (eq t (compare-strings suffix nil nil …))))
    // STRING's length is taken first (so (string-suffix-p 97 0) signals
    // `sequencep 0`, not about 97), a SUFFIX longer than STRING answers nil
    // before any string check, and `compare-strings` signals `stringp` for
    // SUFFIX first.
    let slen = emacs_length(h, &a[1])?;
    let suflen = emacs_length(h, &a[0])?;
    if slen < suflen {
        return Ok(Value::Undef);
    }
    let suf = as_string(h, &a[0])?;
    let s = as_string(h, &a[1])?;
    let fold = cs_fold(a.get(2).is_some_and(|v| !is_nil(v)));
    Ok(nil_or(
        suf.chars()
            .map(&fold)
            .eq(s.chars().skip((slen - suflen) as usize).map(&fold)),
    ))
}
fn string_empty_p(h: &mut ElispHost, a: &[Value]) -> R {
    // simple.el: (string= STRING "") — so a symbol compares by name
    // ((string-empty-p nil) => nil, no error) and anything else draws
    // `string=`'s `stringp` signal.
    match &a[0] {
        v if h.is_string(v) => Ok(nil_or(h.str_text(v).is_some_and(str::is_empty))),
        v if is_nil(v) => Ok(Value::Undef), // symbol name "nil" is non-empty
        v => match h.sym_name(v) {
            Some(name) => Ok(nil_or(name.is_empty())),
            None => Err(format!("wrong-type-argument: stringp {}", h.print(v, true))),
        },
    }
}
fn string_join(h: &mut ElispHost, a: &[Value]) -> R {
    // subr-x: (mapconcat #'identity strings separator) — mapconcat takes
    // `(length STRINGS)` up front, so an improper list signals `listp TAIL`
    // ((string-join (cons '- 9) 1.5) => (wrong-type-argument listp 9)) and a
    // non-sequence signals `sequencep`, before any element is looked at.
    emacs_length(h, &a[0])?;
    let items = h
        .seq_vec(&a[0])
        .ok_or_else(|| format!("wrong-type-argument: sequencep {}", h.print(&a[0], true)))?;
    let sep = a.get(1).cloned().unwrap_or(Value::Undef);
    // Interleave the separator and concatenate: `concat`'s element rules (and its
    // `sequencep` error) are exactly Emacs's here.
    let mut parts: Vec<Value> = Vec::with_capacity(items.len() * 2);
    for (i, it) in items.into_iter().enumerate() {
        if i > 0 && !is_nil(&sep) {
            parts.push(sep.clone());
        }
        parts.push(it);
    }
    concat_fn(h, &parts)
}
fn char_to_string(h: &mut ElispHost, a: &[Value]) -> R {
    let n = as_char(h, &a[0])?;
    Ok(h.new_string(char::from_u32(n).map(|c| c.to_string()).unwrap_or_default()))
}
fn string_to_char(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(Value::Int(
        as_string(h, &a[0])?
            .chars()
            .next()
            .map(|c| c as i64)
            .unwrap_or(0),
    ))
}
fn make_string(h: &mut ElispHost, a: &[Value]) -> R {
    let n = check_array_len_val(h, &a[0])?;
    let c = char::from_u32(as_char(h, &a[1])?).unwrap_or(' ');
    // Fallible allocation, as in `make_vector`: `n * len_utf8` may overflow
    // `usize` or exceed available memory. Emacs signals a plain `error` rather
    // than aborting the process, so reserve up front and map failure to it.
    let bytes = n
        .checked_mul(c.len_utf8())
        .ok_or_else(|| MEMORY_EXHAUSTED.to_string())?;
    let mut s = String::new();
    s.try_reserve_exact(bytes)
        .map_err(|_| MEMORY_EXHAUSTED.to_string())?;
    for _ in 0..n {
        s.push(c);
    }
    Ok(h.new_string(s))
}
/// `(string &rest CHARACTERS)` — a string of CHARACTERS.
///
/// Emacs `Fstring` runs `CHECK_CHARACTER` over every argument, so a non-character
/// signals `(wrong-type-argument characterp ARG)` — not `integerp`, which is what
/// reading the argument as a plain integer reports.
fn string_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let mut s = String::new();
    for v in a {
        let c = as_char(h, v)?;
        if let Some(c) = char::from_u32(c) {
            s.push(c);
        }
    }
    Ok(h.new_string(s))
}
fn string_to_list(h: &mut ElispHost, a: &[Value]) -> R {
    // Emacs defines this as `(append STRING nil)`, so it accepts any sequence and
    // signals `sequencep` — not `stringp` — on anything else.
    match h
        .str_text(&a[0])
        .map(|st| st.chars().map(|c| Value::Int(c as i64)).collect())
    {
        Some(items) => Ok(h.list_from(items)),
        None => match h.seq_vec(&a[0]) {
            Some(items) => Ok(h.list_from(items)),
            None => Err(format!(
                "wrong-type-argument: sequencep {}",
                h.print(&a[0], true)
            )),
        },
    }
}
fn string_search(h: &mut ElispHost, a: &[Value]) -> R {
    let needle = as_string(h, &a[0])?;
    let hay = as_string(h, &a[1])?;
    // Optional START is a char index; search only the tail from there, then map
    // the byte offset back to an absolute char index. Emacs bounds-checks START
    // against [0, len], signalling args-out-of-range with the raw START value.
    let hay_len = hay.chars().count() as i64;
    let start_char = match a.get(2) {
        Some(v) if !is_nil(v) => {
            let n = as_int(h, v)?;
            if n < 0 || n > hay_len {
                return Err(format!("args-out-of-range: {n}"));
            }
            n as usize
        }
        _ => 0,
    };
    let start_byte = hay
        .char_indices()
        .nth(start_char)
        .map(|(b, _)| b)
        .unwrap_or(hay.len());
    Ok(match hay[start_byte..].find(&needle) {
        Some(off) => Value::Int(hay[..start_byte + off].chars().count() as i64),
        None => Value::Undef,
    })
}

// ── regexp ──

/// Char index ↔ byte offset on a UTF-8 string. elisp counts characters; the
/// `regex` crate reports bytes, so every boundary crosses this conversion.
fn byte_of_char(s: &str, char_idx: usize) -> usize {
    s.char_indices()
        .nth(char_idx)
        .map(|(b, _)| b)
        .unwrap_or(s.len())
}
pub(crate) fn char_of_byte(s: &str, byte_idx: usize) -> usize {
    s[..byte_idx].chars().count()
}

/// `\sC` resolved against the live syntax table.
///
/// It borrows the host rather than reaching for the thread-local: every
/// `compile_cf` caller is already inside a subr holding `&mut ElispHost`, so a
/// `with_host` here re-enters the same `RefCell` and aborts with
/// "RefCell already borrowed" on the first `(string-match "\\s_" "-")`.
struct HostSyntax<'a> {
    host: &'a ElispHost,
    /// Set when the translation actually asked for a syntax class — i.e. the
    /// pattern used `\sC`, `\SC`, `\w` or `\W`. Such a translation is only
    /// valid for the syntax table in force at the time, so [`compile_cf`]
    /// caches it under that table's fingerprint.
    used_syntax: std::cell::Cell<bool>,
    /// Likewise for the category table, set by `\cC` / `\CC`.
    used_category: std::cell::Cell<bool>,
    /// The offset of point in the subject; `None` for a string, where `\=`
    /// can never match.
    point: Option<usize>,
}
impl crate::regexp::SyntaxLookup for HostSyntax<'_> {
    fn ranges(&self, class: char) -> Vec<(u32, u32)> {
        self.used_syntax.set(true);
        self.host.syntax_class_ranges(class)
    }
    fn category_ranges(&self, category: u8) -> Vec<(u32, u32)> {
        self.used_category.set(true);
        self.host.category_ranges(category)
    }
    fn at_dot(&self) -> String {
        match self.point {
            None => crate::regexp::NEVER_MATCHES.to_string(),
            // fancy-regex has no point: assert that exactly P characters
            // precede the position (a constant-width lookbehind).
            Some(0) => r"\A".to_string(),
            Some(p) => format!(r"(?<=\A[\s\S]{{{p}}})"),
        }
    }
}

/// Compile an elisp regexp to a `fancy_regex::Regex` (optionally case-insensitively,
/// for `case-fold-search`), surfacing translation and compilation failures as
/// elisp-style `invalid-regexp` errors.
/// A compiled elisp regexp: the `fancy_regex` program plus, when the pattern
/// used `\(?N:…\)`, the Emacs group number of each of its capture groups.
///
/// The map is `None` for the overwhelmingly common case of a pattern built only
/// from plain `\(`, where the two numberings already agree and `run_match` can
/// hand the spans straight through.
pub(crate) struct CompiledRe {
    re: fancy_regex::Regex,
    /// Element `i` is the Emacs group number of compiled group `i + 1`.
    emacs_groups: Option<Vec<u32>>,
}

impl std::ops::Deref for CompiledRe {
    type Target = fancy_regex::Regex;
    fn deref(&self) -> &fancy_regex::Regex {
        &self.re
    }
}

/// One `case-fold-search` setting's worth of compiled regexps. The value keeps
/// the FAILURE as well as the success, so an invalid pattern keeps signalling.
/// An entry that read the syntax table also carries the table fingerprint it was
/// compiled under (`ElispHost::syntax_fingerprint`); it is reused only while that
/// still holds.
type ReCacheMap = HashMap<String, (Option<(TablesRead, u64)>, Result<Rc<CompiledRe>, String>)>;

/// Which tables a regexp translation read: `(syntax table, category table)`.
type TablesRead = (bool, bool);

/// The fingerprint of the tables in TABLES as they stand now.
fn tables_fingerprint(h: &ElispHost, tables: TablesRead) -> u64 {
    let syntax = if tables.0 { h.syntax_fingerprint() } else { 0 };
    let category = if tables.1 {
        h.category_fingerprint()
    } else {
        0
    };
    syntax.rotate_left(1) ^ category
}

thread_local! {
    /// Compiled regexps, keyed by the elisp pattern — one map per
    /// `case-fold-search` setting, so the lookup can borrow the pattern instead
    /// of building a tuple key.
    ///
    /// Every `string-match`/`re-search-forward`/`looking-at` used to re-run the
    /// elisp→`fancy_regex` translation AND `fancy_regex::Regex::new` from
    /// scratch, so a match inside a loop paid a full regexp compile per
    /// iteration: 40 000 `(string-match "\\([a-z]+\\)-\\([0-9]+\\)" "abc-123")`
    /// took 56 s. Emacs keeps a compiled-pattern cache of its own for exactly
    /// this reason (`compile_pattern`/`searchbufs`, search.c).
    ///
    /// The FAILURE is cached with the success: an invalid pattern has to keep
    /// signalling `invalid-regexp` on every call, not silently start matching.
    static RE_CACHE: RefCell<[ReCacheMap; 4]> =
        RefCell::new([HashMap::new(), HashMap::new(), HashMap::new(), HashMap::new()]);
}

/// Entries kept before the cache is dropped wholesale. Bounded because elisp
/// builds patterns at runtime (`regexp-quote` of user input, `rx` expansions),
/// so an unbounded cache would grow with the program's input, not its code.
const RE_CACHE_MAX: usize = 1024;

/// Compile PAT for a match against a string, where `\=` never matches
/// (regex-emacs.c `at_dot` fails without a buffer).
pub(crate) fn compile_cf(
    h: &ElispHost,
    pat: &str,
    case_insensitive: bool,
) -> Result<Rc<CompiledRe>, String> {
    compile_cf_in(h, pat, case_insensitive, None)
}

/// [`compile_cf`] for a match against the current buffer's accessible text,
/// where `\=` matches at point.
pub(crate) fn compile_cf_buf(
    h: &ElispHost,
    pat: &str,
    case_insensitive: bool,
) -> Result<Rc<CompiledRe>, String> {
    let b = h.cur_buf_ref();
    compile_cf_in(h, pat, case_insensitive, Some(b.point - b.begv))
}

/// POINT is the offset of point in the subject, or `None` for a string. Only
/// a pattern that can contain `\=` depends on it, so only such a pattern is
/// cached per point.
fn compile_cf_in(
    h: &ElispHost,
    pat: &str,
    case_insensitive: bool,
    point: Option<usize>,
) -> Result<Rc<CompiledRe>, String> {
    let slot = usize::from(case_insensitive) + 2 * usize::from(point.is_some());
    let key = match point {
        Some(p) if pat.contains("\\=") => format!("{p}\0{pat}"),
        _ => pat.to_string(),
    };
    if let Some((stamp, hit)) = RE_CACHE.with(|c| c.borrow()[slot].get(&key).cloned()) {
        if stamp.is_none_or(|(tables, s)| s == tables_fingerprint(h, tables)) {
            return hit;
        }
    }
    let syntax = HostSyntax {
        host: h,
        used_syntax: std::cell::Cell::new(false),
        used_category: std::cell::Cell::new(false),
        point,
    };
    let compiled = compile_uncached(pat, case_insensitive, &syntax);
    // A pattern whose translation read the syntax table is valid only for the
    // table it read, so it is cached under that table's fingerprint: a stale
    // character set after `modify-syntax-entry` or a buffer switch misses.
    let tables = (syntax.used_syntax.get(), syntax.used_category.get());
    let stamp = (tables.0 || tables.1).then(|| (tables, tables_fingerprint(h, tables)));
    RE_CACHE.with(|c| {
        let mut maps = c.borrow_mut();
        if maps[slot].len() >= RE_CACHE_MAX {
            maps[slot].clear();
        }
        maps[slot].insert(key, (stamp, compiled.clone()));
    });
    compiled
}

fn compile_uncached(
    pat: &str,
    case_insensitive: bool,
    syntax: &HostSyntax<'_>,
) -> Result<Rc<CompiledRe>, String> {
    // `translate` reports Emacs's own diagnostics ("Unmatched [ or [^", …); they
    // ride under the `invalid-regexp` error symbol, as in Emacs.
    let (translated, groups) =
        crate::regexp::translate_groups(pat, syntax).map_err(|e| format!("invalid-regexp: {e}"))?;
    // Elisp `^`/`$` always match line boundaries, so compile in multiline mode;
    // `\``/`\'` (translated to \A/\z) keep matching the absolute start/end.
    let flags = if case_insensitive { "(?mi)" } else { "(?m)" };
    let full = format!("{flags}{translated}");
    let re = fancy_regex::Regex::new(&full).map_err(|e| format!("invalid-regexp: {e}"))?;
    // Identity numbering needs no remap, and skipping it keeps every ordinary
    // pattern on exactly the path it was on before explicit numbering existed.
    let identity = groups.iter().enumerate().all(|(i, &g)| g as usize == i + 1);
    Ok(Rc::new(CompiledRe {
        re,
        emacs_groups: (!identity).then_some(groups),
    }))
}

/// Drop every cached regexp. Called from `reset_host` so a fresh host never
/// inherits patterns compiled against the previous one's syntax table.
pub fn clear_regexp_cache() {
    RE_CACHE.with(|c| {
        let mut maps = c.borrow_mut();
        maps.iter_mut().for_each(HashMap::clear);
    });
}
/// Read the dynamic `case-fold-search` (default t) — string matching folds case
/// unless it is bound to nil.
pub(crate) fn case_fold_search(h: &ElispHost) -> bool {
    match h.find_symbol("case-fold-search") {
        Some(sym) => h
            .get_value(&sym)
            .map(|v| !matches!(v, Value::Undef | Value::Bool(false)))
            .unwrap_or(true),
        None => true,
    }
}

/// Run `re` against `subject` starting at char index `start`, returning the
/// capture spans in *char* positions (group 0 = whole match).
fn run_match(re: &CompiledRe, subject: &str, start: usize) -> Option<Vec<Option<(usize, usize)>>> {
    let start_byte = byte_of_char(subject, start);
    let caps = re.captures_from_pos(subject, start_byte).ok().flatten()?;
    let spans: Vec<Option<(usize, usize)>> = (0..caps.len())
        .map(|i| {
            caps.get(i).map(|m| {
                (
                    char_of_byte(subject, m.start()),
                    char_of_byte(subject, m.end()),
                )
            })
        })
        .collect();
    let Some(map) = &re.emacs_groups else {
        return Some(spans);
    };
    // Scatter the positional spans onto their Emacs group numbers. Groups the
    // pattern never names stay nil, which is what `(match-data)` reports for the
    // holes an explicit number leaves behind.
    let width = map.iter().copied().max().unwrap_or(0) as usize + 1;
    let mut out = vec![None; width];
    out[0] = spans.first().copied().flatten();
    for (i, &g) in map.iter().enumerate() {
        let Some(span) = spans.get(i + 1).copied().flatten() else {
            // Two groups may share one Emacs number (`\(?1:a\)\|\(?1:b\)`); in
            // Emacs they share one register, so the branch that did not match
            // must not erase the one that did.
            continue;
        };
        out[g as usize] = Some(span);
    }
    Some(out)
}

/// `(string-match REGEXP STRING &optional START)` — search STRING for REGEXP,
/// set the match data, and return the char index where the match begins (nil if
/// no match).
fn string_match(h: &mut ElispHost, a: &[Value]) -> R {
    let pat = as_string(h, &a[0])?;
    let subject = as_string(h, &a[1])?;
    let start = match a.get(2) {
        Some(Value::Undef) | Some(Value::Bool(false)) | None => 0,
        Some(v) => {
            // Emacs: a negative START counts from the end (`len + START`); any
            // START outside `[0, len]` after that adjustment is args-out-of-range,
            // whose DATA is `(STRING RAW-START)`.
            let raw = as_int(h, v)?;
            let len = subject.chars().count() as i64;
            let pos = if raw < 0 { len + raw } else { raw };
            if pos < 0 || pos > len {
                return Err(format!("args-out-of-range: {} {raw}", h.print(&a[1], true)));
            }
            pos as usize
        }
    };
    let re = compile_cf(h, &pat, case_fold_search(h))?;
    match run_match(&re, &subject, start) {
        Some(spans) => {
            let begin = spans[0].map(|(b, _)| b as i64).unwrap_or(0);
            h.match_data = Some(MatchData {
                subject,
                spans,
                from_buffer: false,
                buffer: None,
            });
            Ok(Value::Int(begin))
        }
        None => Ok(Value::Undef),
    }
}

/// `(string-match-p REGEXP STRING &optional START)` — like `string-match` but
/// preserves the existing match data.
fn string_match_p(h: &mut ElispHost, a: &[Value]) -> R {
    let saved = h.match_data.take();
    let result = string_match(h, a);
    h.match_data = saved;
    result
}

/// `(match-beginning N)` / `(match-end N)` — the char position of the start/end
/// of the Nth subexpression of the last match, or nil.
fn match_edge(h: &mut ElispHost, a: &[Value], end: bool) -> R {
    let n = as_int(h, &a[0])?.max(0) as usize;
    let edge = h
        .match_data
        .as_ref()
        .and_then(|m| m.spans.get(n).copied().flatten())
        .map(|(b, e)| if end { e } else { b });
    Ok(match edge {
        Some(pos) => Value::Int(pos as i64),
        None => Value::Undef,
    })
}
fn match_beginning(h: &mut ElispHost, a: &[Value]) -> R {
    match_edge(h, a, false)
}
fn match_end(h: &mut ElispHost, a: &[Value]) -> R {
    match_edge(h, a, true)
}

/// `(match-string N &optional STRING)` — the text matched by the Nth
/// subexpression. STRING defaults to the subject of the last `string-match`.
fn match_string(h: &mut ElispHost, a: &[Value]) -> R {
    let n = as_int(h, &a[0])?.max(0) as usize;
    let Some(md) = h.match_data.as_ref() else {
        return Ok(Value::Undef);
    };
    let span = md.spans.get(n).copied().flatten();
    // Buffer matches store 1-based buffer positions; read the current buffer
    // text by char (unless an explicit STRING argument is given).
    let explicit = a.get(1).and_then(|v| h.str_text(v)).map(str::to_string);
    if md.from_buffer && explicit.is_none() {
        return Ok(match span {
            Some((b, e)) => {
                let t = &h.cur_buf().text;
                let (lo, hi) = ((b - 1).min(t.len()), (e - 1).min(t.len()));
                let text = t[lo..hi].iter().collect::<String>();
                h.new_string(text)
            }
            None => Value::Undef,
        });
    }
    let Some(md) = h.match_data.as_ref() else {
        return Ok(Value::Undef);
    };
    let subject = match explicit {
        Some(s) => s,
        None => md.subject.clone(),
    };
    match span {
        Some((b, e)) => {
            let bb = byte_of_char(&subject, b);
            let eb = byte_of_char(&subject, e);
            Ok(h.new_string(subject.get(bb..eb).unwrap_or("").to_string()))
        }
        None => Ok(Value::Undef),
    }
}

/// Port of `Fmatch_data` (search.c): `(match-data &optional INTEGERS REUSE RESEAT)`.
///
/// A match made in a buffer is reported as MARKERS into that buffer (markers
/// pointing nowhere once it is killed), unless INTEGERS is non-nil, in which
/// case the positions are integers and the buffer itself is appended. Only up
/// to the last group that matched is reported. A cons REUSE receives the
/// values in place — surplus cells are set to nil, a shortfall is consed on —
/// and is the value; RESEAT first detaches the markers REUSE holds.
fn match_data_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let integers = a.first().is_some_and(|v| !is_nil(v));
    let reuse = a.get(1).cloned().unwrap_or(Value::Undef);
    if a.get(2).is_some_and(|v| !is_nil(v)) {
        let mut tail = reuse.clone();
        while let Some(Obj::Cons(car, cdr)) = h.obj(&tail).cloned() {
            if h.is_marker(&car) {
                h.set_marker_to(&car, None, 0)?;
                setcar(h, &[tail.clone(), Value::Undef])?;
            }
            tail = cdr;
        }
    }
    let Some(md) = h.match_data.clone() else {
        return Ok(Value::Undef);
    };
    let live = md.buffer.filter(|&bi| h.buffers[bi].name.is_some());
    let mut data = Vec::with_capacity(md.spans.len() * 2 + 1);
    let mut len = 0;
    for span in &md.spans {
        match *span {
            Some((b, e)) => {
                if md.buffer.is_none() || integers {
                    data.push(Value::Int(b as i64));
                    data.push(Value::Int(e as i64));
                } else {
                    data.push(h.alloc_marker(live, if live.is_some() { b } else { 0 }, false));
                    data.push(h.alloc_marker(live, if live.is_some() { e } else { 0 }, false));
                }
                len = data.len();
            }
            None => {
                data.push(Value::Undef);
                data.push(Value::Undef);
            }
        }
    }
    data.truncate(len);
    if let (Some(bi), true) = (md.buffer, integers) {
        data.push(h.buffer_object(bi));
    }
    if !matches!(h.obj(&reuse), Some(Obj::Cons(..))) {
        return Ok(h.list_from(data));
    }
    let mut items = data.into_iter();
    let mut tail = reuse.clone();
    let mut prev = tail.clone();
    while let Some(Obj::Cons(_, cdr)) = h.obj(&tail).cloned() {
        setcar(h, &[tail.clone(), items.next().unwrap_or(Value::Undef)])?;
        prev = tail;
        tail = cdr;
    }
    let rest: Vec<Value> = items.collect();
    if !rest.is_empty() {
        let rest = h.list_from(rest);
        setcdr(h, &[prev, rest])?;
    }
    Ok(reuse)
}

/// Port of `Fset_match_data` (search.c): `(set-match-data LIST &optional RESEAT)`.
///
/// LIST is what `match-data` produces: integer or marker pairs, nil pairs for
/// groups that did not match, optionally ending in a buffer. A marker or a
/// trailing buffer makes the data a buffer match in that buffer; a marker
/// pointing nowhere reads as 0. RESEAT detaches each marker once read.
fn set_match_data(h: &mut ElispHost, a: &[Value]) -> R {
    let list = a[0].clone();
    if !is_nil(&list) && !matches!(h.obj(&list), Some(Obj::Cons(..))) {
        return Err(h.signal_wrong_type("listp", &list));
    }
    let reseat = a.get(1).is_some_and(|v| !is_nil(v));
    let flat = h.list_vec(&list).unwrap_or_default();
    let pairs = flat.len() / 2;
    let mut buffer: Option<usize> = None;
    let mut spans: Vec<Option<(usize, usize)>> = Vec::with_capacity(pairs);
    let pos = |h: &mut ElispHost, v: &Value, buffer: &mut Option<usize>| -> Result<i64, String> {
        if h.is_marker(v) {
            let p = match h.marker_buffer(v) {
                Some(bv) => {
                    if let Some(Obj::Buffer(bi)) = h.obj(&bv) {
                        *buffer = Some(*bi);
                    }
                    h.marker_position(v).unwrap_or(0) as i64
                }
                None => 0,
            };
            if reseat {
                h.set_marker_to(v, None, 0)?;
            }
            return Ok(p);
        }
        as_int_or_marker(h, v, "integer-or-marker-p")
    };
    let mut i = 0;
    while i < flat.len() {
        if let Some(Obj::Buffer(bi)) = h.obj(&flat[i]) {
            buffer = Some(*bi);
            break;
        }
        if spans.len() >= pairs {
            break;
        }
        if is_nil(&flat[i]) {
            // A nil start skips its (unread) end as well.
            spans.push(None);
            i += 2;
            continue;
        }
        let from = pos(h, &flat[i], &mut buffer)?;
        let Some(end_v) = flat.get(i + 1).cloned() else {
            break;
        };
        let to = pos(h, &end_v, &mut buffer)?;
        spans.push(Some((from.max(0) as usize, to.max(0) as usize)));
        i += 2;
    }
    while spans.last().is_some_and(|s| s.is_none()) {
        spans.pop();
    }
    if spans.is_empty() {
        h.match_data = None;
        return Ok(Value::Undef);
    }
    let subject = h
        .match_data
        .as_ref()
        .map(|m| m.subject.clone())
        .unwrap_or_default();
    h.match_data = Some(MatchData {
        subject,
        spans,
        from_buffer: buffer.is_some(),
        buffer,
    });
    Ok(Value::Undef)
}

/// `(regexp-quote STRING)` — STRING with every regexp-special character escaped
/// so it matches literally under elisp regexp rules.
fn regexp_quote(h: &mut ElispHost, a: &[Value]) -> R {
    let s = as_string(h, &a[0])?;
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        // The set Emacs's own `regexp-quote` escapes (search.c Fregexp_quote:
        // `*.\?+[^$`). Notably `]` is NOT escaped.
        if matches!(c, '.' | '*' | '+' | '?' | '[' | '^' | '$' | '\\') {
            out.push('\\');
        }
        out.push(c);
    }
    Ok(h.new_string(out))
}

/// Adapt REP's case to MATCHED's (Emacs FIXEDCASE-nil behavior): an all-uppercase
/// match upcases REP; a capitalized match (first letter upper, some lowercase)
/// upcases the first letter of each word in REP; otherwise REP is unchanged.
fn adapt_replacement_case(matched: &str, rep: String) -> String {
    let (mut upper, mut lower, mut first_upper) = (0u32, 0u32, None);
    for c in matched.chars() {
        if c.is_alphabetic() {
            if c.is_uppercase() {
                upper += 1;
            } else {
                lower += 1;
            }
            if first_upper.is_none() {
                first_upper = Some(c.is_uppercase());
            }
        }
    }
    if upper > 0 && lower == 0 {
        rep.to_uppercase()
    } else if first_upper == Some(true) {
        // Upcase the first letter of each word (run of alphanumerics), keep the rest.
        let mut out = String::with_capacity(rep.len());
        let mut prev_word = false;
        for c in rep.chars() {
            if c.is_alphabetic() && !prev_word {
                out.extend(c.to_uppercase());
            } else {
                out.push(c);
            }
            prev_word = c.is_alphanumeric();
        }
        out
    } else {
        rep
    }
}

// `replace-regexp-in-string` is a Lisp function in Emacs (subr.el) and here
// (prelude.rs): its argument checks, function-valued REP, and zero-width-match
// stepping all fall out of the Lisp definition, which a Rust reimplementation
// kept getting subtly wrong (it type-checked REP eagerly and appended a
// replacement for the empty match at end-of-string).

// ── numeric: float → integer rounding, and integer bit ops ──
/// Rounding mode for `floor`/`ceiling`/`round`/`truncate`.
#[derive(Clone, Copy)]
enum Rm {
    Floor,
    Ceil,
    Trunc,
    Round,
}
/// `(OP NUMBER &optional DIVISOR)` — round NUMBER (or NUMBER/DIVISOR) to an
/// integer under `rm`. Integer operands use exact integer division so large
/// magnitudes don't lose precision; a float operand routes through `f64`.
fn quotient(h: &mut ElispHost, a: &[Value], rm: Rm) -> R {
    // `floor`/`ceiling`/`round`/`truncate` signal `numberp`, not
    // `number-or-marker-p`.
    // Integer operands stay exact — `(floor (expt 2 70) 3)` is a bignum, and
    // `(truncate 1e30)` is the exact integer value of that float, not a clamped
    // i64.
    let xn = as_number_p(h, &a[0], false)?;
    match a.get(1) {
        Some(d) if !is_nil(d) => {
            let dn = as_number_p(h, d, false)?;
            if let (Num::Int(x), Num::Int(y)) = (&xn, &dn) {
                if *y == BigInt::from(0) {
                    return Err("arith-error: division by zero".to_string());
                }
                let q = big_div(x, y, rm);
                return Ok(h.make_integer(q));
            }
            // A float on either side. Emacs does NOT round the `f64` quotient —
            // it divides *exactly*, because every finite float is an exact
            // dyadic rational. `(floor 1e30 3)' is 333333333333333339961541612885
            // (the exact integer 1e30 denotes, divided by 3), not
            // 333333333333333316505293553664 (`floor' of the `f64' quotient),
            // and not a saturated `i64::MAX'.
            let df = dn.to_f64();
            if df == 0.0 {
                return Err("arith-error: division by zero".to_string());
            }
            if matches!(xn, Num::Float(f) if !f.is_finite()) {
                // A non-finite NUMERATOR has no integer value at all.
                // (floor 1.0e+INF 2) and (floor 0.0e+NaN 2) => overflow-error.
                return Err("overflow-error".to_string());
            }
            if df.is_nan() {
                // (floor 2 0.0e+NaN) => overflow-error, but an *infinite*
                // divisor is not an error: Emacs rounds the exactly-zero
                // quotient, so (ceiling 2 1.0e+INF) is 0, not 1.
                return Err("overflow-error".to_string());
            }
            if df.is_infinite() {
                return Ok(Value::Int(0));
            }
            let (xnum, xden) = exact_ratio(&xn);
            let (dnum, dden) = exact_ratio(&dn);
            Ok(h.make_integer(big_div(&(xnum * dden), &(xden * dnum), rm)))
        }
        _ => match xn {
            Num::Int(i) => Ok(h.make_integer(i)),
            Num::Float(f) => {
                if !f.is_finite() {
                    // (truncate 1.0e+INF), (round (/ 0.0 0.0)) => overflow-error.
                    return Err("overflow-error".to_string());
                }
                Ok(float_to_integer(h, apply_rm(f, rm)))
            }
        },
    }
}
/// Divide two exact integers with the given rounding mode (Emacs's `floor`,
/// `ceiling`, `round`, `truncate` with a DIVISOR).
fn big_div(x: &BigInt, y: &BigInt, rm: Rm) -> BigInt {
    use num_integer::Integer;
    let zero = BigInt::from(0);
    let (q, r) = x.div_rem(y);
    match rm {
        Rm::Trunc => q,
        Rm::Floor if r != zero && (r < zero) != (*y < zero) => q - 1,
        Rm::Ceil if r != zero && (r < zero) == (*y < zero) => q + 1,
        Rm::Round => {
            // Round half to even, as Emacs does: compare |2r| with |y|.
            use num_traits::Signed;
            let twice: BigInt = (&r * BigInt::from(2)).abs();
            let mag = y.abs();
            let away = match twice.cmp(&mag) {
                std::cmp::Ordering::Greater => true,
                std::cmp::Ordering::Equal => q.is_odd(),
                std::cmp::Ordering::Less => false,
            };
            let toward = if (r < zero) != (*y < zero) { -1 } else { 1 };
            if away {
                q + toward
            } else {
                q
            }
        }
        _ => q,
    }
}

/// A finite number as the exact fraction `num / den`, `den` always positive.
///
/// Every finite `f64` is a dyadic rational — mantissa times a power of two — so
/// this loses nothing. It is what lets `floor`/`ceiling`/`round`/`truncate`
/// divide a float by an integer exactly, the way Emacs does, instead of
/// rounding an already-lossy `f64` quotient.
fn exact_ratio(n: &Num) -> (BigInt, BigInt) {
    let one = BigInt::from(1);
    let f = match n {
        Num::Int(i) => return (i.clone(), one),
        Num::Float(f) => *f,
    };
    let bits = f.to_bits();
    let biased = ((bits >> 52) & 0x7ff) as i64;
    let frac = bits & ((1u64 << 52) - 1);
    // A subnormal has no implicit leading 1 and a fixed exponent; a normal
    // number carries the hidden bit. 1075 = 1023 bias + 52 mantissa bits.
    let (mantissa, exp) = if biased == 0 {
        (frac, -1074)
    } else {
        (frac | (1u64 << 52), biased - 1075)
    };
    let mut num = BigInt::from(mantissa);
    if bits >> 63 == 1 {
        num = -num;
    }
    if exp >= 0 {
        (num << exp as usize, one)
    } else {
        (num, one << (-exp) as usize)
    }
}

/// An already-rounded `f64` as an exact elisp integer. A float beyond `i64` is a
/// bignum in Emacs: `(truncate 1e30)` is 1000000000000000019884624838656.
fn float_to_integer(h: &mut ElispHost, f: f64) -> Value {
    use num_traits::ToPrimitive;
    match f.to_i64() {
        Some(i) => h.make_integer(BigInt::from(i)),
        None => match <BigInt as num_traits::FromPrimitive>::from_f64(f) {
            Some(b) => h.make_integer(b),
            None => Value::Float(f),
        },
    }
}

fn apply_rm(f: f64, rm: Rm) -> f64 {
    match rm {
        Rm::Floor => f.floor(),
        Rm::Ceil => f.ceil(),
        Rm::Trunc => f.trunc(),
        Rm::Round => f.round_ties_even(),
    }
}
fn floor_fn(h: &mut ElispHost, a: &[Value]) -> R {
    quotient(h, a, Rm::Floor)
}
fn ceiling_fn(h: &mut ElispHost, a: &[Value]) -> R {
    quotient(h, a, Rm::Ceil)
}
fn round_fn(h: &mut ElispHost, a: &[Value]) -> R {
    // Emacs rounds half to even (banker's rounding): (round 2.5) => 2, (round 0.5) => 0.
    quotient(h, a, Rm::Round)
}
fn truncate_fn(h: &mut ElispHost, a: &[Value]) -> R {
    quotient(h, a, Rm::Trunc)
}
fn float_fn(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(Value::Float(as_number_p(h, &a[0], false)?.to_f64()))
}
/// The exact integer value of `v` for a bit/shift op, bignum included.
/// Emacs's bitwise ops reject floats (`integer-or-marker-p`) but accept any
/// integer, of any size: `(logand (expt 2 70) (expt 2 70))` is 2^70.
fn as_int_exact(h: &ElispHost, v: &Value) -> Result<BigInt, String> {
    as_int_exact_p(h, v, true)
}

/// [`as_int_exact`] with Emacs's predicate for the calling builtin: the bit-logic
/// ops (`logand`/`logior`/`logxor`/`%`) take a marker and signal
/// `integer-or-marker-p`, while the shifts and `lognot`/`logcount` take strictly
/// an integer and signal `integerp`.
/// The exact integer of a bit-logic argument (`logand`/`logior`/`logxor`), with
/// the predicate Emacs names for that *position*.
///
/// Emacs's `bit_op` checks the FIRST argument with a direct `CHECK_INTEGER`, so a
/// bad one there is always `integer-or-marker-p`. Each *later* argument is checked
/// for number-ness first, so a non-number there is `number-or-marker-p` while a
/// float is still `integer-or-marker-p`:
///
/// ```text
/// (logand "x" 2)  => (wrong-type-argument integer-or-marker-p "x")   ; first
/// (logand 2 "x")  => (wrong-type-argument number-or-marker-p  "x")   ; later
/// (logand 2 1.0)  => (wrong-type-argument integer-or-marker-p 1.0)   ; a number
/// ```
fn as_int_bitop(h: &ElispHost, v: &Value, first: bool) -> Result<BigInt, String> {
    if !first && !h.is_number(v) && h.marker_position(v).is_none() {
        return Err(format!(
            "wrong-type-argument: number-or-marker-p {}",
            h.print(v, true)
        ));
    }
    as_int_exact(h, v)
}

fn as_int_exact_p(h: &ElispHost, v: &Value, markers_ok: bool) -> Result<BigInt, String> {
    match v {
        Value::Int(n) => Ok(BigInt::from(*n)),
        _ => {
            if let Some(b) = h.as_bigint(v) {
                return Ok(b);
            }
            if markers_ok {
                if let Some(p) = h.marker_position(v) {
                    return Ok(BigInt::from(p));
                }
            }
            Err(format!(
                "wrong-type-argument: {} {}",
                if markers_ok {
                    "integer-or-marker-p"
                } else {
                    "integerp"
                },
                h.print(v, true)
            ))
        }
    }
}

fn logand_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let mut r = BigInt::from(-1);
    for (i, v) in a.iter().enumerate() {
        r &= as_int_bitop(h, v, i == 0)?;
    }
    Ok(h.make_integer(r))
}
fn logior_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let mut r = BigInt::from(0);
    for (i, v) in a.iter().enumerate() {
        r |= as_int_bitop(h, v, i == 0)?;
    }
    Ok(h.make_integer(r))
}
fn logxor_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let mut r = BigInt::from(0);
    for (i, v) in a.iter().enumerate() {
        r ^= as_int_bitop(h, v, i == 0)?;
    }
    Ok(h.make_integer(r))
}
fn lognot_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let n = as_int_exact_p(h, &a[0], false)?;
    Ok(h.make_integer(!n))
}
/// `(ash VALUE COUNT)` — arithmetic shift. A left shift is exact: Emacs's
/// integers are unbounded, so `(ash 1 70)` is 2^70, not a wrapped fixnum.
/// The `integer-width` bound in bits: how wide a bignum Emacs will build before
/// signalling `overflow-error`. Defaults to 65536, as `emacs -Q` reports.
fn integer_width(h: &ElispHost) -> u64 {
    h.find_symbol("integer-width")
        .and_then(|s| h.get_value(&s).ok())
        .and_then(|v| match v {
            Value::Int(n) if n > 0 => Some(n as u64),
            _ => None,
        })
        .unwrap_or(65536)
}

fn ash_fn(h: &mut ElispHost, a: &[Value]) -> R {
    use num_traits::{Signed, ToPrimitive};
    let n = as_int_exact_p(h, &a[0], false)?;
    let cb = as_int_exact_p(h, &a[1], false)?;
    let c = match cb.to_i64() {
        Some(c) => c,
        // A count that does not even fit an i64: shifting left by it would exhaust
        // memory; shifting right by it collapses to the sign.
        None if cb.is_negative() => {
            return Ok(h.make_integer(if n.is_negative() {
                BigInt::from(-1)
            } else {
                BigInt::from(0)
            }))
        }
        None => return Err("overflow-error".to_string()),
    };
    let r = if c >= 0 {
        // Emacs bounds an integer at `integer-width` bits (65536 by default) and
        // signals `overflow-error` for a result wider than that — rather than
        // building the 15-megabyte number `(ash 3 123456788)` asks for. Zero
        // shifts to zero at any count, so it is not bounded.
        let width = integer_width(h);
        if n.sign() != num_bigint::Sign::NoSign && n.bits().saturating_add(c as u64) > width {
            return Err("overflow-error".to_string());
        }
        n << (c as u64)
    } else {
        // `BigInt`'s `>>` is already an arithmetic shift (it floors toward
        // negative infinity for negatives), which is what Emacs's `ash` does.
        let sh = c.unsigned_abs();
        if sh > 1 << 30 {
            if n.sign() == num_bigint::Sign::Minus {
                BigInt::from(-1)
            } else {
                BigInt::from(0)
            }
        } else {
            n >> sh
        }
    };
    Ok(h.make_integer(r))
}

/// `(lsh VALUE COUNT)` — *logical* shift, unlike `ash`'s arithmetic shift.
/// Left shift matches `ash`. For a right shift (negative COUNT) Emacs treats the
/// fixnum as an *unsigned* value of the fixnum bit width, so vacated high bits
/// fill with zeros rather than the sign bit: `(lsh -1 -1)` => 2305843009213693951
/// (`(2^62-1) >> 1`), not -1. Fixnums are 62-bit here (`most-positive-fixnum`
/// = 2^61-1), so mask to 62 bits before the unsigned shift.
fn lsh_fn(h: &mut ElispHost, a: &[Value]) -> R {
    const FIXNUM_MASK: u64 = (1u64 << 62) - 1;
    // VALUE goes through `CHECK_NUMBER` before its integer check, so a
    // non-number reports `number-or-marker-p` and a float reports `integerp`;
    // COUNT goes straight through `CHECK_INTEGER` and always reports `integerp`.
    // Measured on GNU Emacs 30.2:
    //
    //   (lsh ""  6)  => (wrong-type-argument number-or-marker-p "")
    //   (lsh 1.5 2)  => (wrong-type-argument integerp 1.5)
    //   (lsh 1  "")  => (wrong-type-argument integerp "")
    //
    // The check has to come first: the exact-shift path below reports `integerp`
    // on its own and would answer for VALUE with the wrong predicate.
    if as_number_p(h, &a[0], true).is_err() {
        let v = a[0].clone();
        return Err(h.signal_wrong_type("number-or-marker-p", &v));
    }
    // A left shift is exact, like `ash` — `(lsh 1 70)` is 2^70.
    if let Ok(c) = as_integer(h, &a[1]) {
        if c >= 0 {
            let n = as_int_exact_p(h, &a[0], false)?;
            if c > 1 << 30 {
                return Err("overflow-error".to_string());
            }
            let r = n << (c as u64);
            return Ok(h.make_integer(r));
        }
    }
    // `Flsh` runs `CHECK_NUMBER` first (data.c), so a non-number reports
    // `number-or-marker-p` — `ash`, which runs `CHECK_INTEGER`, reports
    // `integerp`. The two differ and elisp code reads the predicate.
    let n = as_integer(h, &a[0])?;
    let c = as_integer(h, &a[1])?;
    Ok(Value::Int(if c >= 0 {
        n.wrapping_shl(c as u32)
    } else {
        let sh = (-c) as u32;
        // Masked value is < 2^62, so any shift ≥ 62 yields 0 (and this also
        // avoids an out-of-range `>>` on the u64).
        if sh >= 62 {
            0
        } else {
            (((n as u64) & FIXNUM_MASK) >> sh) as i64
        }
    }))
}

// ── parity: float math / numeric parsing / introspection ──

/// `(expt BASE EXP)` — integer power when BASE is an integer and EXP a
/// non-negative integer; otherwise float `BASE**EXP` (covers negative and
/// fractional exponents). `(expt 2 10)`=>1024, `(expt 2 -1)`=>0.5, `(expt 2.0 0.5)`.
fn expt_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let base = as_number_p(h, &a[0], false)?;
    let exp = as_number_p(h, &a[1], false)?;
    if let (Num::Int(b), Num::Int(e)) = (&base, &exp) {
        use num_traits::{Signed, ToPrimitive};
        if !e.is_negative() {
            // Exact: `(expt 2 70)` is 2^70, not a wrapped i64. A huge exponent
            // would exhaust memory; Emacs signals rather than trying.
            let e_u32 = e.to_u32().ok_or_else(|| "overflow-error".to_string())?;
            if e_u32 > 1 << 24 {
                return Err("overflow-error".to_string());
            }
            let r = num_traits::Pow::pow(b.clone(), e_u32);
            return Ok(h.make_integer(r));
        }
    }
    Ok(Value::Float(base.to_f64().powf(exp.to_f64())))
}
fn sqrt_fn(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(Value::Float(as_number_p(h, &a[0], false)?.to_f64().sqrt()))
}
fn exp_fn(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(Value::Float(as_number_p(h, &a[0], false)?.to_f64().exp()))
}
fn log_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let x = as_number_p(h, &a[0], false)?.to_f64();
    Ok(Value::Float(match a.get(1) {
        // Emacs uses `log10`/`log2` for base 10/2 (exact for powers of the base:
        // (log 1000 10) => 3.0), falling back to ln(x)/ln(base) otherwise.
        Some(b) => {
            let base = as_num(h, b)?.1;
            if base == 10.0 {
                x.log10()
            } else if base == 2.0 {
                x.log2()
            } else {
                x.ln() / base.ln()
            }
        }
        None => x.ln(),
    }))
}
fn sin_fn(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(Value::Float(as_number_p(h, &a[0], false)?.to_f64().sin()))
}
fn cos_fn(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(Value::Float(as_number_p(h, &a[0], false)?.to_f64().cos()))
}
fn tan_fn(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(Value::Float(as_number_p(h, &a[0], false)?.to_f64().tan()))
}
fn asin_fn(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(Value::Float(as_number_p(h, &a[0], false)?.to_f64().asin()))
}
fn acos_fn(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(Value::Float(as_number_p(h, &a[0], false)?.to_f64().acos()))
}
fn atan_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let y = as_number_p(h, &a[0], false)?.to_f64();
    Ok(Value::Float(match a.get(1) {
        // X takes the same `CHECK_NUMBER` as Y (floatfns.c `Fatan`), so it reports
        // `numberp` — `as_num` reports `number-or-marker-p`, which is the
        // predicate the arithmetic ops use, not this one.
        Some(x) => {
            let xv = as_number_p(h, x, false)
                .map_err(|_| format!("wrong-type-argument: numberp {}", h.print(x, true)))?;
            y.atan2(xv.to_f64())
        }
        None => y.atan(),
    }))
}
/// `ldexp(x, n)` = `x * 2^n`, computed like C's `scalbn` (musl) so subnormal
/// results are preserved instead of flushing to 0. A naive `x * 2f64.powi(n)`
/// overflows `2^n` to infinity for very negative `n` and returns 0.0, whereas
/// Emacs (via C `ldexp`) yields the smallest subnormal (e.g. `(ldexp 1.0 -1074)`
/// => 5e-324). The staged scaling keeps every intermediate in range.
pub(crate) fn scalbn(x: f64, mut n: i64) -> f64 {
    let two_1023 = 2f64.powi(1023);
    let two_m1022 = f64::MIN_POSITIVE; // 2^-1022
    let two_53 = (1u64 << 53) as f64; // 2^53
    let mut y = x;
    if n > 1023 {
        y *= two_1023;
        n -= 1023;
        if n > 1023 {
            y *= two_1023;
            n -= 1023;
            if n > 1023 {
                n = 1023;
            }
        }
    } else if n < -1022 {
        // Keep the final n < -53 to avoid double rounding in the subnormal range.
        y *= two_m1022 * two_53;
        n += 1022 - 53;
        if n < -1022 {
            y *= two_m1022 * two_53;
            n += 1022 - 53;
            if n < -1022 {
                n = -1022;
            }
        }
    }
    y * f64::from_bits(((0x3ff + n) as u64) << 52)
}
fn ldexp_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let m = as_number_p(h, &a[0], false)?.to_f64();
    let e = as_num(h, &a[1])?.0;
    Ok(Value::Float(scalbn(m, e)))
}
/// `(copysign X Y)` — X with Y's sign.
///
/// Both arguments must be *floats*: Emacs `Fcopysign` uses `CHECK_TYPE (FLOATP …)`
/// rather than the number check the rest of the float library uses, so an integer
/// signals `(wrong-type-argument floatp N)` instead of being coerced.
fn copysign_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let f = |h: &mut ElispHost, v: &Value| -> Result<f64, String> {
        match v {
            Value::Float(x) => Ok(*x),
            _ => Err(h.signal_wrong_type("floatp", v)),
        }
    };
    let x = f(h, &a[0])?;
    let y = f(h, &a[1])?;
    Ok(Value::Float(x.copysign(y)))
}
/// Decompose V into (SIGNIFICAND . EXPONENT) with the significand in [0.5,1).
/// Bit-level port of C `frexp` (musl): exact for all values including subnormals
/// and huge magnitudes. The old `log2`-based formula divided by `2^e`, which
/// overflowed/underflowed to give `(0.0 . 1024)` for 1e308 and `(inf . -1073)`
/// for the smallest subnormal instead of Emacs's `(0.5562… . 1024)` / `(0.5 . -1073)`.
fn frexp_parts(x: f64) -> (f64, i64) {
    let bits = x.to_bits();
    let ee = (bits >> 52) & 0x7ff;
    if ee == 0 {
        // Subnormal or zero.
        if x == 0.0 {
            (x, 0) // preserves -0.0
        } else {
            // Normalize by scaling up 2^64, then correct the exponent.
            let (m, e) = frexp_parts(x * 2f64.powi(64));
            (m, e - 64)
        }
    } else if ee == 0x7ff {
        (x, 0) // inf or NaN
    } else {
        let e = ee as i64 - 0x3fe;
        let m = f64::from_bits((bits & 0x800f_ffff_ffff_ffff) | 0x3fe0_0000_0000_0000);
        (m, e)
    }
}
fn frexp_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let (m, e) = frexp_parts(as_number_p(h, &a[0], false)?.to_f64());
    Ok(h.cons(Value::Float(m), Value::Int(e)))
}
fn isnan_fn(h: &mut ElispHost, a: &[Value]) -> R {
    match a[0] {
        Value::Float(f) => Ok(nil_or(f.is_nan())),
        _ => Err(format!(
            "wrong-type-argument: floatp {}",
            h.print(&a[0], true)
        )),
    }
}
/// The argument of the `f*` rounding subrs (`fround`/`ffloor`/`fceiling`/
/// `ftruncate`): exactly a float — Emacs's `CHECK_FLOAT` — so an integer is as
/// much a `(wrong-type-argument floatp X)` as a non-number is.
fn as_float_strict(h: &ElispHost, v: &Value) -> Result<f64, String> {
    match v {
        Value::Float(f) => Ok(*f),
        _ => Err(format!("wrong-type-argument: floatp {}", h.print(v, true))),
    }
}
fn fround_fn(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(Value::Float(as_float_strict(h, &a[0])?.round_ties_even()))
}
fn ffloor_fn(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(Value::Float(as_float_strict(h, &a[0])?.floor()))
}
fn fceiling_fn(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(Value::Float(as_float_strict(h, &a[0])?.ceil()))
}
fn ftruncate_fn(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(Value::Float(as_float_strict(h, &a[0])?.trunc()))
}

/// `(string-to-number STRING &optional BASE)` — parse a leading number. With
/// BASE (2–16) parse an integer in that radix; otherwise parse an int, or a
/// float when a `.` or exponent is present. Non-numeric input yields 0.
fn string_to_number(h: &mut ElispHost, a: &[Value]) -> R {
    let raw = as_string(h, &a[0])?;
    // Emacs skips exactly SPC and TAB, never the rest of the ASCII whitespace
    // set and never Unicode spaces: `(string-to-number "\n12")` is 0, as are the
    // `\r` `\f` `\v` U+00A0 and U+3000 forms. `trim_start` skipped all of them.
    let s = raw.trim_start_matches([' ', '\t']);
    if let Some(bv) = a.get(1) {
        // Base 10 (and nil) use the float-capable default parser below; only a
        // non-decimal base forces integer-only parsing.
        if !is_nil(bv) {
            // BASE is CHECK_FIXNUM: a float, a bignum, a marker and `t` are all
            // `fixnump`, and that check precedes the 2..=16 range check.
            let base_i = match bv {
                Value::Int(n) => *n,
                v => {
                    return Err(format!("wrong-type-argument: fixnump {}", h.print(v, true)));
                }
            };
            // Emacs restricts BASE to 2..16 and signals args-out-of-range
            // otherwise (checked before the base==10 fast path).
            if !(2..=16).contains(&base_i) {
                return Err(format!("args-out-of-range: {base_i}"));
            }
            if base_i != 10 {
                let base = base_i as u32;
                let mut chars = s.chars().peekable();
                let mut sign = 1i64;
                match chars.peek() {
                    Some('+') => {
                        chars.next();
                    }
                    Some('-') => {
                        sign = -1;
                        chars.next();
                    }
                    _ => {}
                }
                let (mut n, mut seen) = (BigInt::from(0), false);
                for c in chars {
                    match c.to_digit(base) {
                        Some(d) => {
                            n = n * base as i64 + d as i64;
                            seen = true;
                        }
                        None => break,
                    }
                }
                return Ok(if seen {
                    h.make_integer(n * sign)
                } else {
                    Value::Int(0)
                });
            }
        }
    }
    let b: Vec<char> = s.chars().collect();
    let (mut i, n) = (0usize, b.len());
    let start = i;
    if i < n && (b[i] == '+' || b[i] == '-') {
        i += 1;
    }
    let (mut has_digit, mut is_float) = (false, false);
    while i < n && b[i].is_ascii_digit() {
        i += 1;
        has_digit = true;
    }
    // A bare trailing dot (no fractional digit, no exponent) keeps the number an
    // integer in Emacs: `(string-to-number "1.")` => 1, not 1.0. Only a digit
    // after the dot — or an exponent below — makes it a float.
    let mut dot_pos = None;
    if i < n && b[i] == '.' {
        dot_pos = Some(i);
        i += 1;
        while i < n && b[i].is_ascii_digit() {
            i += 1;
            has_digit = true;
            is_float = true;
        }
    }
    // Non-finite float syntax, straight out of lread.c `string_to_number': after
    // `e' an explicit `+' may be followed by the literal `INF' or `NaN'. Both are
    // case-sensitive and both require the `+' — `1.0e-INF', `1.0eINF' and
    // `1.0e+inf' are not numbers. Without this, `(string-to-number "1.0e+INF")'
    // silently answered the finite 1.0, so any float round-tripped through
    // `number-to-string' lost its infinity.
    let mut nonfinite: Option<f64> = None;
    if has_digit && i < n && (b[i] == 'e' || b[i] == 'E') {
        let mut j = i + 1;
        let plus = j < n && b[j] == '+';
        if j < n && (b[j] == '+' || b[j] == '-') {
            j += 1;
        }
        if j < n && b[j].is_ascii_digit() {
            is_float = true;
            i = j;
            while i < n && b[i].is_ascii_digit() {
                i += 1;
            }
        } else if plus && b[j..].starts_with(&['I', 'N', 'F']) {
            is_float = true;
            nonfinite = Some(f64::INFINITY);
            i = j + 3;
        } else if plus && b[j..].starts_with(&['N', 'a', 'N']) {
            is_float = true;
            // The payload is the token's leading integer, as in the reader.
            let mant: String = b[start..i].iter().collect();
            nonfinite = Some(crate::reader::nan_with_payload(
                crate::reader::leading_integer(&mant),
                false,
            ));
            i = j + 3;
        }
    }
    if !has_digit {
        return Ok(Value::Int(0));
    }
    if is_float {
        // lread.c negates the value itself so `-0.0e+NaN' and `-1.0e+INF' keep
        // their sign — the sign is not part of what INF/NaN parsed.
        if let Some(v) = nonfinite {
            return Ok(Value::Float(if b[start] == '-' { -v } else { v }));
        }
        let tok: String = b[start..i].iter().collect();
        Ok(Value::Float(tok.parse().unwrap_or(0.0)))
    } else {
        // Integer parse must exclude a trailing dot ("1." => 1), so stop at the
        // dot position when one was consumed without becoming a float.
        let end = dot_pos.unwrap_or(i);
        let tok: String = b[start..end].iter().collect();
        // Exact at any size: `(string-to-number "1180591620717411303424")` is that
        // integer, not the 0 an `i64` parse failure used to yield.
        match tok.parse::<BigInt>() {
            Ok(n) => Ok(h.make_integer(n)),
            Err(_) => Ok(Value::Int(0)),
        }
    }
}

// ── sxhash ──
// fns.c's `sxhash_obj` for the objects whose hash Emacs derives from their
// contents (fixnums, floats, bignums, strings, conses, vectors, bool-vectors),
// on a 64-bit build (`EMACS_INT_WIDTH` 64, `FIXNUM_BITS` 62). Symbols and the
// other objects Emacs hashes by address keep an elisprs-local hash: equal
// objects still hash equally, but the numbers are not Emacs's.
const SXHASH_MAX_DEPTH: u32 = 3;
const SXHASH_MAX_LEN: usize = 7;
const INTMASK: u64 = (1 << 62) - 1;
fn hash_mix(acc: u64, x: u64) -> u64 {
    (acc ^ x)
        .wrapping_mul(0x100000001b3)
        .wrapping_add(0x9e3779b97f4a7c15)
}
fn hash_bytes(s: &str) -> u64 {
    let mut acc = 0xcbf29ce484222325u64;
    for b in s.bytes() {
        acc = hash_mix(acc, b as u64);
    }
    acc
}
/// lisp.h `sxhash_combine`.
fn sxhash_combine(x: u64, y: u64) -> u64 {
    (x << 4).wrapping_add(x >> 60).wrapping_add(y)
}
/// fns.c `hash_char_array` over a string's internal (UTF-8) bytes.
fn hash_char_array(p: &[u8]) -> u64 {
    let len = p.len();
    let mut hash = len as u64;
    let word = |i: usize| u64::from_ne_bytes(p[i..i + 8].try_into().unwrap());
    if len >= 8 {
        let step = 8.max(len >> 3);
        let mut i = 0;
        while i + 8 <= len {
            hash = sxhash_combine(hash, word(i));
            i += step;
        }
        hash = sxhash_combine(hash, word(len - 8));
    } else {
        let mut tail = 0u64;
        let mut i = 0;
        if len - i >= 4 {
            tail = (tail << 32) + u32::from_ne_bytes(p[i..i + 4].try_into().unwrap()) as u64;
            i += 4;
        }
        if len - i >= 2 {
            tail = (tail << 16) + u16::from_ne_bytes(p[i..i + 2].try_into().unwrap()) as u64;
            i += 2;
        }
        if i < len {
            tail = (tail << 8) + p[i] as u64;
        }
        hash = sxhash_combine(hash, tail);
    }
    hash
}
/// fns.c `sxhash_obj`.
fn sxhash_obj(h: &ElispHost, v: &Value, depth: u32) -> u64 {
    if depth > SXHASH_MAX_DEPTH {
        return 0;
    }
    // `sxhash_bignum`: the sign, then each 64-bit limb of the magnitude.
    if let Some(b) = h.as_bigint(v).filter(|_| h.is_bignum(v)) {
        let mut hash = u64::from(b.sign() == num_bigint::Sign::Minus);
        for limb in b.magnitude().iter_u64_digits() {
            hash = sxhash_combine(hash, limb);
        }
        return hash;
    }
    match v {
        Value::Int(n) => (*n as u64) & INTMASK,
        // `sxhash_float`: one word per double on a 64-bit build.
        Value::Float(f) => sxhash_combine(0, f.to_bits()),
        Value::Str(s) => hash_char_array(s.as_bytes()),
        // `XHASH (Qnil)` is 0: nil is the first entry of `lispsym`.
        Value::Bool(false) | Value::Undef => 0,
        Value::Bool(true) => 1,
        Value::Obj(_) => match h.obj(v) {
            Some(Obj::Str(s)) => hash_char_array(s.as_bytes()),
            // `XHASH` of a symbol is its tagged address, which on a 64-bit
            // host stays below 2^47; the name-derived stand-in keeps that range.
            Some(Obj::Symbol(s)) => hash_mix(0x5111, hash_bytes(&s.name)) & ((1 << 47) - 1),
            Some(Obj::Cons(..)) => {
                // `sxhash_list`.
                let mut hash = 0u64;
                let mut list = v.clone();
                if depth < SXHASH_MAX_DEPTH {
                    let mut i = 0;
                    while let Some(Obj::Cons(car, cdr)) = h.obj(&list) {
                        if i >= SXHASH_MAX_LEN {
                            break;
                        }
                        let (car, cdr) = (car.clone(), cdr.clone());
                        hash = sxhash_combine(hash, sxhash_obj(h, &car, depth + 1));
                        list = cdr;
                        i += 1;
                    }
                }
                if !matches!(list, Value::Undef | Value::Bool(false)) {
                    hash = sxhash_combine(hash, sxhash_obj(h, &list, depth + 1));
                }
                hash
            }
            Some(Obj::Vector(items)) => {
                // `sxhash_vector`.
                let mut hash = items.len() as u64;
                for it in items.iter().take(SXHASH_MAX_LEN) {
                    hash = sxhash_combine(hash, sxhash_obj(h, it, depth + 1));
                }
                hash
            }
            Some(Obj::BoolVector(bits)) => {
                // `sxhash_bool_vector`: the size, then the first words of bits.
                let mut hash = bits.len() as u64;
                for chunk in bits.chunks(64).take(SXHASH_MAX_LEN) {
                    let word =
                        chunk
                            .iter()
                            .enumerate()
                            .fold(0u64, |w, (i, &b)| if b { w | (1 << i) } else { w });
                    hash = sxhash_combine(hash, word);
                }
                hash
            }
            _ => 0x6,
        },
        _ => 0x8,
    }
}
/// fns.c `sxhash_eq` (`XHASH (k) ^ XTYPE (k)`) for a fixnum, whose tag is
/// `Lisp_Int0` (2) or `Lisp_Int1` (6) by its low bit; other objects hash by
/// identity here (an address in Emacs).
fn sxhash_eq(v: &Value) -> u64 {
    match v {
        Value::Int(n) => ((*n as u64) & INTMASK) ^ if n & 1 == 0 { 2 } else { 6 },
        Value::Float(f) => f.to_bits(),
        Value::Bool(false) | Value::Undef => 0,
        Value::Bool(true) => 1,
        Value::Str(s) => hash_bytes(s),
        Value::Obj(id) => hash_mix(0xab, *id as u64),
        _ => 0x8,
    }
}
/// fns.c `reduce_emacs_uint_to_fixnum`: `SXHASH_REDUCE` folds the top bits in
/// and masks to `INTMASK`; `make_ufixnum` then reads back as a signed fixnum.
fn sxhash_fixnum(x: u64) -> Value {
    let r = (x ^ (x >> 2)) & INTMASK;
    Value::Int(((r << 2) as i64) >> 2)
}
fn sxhash_equal_fn(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(sxhash_fixnum(sxhash_obj(h, &a[0], 0)))
}
fn sxhash_eq_fn(_h: &mut ElispHost, a: &[Value]) -> R {
    Ok(sxhash_fixnum(sxhash_eq(&a[0])))
}
fn sxhash_eql_fn(h: &mut ElispHost, a: &[Value]) -> R {
    // fns.c `sxhash_eql`: floats and bignums by value, the rest as `sxhash_eq`.
    let x = match &a[0] {
        Value::Float(_) => sxhash_obj(h, &a[0], 0),
        other if h.is_bignum(other) => sxhash_obj(h, other, 0),
        other => sxhash_eq(other),
    };
    Ok(sxhash_fixnum(x))
}

/// `(type-of OBJECT)` — the symbol naming OBJECT's primitive type.
fn type_of(h: &mut ElispHost, a: &[Value]) -> R {
    // A record (including every cl-defstruct instance) reports its slot 0 verbatim
    // — the type symbol for a normal record — matching Emacs's `Ftype_of`.
    if let Some(Obj::Record(items)) = h.obj(&a[0]) {
        let slot0 = items.first().cloned();
        return match slot0 {
            Some(t) => Ok(t),
            None => Ok(h.intern("record")),
        };
    }
    let name = match &a[0] {
        Value::Int(_) => "integer",
        Value::Float(_) => "float",
        Value::Str(_) => "string",
        _ if h.is_string(&a[0]) => "string",
        Value::Bool(_) | Value::Undef => "symbol",
        Value::Obj(_) => match h.obj(&a[0]) {
            Some(Obj::Cons(..)) => "cons",
            Some(Obj::Overlay(_)) => "overlay",
            Some(Obj::Window(_)) => "window",
            Some(Obj::Frame(_)) => "frame",
            Some(Obj::WindowConfig(_)) => "window-configuration",
            // Emacs answers `integer` for a bignum too — fixnum and bignum are one
            // type, split only by `fixnump`/`bignump`.
            Some(Obj::Bignum(_)) => "integer",
            Some(Obj::Symbol(_)) => "symbol",
            Some(Obj::Vector(_)) => "vector",
            // Unreachable: a record is handled by the early return above; this arm
            // only keeps the match exhaustive over `Obj`.
            Some(Obj::Record(_)) => "record",
            Some(Obj::BoolVector(_)) => "bool-vector",
            // Unreachable: the `Value::Str` arm above matches first, because
            // `type_of` views its argument through `str_view`. Here for exhaustiveness.
            Some(Obj::Str(_)) => "string",
            Some(Obj::Subr { .. }) => "subr",
            // Emacs 30 renamed the interpreted-closure type: `(type-of (lambda ()))`
            // is `interpreted-function` (it was `function` only up to Emacs 29).
            // A macro is not a function object at all in Emacs — the function cell
            // holds the cons `(macro . FUNCTION)` — so `type-of` answers `cons`,
            // which is also what this printer already emits for one.
            Some(Obj::Closure { is_macro, .. }) => {
                if *is_macro {
                    "cons"
                } else {
                    "interpreted-function"
                }
            }
            Some(Obj::HashTable(_)) => "hash-table",
            Some(Obj::CharTable(_)) => "char-table",
            Some(Obj::Buffer(_)) => "buffer",
            Some(Obj::Marker(_)) => "marker",
            Some(Obj::Obarray(_)) => "obarray",
            None => "symbol",
        },
        _ => "symbol",
    };
    Ok(h.intern(name))
}
/// `(recordp OBJECT)` — non-nil for any record (a `record`/`make-record` result,
/// a `#s(…)` literal, or a cl-defstruct instance). Distinct from `cl-struct-p`,
/// which the prelude overrides to accept only cl-defstruct records.
fn recordp(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(nil_or(matches!(h.obj(&a[0]), Some(Obj::Record(_)))))
}

// ── OClosure C primitives (oclosure.el) ──
// These implement the host-specific seam `oclosure.el` builds on. The rest of
// oclosure.el is ported faithfully into the prelude. Because elisprs closures
// are compiled (not aref-indexable interpreted-functions), the type + slot
// layout is attached via a side table and slot values live in the closure's
// captured env — see `ElispHost::oclosure_*`.

/// `(closurep OBJECT)` — t if OBJECT is a closure.
/// `(elisprs--prelude-closure-p OBJECT)`: OBJECT is a closure the prelude
/// defined — Lisp that Emacs ships byte-compiled, so it answers
/// `byte-code-function-p` and `compiled-function-p` where a user closure does
/// not.
fn prelude_closure_p_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let macro_cell = matches!(h.obj(&a[0]), Some(Obj::Closure { is_macro: true, .. }));
    Ok(nil_or(
        h.is_closure(&a[0]) && !macro_cell && h.is_prelude_object(&a[0]),
    ))
}

fn closurep_fn(h: &mut ElispHost, a: &[Value]) -> R {
    // A macro is the cons `(macro . FN)` in Emacs, so `CLOSUREP` is false for it.
    let macro_cell = matches!(h.obj(&a[0]), Some(Obj::Closure { is_macro: true, .. }));
    Ok(nil_or(h.is_closure(&a[0]) && !macro_cell))
}

/// `(oclosure--fix-type TYPE SLOTS MUTABLES CLOSURE)` — mark CLOSURE as an
/// OClosure of TYPE with the given ordered SLOTS; returns CLOSURE. In Emacs this
/// is a 2-arg cconv marker whose type rides in the lambda's `:documentation`;
/// elisprs passes the type + slot names explicitly (its closures have no
/// aref-addressable docstring slot) — a NAMED divergence of the internal seam,
/// not of the observable API.
fn oclosure_fix_type(h: &mut ElispHost, a: &[Value]) -> R {
    let closure = a[3].clone();
    if !h.is_closure(&closure) {
        return Err("cl-assertion-failed: (closurep oclosure)".to_string());
    }
    let ty = h
        .as_sym_handle(&a[0])
        .ok_or("oclosure--fix-type: type is not a symbol")?;
    let slot_vals = h
        .list_vec(&a[1])
        .ok_or("oclosure--fix-type: slots is not a proper list")?;
    let mut slots = Vec::with_capacity(slot_vals.len());
    for s in &slot_vals {
        slots.push(
            h.as_sym_handle(s)
                .ok_or("oclosure--fix-type: slot name is not a symbol")?,
        );
    }
    h.oclosure_set_meta(&closure, ty, slots);
    Ok(closure)
}

/// `(oclosure-type OCLOSURE)` — the type symbol of OCLOSURE, or nil.
fn oclosure_type_fn(h: &mut ElispHost, a: &[Value]) -> R {
    match h.oclosure_type_of(&a[0]) {
        Some(id) => Ok(Value::Obj(id)),
        None => Ok(Value::Undef),
    }
}

/// `(oclosure--get OCLOSURE INDEX MUTABLE)` — value of slot INDEX. MUTABLE is
/// accepted for signature compatibility but unused (slot values always live in a
/// mutable env cell; mutability is enforced by the class in `oclosure--set-slot-value`).
fn oclosure_get_fn(h: &mut ElispHost, a: &[Value]) -> R {
    if !h.is_closure(&a[0]) {
        return Err("cl-assertion-failed: (closurep oclosure)".to_string());
    }
    let idx = as_int(h, &a[1])? as usize;
    h.oclosure_get(&a[0], idx)
        .ok_or_else(|| "oclosure--get: slot index out of range".to_string())
}

/// `(oclosure--set V OCLOSURE INDEX)` — set slot INDEX to V; returns V.
fn oclosure_set_fn(h: &mut ElispHost, a: &[Value]) -> R {
    if !h.is_closure(&a[1]) {
        return Err("cl-assertion-failed: (closurep oclosure)".to_string());
    }
    let idx = as_int(h, &a[2])? as usize;
    if h.oclosure_set(&a[1], idx, &a[0]) {
        Ok(a[0].clone())
    } else {
        Err("oclosure--set: slot index out of range".to_string())
    }
}

/// `(oclosure--copy OCLOSURE MUTLIST &rest ARGS)` — functional copy of OCLOSURE
/// with the first `(length ARGS)` slots replaced. MUTLIST (bytecode mutable-cell
/// wrapping) is irrelevant to elisprs's env-cell slots and ignored.
fn oclosure_copy_fn(h: &mut ElispHost, a: &[Value]) -> R {
    if !h.is_closure(&a[0]) {
        return Err("cl-assertion-failed: (closurep oclosure)".to_string());
    }
    let args: Vec<Value> = a[2..].to_vec();
    h.oclosure_copy(&a[0], &args)
        .ok_or_else(|| "oclosure--copy: not an OClosure".to_string())
}

/// `(functionp OBJECT)` — non-nil if OBJECT can be called as a function (a subr,
/// a non-macro closure, or a symbol whose function cell resolves to one).
fn functionp(h: &mut ElispHost, a: &[Value]) -> R {
    // eval.c `FUNCTIONP`: a SUBR object is a function only when its `max_args`
    // is not `UNEVALLED`, so `(functionp (symbol-function 'if))` is nil even
    // though the subr object itself resolves.
    if let Some(Obj::Subr { name, .. }) = h.obj(&a[0]) {
        if SPECIAL_FORMS.iter().any(|(sf, _)| *sf == name.as_str()) {
            return Ok(Value::Bool(false));
        }
    }
    // A list is a function when its car is `lambda`, and a symbol whose
    // indirect definition is an `autoload` is one unless TYPE (the fifth
    // element) is non-nil — a macro or keymap autoload.
    if h.indirect_lambda_list(&a[0]).is_some() {
        return Ok(Value::Bool(true));
    }
    let mut cur = a[0].clone();
    for _ in 0..64 {
        match h.obj(&cur) {
            Some(Obj::Symbol(s)) => match &s.function {
                Some(def) => cur = def.clone(),
                None => break,
            },
            _ => break,
        }
    }
    if let Some(items) = h.list_vec(&cur) {
        if items.first().and_then(|c| h.sym_name(c)).as_deref() == Some("autoload")
            && matches!(h.obj(&a[0]), Some(Obj::Symbol(_)))
        {
            return Ok(nil_or(!items.get(4).is_some_and(crate::host::el_truthy)));
        }
    }
    let ok = match h.resolve_function(&a[0]) {
        Ok(Resolved::Subr { .. }) => true,
        Ok(Resolved::Closure { is_macro, .. }) => !is_macro,
        Err(_) => false,
    };
    Ok(nil_or(ok))
}
fn char_or_string_p(_h: &mut ElispHost, a: &[Value]) -> R {
    // A "character" is an integer in [0, #x3FFFFF]; strings always qualify.
    let ok = match &a[0] {
        Value::Int(n) => (0..=0x3F_FFFF).contains(n),
        v => _h.is_string(v),
    };
    Ok(nil_or(ok))
}
/// `(char-width CHAR)` — a C primitive in Emacs (`Fchar_width`, `indent.c`), so
/// it is one here too rather than a prelude `defun`; `format`'s column-measured
/// width and precision need the same table from Rust, and two copies of it
/// would be two answers.
fn char_width_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let c = as_char(h, &a[0])?;
    Ok(Value::Int(char_display_width(c) as i64))
}
fn char_equal(h: &mut ElispHost, a: &[Value]) -> R {
    // `CHECK_CHARACTER`, not `CHECK_FIXNUM`: a float, a negative code, a code
    // past MAX_CHAR and a marker are all `(wrong-type-argument characterp X)`.
    let (c1, c2) = (as_char(h, &a[0])? as i64, as_char(h, &a[1])? as i64);
    if c1 == c2 {
        return Ok(Value::Bool(true));
    }
    // With case-fold-search (default t), compare case-insensitively.
    if case_fold_search(h) {
        if let (Some(x), Some(y)) = (char::from_u32(c1 as u32), char::from_u32(c2 as u32)) {
            let eq = x.to_lowercase().eq(y.to_lowercase());
            return Ok(nil_or(eq));
        }
    }
    Ok(Value::Bool(false))
}
/// `(symbol-function SYMBOL)` — the symbol's function-cell value, or nil.
fn symbol_function(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(h.introspect_function_cell(&a[0]).unwrap_or(Value::Undef))
}
/// The body of a subr whose calls `host::call_function` intercepts by name. It
/// exists so the function cell — and therefore `fboundp`, `functionp`,
/// `func-arity`, `subrp`, `indirect-function` and `symbol-function` — reports
/// what Emacs reports. Reaching it means a call site bypassed the intercept,
/// which is a routing bug, not a user error.
pub(crate) fn intercepted_subr(_h: &mut ElispHost, _a: &[Value]) -> R {
    Err(
        "internal: an intercepted higher-order primitive was called through its \
         subr body; host::call_function should have matched it by name"
            .to_string(),
    )
}
/// `(--set-intrinsic-macro-cell SYM CELL)` — record the `(macro . FUNCTION)` an
/// intrinsically-lowered macro reports through `symbol-function` / `fboundp` /
/// `indirect-function`. Called once from the prelude; not an Emacs function.
fn set_intrinsic_macro_cell(h: &mut ElispHost, a: &[Value]) -> R {
    h.set_intrinsic_macro_cell(&a[0], a[1].clone());
    Ok(a[0].clone())
}
/// `(intern-soft NAME)` — the interned symbol named NAME, or nil if none exists.
fn intern_soft(h: &mut ElispHost, a: &[Value]) -> R {
    let name = match &a[0] {
        v if h.is_string(v) => h.str_text(v).unwrap_or_default().to_string(),
        // `t` and `nil` ARE interned symbols in Emacs; elisprs represents them as
        // `Value::Bool`/`Value::Undef` rather than heap symbols, so `sym_name`
        // misses them and `(intern-soft t)` answered nil where Emacs answers `t`.
        Value::Bool(true) => "t".to_string(),
        v if is_nil(v) => "nil".to_string(),
        // A symbol argument is looked up by its own name; anything else names
        // itself in the error data, as Emacs's `CHECK_STRING` does.
        v => h
            .sym_name(v)
            .ok_or_else(|| format!("wrong-type-argument: stringp {}", h.print(v, true)))?,
    };
    match obarray_arg(h, a.get(1))? {
        None => match name.as_str() {
            // Not heap symbols here, but interned symbols in Emacs, so they must
            // answer themselves rather than "no such symbol".
            "t" => Ok(Value::Bool(true)),
            "nil" => Ok(Value::Undef),
            _ => Ok(h.find_symbol(&name).unwrap_or(Value::Undef)),
        },
        Some(id) => Ok(h.obarray_intern_soft(id, &name)),
    }
}
fn subrp(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(nil_or(matches!(h.obj(&a[0]), Some(Obj::Subr { .. }))))
}
/// `(--set-subr-intspec SYMBOL SPEC)`: the primitive in SYMBOL's function cell
/// is a command whose `DEFUN` intspec is SPEC (a string, or the form a spec
/// starting with `(` reads as). Called from the prelude; not an Emacs function.
fn set_subr_intspec(h: &mut ElispHost, a: &[Value]) -> R {
    match h.introspect_function_cell(&a[0]) {
        Some(Value::Obj(id)) if matches!(h.obj(&Value::Obj(id)), Some(Obj::Subr { .. })) => {
            h.subr_intspecs.insert(id, a[1].clone());
            Ok(a[0].clone())
        }
        _ => Err(h.signal_wrong_type("subrp", &a[0])),
    }
}
/// `(--subr-intspec SUBR)`: SUBR's interactive spec, or nil when it is not a
/// command (eval.c `Fcommandp` / data.c `Finteractive_form` read `intspec`).
fn subr_intspec(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(match &a[0] {
        Value::Obj(id) => h.subr_intspecs.get(id).cloned().unwrap_or(Value::Undef),
        _ => Value::Undef,
    })
}
// Forms elisprs lowers as compiler intrinsics but which Emacs classifies as
// *macros* (`lambda`/`when`/… are macros there, not special forms). Each carries
// the minimum arity of its Emacs `subr.el` lambda-list (max is always `many`),
// used by `func-arity`.
const INTRINSIC_MACROS: &[(&str, i64)] = &[
    ("lambda", 0),
    ("when", 1),
    ("unless", 1),
    ("defun", 2),
    ("defmacro", 2),
];
// The genuine special forms, matching Emacs's `special-form-p`. Each carries the
// C-level minimum arity Emacs's `func-arity` reports (max is always `unevalled`).
// `prog2` is a macro in Emacs, not a special form; `interactive`/`inline` are.
const SPECIAL_FORMS: &[(&str, i64)] = &[
    ("and", 0),
    ("catch", 1),
    ("cond", 0),
    ("condition-case", 2),
    ("defconst", 2),
    ("defvar", 1),
    ("function", 1),
    ("if", 2),
    ("inline", 0),
    ("interactive", 0),
    ("let", 1),
    ("let*", 1),
    ("or", 0),
    ("prog1", 1),
    ("progn", 0),
    ("quote", 1),
    ("save-current-buffer", 0),
    ("save-excursion", 0),
    ("save-restriction", 0),
    ("setq", 0),
    ("unwind-protect", 1),
    ("while", 1),
];
/// `(macrop OBJECT)` — non-nil if OBJECT is (or names) a macro.
fn macrop(h: &mut ElispHost, a: &[Value]) -> R {
    if matches!(
        h.resolve_function(&a[0]),
        Ok(Resolved::Closure { is_macro: true, .. })
    ) {
        return Ok(Value::Bool(true));
    }
    // The intrinsic forms have no closure to resolve, but are macros in Emacs.
    let ok = h
        .sym_name(&a[0])
        .is_some_and(|n| INTRINSIC_MACROS.iter().any(|(m, _)| *m == n.as_str()));
    Ok(nil_or(ok))
}
/// `(special-form-p OBJECT)` — non-nil if OBJECT names a special form (per
/// Emacs's classification, not elisprs's internal lowering).
fn special_form_p(h: &mut ElispHost, a: &[Value]) -> R {
    // Emacs `Fspecial_form_p` dereferences a symbol to its function and then asks
    // the *subr* whether its `max_args` is `UNEVALLED`, so the subr object answers
    // `t` just as the symbol naming it does: `(special-form-p (symbol-function
    // 'if))` is `t`, not nil.
    let name = match h.obj(&a[0]) {
        Some(Obj::Subr { name, .. }) => Some(name.clone()),
        _ => h.sym_name(&a[0]),
    };
    let ok = name.is_some_and(|n| SPECIAL_FORMS.iter().any(|(sf, _)| *sf == n.as_str()));
    Ok(nil_or(ok))
}
fn char_uppercase_p(h: &mut ElispHost, a: &[Value]) -> R {
    let c = char::from_u32(as_int(h, &a[0])? as u32);
    Ok(nil_or(c.is_some_and(|c| c.is_uppercase())))
}
/// `(string-distance S1 S2 &optional BYTECOMPARE)` — Levenshtein edit distance.
/// With BYTECOMPARE non-nil, Emacs measures over UTF-8 bytes, not characters
/// (editfns.c Fstring_distance).
fn string_distance(h: &mut ElispHost, a: &[Value]) -> R {
    let a0 = as_string(h, &a[0])?;
    let a1 = as_string(h, &a[1])?;
    let bytewise = a.len() > 2 && !is_nil(&a[2]);
    let (s1, s2): (Vec<u32>, Vec<u32>) = if bytewise {
        (
            a0.bytes().map(|b| b as u32).collect(),
            a1.bytes().map(|b| b as u32).collect(),
        )
    } else {
        (
            a0.chars().map(|c| c as u32).collect(),
            a1.chars().map(|c| c as u32).collect(),
        )
    };
    let m = s2.len();
    let mut prev: Vec<usize> = (0..=m).collect();
    let mut cur = vec![0usize; m + 1];
    for (i, c1) in s1.iter().enumerate() {
        cur[0] = i + 1;
        for (j, c2) in s2.iter().enumerate() {
            let cost = if c1 == c2 { 0 } else { 1 };
            cur[j + 1] = (prev[j + 1] + 1).min(cur[j] + 1).min(prev[j] + cost);
        }
        std::mem::swap(&mut prev, &mut cur);
    }
    Ok(Value::Int(prev[m] as i64))
}
/// `(vconcat &rest SEQUENCES)` — concatenate any sequences (lists, vectors,
/// strings) into a new vector. `(vconcat [1 2] "a")` => `[1 2 97]`.
fn vconcat_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let mut out = Vec::new();
    for v in a {
        if is_nil(v) {
            continue;
        }
        match h.obj(v) {
            Some(Obj::Vector(items)) => out.extend(items.clone()),
            _ => match h
                .str_text(v)
                .map(|s| s.chars().map(|c| Value::Int(c as i64)).collect::<Vec<_>>())
            {
                Some(chars) => out.extend(chars),
                // Fvconcat's list walk names a dotted TAIL with listp
                // ((vconcat '(t . 9)) => listp 9) and a non-sequence with
                // sequencep — exactly seq_vec_checked's contract.
                _ => out.extend(h.seq_vec_checked(v)?),
            },
        }
    }
    Ok(h.alloc(Obj::Vector(out)))
}
/// `(abs NUMBER)` — absolute value, keeping the int/float type (and turning
/// `-0.0` into `0.0`, which a `(< x 0)` test would miss).
fn abs_fn(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(match as_number_p(h, &a[0], false)? {
        Num::Int(n) => {
            use num_traits::Signed;
            h.make_integer(n.abs())
        }
        Num::Float(f) => Value::Float(f.abs()),
    })
}
/// `(logcount N)` — count of set bits for N≥0, or of clear bits for N<0 (i.e.
/// bits differing from the sign bit), matching Emacs.
fn logcount_fn(h: &mut ElispHost, a: &[Value]) -> R {
    use num_traits::Signed;
    let n = as_int_exact_p(h, &a[0], false)?;
    // Emacs counts set bits for N>=0 and clear bits (of the two's complement)
    // for N<0 — i.e. the bits that differ from the sign bit either way.
    let counted = if n.is_negative() { !n } else { n };
    let bits: u64 = counted
        .to_bytes_le()
        .1
        .iter()
        .map(|b| b.count_ones() as u64)
        .sum();
    Ok(Value::Int(bits as i64))
}
// ── secure-hash / sha1 / md5 (self-contained, no crates) ──
fn sha1_bytes(msg: &[u8]) -> Vec<u8> {
    let mut h: [u32; 5] = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0];
    let ml = (msg.len() as u64).wrapping_mul(8);
    let mut data = msg.to_vec();
    data.push(0x80);
    while data.len() % 64 != 56 {
        data.push(0);
    }
    data.extend_from_slice(&ml.to_be_bytes());
    for chunk in data.chunks(64) {
        let mut w = [0u32; 80];
        for (i, wi) in w.iter_mut().enumerate().take(16) {
            *wi = u32::from_be_bytes([
                chunk[i * 4],
                chunk[i * 4 + 1],
                chunk[i * 4 + 2],
                chunk[i * 4 + 3],
            ]);
        }
        for i in 16..80 {
            w[i] = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]).rotate_left(1);
        }
        let (mut a, mut b, mut c, mut d, mut e) = (h[0], h[1], h[2], h[3], h[4]);
        for (i, &wi) in w.iter().enumerate() {
            let (f, k) = match i {
                0..=19 => ((b & c) | ((!b) & d), 0x5A827999u32),
                20..=39 => (b ^ c ^ d, 0x6ED9EBA1),
                40..=59 => ((b & c) | (b & d) | (c & d), 0x8F1BBCDC),
                _ => (b ^ c ^ d, 0xCA62C1D6),
            };
            let tmp = a
                .rotate_left(5)
                .wrapping_add(f)
                .wrapping_add(e)
                .wrapping_add(k)
                .wrapping_add(wi);
            e = d;
            d = c;
            c = b.rotate_left(30);
            b = a;
            a = tmp;
        }
        h[0] = h[0].wrapping_add(a);
        h[1] = h[1].wrapping_add(b);
        h[2] = h[2].wrapping_add(c);
        h[3] = h[3].wrapping_add(d);
        h[4] = h[4].wrapping_add(e);
    }
    h.iter().flat_map(|x| x.to_be_bytes()).collect()
}
/// Generic SHA-2 (32-bit words: SHA-224/SHA-256).  `iv` is the initial hash
/// state; the digest is truncated to `out_len` bytes (28 for SHA-224).
fn sha2_32(msg: &[u8], iv: [u32; 8], out_len: usize) -> Vec<u8> {
    const K: [u32; 64] = [
        0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4,
        0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe,
        0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f,
        0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
        0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
        0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
        0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116,
        0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
        0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
        0xc67178f2,
    ];
    let mut h = iv;
    let ml = (msg.len() as u64).wrapping_mul(8);
    let mut data = msg.to_vec();
    data.push(0x80);
    while data.len() % 64 != 56 {
        data.push(0);
    }
    data.extend_from_slice(&ml.to_be_bytes());
    for chunk in data.chunks(64) {
        let mut w = [0u32; 64];
        for (i, wi) in w.iter_mut().enumerate().take(16) {
            *wi = u32::from_be_bytes([
                chunk[i * 4],
                chunk[i * 4 + 1],
                chunk[i * 4 + 2],
                chunk[i * 4 + 3],
            ]);
        }
        for i in 16..64 {
            let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
            let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
            w[i] = w[i - 16]
                .wrapping_add(s0)
                .wrapping_add(w[i - 7])
                .wrapping_add(s1);
        }
        let mut v = h;
        for i in 0..64 {
            let s1 = v[4].rotate_right(6) ^ v[4].rotate_right(11) ^ v[4].rotate_right(25);
            let ch = (v[4] & v[5]) ^ ((!v[4]) & v[6]);
            let t1 = v[7]
                .wrapping_add(s1)
                .wrapping_add(ch)
                .wrapping_add(K[i])
                .wrapping_add(w[i]);
            let s0 = v[0].rotate_right(2) ^ v[0].rotate_right(13) ^ v[0].rotate_right(22);
            let maj = (v[0] & v[1]) ^ (v[0] & v[2]) ^ (v[1] & v[2]);
            let t2 = s0.wrapping_add(maj);
            v = [
                t1.wrapping_add(t2),
                v[0],
                v[1],
                v[2],
                v[3].wrapping_add(t1),
                v[4],
                v[5],
                v[6],
            ];
        }
        for (hi, vi) in h.iter_mut().zip(v.iter()) {
            *hi = hi.wrapping_add(*vi);
        }
    }
    let full: Vec<u8> = h.iter().flat_map(|x| x.to_be_bytes()).collect();
    full[..out_len].to_vec()
}
fn sha256_bytes(msg: &[u8]) -> Vec<u8> {
    sha2_32(
        msg,
        [
            0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
            0x5be0cd19,
        ],
        32,
    )
}
fn sha224_bytes(msg: &[u8]) -> Vec<u8> {
    sha2_32(
        msg,
        [
            0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7,
            0xbefa4fa4,
        ],
        28,
    )
}
/// Generic SHA-2 (64-bit words: SHA-384/SHA-512).  `iv` is the initial hash
/// state; the digest is truncated to `out_len` bytes (48 for SHA-384).
fn sha2_64(msg: &[u8], iv: [u64; 8], out_len: usize) -> Vec<u8> {
    const K: [u64; 80] = [
        0x428a2f98d728ae22,
        0x7137449123ef65cd,
        0xb5c0fbcfec4d3b2f,
        0xe9b5dba58189dbbc,
        0x3956c25bf348b538,
        0x59f111f1b605d019,
        0x923f82a4af194f9b,
        0xab1c5ed5da6d8118,
        0xd807aa98a3030242,
        0x12835b0145706fbe,
        0x243185be4ee4b28c,
        0x550c7dc3d5ffb4e2,
        0x72be5d74f27b896f,
        0x80deb1fe3b1696b1,
        0x9bdc06a725c71235,
        0xc19bf174cf692694,
        0xe49b69c19ef14ad2,
        0xefbe4786384f25e3,
        0x0fc19dc68b8cd5b5,
        0x240ca1cc77ac9c65,
        0x2de92c6f592b0275,
        0x4a7484aa6ea6e483,
        0x5cb0a9dcbd41fbd4,
        0x76f988da831153b5,
        0x983e5152ee66dfab,
        0xa831c66d2db43210,
        0xb00327c898fb213f,
        0xbf597fc7beef0ee4,
        0xc6e00bf33da88fc2,
        0xd5a79147930aa725,
        0x06ca6351e003826f,
        0x142929670a0e6e70,
        0x27b70a8546d22ffc,
        0x2e1b21385c26c926,
        0x4d2c6dfc5ac42aed,
        0x53380d139d95b3df,
        0x650a73548baf63de,
        0x766a0abb3c77b2a8,
        0x81c2c92e47edaee6,
        0x92722c851482353b,
        0xa2bfe8a14cf10364,
        0xa81a664bbc423001,
        0xc24b8b70d0f89791,
        0xc76c51a30654be30,
        0xd192e819d6ef5218,
        0xd69906245565a910,
        0xf40e35855771202a,
        0x106aa07032bbd1b8,
        0x19a4c116b8d2d0c8,
        0x1e376c085141ab53,
        0x2748774cdf8eeb99,
        0x34b0bcb5e19b48a8,
        0x391c0cb3c5c95a63,
        0x4ed8aa4ae3418acb,
        0x5b9cca4f7763e373,
        0x682e6ff3d6b2b8a3,
        0x748f82ee5defb2fc,
        0x78a5636f43172f60,
        0x84c87814a1f0ab72,
        0x8cc702081a6439ec,
        0x90befffa23631e28,
        0xa4506cebde82bde9,
        0xbef9a3f7b2c67915,
        0xc67178f2e372532b,
        0xca273eceea26619c,
        0xd186b8c721c0c207,
        0xeada7dd6cde0eb1e,
        0xf57d4f7fee6ed178,
        0x06f067aa72176fba,
        0x0a637dc5a2c898a6,
        0x113f9804bef90dae,
        0x1b710b35131c471b,
        0x28db77f523047d84,
        0x32caab7b40c72493,
        0x3c9ebe0a15c9bebc,
        0x431d67c49c100d4c,
        0x4cc5d4becb3e42b6,
        0x597f299cfc657e2a,
        0x5fcb6fab3ad6faec,
        0x6c44198c4a475817,
    ];
    let mut h = iv;
    let bitlen = (msg.len() as u128).wrapping_mul(8);
    let mut data = msg.to_vec();
    data.push(0x80);
    while data.len() % 128 != 112 {
        data.push(0);
    }
    data.extend_from_slice(&bitlen.to_be_bytes());
    for chunk in data.chunks(128) {
        let mut w = [0u64; 80];
        for (i, wi) in w.iter_mut().enumerate().take(16) {
            *wi = u64::from_be_bytes([
                chunk[i * 8],
                chunk[i * 8 + 1],
                chunk[i * 8 + 2],
                chunk[i * 8 + 3],
                chunk[i * 8 + 4],
                chunk[i * 8 + 5],
                chunk[i * 8 + 6],
                chunk[i * 8 + 7],
            ]);
        }
        for i in 16..80 {
            let s0 = w[i - 15].rotate_right(1) ^ w[i - 15].rotate_right(8) ^ (w[i - 15] >> 7);
            let s1 = w[i - 2].rotate_right(19) ^ w[i - 2].rotate_right(61) ^ (w[i - 2] >> 6);
            w[i] = w[i - 16]
                .wrapping_add(s0)
                .wrapping_add(w[i - 7])
                .wrapping_add(s1);
        }
        let mut v = h;
        for i in 0..80 {
            let s1 = v[4].rotate_right(14) ^ v[4].rotate_right(18) ^ v[4].rotate_right(41);
            let ch = (v[4] & v[5]) ^ ((!v[4]) & v[6]);
            let t1 = v[7]
                .wrapping_add(s1)
                .wrapping_add(ch)
                .wrapping_add(K[i])
                .wrapping_add(w[i]);
            let s0 = v[0].rotate_right(28) ^ v[0].rotate_right(34) ^ v[0].rotate_right(39);
            let maj = (v[0] & v[1]) ^ (v[0] & v[2]) ^ (v[1] & v[2]);
            let t2 = s0.wrapping_add(maj);
            v = [
                t1.wrapping_add(t2),
                v[0],
                v[1],
                v[2],
                v[3].wrapping_add(t1),
                v[4],
                v[5],
                v[6],
            ];
        }
        for (hi, vi) in h.iter_mut().zip(v.iter()) {
            *hi = hi.wrapping_add(*vi);
        }
    }
    let full: Vec<u8> = h.iter().flat_map(|x| x.to_be_bytes()).collect();
    full[..out_len].to_vec()
}
fn sha512_bytes(msg: &[u8]) -> Vec<u8> {
    sha2_64(
        msg,
        [
            0x6a09e667f3bcc908,
            0xbb67ae8584caa73b,
            0x3c6ef372fe94f82b,
            0xa54ff53a5f1d36f1,
            0x510e527fade682d1,
            0x9b05688c2b3e6c1f,
            0x1f83d9abfb41bd6b,
            0x5be0cd19137e2179,
        ],
        64,
    )
}
fn sha384_bytes(msg: &[u8]) -> Vec<u8> {
    sha2_64(
        msg,
        [
            0xcbbb9d5dc1059ed8,
            0x629a292a367cd507,
            0x9159015a3070dd17,
            0x152fecd8f70e5939,
            0x67332667ffc00b31,
            0x8eb44a8768581511,
            0xdb0c2e0d64f98fa7,
            0x47b5481dbefa4fa4,
        ],
        48,
    )
}
fn md5_bytes(msg: &[u8]) -> Vec<u8> {
    const S: [u32; 64] = [
        7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5,
        9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10,
        15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,
    ];
    const K: [u32; 64] = [
        0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613,
        0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193,
        0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d,
        0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
        0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122,
        0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa,
        0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244,
        0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
        0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb,
        0xeb86d391,
    ];
    let (mut a0, mut b0, mut c0, mut d0) =
        (0x67452301u32, 0xefcdab89u32, 0x98badcfeu32, 0x10325476u32);
    let ml = (msg.len() as u64).wrapping_mul(8);
    let mut data = msg.to_vec();
    data.push(0x80);
    while data.len() % 64 != 56 {
        data.push(0);
    }
    data.extend_from_slice(&ml.to_le_bytes());
    for chunk in data.chunks(64) {
        let mut m = [0u32; 16];
        for (i, mi) in m.iter_mut().enumerate() {
            *mi = u32::from_le_bytes([
                chunk[i * 4],
                chunk[i * 4 + 1],
                chunk[i * 4 + 2],
                chunk[i * 4 + 3],
            ]);
        }
        let (mut a, mut b, mut c, mut d) = (a0, b0, c0, d0);
        for i in 0..64 {
            let (f, g) = match i {
                0..=15 => ((b & c) | ((!b) & d), i),
                16..=31 => ((d & b) | ((!d) & c), (5 * i + 1) % 16),
                32..=47 => (b ^ c ^ d, (3 * i + 5) % 16),
                _ => (c ^ (b | (!d)), (7 * i) % 16),
            };
            let f = f.wrapping_add(a).wrapping_add(K[i]).wrapping_add(m[g]);
            a = d;
            d = c;
            c = b;
            b = b.wrapping_add(f.rotate_left(S[i]));
        }
        a0 = a0.wrapping_add(a);
        b0 = b0.wrapping_add(b);
        c0 = c0.wrapping_add(c);
        d0 = d0.wrapping_add(d);
    }
    [a0, b0, c0, d0]
        .iter()
        .flat_map(|x| x.to_le_bytes())
        .collect()
}
fn to_hex(bytes: &[u8]) -> String {
    let mut s = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        s.push_str(&format!("{b:02x}"));
    }
    s
}
/// The string argument's bytes between optional char START/END.
fn hash_input(h: &mut ElispHost, a: &[Value], obj_idx: usize) -> Result<Vec<u8>, String> {
    // Emacs's `secure_hash` accepts a string or a buffer and rejects anything
    // else with `xsignal2 (Qerror, "Invalid object argument", OBJECT)` — a plain
    // `error` carrying the object beside the message, not the
    // `wrong-type-argument` a string accessor reports.
    let s = match as_string(h, &a[obj_idx]) {
        Ok(s) => s,
        Err(_) => {
            let v = a[obj_idx].clone();
            return Err(h.signal_error_with("Invalid object argument", &v));
        }
    };
    // START and END index the *encoded bytes*, not the characters: Emacs hashes
    // the string's byte representation, so `(md5 "αβγ" 0 3)` covers three of its
    // six UTF-8 bytes and is NOT the whole three-character string.
    let bytes = s.as_bytes();
    let len = bytes.len() as i64;
    let idx = |h: &mut ElispHost, v: &Value| -> Result<i64, String> {
        // A float index is `(wrong-type-argument integerp F)` — `as_int` would
        // truncate it and hash some other range instead.
        match v {
            Value::Int(n) => Ok(*n),
            _ if as_integer(h, v).is_ok() => as_integer(h, v),
            _ => Err(h.signal_wrong_type("integerp", v)),
        }
    };
    let raw_start = match a.get(obj_idx + 1) {
        Some(v) if !is_nil(v) => Some(idx(h, &v.clone())?),
        _ => None,
    };
    let raw_end = match a.get(obj_idx + 2) {
        Some(v) if !is_nil(v) => Some(idx(h, &v.clone())?),
        _ => None,
    };
    // A negative bound counts from the end (`validate_subarray` adds the length
    // once), so `(md5 "abc" -1)` hashes "c".
    let adj = |n: i64| if n < 0 { n + len } else { n };
    let start = raw_start.map_or(0, adj);
    let end = raw_end.map_or(len, adj);
    // Emacs `validate_subarray`: START and END must bracket a real subrange, and
    // one that does not is `(args-out-of-range OBJECT START END)` with the two
    // bounds *as written* (nil included). Clamping them instead quietly hashed
    // the empty string — `(secure-hash 'md5 "abc" 5 nil)` answered the digest of
    // "" rather than signalling.
    if start < 0 || end > len || start > end {
        let obj = h.print(&a[obj_idx], true);
        let sv = raw_start.map_or("nil".to_string(), |n| n.to_string());
        let ev = raw_end.map_or("nil".to_string(), |n| n.to_string());
        return Err(format!("args-out-of-range: {obj} {sv} {ev}"));
    }
    Ok(bytes[start as usize..end as usize].to_vec())
}
fn sha1_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let digest = to_hex(&sha1_bytes(&hash_input(h, a, 0)?));
    Ok(h.new_string(digest))
}
fn md5_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let digest = to_hex(&md5_bytes(&hash_input(h, a, 0)?));
    Ok(h.new_string(digest))
}
/// `(secure-hash ALGORITHM OBJECT &optional START END BINARY)`.
fn secure_hash(h: &mut ElispHost, a: &[Value]) -> R {
    // ALGORITHM is a symbol (md5/sha1/sha256/…); accept a string too.
    let algo = h
        .sym_name(&a[0])
        .or_else(|| as_string(h, &a[0]).ok())
        .unwrap_or_default();
    let bytes = hash_input(h, a, 1)?;
    let digest = match algo.as_str() {
        "md5" => md5_bytes(&bytes),
        "sha1" => sha1_bytes(&bytes),
        "sha224" => sha224_bytes(&bytes),
        "sha256" => sha256_bytes(&bytes),
        "sha384" => sha384_bytes(&bytes),
        "sha512" => sha512_bytes(&bytes),
        // Emacs `secure_hash` (fns.c): `error ("Invalid algorithm arg: %s", …)`,
        // with the argument rendered by `prin1` (a symbol prints bare).
        other => return Err(format!("error: Invalid algorithm arg: {other}")),
    };
    // BINARY (4th optional, index 4): return the raw bytes as a string.
    if a.get(4).is_some_and(|v| !is_nil(v)) {
        Ok(h.new_string(digest.iter().map(|&b| b as char).collect::<String>()))
    } else {
        Ok(h.new_string(to_hex(&digest)))
    }
}
/// `(secure-hash-algorithms)` — the list of algorithms `secure-hash' accepts.
/// Faithful to C `Fsecure_hash_algorithms` (fns.c): a fixed 6-symbol list.
fn secure_hash_algorithms(h: &mut ElispHost, _a: &[Value]) -> R {
    let syms = ["md5", "sha1", "sha224", "sha256", "sha384", "sha512"]
        .iter()
        .map(|n| h.intern(n))
        .collect();
    Ok(h.list_from(syms))
}
// ── base64 / url encoding ──
const B64_STD: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const B64_URL: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
fn b64_encode(input: &[u8], alphabet: &[u8; 64], pad: bool) -> String {
    let mut out = String::new();
    for chunk in input.chunks(3) {
        let b = [
            chunk[0],
            *chunk.get(1).unwrap_or(&0),
            *chunk.get(2).unwrap_or(&0),
        ];
        let n = ((b[0] as u32) << 16) | ((b[1] as u32) << 8) | (b[2] as u32);
        out.push(alphabet[((n >> 18) & 63) as usize] as char);
        out.push(alphabet[((n >> 12) & 63) as usize] as char);
        if chunk.len() > 1 {
            out.push(alphabet[((n >> 6) & 63) as usize] as char);
        } else if pad {
            out.push('=');
        }
        if chunk.len() > 2 {
            out.push(alphabet[(n & 63) as usize] as char);
        } else if pad {
            out.push('=');
        }
    }
    out
}
/// Insert a newline every 76 output characters (Emacs base64 default wrapping).
fn b64_wrap(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + s.len() / 76);
    for (i, c) in s.chars().enumerate() {
        if i > 0 && i % 76 == 0 {
            out.push('\n');
        }
        out.push(c);
    }
    out
}
/// Emacs's own diagnostic (fns.c `base64_decode_string`), capitalised as it is
/// there — elisp code catches this error and prints the string.
const INVALID_B64: &str = "error: Invalid base64 data";

/// Decode base64 (`url` selects the `-_` alphabet and the unpadded reading Emacs
/// uses for its BASE64URL argument).
///
/// The padded form is *strict*, as `base64_decode_1` is: whitespace is ignored
/// anywhere, but what is left must be whole 4-character quadruples over the
/// `+/` alphabet, `=` may only trail inside a quadruple, and a quadruple
/// carrying fewer than two data characters is rejected. Reading the input as a
/// loose bit stream instead accepted `"YWJ"` (which Emacs rejects) and `"-_-_"`
/// (whose alphabet belongs to the other mode).
fn b64_decode(input: &str, url: bool) -> Result<Vec<u8>, String> {
    let val = |c: u8| -> Option<u32> {
        match c {
            b'A'..=b'Z' => Some((c - b'A') as u32),
            b'a'..=b'z' => Some((c - b'a' + 26) as u32),
            b'0'..=b'9' => Some((c - b'0' + 52) as u32),
            b'+' if !url => Some(62),
            b'/' if !url => Some(63),
            b'-' if url => Some(62),
            b'_' if url => Some(63),
            _ => None,
        }
    };
    let chars: Vec<u8> = input.bytes().filter(|b| !b.is_ascii_whitespace()).collect();
    let mut out = Vec::with_capacity(chars.len() / 4 * 3);
    // BASE64URL padding is optional, but everything else about a quadruple still
    // holds: a short final group may carry no `=` at all (`"YWJ"` decodes,
    // `"YQ="` does not), and no group may hold fewer than two data characters
    // (`"A==="` and `"===="` are errors even here).
    if !url && !chars.len().is_multiple_of(4) {
        return Err(INVALID_B64.into());
    }
    for quad in chars.chunks(4) {
        if quad.len() < 4 {
            if quad.len() < 2 || quad.contains(&b'=') {
                return Err(INVALID_B64.into());
            }
            let mut v = [0u32; 3];
            for (i, &c) in quad.iter().enumerate() {
                v[i] = val(c).ok_or(INVALID_B64)?;
            }
            out.push(((v[0] << 2) | (v[1] >> 4)) as u8);
            if quad.len() == 3 {
                out.push((((v[1] & 0x0F) << 4) | (v[2] >> 2)) as u8);
            }
            continue;
        }
        let mut v = [0u32; 4];
        let mut n = 0usize;
        let mut padded = false;
        for (i, &c) in quad.iter().enumerate() {
            if c == b'=' {
                padded = true;
                continue;
            }
            // `"AB=C"`: once a quadruple has started padding, everything after it
            // must be padding too.
            if padded {
                return Err(INVALID_B64.into());
            }
            v[i] = val(c).ok_or(INVALID_B64)?;
            n += 1;
        }
        // `"===="` carries no data and `"A==="` carries too few bits to make even
        // one byte; both are errors, not empty output.
        if n < 2 {
            return Err(INVALID_B64.into());
        }
        out.push(((v[0] << 2) | (v[1] >> 4)) as u8);
        if n >= 3 {
            out.push((((v[1] & 0x0F) << 4) | (v[2] >> 2)) as u8);
        }
        if n == 4 {
            out.push((((v[2] & 0x03) << 6) | v[3]) as u8);
        }
    }
    Ok(out)
}

/// The bytes Emacs's base64 encoders see for STRING.
///
/// Emacs encodes a *unibyte* string one byte per character and refuses a
/// multibyte one outright (`error ("Multibyte character in data for base64
/// encoding")`), so the input's characters are the bytes — not their UTF-8
/// expansion, which is what `str::as_bytes` yields and which made
/// `(base64-encode-string "\303\251")` answer `"w4PCqQ=="` where Emacs answers
/// `"w6k="`.
fn b64_input_bytes(s: &str) -> Result<Vec<u8>, String> {
    s.chars()
        .map(|c| {
            u8::try_from(c as u32)
                .map_err(|_| "error: Multibyte character in data for base64 encoding".to_string())
        })
        .collect()
}
/// Render decoded bytes as a string with each byte a char 0–255 (unibyte-ish).
fn bytes_to_str(h: &mut ElispHost, bytes: &[u8]) -> Value {
    let text = bytes.iter().map(|&b| b as char).collect::<String>();
    h.new_string(text)
}
fn base64_encode_string(h: &mut ElispHost, a: &[Value]) -> R {
    let raw = b64_encode(&b64_input_bytes(&as_string(h, &a[0])?)?, B64_STD, true);
    let no_break = a.get(1).is_some_and(|v| !is_nil(v));
    Ok(h.new_string(if no_break { raw } else { b64_wrap(&raw) }))
}
/// `(base64-decode-string STRING &optional BASE64URL IGNORE-INVALID)`.
fn base64_decode_string(h: &mut ElispHost, a: &[Value]) -> R {
    let url = a.get(1).is_some_and(|v| !is_nil(v));
    let bytes = b64_decode(&as_string(h, &a[0])?, url)?;
    Ok(bytes_to_str(h, &bytes))
}
fn base64url_encode_string(h: &mut ElispHost, a: &[Value]) -> R {
    let no_pad = a.get(1).is_some_and(|v| !is_nil(v));
    Ok(h.new_string(b64_encode(
        &b64_input_bytes(&as_string(h, &a[0])?)?,
        B64_URL,
        !no_pad,
    )))
}
fn base64url_decode_string(h: &mut ElispHost, a: &[Value]) -> R {
    let bytes = b64_decode(&as_string(h, &a[0])?, true)?;
    Ok(bytes_to_str(h, &bytes))
}
/// `(url-hexify-string STRING)` — percent-encode all but `[A-Za-z0-9-._~]`.
fn url_hexify_string(h: &mut ElispHost, a: &[Value]) -> R {
    // Emacs's `url-hexify-string` is a `mapconcat` over its argument, so it takes
    // any *sequence* — `[1 2]` hexifies to "%01%02" and nil to "" — and a
    // non-sequence reports `sequencep`, not `stringp`.
    let src = match h.str_text(&a[0]).map(str::to_string) {
        Some(s) => s,
        None => {
            let v = &a[0];
            let items = h
                .seq_vec(v)
                .ok_or_else(|| h.signal_wrong_type("sequencep", v))?;
            let mut acc = String::new();
            for it in &items {
                match char::from_u32(as_char(h, it)?) {
                    Some(c) => acc.push(c),
                    None => return Err(h.signal_wrong_type("characterp", it)),
                }
            }
            acc
        }
    };
    let mut out = String::new();
    for b in src.as_bytes() {
        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
            out.push(*b as char);
        } else {
            out.push_str(&format!("%{b:02X}"));
        }
    }
    Ok(h.new_string(out))
}
/// `(url-unhex-string STRING)` — decode `%XX` escapes.
fn url_unhex_string(h: &mut ElispHost, a: &[Value]) -> R {
    let s = as_string(h, &a[0])?;
    // Character-wise, not byte-wise: only `%XX` names a byte; every other
    // character is copied through as itself. Walking the UTF-8 bytes expanded
    // each non-ASCII character into its encoding, so `(url-unhex-string "αβγ")`
    // — which contains no escape at all — came back six characters long.
    let chars: Vec<char> = s.chars().collect();
    let hex = |c: char| c.is_ascii_hexdigit();
    let mut out = String::with_capacity(s.len());
    let mut i = 0;
    while i < chars.len() {
        if chars[i] == '%' && i + 2 < chars.len() && hex(chars[i + 1]) && hex(chars[i + 2]) {
            let pair: String = chars[i + 1..i + 3].iter().collect();
            if let Ok(v) = u8::from_str_radix(&pair, 16) {
                // An escape names one *byte*, and it stays one byte: Emacs hands
                // the raw bytes back and leaves decoding to the caller, so
                // `(url-unhex-string "%CE%B1")` is two characters (206 177), not
                // the one character those bytes happen to spell in UTF-8.
                // Re-assembling them made it answer `(945)`, with length 1.
                out.push(v as char);
                i += 3;
                continue;
            }
        }
        out.push(chars[i]);
        i += 1;
    }
    Ok(h.new_string(out))
}
/// `(string-to-vector STRING)` — a vector of STRING's character codes.
fn string_to_vector(h: &mut ElispHost, a: &[Value]) -> R {
    // `(string-to-vector SEQ)` is `(vconcat SEQ)`: any sequence, so `nil` is the
    // empty vector rather than a `stringp` error.
    let items = h
        .seq_vec(&a[0])
        .ok_or_else(|| format!("wrong-type-argument: sequencep {}", h.print(&a[0], true)))?;
    Ok(h.alloc(Obj::Vector(items)))
}
/// `(logb X)` — the binary exponent of |X|: floor(log2(|X|)).
///
/// Faithful to Emacs 30 `Flogb` (floatfns.c): a finite nonzero argument yields
/// the integer `frexp` exponent minus one; every other case (zero, ±infinity,
/// NaN) falls through to C `logb`, which returns a *float* — `-inf` for zero,
/// `+inf` for either infinity, and NaN for NaN.
fn logb_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let n = as_number_p(h, &a[0], false)?;
    // An integer answer is exact in Emacs (`Flogb` takes the integer path for an
    // integer argument), and converting through `f64` first rounds: 2^61-1 rounds
    // UP to 2^61, so `(logb 2305843009213693951)` answered 61 where Emacs answers
    // 60. The exponent is the bit length of |N| minus one.
    if let crate::host::Num::Int(i) = &n {
        let bits = i.bits();
        if bits > 0 {
            return Ok(Value::Int(bits as i64 - 1));
        }
    }
    let f = n.to_f64();
    if f.is_finite() && f != 0.0 {
        return Ok(Value::Int(f.abs().log2().floor() as i64));
    }
    let val = if f.is_nan() {
        // A NaN passes through unchanged, sign and payload included — Emacs
        // prints `-0.0e+NaN` for `(logb -0.0e+NaN)`, and a freshly built
        // `f64::NAN` is a different NaN.
        f
    } else if f == 0.0 {
        f64::NEG_INFINITY
    } else {
        f64::INFINITY
    };
    Ok(Value::Float(val))
}
/// `(max-char &optional UNICODE)` — the largest character code. With non-nil
/// UNICODE the max Unicode scalar (`#x10FFFF`); otherwise the max Emacs char
/// code (`#x3FFFFF`), which spans the raw-byte / eight-bit range too.
fn max_char(_h: &mut ElispHost, a: &[Value]) -> R {
    let unicode = a.first().map(|v| !is_nil(v)).unwrap_or(false);
    Ok(Value::Int(if unicode { 0x10_FFFF } else { 0x3F_FFFF }))
}
/// `(byteorder)` — `?l` (108) on a little-endian host, `?B` (66) on big-endian.
fn byteorder(_h: &mut ElispHost, _a: &[Value]) -> R {
    Ok(Value::Int(if cfg!(target_endian = "little") {
        108
    } else {
        66
    }))
}
// ── character modifiers / descriptions (faithful C ports) ──
// Modifier bit values from src/lisp.h; base-character mask is CHARACTERBITS=22.
const CHAR_ALT: i64 = 0x0400000;
const CHAR_SUPER: i64 = 0x0800000;
const CHAR_HYPER: i64 = 0x1000000;
const CHAR_SHIFT: i64 = 0x2000000;
const CHAR_CTL: i64 = 0x4000000;
const CHAR_META: i64 = 0x8000000;
const CHAR_MODIFIER_MASK: i64 =
    CHAR_ALT | CHAR_SUPER | CHAR_HYPER | CHAR_SHIFT | CHAR_CTL | CHAR_META;
const MAX_CHAR: i64 = 0x3F_FFFF;
const MAX_5_BYTE_CHAR: i64 = 0x3F_FF7F;

/// `ASCII_CHAR_P(c)` (src/character.h): `0 <= c && c < 0x80`.
fn ascii_char_p(c: i64) -> bool {
    (0..0x80).contains(&c)
}
/// `CHECK_CHARACTER`: a character is a fixnum in `0..=MAX_CHAR` (`0x3FFFFF`).
fn check_character(h: &ElispHost, v: &Value) -> Result<i64, String> {
    let c = as_int(h, v)?;
    if (0..=MAX_CHAR).contains(&c) {
        Ok(c)
    } else {
        Err(format!("wrong-type-argument: characterp {c}"))
    }
}

/// `(char-resolve-modifiers CHAR)` — port of `char_resolve_modifier_mask`
/// (src/character.c). Fold the Shift and Control modifier bits of an ASCII base
/// character into the code; Meta and other modifiers are left in place. CHAR is
/// any integer (`CHECK_FIXNUM`), not just a valid character.
fn char_resolve_modifiers(h: &mut ElispHost, a: &[Value]) -> R {
    let mut c = as_int(h, &a[0])?;
    // A non-ASCII base character can't reflect modifier bits into the code.
    if !ascii_char_p(c & !CHAR_MODIFIER_MASK) {
        return Ok(Value::Int(c));
    }
    if c & CHAR_SHIFT != 0 {
        let base = c & 0o377;
        // Shift is valid only with [A-Za-z]; on control chars / SPC it's dropped.
        if (b'A' as i64..=b'Z' as i64).contains(&base) {
            c &= !CHAR_SHIFT;
        } else if (b'a' as i64..=b'z' as i64).contains(&base) {
            c = (c & !CHAR_SHIFT) - (b'a' as i64 - b'A' as i64);
        } else if (c & !CHAR_MODIFIER_MASK) <= 0x20 {
            c &= !CHAR_SHIFT;
        }
    }
    if c & CHAR_CTL != 0 {
        let base = c & 0o377;
        // Allow `\C- ` and `\C-?`; otherwise make ASCII control chars from
        // letters (both cases) and the non-letters within 0100..0137.
        if base == b' ' as i64 {
            c &= !0o177 & !CHAR_CTL;
        } else if base == b'?' as i64 {
            c = 0o177 | (c & !0o177 & !CHAR_CTL);
        } else if (0o101..=0o132).contains(&(c & 0o137)) || (0o100..=0o137).contains(&(c & 0o177)) {
            c &= 0o37 | (!0o177 & !CHAR_CTL);
        }
    }
    Ok(Value::Int(c))
}

/// `(text-char-description CHARACTER)` — port of `Ftext_char_description`
/// (src/keymap.c) + `push_text_char_description`. ASCII control chars become
/// `^X`, DEL becomes `^?`, everything else renders as itself. Modifier bits
/// (Meta etc.) fail the `characterp` check. Characters outside Unicode
/// (eight-bit / raw internal codes) can't be held in a UTF-8 string here, so
/// they yield the empty string.
fn text_char_description(h: &mut ElispHost, a: &[Value]) -> R {
    let c = check_character(h, &a[0])?;
    if ascii_char_p(c) {
        let s = if c < 0o40 {
            format!("^{}", (c as u8 + 64) as char)
        } else if c == 0o177 {
            "^?".to_string()
        } else {
            (c as u8 as char).to_string()
        };
        Ok(h.new_string(s))
    } else {
        Ok(h.new_string(
            char::from_u32(c as u32)
                .map(|c| c.to_string())
                .unwrap_or_default(),
        ))
    }
}

/// `(unibyte-char-to-multibyte BYTE)` — port of `Funibyte_char_to_multibyte`
/// (src/charset.c). ASCII bytes map to themselves; bytes `0x80..=0xFF` become
/// the eight-bit character `0x3FFF00 + byte`. BYTE above 255 is not unibyte.
fn unibyte_char_to_multibyte(h: &mut ElispHost, a: &[Value]) -> R {
    let c = check_character(h, &a[0])?;
    if c >= 256 {
        return Err(format!("error: Not a unibyte character: {c}"));
    }
    Ok(Value::Int(if c < 0x80 { c } else { c + 0x3F_FF00 }))
}

/// `(multibyte-char-to-unibyte CHAR)` — port of `Fmultibyte_char_to_unibyte`
/// (src/charset.c). Characters below 256 map to themselves, eight-bit chars
/// (above `MAX_5_BYTE_CHAR`) map to their raw byte, all others map to -1.
fn multibyte_char_to_unibyte(h: &mut ElispHost, a: &[Value]) -> R {
    let c = check_character(h, &a[0])?;
    let byte = if c < 256 {
        c
    } else if c > MAX_5_BYTE_CHAR {
        c - 0x3F_FF00
    } else {
        -1
    };
    Ok(Value::Int(byte))
}

/// Read a `decode-char` CODE-POINT argument: an integer, an integral float, or
/// a cons `(HIGH . LOW)` giving `HIGH * 0x10000 + LOW` (the obsolescent form).
/// This mirrors the `CONSP`/`FIXNUM`/`FLOATP` dispatch in `Fdecode_char`
/// (src/charset.c).
fn decode_char_code_point(h: &ElispHost, v: &Value) -> Result<i64, String> {
    if let Some(Obj::Cons(hi, lo)) = h.obj(v) {
        let hi = as_int(h, &hi.clone())?;
        let lo = as_int(h, &lo.clone())?;
        return Ok((hi << 16) | lo);
    }
    as_int(h, v)
}

/// `(decode-char CHARSET CODE-POINT)` — port of `Fdecode_char` (src/charset.c).
/// Decode CODE-POINT in CHARSET to a character, or nil if the code point is not
/// valid in CHARSET. CODE-POINT must lie in `0..=0xFFFFFFFF`; anything else
/// signals the `error` "Not an in-range integer, integral float, or cons of
/// integers".
///
/// Only charsets whose mapping is pure arithmetic — no external mule map tables
/// — are supported faithfully: `ascii`, `eight-bit`, `iso-8859-1`, and the
/// Unicode charsets `ucs`/`unicode` (full range) and `unicode-bmp` (BMP only).
/// Every other symbol takes the `CHECK_CHARSET_GET_CHARSET` failure path and
/// signals `wrong-type-argument charsetp SYM`, exactly as Emacs does for an
/// unknown charset (the mule-table national charsets like `japanese-jisx0208`
/// are not registered here, so they land on that path rather than being
/// approximated).
fn decode_char(h: &mut ElispHost, a: &[Value]) -> R {
    let name = h
        .sym_name(&a[0])
        .filter(|n| {
            matches!(
                n.as_str(),
                "ascii" | "eight-bit" | "iso-8859-1" | "ucs" | "unicode" | "unicode-bmp"
            )
        })
        .ok_or_else(|| format!("wrong-type-argument: charsetp {}", h.print(&a[0], true)))?;
    let code = decode_char_code_point(h, &a[1])?;
    if !(0..=0xFFFF_FFFF).contains(&code) {
        return Err(
            "error: Not an in-range integer, integral float, or cons of integers".to_string(),
        );
    }
    let ch = match name.as_str() {
        "ascii" => (0..=0x7F).contains(&code).then_some(code),
        "eight-bit" => (0x80..=0xFF).contains(&code).then_some(0x3F_FF00 + code),
        "iso-8859-1" => (0..=0xFF).contains(&code).then_some(code),
        "unicode-bmp" => (0..=0xFFFF).contains(&code).then_some(code),
        // "ucs" | "unicode"
        _ => (0..=0x10_FFFF).contains(&code).then_some(code),
    };
    Ok(ch.map(Value::Int).unwrap_or(Value::Undef))
}

/// `(emacs-pid)` — the process id of the running interpreter.
fn emacs_pid(_h: &mut ElispHost, _a: &[Value]) -> R {
    Ok(Value::Int(std::process::id() as i64))
}

/// `(load-average &optional USE-FLOATS)` — port of `Fload_average` (src/fns.c).
/// The 1/5/15-minute system load averages: each `load` (a float) when
/// USE-FLOATS is non-nil, else `trunc(100 * load)` as an integer.
fn load_average(h: &mut ElispHost, a: &[Value]) -> R {
    let use_floats = a.first().map(|v| !is_nil(v)).unwrap_or(false);
    let mut loads = [0f64; 3];
    let n = unsafe { libc::getloadavg(loads.as_mut_ptr(), 3) };
    if n < 0 {
        return Err("error: load-average not implemented for this operating system".to_string());
    }
    let items = loads[..n as usize]
        .iter()
        .map(|&l| {
            if use_floats {
                Value::Float(l)
            } else {
                Value::Int((100.0 * l) as i64)
            }
        })
        .collect();
    Ok(h.list_from(items))
}

/// `(bare-symbol-p OBJECT)` — non-nil if OBJECT is a symbol without position.
/// elisprs has no symbol-with-position type, so every symbol is bare — this is
/// exactly `symbolp` (nil and t count as symbols).
fn bare_symbol_p(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(nil_or(
        matches!(a[0], Value::Bool(true))
            || is_nil(&a[0])
            || matches!(h.obj(&a[0]), Some(Obj::Symbol(_))),
    ))
}
/// `(car-less-than-car A B)` — `(< (car A) (car B))`, the standard comparator
/// for sorting alists (Emacs `car-less-than-car`).
fn car_less_than_car(h: &mut ElispHost, a: &[Value]) -> R {
    let car_of = |h: &ElispHost, v: &Value| -> Result<Value, String> {
        match h.obj(v) {
            Some(Obj::Cons(x, _)) => Ok(x.clone()),
            _ if is_nil(v) => Ok(Value::Undef),
            _ => Err(format!("wrong-type-argument: listp {}", h.print(v, true))),
        }
    };
    let a0 = car_of(h, &a[0])?;
    let b0 = car_of(h, &a[1])?;
    Ok(nil_or(as_num(h, &a0)?.1 < as_num(h, &b0)?.1))
}
/// `(subr-name SUBR)` — the name of a primitive SUBR as a string. Signals
/// `wrong-type-argument` when SUBR is not a subr (e.g. a plain symbol).
fn subr_name(h: &mut ElispHost, a: &[Value]) -> R {
    match h.obj(&a[0]) {
        Some(Obj::Subr { name, .. }) => Ok(h.new_string(name.clone())),
        _ => Err(format!(
            "wrong-type-argument: subrp {}",
            h.print(&a[0], true)
        )),
    }
}
/// `(default-boundp SYMBOL)` — non-nil if SYMBOL has a default value, i.e. its
/// global value cell is bound (ignoring any buffer-local binding).
fn default_boundp(h: &mut ElispHost, a: &[Value]) -> R {
    check_symbol(h, &a[0])?;
    let bound = is_nil(&a[0]) || matches!(a[0], Value::Bool(true)) || h.default_boundp_raw(&a[0]);
    Ok(nil_or(bound))
}
/// `(default-toplevel-value SYMBOL)` — SYMBOL's default (toplevel) value, ignoring
/// any buffer-local binding; signals `void-variable` when the default is unbound.
fn default_toplevel_value(h: &mut ElispHost, a: &[Value]) -> R {
    h.raw_global_value(&a[0])
}
/// `(read STRING)` — read the first Lisp form from STRING.
/// `(read &optional STREAM)` (lread.c `Fread`). A string is read from its
/// start. A buffer is read from ITS point (current or not) up to its `ZV`, and
/// its point is left just past the object; a marker is read from its position
/// in its buffer, and the marker is advanced instead.
fn read_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let stream = a.first().cloned().unwrap_or(Value::Undef);
    let (bi, marker) = match h.obj(&stream) {
        Some(Obj::Buffer(idx)) => (*idx, None),
        Some(Obj::Marker(m)) => match m.borrow().buffer {
            Some(idx) => (idx, Some(m.clone())),
            None => return Err("error: Marker does not point anywhere".to_string()),
        },
        // lread.c `read_internal_start`: one object from the start of the
        // string; whatever follows it is never looked at.
        _ => {
            let s = as_string(h, &stream)?;
            return crate::reader::read_one(h, &s, 0).map(|(form, _)| form);
        }
    };
    let (start, text) = {
        let b = &h.buffers[bi];
        let start = marker.as_ref().map_or(b.point, |m| m.borrow().pos);
        let start = start.clamp(b.begv, b.zv);
        (
            start,
            b.text[start - 1..b.zv - 1].iter().collect::<String>(),
        )
    };
    // Running out of text consumes all of it: point (or the marker) is at
    // `ZV` when `end-of-file` is signalled.
    let r = crate::reader::read_one(h, &text, 0);
    let end = match &r {
        Ok((_, end)) => start + end,
        Err(e) if e == "end-of-file" => start + text.chars().count(),
        Err(_) => start,
    };
    let from_buffer = marker.is_none();
    match marker {
        Some(m) => m.borrow_mut().pos = end,
        None => h.buffers[bi].point = end,
    }
    match r {
        // lread.c `end_of_file_error`: a buffer source is the datum; a marker
        // source is not a buffer source and signals bare.
        Err(e) if e == "end-of-file" && from_buffer => {
            let sym = h.intern("end-of-file");
            let obj = h.list_from(vec![sym, stream]);
            h.set_pending_error(&e, obj);
            Err(e)
        }
        r => r.map(|(form, _)| form),
    }
}
/// `(read-from-minibuffer PROMPT &optional INITIAL-CONTENTS KEYMAP READ HIST
/// DEFAULT-VALUE INHERIT-INPUT-METHOD)` as Emacs runs it in batch (minibuf.c
/// `read_minibuf_noninteractive`): write PROMPT to stdout, read one line from
/// stdin up to `\n` or `\r` (not included), and return it. EOF with nothing
/// read signals `(end-of-file "Error reading from stdin")`. With READ non-nil
/// the line is parsed as one Lisp object (`string_to_object`). INITIAL-CONTENTS,
/// KEYMAP, HIST and INHERIT-INPUT-METHOD play no part without a minibuffer.
fn read_from_minibuffer(h: &mut ElispHost, a: &[Value]) -> R {
    use std::io::Read;
    let prompt = as_string(h, &a[0])?;
    h.write_stdout(&prompt);
    let mut line = Vec::new();
    let mut ended = false;
    let mut byte = [0u8; 1];
    while let Ok(1) = h.stdin.read(&mut byte) {
        if matches!(byte[0], b'\n' | b'\r') {
            ended = true;
            break;
        }
        line.push(byte[0]);
    }
    if line.is_empty() && !ended {
        let msg = h.new_string("Error reading from stdin");
        return Err(signal_with_data(h, "end-of-file", vec![msg]));
    }
    let text = String::from_utf8_lossy(&line).into_owned();
    if a.get(3).is_none_or(is_nil) {
        return Ok(h.new_string(text));
    }
    string_to_object(h, text, a.get(5))
}

/// minibuf.c `string_to_object`: read one object from TEXT (an empty TEXT
/// reads DEFAULT, or its car when it is a list); anything but whitespace after
/// the object signals `invalid-read-syntax`.
fn string_to_object(h: &mut ElispHost, text: String, default: Option<&Value>) -> R {
    let mut val = h.new_string(text);
    if h.str_text(&val).is_some_and(str::is_empty) {
        let default = default.cloned().unwrap_or(Value::Undef);
        let car = match h.obj(&default) {
            Some(Obj::Cons(car, _)) => car.clone(),
            _ => Value::Undef,
        };
        if h.str_text(&default).is_some() {
            val = default;
        } else if h.str_text(&car).is_some() {
            val = car;
        }
    }
    let read = read_from_string(h, std::slice::from_ref(&val))?;
    let Some(Obj::Cons(obj, end)) = h.obj(&read).cloned() else {
        unreachable!("read-from-string returns (OBJECT . END)")
    };
    let rest: String = as_string(h, &val)?
        .chars()
        .skip(usize::try_from(as_integer(h, &end)?).unwrap_or(0))
        .collect();
    if rest.chars().any(|c| !matches!(c, ' ' | '\t' | '\n')) {
        let msg = h.new_string("Trailing garbage following expression");
        return Err(signal_with_data(h, "invalid-read-syntax", vec![msg]));
    }
    Ok(obj)
}

/// `(read-string PROMPT &optional INITIAL-INPUT HISTORY DEFAULT-VALUE
/// INHERIT-INPUT-METHOD)`: `read-from-minibuffer`, except that an empty answer
/// returns DEFAULT-VALUE (its car when it is a list) when that is non-nil.
fn read_string(h: &mut ElispHost, a: &[Value]) -> R {
    let get = |i: usize| a.get(i).cloned().unwrap_or(Value::Undef);
    let default = get(3);
    let val = read_from_minibuffer(
        h,
        &[
            get(0),
            get(1),
            Value::Undef,
            Value::Undef,
            get(2),
            default.clone(),
            get(4),
        ],
    )?;
    if h.str_text(&val).is_some_and(str::is_empty) && !is_nil(&default) {
        return Ok(match h.obj(&default) {
            Some(Obj::Cons(car, _)) => car.clone(),
            _ => default,
        });
    }
    Ok(val)
}

/// Signal `(SYMBOL . DATA)`: the error string a subr returns plus the error
/// object `condition-case` binds (eval.c `xsignal`).
fn signal_with_data(h: &mut ElispHost, symbol: &str, data: Vec<Value>) -> String {
    let data = h.list_from(data);
    let msg = format!("{symbol}: {}", h.print(&data, true));
    let sym = h.intern(symbol);
    let obj = h.cons(sym, data);
    h.set_pending_error(&msg, obj);
    msg
}

/// `(read-from-string STRING &optional START END)` — read the first object from
/// STRING (from char index START), returning `(OBJECT . END-INDEX)`.
fn read_from_string(h: &mut ElispHost, a: &[Value]) -> R {
    let s = as_string(h, &a[0])?;
    let size = s.chars().count() as i64;
    // START/END follow Emacs `validate_subarray`: a negative index counts from
    // the end (`i + len`), nil defaults to 0 / len, and the checked range is
    // `0 <= from <= to <= len`; a violation is args-out-of-range whose DATA is
    // `(STRING RAW-START RAW-END)` built from the *original* (unadjusted) args.
    let adj = |v: Option<&Value>, default: i64| -> i64 {
        match v {
            Some(Value::Int(n)) => {
                if *n < 0 {
                    n + size
                } else {
                    *n
                }
            }
            _ => default,
        }
    };
    let from = adj(a.get(1), 0);
    let to = adj(a.get(2), size);
    if !(0 <= from && from <= to && to <= size) {
        let disp = |v: Option<&Value>| match v {
            None | Some(Value::Undef) | Some(Value::Bool(false)) => "nil".to_string(),
            Some(v) => h.print(v, true),
        };
        return Err(format!(
            "args-out-of-range: {} {} {}",
            h.print(&a[0], true),
            disp(a.get(1)),
            disp(a.get(2))
        ));
    }
    // Limit the reader to the first `to` characters. Char indices in the prefix
    // are identical to the original, so the returned END position stays valid.
    let limited: String = s.chars().take(to as usize).collect();
    let (form, end) = crate::reader::read_one(h, &limited, from as usize)?;
    Ok(h.cons(form, Value::Int(end as i64)))
}
/// fns.c `validate_subarray`, as `Fcompare_strings` calls it: resolve FROM/TO
/// against a sequence of `size` elements.
///
/// A nil bound takes its default (0 / `size`); a negative one counts from the
/// end; **anything else is `(wrong-type-argument integerp BOUND)`** — which is
/// the whole point of porting it, since elisprs previously defaulted a
/// non-integer bound silently and answered a comparison where Emacs signals.
/// A resolved range outside `0 <= from <= to <= size` is
/// `args_out_of_range_3`: `(args-out-of-range ARRAY FROM TO)`.
///
/// `Fcompare_strings` first clamps a too-large *positive* END down to `size`
/// "for backward compatibility", so only a negative or start-crossing bound can
/// reach the range error through it. The clamped value is what the error data
/// reports, exactly as in C.
fn validate_subarray(
    h: &ElispHost,
    array: &Value,
    from: &Value,
    to: Option<&Value>,
    size: usize,
) -> Result<(usize, usize), String> {
    let to = to.cloned().unwrap_or(Value::Undef);
    // The END clamp happens in Fcompare_strings, before validate_subarray.
    let to = match to {
        Value::Int(n) if n > size as i64 => Value::Int(size as i64),
        other => other,
    };
    let resolve = |v: &Value, default: i64| -> Result<i64, String> {
        match v {
            Value::Int(n) => Ok(if *n < 0 { n + size as i64 } else { *n }),
            _ if is_nil(v) => Ok(default),
            _ => Err(format!(
                "wrong-type-argument: integerp {}",
                h.print(v, true)
            )),
        }
    };
    let f = resolve(from, 0)?;
    let t = resolve(&to, size as i64)?;
    if !(0 <= f && f <= t && t <= size as i64) {
        return Err(format!(
            "args-out-of-range: {} {} {}",
            h.print(array, true),
            h.print(from, true),
            h.print(&to, true)
        ));
    }
    Ok((f as usize, t as usize))
}

/// `(compare-strings S1 START1 END1 S2 START2 END2 &optional IGNORE-CASE)` —
/// `t` if the substrings are equal, else a signed 1-based index of the first
/// mismatch (negative when S1 sorts before S2), per Emacs.
fn compare_strings(h: &mut ElispHost, a: &[Value]) -> R {
    let s1: Vec<char> = as_string(h, &a[0])?.chars().collect();
    let s2: Vec<char> = as_string(h, &a[3])?.chars().collect();
    let (start1, end1) = validate_subarray(h, &a[0], &a[1], a.get(2), s1.len())?;
    let (start2, end2) = validate_subarray(h, &a[3], &a[4], a.get(5), s2.len())?;
    let ignore_case = a.get(6).is_some_and(|v| !is_nil(v));
    let sub1 = &s1[start1..end1];
    let sub2 = &s2[start2..end2];
    let fold = |c: char| {
        if ignore_case {
            c.to_lowercase().next().unwrap_or(c)
        } else {
            c
        }
    };
    let n = sub1.len().min(sub2.len());
    for i in 0..n {
        let (x, y) = (fold(sub1[i]), fold(sub2[i]));
        if x != y {
            let idx = (i + 1) as i64;
            return Ok(Value::Int(if x < y { -idx } else { idx }));
        }
    }
    match sub1.len().cmp(&sub2.len()) {
        std::cmp::Ordering::Less => Ok(Value::Int(-((n + 1) as i64))),
        std::cmp::Ordering::Greater => Ok(Value::Int((n + 1) as i64)),
        std::cmp::Ordering::Equal => Ok(Value::Bool(true)),
    }
}

/// `(member-ignore-case ELT LIST)` — like `member`, but the comparison is
/// case-insensitive and ELT is compared only against the *string* elements of
/// LIST (non-strings are skipped, never match). Returns the tail of LIST that
/// begins with the first matching element, else nil. Mirrors GNU Emacs subr.el:
/// each candidate is tested via `(compare-strings ELT 0 nil CAND 0 nil t)` which
/// signals `wrong-type-argument stringp` if ELT is not a string and a string
/// candidate is reached; an all-non-string / empty LIST returns nil silently.
fn member_ignore_case(h: &mut ElispHost, a: &[Value]) -> R {
    let elt = a[0].clone();
    let mut cur = a[1].clone();
    loop {
        // Pull car/cdr out into owned values so the immutable arena borrow ends
        // before the mutable `compare_strings` call below.
        let (car, cdr) = match h.obj(&cur) {
            Some(Obj::Cons(car, cdr)) => (car.clone(), cdr.clone()),
            // Emacs walks LIST with `CHECK_LIST_END`, so running off a non-nil
            // tail is `(wrong-type-argument listp TAIL)` — reaching the end only
            // answers nil when the end is actually nil. `(member-ignore-case "a"
            // 1.5)` answered nil here where Emacs signals, and so did every
            // improper list whose match was not found before the tail.
            _ if is_nil(&cur) => return Ok(Value::Undef),
            _ => return Err(h.signal_wrong_type("listp", &cur)),
        };
        if h.is_string(&car) {
            let cmp = compare_strings(
                h,
                &[
                    elt.clone(),
                    Value::Int(0),
                    Value::Undef,
                    car,
                    Value::Int(0),
                    Value::Undef,
                    Value::Bool(true),
                ],
            )?;
            if matches!(cmp, Value::Bool(true)) {
                return Ok(cur);
            }
        }
        cur = cdr;
    }
}

// ── time ──
fn now_secs() -> f64 {
    use std::time::{SystemTime, UNIX_EPOCH};
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs_f64())
        .unwrap_or(0.0)
}

// ── random ──
thread_local! {
    static RNG_STATE: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// Seed the PRNG from the system clock (xorshift never starts from 0).
fn rng_seed() -> u64 {
    use std::time::{SystemTime, UNIX_EPOCH};
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_nanos() as u64)
        .unwrap_or(0x9e3779b97f4a7c15);
    nanos | 1
}
pub(crate) fn rng_next() -> u64 {
    RNG_STATE.with(|s| {
        let mut x = s.get();
        if x == 0 {
            x = rng_seed();
        }
        // xorshift64
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        s.set(x);
        x
    })
}
/// A random fixnum over the whole fixnum range, as `get_random_fixnum`'s
/// unbounded case: 62 random bits, sign-extended.
fn random_fixnum() -> i64 {
    ((rng_next() << 2) as i64) >> 2
}
/// Port of `Frandom` (fns.c). LIMIT t reseeds from the clock and a string
/// reseeds from its contents; either way, as for any other non-integer LIMIT,
/// the answer is a random fixnum, negative ones included. An integer LIMIT —
/// a bignum too — must be positive (`(args-out-of-range LIMIT)`) and bounds
/// the answer to [0, LIMIT).
fn random_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let limit = a.first().cloned().unwrap_or(Value::Undef);
    match &limit {
        Value::Bool(true) => RNG_STATE.with(|s| s.set(rng_seed())),
        Value::Int(n) => {
            if *n <= 0 {
                return Err(args_out_of_range_values(h, vec![limit.clone()]));
            }
            return Ok(Value::Int((rng_next() % *n as u64) as i64));
        }
        _ => {
            if let Some(Obj::Bignum(b)) = h.obj(&limit) {
                let b = b.clone();
                if b.sign() != num_bigint::Sign::Plus {
                    return Err(args_out_of_range_values(h, vec![limit.clone()]));
                }
                // 64 bits past LIMIT's width keep the modulo bias negligible.
                let words = b.bits() / 64 + 2;
                let mut r = BigInt::from(0u8);
                for _ in 0..words {
                    r = (r << 64) + BigInt::from(rng_next());
                }
                return Ok(h.make_integer(r % b));
            }
            if h.is_string(&limit) {
                let s = as_string(h, &limit)?;
                // `seed_random`: the same string always restarts the same sequence.
                let seed = s.bytes().fold(0xcbf2_9ce4_8422_2325u64, |acc, c| {
                    (acc ^ c as u64).wrapping_mul(0x0100_0000_01b3)
                });
                RNG_STATE.with(|st| st.set(seed | 1));
            }
        }
    }
    Ok(Value::Int(random_fixnum()))
}

/// Convert an elisp TIME value to epoch seconds (float). Accepts nil (= now), an
/// integer/float of seconds, a `(TICKS . HZ)` pair, or a `(HIGH LOW [USEC ...])`
/// legacy list.
fn time_arg_secs(h: &ElispHost, v: Option<&Value>) -> Result<f64, String> {
    crate::timefns::float_seconds(h, v)
}

/// TIME as whole seconds (floored) and the nanoseconds past them (truncated),
/// both exact — `format-time-string`'s `%s` and `%N` read these, not a double.
fn time_arg_split(h: &ElispHost, v: Option<&Value>) -> Result<(i64, i64), String> {
    use num_integer::Integer;
    let t = crate::timefns::decode(h, v, false)?;
    let (secs, frac) = t.ticks.div_mod_floor(&t.hz);
    let secs = num_traits::ToPrimitive::to_i64(&secs).ok_or_else(crate::timefns::overflow)?;
    let nanos = (frac * BigInt::from(1_000_000_000)).div_floor(&t.hz);
    Ok((secs, num_traits::ToPrimitive::to_i64(&nanos).unwrap_or(0)))
}

/// A resolved ZONE argument — timefns.c `tzlookup`.
enum TimeZone {
    /// nil and `wall`: the process's own zone.
    Local,
    /// `t`, and any offset or TZ string libc cannot use.
    Utc,
    /// Seconds east of UTC and the abbreviation `%Z` prints: an integer ZONE
    /// (abbreviated `+HH[MM[SS]]`) or an `(OFFSET ABBR)` list.
    Fixed(i64, String),
    /// A TZ string handed to libc: `"America/New_York"`, `"EST5EDT"`, `"JST-9"`.
    Named(String),
}

/// POSIX TZ strings carry at most 167:59:59 of offset; Emacs falls back to UTC
/// beyond it (`(format-time-string "%Z" 0 604800)` is "UTC").
const MAX_ZONE_OFFSET: i64 = 7 * 24 * 3600;

/// timefns.c `tzlookup`.
///
/// The accepted spellings are exactly: `nil` and the symbol `wall` (local time),
/// `t` (UTC), an integer offset in seconds, a TZ string, and an `(OFFSET ABBR)`
/// list whose OFFSET is an integer. Everything else — any *other* symbol, a
/// float, a vector, a list that does not start with an integer and have a second
/// element — is `(error "Invalid time zone specification" ZONE)`. An ABBR that
/// is not a string is `(wrong-type-argument stringp ABBR)`, and a third element
/// is ignored. Measured on GNU Emacs 31.1:
///
/// ```text
/// (format-time-string "%Z" 0 3600)        => "+01"
/// (format-time-string "%Z" 0 3601)        => "+010001"
/// (format-time-string "%Z" 0 '(3600 "X")) => "X"
/// (format-time-string "%Z" 0 '(1 2))      => (wrong-type-argument stringp 2)
/// (format-time-string "%Z" 0 'utc)        => error, `utc' is not a spelling
/// ```
fn time_zone_arg(h: &mut ElispHost, zone: Option<&Value>) -> Result<TimeZone, String> {
    let Some(z) = zone else {
        return Ok(TimeZone::Local);
    };
    let invalid = |h: &mut ElispHost| {
        let z = z.clone();
        Err(h.signal_error_with("Invalid time zone specification", &z))
    };
    match z {
        Value::Undef | Value::Bool(false) => return Ok(TimeZone::Local),
        Value::Bool(true) => return Ok(TimeZone::Utc),
        Value::Int(off) => return Ok(fixed_time_zone(*off, None)),
        _ => {}
    }
    if h.is_string(z) {
        let tz = as_string(h, z)?;
        return Ok(TimeZone::Named(tz));
    }
    match h.obj(z) {
        Some(Obj::Symbol(s)) if s.name == "wall" => Ok(TimeZone::Local),
        Some(Obj::Cons(car, cdr)) => {
            let (car, cdr) = (car.clone(), cdr.clone());
            let name = match h.obj(&cdr) {
                Some(Obj::Cons(name, _)) => name.clone(),
                _ => return invalid(h),
            };
            let Value::Int(off) = car else {
                return invalid(h);
            };
            if !h.is_string(&name) {
                return Err(h.signal_wrong_type("stringp", &name));
            }
            let abbr = as_string(h, &name)?;
            Ok(fixed_time_zone(off, Some(abbr)))
        }
        _ => invalid(h),
    }
}

/// A fixed-offset zone. An integer ZONE is named by its offset, `+HH` with
/// minutes and seconds appended only when non-zero; an offset of 0 is plain
/// UTC. An `(OFFSET ABBR)` zone is named ABBR.
fn fixed_time_zone(off: i64, abbr: Option<String>) -> TimeZone {
    if off.abs() >= MAX_ZONE_OFFSET {
        return TimeZone::Utc;
    }
    if let Some(abbr) = abbr {
        return TimeZone::Fixed(off, abbr);
    }
    if off == 0 {
        return TimeZone::Utc;
    }
    let a = off.abs();
    let (hh, mm, ss) = (a / 3600, (a % 3600) / 60, a % 60);
    let sign = if off < 0 { '-' } else { '+' };
    let name = match (mm, ss) {
        (0, 0) => format!("{sign}{hh:02}"),
        (_, 0) => format!("{sign}{hh:02}{mm:02}"),
        _ => format!("{sign}{hh:02}{mm:02}{ss:02}"),
    };
    TimeZone::Fixed(off, name)
}

/// Serializes every use of libc's `TZ` state: a named zone swaps the variable in,
/// and the local zone reads it, so a `localtime_r` on another thread must not run
/// inside the swap.
static TZ_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

/// libc's `TZ` is process state, so a named zone is evaluated with the variable
/// swapped in and put back — the same dance gnulib's `localtime_rz` performs on
/// platforms without a native one.
fn with_tz_env<T>(tz: &str, f: impl FnOnce() -> T) -> T {
    extern "C" {
        fn tzset();
    }
    let _guard = TZ_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    let saved = std::env::var_os("TZ");
    std::env::set_var("TZ", tz);
    unsafe { tzset() };
    let out = f();
    match saved {
        Some(v) => std::env::set_var("TZ", v),
        None => std::env::remove_var("TZ"),
    }
    unsafe { tzset() };
    out
}

/// A `struct tm` and the storage its `tm_zone` points into, so the abbreviation
/// stays valid for as long as the pair does.
struct DecodedTime {
    tm: libc::tm,
    _zone_name: Option<std::ffi::CString>,
}

/// Days since 1970-01-01 of the proleptic Gregorian date Y-M-D (M 1..=12).
fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {
    let y = if m <= 2 { y - 1 } else { y };
    let era = y.div_euclid(400);
    let yoe = y.rem_euclid(400);
    let mp = (m + 9) % 12;
    let doy = (153 * mp + 2) / 5 + d - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    era * 146_097 + doe - 719_468
}

/// The proleptic Gregorian `(year, month 1..=12, day)` of day number Z
/// (days since 1970-01-01).
fn civil_from_days(z: i64) -> (i64, i64, i64) {
    let z = z + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z.rem_euclid(146_097);
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = yoe + era * 400 + i64::from(m <= 2);
    (y, m, d)
}

/// Break UTC-relative epoch seconds into calendar fields without libc, so the
/// range is the whole of `tm_year`'s `int` rather than the platform's
/// `gmtime_r` window. `None` when the year does not fit `tm_year`
/// (`time_overflow`).
fn civil_tm(secs: i64) -> Option<libc::tm> {
    let days = secs.div_euclid(86_400);
    let rem = secs.rem_euclid(86_400);
    let (y, m, d) = civil_from_days(days);
    let mut tm: libc::tm = unsafe { std::mem::zeroed() };
    tm.tm_year = libc::c_int::try_from(y - 1900).ok()?;
    tm.tm_mon = (m - 1) as libc::c_int;
    tm.tm_mday = d as libc::c_int;
    tm.tm_hour = (rem / 3600) as libc::c_int;
    tm.tm_min = (rem % 3600 / 60) as libc::c_int;
    tm.tm_sec = (rem % 60) as libc::c_int;
    tm.tm_wday = (days + 4).rem_euclid(7) as libc::c_int;
    tm.tm_yday = (days - days_from_civil(y, 1, 1)) as libc::c_int;
    Some(tm)
}

/// Epoch seconds of a broken-down `tm` read as UTC, normalising out-of-range
/// fields the way `timegm` does (month 13 is January of the next year).
fn civil_secs(tm: &libc::tm) -> i64 {
    let months = i64::from(tm.tm_year) * 12 + i64::from(tm.tm_mon);
    let year = 1900 + months.div_euclid(12);
    let mon = months.rem_euclid(12) + 1;
    let days = days_from_civil(year, mon, 1) + i64::from(tm.tm_mday) - 1;
    days * 86_400 + i64::from(tm.tm_hour) * 3600 + i64::from(tm.tm_min) * 60 + i64::from(tm.tm_sec)
}

// `tm_gmtoff` is `c_long`; `i64::from` is needed on 32-bit targets.
#[allow(clippy::useless_conversion)]
/// `mktime` in the zone libc currently has set. `mktime` reports failure as -1,
/// which it also returns for dates its platform window rejects (macOS refuses
/// everything before 1900); those are resolved by inverting `localtime_r`, which
/// has the zone's earlier rules (local mean time) — the answer gnulib's
/// `mktime_z` gives.
fn zone_mktime(tm: &mut libc::tm) -> i64 {
    let probe = *tm;
    let r = unsafe { libc::mktime(tm) } as i64;
    if r != -1 {
        return r;
    }
    let wall = civil_secs(&probe);
    let mut guess = wall;
    for _ in 0..4 {
        let mut out: libc::tm = unsafe { std::mem::zeroed() };
        let t = guess as libc::time_t;
        if unsafe { libc::localtime_r(&t, &mut out) }.is_null() {
            break;
        }
        let next = wall - i64::from(out.tm_gmtoff);
        if next == guess {
            break;
        }
        guess = next;
    }
    guess
}

/// Decompose epoch seconds into a `struct tm` for ZONE; `time_overflow` when
/// the result's year does not fit.
fn time_decompose(secs: i64, zone: &TimeZone) -> Result<DecodedTime, String> {
    let t = secs as libc::time_t;
    let mut tm: libc::tm = unsafe { std::mem::zeroed() };
    let mut name: Option<std::ffi::CString> = None;
    match zone {
        TimeZone::Local => {
            let _guard = TZ_LOCK.lock().unwrap_or_else(|e| e.into_inner());
            if unsafe { libc::localtime_r(&t, &mut tm) }.is_null() {
                return Err(crate::timefns::overflow());
            }
        }
        TimeZone::Utc => {
            tm = civil_tm(secs).ok_or_else(crate::timefns::overflow)?;
            // Emacs reaches UTC by setting `TZ=UTC0`, so `%Z` there is "UTC" on
            // every platform (measured: `emacs --batch --eval
            // '(format-time-string "%Z" 0 t)'`), whatever libc's `gmtime_r`
            // would call it.
            name = Some(std::ffi::CString::new("UTC").expect("no NUL"));
        }
        TimeZone::Fixed(off, abbr) => {
            let shifted = secs
                .checked_add(*off)
                .ok_or_else(crate::timefns::overflow)?;
            tm = civil_tm(shifted).ok_or_else(crate::timefns::overflow)?;
            tm.tm_gmtoff = *off as libc::c_long;
            name = Some(std::ffi::CString::new(abbr.replace('\0', "")).expect("NUL removed"));
        }
        TimeZone::Named(tz) => {
            let ok = with_tz_env(tz, || {
                if unsafe { libc::localtime_r(&t, &mut tm) }.is_null() {
                    return false;
                }
                if !tm.tm_zone.is_null() {
                    let s = unsafe { std::ffi::CStr::from_ptr(tm.tm_zone) };
                    name = Some(s.to_owned());
                }
                true
            });
            if !ok {
                return Err(crate::timefns::overflow());
            }
        }
    }
    if let Some(n) = &name {
        tm.tm_zone = n.as_ptr() as *mut libc::c_char;
    }
    Ok(DecodedTime {
        tm,
        _zone_name: name,
    })
}

/// `format_time_string`: FMT over the broken-down TM, the way `nstrftime` does.
fn fmt_time_string(
    h: &mut ElispHost,
    fmt: &str,
    tm: &libc::tm,
    secs: i64,
    nanos: i64,
) -> Result<Value, String> {
    let bytes = crate::strftime::format(fmt.as_bytes(), tm, secs, nanos)
        .map_err(|_| crate::timefns::overflow())?;
    Ok(h.new_string(String::from_utf8_lossy(&bytes).into_owned()))
}

fn float_time(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(Value::Float(time_arg_secs(h, a.first())?))
}

/// `(sleep-for SECONDS &optional MILLISECONDS)` — dispnew.c `Fsleep_for`:
/// SECONDS is any number (`extract_float`), MILLISECONDS a fixnum added to it;
/// a duration that is not positive returns at once. Batch Emacs has no
/// subprocess output to wake it early, so this is a plain wait.
fn sleep_for(h: &mut ElispHost, a: &[Value]) -> R {
    let mut duration = as_number_p(h, &a[0], false)?.to_f64();
    if let Some(ms) = a.get(1).filter(|v| !is_nil(v)) {
        duration += as_fixnum_named(h, ms, "fixnump")? as f64 / 1000.0;
    }
    if duration > 0.0 {
        std::thread::sleep(std::time::Duration::from_secs_f64(duration));
    }
    Ok(Value::Undef)
}

fn current_time(_h: &mut ElispHost, _a: &[Value]) -> R {
    let secs = now_secs();
    let isec = secs.floor() as i64;
    let usec = ((secs - secs.floor()) * 1.0e6) as i64;
    Ok(_h.list_from(vec![
        Value::Int(isec >> 16),
        Value::Int(isec & 0xffff),
        Value::Int(usec),
        Value::Int(0),
    ]))
}

// `emacs-build-time' (lisp/version.el) is `(current-time)' evaluated while the
// binary is being DUMPED, so in a real Emacs it is a constant of the build:
//
//   $ for i in 1 2 3; do emacs -Q --batch --eval '(prin1 emacs-build-time)'; done
//   (27285 4897 897505 0)(27285 4897 897505 0)(27285 4897 897505 0)
//
// elisprs has no dump step, and evaluating `(current-time)' when the prelude
// runs made the value change on every invocation. The fixed point that
// corresponds to "when this build was made" here is the executable's mtime,
// which is what this returns, in `current-time' list form.
//
// It is also what makes the cache's shared post-prelude base reproducible: the
// base is one image for every entry in the shard, so a value that differs per
// process cannot live in it. A `(current-time)' there additionally meant a warm
// run replayed an older timestamp than a cold run computed — a cold/warm
// disagreement on the side Emacs does not have.
fn build_time(h: &mut ElispHost, _a: &[Value]) -> R {
    use std::os::unix::fs::MetadataExt;
    let (isec, nsec) = std::env::current_exe()
        .ok()
        .and_then(|p| std::fs::metadata(p).ok())
        .map(|m| (m.mtime(), m.mtime_nsec()))
        .unwrap_or((0, 0));
    Ok(h.list_from(vec![
        Value::Int(isec >> 16),
        Value::Int(isec & 0xffff),
        Value::Int(nsec / 1000),
        Value::Int(0),
    ]))
}

fn format_time_string(h: &mut ElispHost, a: &[Value]) -> R {
    let fmt = as_string(h, &a[0])?;
    let (secs, nanos) = time_arg_split(h, a.get(1))?;
    let zone = time_zone_arg(h, a.get(2))?;
    let decoded = time_decompose(secs, &zone)?;
    fmt_time_string(h, &fmt, &decoded.tm, secs, nanos)
}

fn current_time_string(h: &mut ElispHost, a: &[Value]) -> R {
    let (secs, nanos) = time_arg_split(h, a.first())?;
    let zone = time_zone_arg(h, a.get(1))?;
    let decoded = time_decompose(secs, &zone)?;
    fmt_time_string(h, "%a %b %e %H:%M:%S %Y", &decoded.tm, secs, nanos)
}

// `tm_gmtoff` is `c_long`; `i64::from` is needed on 32-bit but a no-op here.
#[allow(clippy::useless_conversion)]
fn decode_time(h: &mut ElispHost, a: &[Value]) -> R {
    // timefns.c `Fdecode_time`: FORM t keeps TIME's resolution in the seconds
    // element, `(TICKS . HZ)`; any other FORM decodes whole seconds only.
    let exact = if matches!(a.get(2), Some(Value::Bool(true))) {
        Some(crate::timefns::decode(h, a.first(), false)?)
    } else {
        None
    };
    let secs = match &exact {
        Some(t) => crate::timefns::floor_seconds(t)?,
        None => crate::timefns::seconds_argument(h, a.first())?,
    };
    let zone = time_zone_arg(h, a.get(1))?;
    let decoded = time_decompose(secs, &zone)?;
    let tm = decoded.tm;
    let dst = match tm.tm_isdst {
        0 => Value::Undef,
        n if n > 0 => Value::Bool(true),
        _ => Value::Int(-1),
    };
    let sec = match exact {
        Some(t) if t.hz != BigInt::from(1) => {
            use num_integer::Integer;
            let ticks = t.ticks.mod_floor(&t.hz) + &t.hz * BigInt::from(tm.tm_sec);
            let ticks = h.make_integer(ticks);
            let hz = h.make_integer(t.hz);
            h.cons(ticks, hz)
        }
        _ => Value::Int(tm.tm_sec as i64),
    };
    Ok(h.list_from(vec![
        sec,
        Value::Int(tm.tm_min as i64),
        Value::Int(tm.tm_hour as i64),
        Value::Int(tm.tm_mday as i64),
        Value::Int(tm.tm_mon as i64 + 1),
        Value::Int(tm.tm_year as i64 + 1900),
        Value::Int(tm.tm_wday as i64),
        dst,
        Value::Int(i64::from(tm.tm_gmtoff)),
    ]))
}

/// timefns.c `Fencode_time`. The seconds element is any time value, so a
/// sub-second one comes back as `(TICKS . HZ)` at its own resolution; whole
/// seconds come back as `(HI LO)`.
fn encode_time(h: &mut ElispHost, a: &[Value]) -> R {
    let mut isdst: libc::c_int = -1;
    let (fields, zone): (Vec<Value>, Value) = if a.len() == 1 {
        let mut fields = Vec::with_capacity(6);
        let mut tail = a[0].clone();
        for _ in 0..6 {
            let Some(Obj::Cons(car, cdr)) = h.obj(&tail) else {
                return Err(h.signal_wrong_type("consp", &tail));
            };
            fields.push(car.clone());
            tail = cdr.clone();
        }
        let mut zone = Value::Undef;
        if !is_nil(&tail) {
            let Some(Obj::Cons(_, rest)) = h.obj(&tail) else {
                return Err(h.signal_wrong_type("consp", &tail));
            };
            let rest = rest.clone();
            let Some(Obj::Cons(dstflag, rest2)) = h.obj(&rest) else {
                return Err(h.signal_wrong_type("consp", &rest));
            };
            let (dstflag, rest2) = (dstflag.clone(), rest2.clone());
            let Some(Obj::Cons(z, _)) = h.obj(&rest2) else {
                return Err(h.signal_wrong_type("consp", &rest2));
            };
            zone = z.clone();
            let is_symbol = is_nil(&dstflag)
                || matches!(dstflag, Value::Bool(true))
                || h.sym_name(&dstflag).is_some();
            let zone_fixnum_or_cons =
                matches!(zone, Value::Int(_)) || matches!(h.obj(&zone), Some(Obj::Cons(..)));
            if is_symbol && !zone_fixnum_or_cons {
                isdst = libc::c_int::from(!is_nil(&dstflag));
            }
        }
        (fields, zone)
    } else if a.len() < 6 {
        let f = h.intern("encode-time");
        let n = h.list_from(vec![f, Value::Int(a.len() as i64)]);
        let sym = h.intern("wrong-number-of-arguments");
        let obj = h.cons(sym, n);
        let msg = format!("wrong-number-of-arguments: encode-time {}", a.len());
        h.set_pending_error(&msg, obj);
        return Err(msg);
    } else {
        let zone = if a.len() > 6 {
            a[a.len() - 1].clone()
        } else {
            Value::Undef
        };
        (a[..6].to_vec(), zone)
    };
    let t = crate::timefns::decode(h, Some(&fields[0]), false)?;
    let (sec, subsec) = {
        use num_integer::Integer;
        t.ticks.div_mod_floor(&t.hz)
    };
    // `check_tm_member`: each field a fixnum whose offset value fits an int.
    let member = |h: &mut ElispHost, v: &Value, offset: i64| -> Result<libc::c_int, String> {
        let Value::Int(n) = v else {
            return Err(h.signal_wrong_type("fixnump", v));
        };
        libc::c_int::try_from(n - offset).map_err(|_| crate::timefns::overflow())
    };
    let sec_v = h.make_integer(sec);
    let mut tm: libc::tm = unsafe { std::mem::zeroed() };
    tm.tm_sec = member(h, &sec_v, 0)?;
    tm.tm_min = member(h, &fields[1], 0)?;
    tm.tm_hour = member(h, &fields[2], 0)?;
    tm.tm_mday = member(h, &fields[3], 0)?;
    tm.tm_mon = member(h, &fields[4], 1)?;
    tm.tm_year = member(h, &fields[5], 1900)?;
    tm.tm_isdst = isdst;
    let tz = time_zone_arg(h, Some(&zone))?;
    // gnulib `mktime_z` hands the normalised broken-down time back through
    // `localtime_rz`, which fails (`EOVERFLOW`) when the carry out of the month,
    // day, hour, minute or second fields leaves `tm_year` outside an `int`.
    if civil_tm(civil_secs(&tm)).is_none() {
        return Err(crate::timefns::overflow());
    }
    let value: i64 = match &tz {
        TimeZone::Fixed(off, _) => civil_secs(&tm) - *off,
        TimeZone::Local => {
            let _guard = TZ_LOCK.lock().unwrap_or_else(|e| e.into_inner());
            zone_mktime(&mut tm)
        }
        TimeZone::Utc => civil_secs(&tm),
        TimeZone::Named(name) => with_tz_env(name, || zone_mktime(&mut tm)),
    };
    if t.hz == BigInt::from(1) {
        return Ok(h.list_from(vec![Value::Int(value >> 16), Value::Int(value & 0xffff)]));
    }
    let ticks = BigInt::from(value) * &t.hz + subsec;
    let ticks = h.make_integer(ticks);
    let hz = h.make_integer(t.hz);
    Ok(h.cons(ticks, hz))
}

// ── environment / working directory ──
/// The string entries of the environment list ENV. `getenv_internal_1` walks
/// every cons and skips a non-string car; `make_environment_block` stops at
/// the first one (STOP_AT_NON_STRING).
fn env_entries(h: &ElispHost, env: &Value, stop_at_non_string: bool) -> Vec<String> {
    let mut out = Vec::new();
    let mut cur = env.clone();
    while let Some(Obj::Cons(car, cdr)) = h.obj(&cur) {
        match h.str_text(car) {
            Some(s) => out.push(s.to_string()),
            None if stop_at_non_string => break,
            None => {}
        }
        cur = cdr.clone();
    }
    out
}

/// callproc.c `getenv_internal_1`: the first entry of ENV naming VAR. `Some(Some
/// value)` for `VAR=value`, `Some(None)` for a lone `VAR` (the variable is
/// removed), `None` when ENV does not mention VAR.
fn env_lookup(entries: &[String], var: &str) -> Option<Option<String>> {
    entries.iter().find_map(|entry| {
        let rest = entry.strip_prefix(var)?;
        match rest.strip_prefix('=') {
            Some(value) => Some(Some(value.to_string())),
            None if rest.is_empty() => Some(None),
            None => None,
        }
    })
}

/// The value of the global variable NAME, nil when it is void.
fn symbol_value_or_nil(h: &mut ElispHost, name: &str) -> Value {
    let sym = h.intern(name);
    h.get_value(&sym).unwrap_or(Value::Undef)
}

/// `(getenv-internal VARIABLE &optional ENV)` — callproc.c. Searches
/// `process-environment`, or the list ENV, for VARIABLE. With a list ENV, a
/// lone `VARIABLE` entry answers t; otherwise it means unset. `DISPLAY` falls
/// back to `initial-environment` (batch has no frame `display` parameter).
fn getenv_internal(h: &mut ElispHost, a: &[Value]) -> R {
    let Some(var) = h.str_text(&a[0]).map(str::to_string) else {
        return Err(format!(
            "wrong-type-argument: stringp {}",
            h.print(&a[0], true)
        ));
    };
    let env = a.get(1).cloned().unwrap_or(Value::Undef);
    if matches!(h.obj(&env), Some(Obj::Cons(..))) {
        let entries = env_entries(h, &env, false);
        return Ok(match env_lookup(&entries, &var) {
            Some(Some(value)) => h.new_string(value),
            Some(None) => Value::Bool(true),
            None => Value::Undef,
        });
    }
    let process_env = symbol_value_or_nil(h, "process-environment");
    let mut found = env_lookup(&env_entries(h, &process_env, false), &var);
    if found.is_none() && var == "DISPLAY" {
        let initial = symbol_value_or_nil(h, "initial-environment");
        found = env_lookup(&env_entries(h, &initial, false), &var);
    }
    Ok(match found {
        Some(Some(value)) => h.new_string(value),
        _ => Value::Undef,
    })
}

/// callproc.c `egetenv`: VAR's value in `process-environment` (a lone `VAR`
/// entry, like no entry, is unset). What the C reads `HOME` and friends with.
pub(crate) fn egetenv(h: &mut ElispHost, var: &str) -> Option<String> {
    let process_env = symbol_value_or_nil(h, "process-environment");
    env_lookup(&env_entries(h, &process_env, false), var).flatten()
}

/// `(set-time-zone-rule TZ)` — timefns.c: `tzlookup (NILP (tz) ? Qwall : tz,
/// true)`, which validates TZ like any ZONE argument and then sets the
/// process's `TZ` to the rule string it builds (`wall` unsets it, `t` and 0
/// are `UTC0`, an offset is `<+HH>-H:MM:SS`, `(OFFSET ABBR)` is
/// `<ABBR>-H:MM:SS`). `process-environment` is not touched.
fn set_time_zone_rule(h: &mut ElispHost, a: &[Value]) -> R {
    let tz = a[0].clone();
    if !is_nil(&tz) {
        time_zone_arg(h, Some(&tz))?;
    }
    let offset_rule = |off: i64, abbr: Option<String>| {
        let abszone = off.abs();
        let (hour, rem) = (abszone / 3600, abszone % 3600);
        let (min, sec) = (rem / 60, rem % 60);
        let sign = if off < 0 { "" } else { "-" };
        let name = abbr.unwrap_or_else(|| {
            let (mut prec, mut numzone) = (2, hour);
            if rem != 0 {
                prec += 2;
                numzone = 100 * numzone + min;
                if sec != 0 {
                    prec += 2;
                    numzone = 100 * numzone + sec;
                }
            }
            let numzone = if off < 0 { -numzone } else { numzone };
            format!("{numzone:+0width$}", width = prec + 1)
        });
        format!("<{name}>{sign}{hour}:{min:02}:{sec:02}")
    };
    let rule: Option<String> = match &tz {
        Value::Undef | Value::Bool(false) => None,
        Value::Bool(true) | Value::Int(0) => Some("UTC0".to_string()),
        Value::Int(off) => Some(offset_rule(*off, None)),
        _ if h.is_string(&tz) => Some(as_string(h, &tz)?),
        _ => match h.obj(&tz) {
            Some(Obj::Cons(Value::Int(off), rest)) => {
                let (off, rest) = (*off, rest.clone());
                let abbr = match h.obj(&rest) {
                    Some(Obj::Cons(abbr, _)) => abbr.clone(),
                    _ => Value::Undef,
                };
                Some(offset_rule(off, Some(as_string(h, &abbr)?)))
            }
            // `wall`.
            _ => None,
        },
    };
    extern "C" {
        fn tzset();
    }
    let _guard = TZ_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    match rule {
        Some(rule) => std::env::set_var("TZ", rule),
        None => std::env::remove_var("TZ"),
    }
    unsafe { tzset() };
    Ok(Value::Undef)
}

/// The environment a subprocess starts with — callproc.c
/// `make_environment_block`. `PWD`, when `process-environment` sets it, is
/// the child's working directory without its trailing slashes; `DISPLAY`, when
/// `process-environment` does not mention it, comes from
/// `initial-environment`; then every entry of `process-environment`, the first
/// one for a name winning and a lone `NAME` removing that variable.
fn child_environment(h: &mut ElispHost, current_dir: &str) -> Vec<(String, String)> {
    let process_env = symbol_value_or_nil(h, "process-environment");
    let entries = env_entries(h, &process_env, true);
    let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
    let mut out = Vec::new();
    if let Some(Some(_)) = env_lookup(&env_entries(h, &process_env, false), "PWD") {
        let mut pwd = current_dir.to_string();
        while pwd.len() > 2 && pwd.ends_with('/') {
            pwd.pop();
        }
        seen.insert("PWD".to_string());
        out.push(("PWD".to_string(), pwd));
    }
    let mentions_display = entries
        .iter()
        .any(|e| e == "DISPLAY" || e.starts_with("DISPLAY="));
    if !mentions_display {
        let initial = symbol_value_or_nil(h, "initial-environment");
        if let Some(Some(display)) = env_lookup(&env_entries(h, &initial, false), "DISPLAY") {
            seen.insert("DISPLAY".to_string());
            out.push(("DISPLAY".to_string(), display));
        }
    }
    for entry in entries {
        let (name, value) = match entry.split_once('=') {
            Some((n, v)) => (n.to_string(), Some(v.to_string())),
            None => (entry.clone(), None),
        };
        if seen.insert(name.clone()) {
            if let Some(value) = value {
                out.push((name, value));
            }
        }
    }
    out
}

/// callproc.c `get_current_directory`: `default-directory` (or "~" when it
/// is not a string), expanded and without its trailing slash, must name an
/// accessible directory; otherwise `(file-missing "Setting current directory"
/// ERRSTRING DEFAULT-DIRECTORY)` naming the unexpanded value.
fn subprocess_directory(h: &mut ElispHost) -> Result<String, String> {
    let curdir = symbol_value_or_nil(h, "default-directory");
    let dir = if h.is_string(&curdir) {
        curdir.clone()
    } else {
        h.new_string("~")
    };
    let expanded = crate::fileio::expand_file_name(h, &[dir])?;
    let file = crate::fileio::directory_file_name(h, &[expanded])?;
    let dir = remove_slash_colon(&as_string(h, &file)?).to_string();
    if let Err(e) = accessible_directory(&dir) {
        let shown = h.str_text(&curdir).map(str::to_string);
        let shown = shown.unwrap_or_else(|| h.print(&curdir, false));
        return Err(report_file_errno(
            h,
            "Setting current directory",
            &[&shown],
            &e,
        ));
    }
    Ok(dir)
}

/// fileio.c `file_accessible_directory_p`: `access ("DIR/", F_OK)`, so a file
/// that is not a directory fails with `ENOTDIR`.
fn accessible_directory(dir: &str) -> std::io::Result<()> {
    let probe = if dir.ends_with('/') {
        dir.to_string()
    } else {
        format!("{dir}/")
    };
    let c = std::ffi::CString::new(probe)
        .map_err(|_| std::io::Error::from_raw_os_error(libc::ENOENT))?;
    // SAFETY: `c` is a valid NUL-terminated path for the duration of the call.
    if unsafe { libc::access(c.as_ptr(), libc::F_OK) } == 0 {
        Ok(())
    } else {
        Err(std::io::Error::last_os_error())
    }
}

/// `openp (Vexec_path, PROGRAM, exec-suffixes, X_OK)` as `call-process` runs
/// it: an absolute or `~` name is tried once; any other is expanded against
/// each `exec-path` element (nil meaning `default-directory`) with each of
/// `exec-suffixes`, and the first executable non-directory wins. The `PATH`
/// in `process-environment` plays no part. Not found is `(file-missing
/// "Searching for program" "No such file or directory" PROGRAM)`.
fn find_program(h: &mut ElispHost, program: &str) -> Result<String, String> {
    let dirs = if program.starts_with('/') || program.starts_with('~') {
        vec![Value::Undef]
    } else {
        let path = symbol_value_or_nil(h, "exec-path");
        h.list_vec(&path).unwrap_or_default()
    };
    let suffixes_v = symbol_value_or_nil(h, "exec-suffixes");
    let mut suffixes: Vec<String> = h
        .list_vec(&suffixes_v)
        .unwrap_or_default()
        .iter()
        .filter_map(|s| h.str_text(s).map(str::to_string))
        .collect();
    if suffixes.is_empty() {
        suffixes.push(String::new());
    }
    for dir in dirs {
        let dir = if is_nil(&dir) {
            symbol_value_or_nil(h, "default-directory")
        } else {
            dir
        };
        if !is_nil(&dir) && !h.is_string(&dir) {
            continue;
        }
        for suffix in &suffixes {
            let name = h.new_string(format!("{program}{suffix}"));
            let full = crate::fileio::expand_file_name(h, &[name, dir.clone()])?;
            let full = as_string(h, &full)?;
            let is_file = std::fs::metadata(&full).is_ok_and(|m| !m.is_dir());
            if is_file && fs_access(std::path::Path::new(&full), libc::X_OK) {
                return Ok(full);
            }
        }
    }
    let e = std::io::Error::from_raw_os_error(libc::ENOENT);
    Err(report_file_errno(
        h,
        "Searching for program",
        &[program],
        &e,
    ))
}

/// callproc.c `init_callproc`: `exec-path` is `PATH` split on `:`, an empty
/// element meaning ".", followed by `exec-directory` without its trailing
/// slash, and `shell-file-name` is `SHELL`, or "/bin/sh" when it is unset.
/// Per-run state, like the environment it is read from: a cached heap
/// image would otherwise keep the `PATH` and `SHELL` of the run that wrote it.
pub(crate) fn install_exec_path(h: &mut ElispHost) {
    let path = egetenv(h, "PATH").unwrap_or_default();
    let mut dirs: Vec<Value> = path
        .split(':')
        .map(|d| h.new_string(if d.is_empty() { "." } else { d }))
        .collect();
    let exec_dir = symbol_value_or_nil(h, "exec-directory");
    if h.is_string(&exec_dir) {
        if let Ok(d) = crate::fileio::directory_file_name(h, &[exec_dir]) {
            dirs.push(d);
        }
    }
    let exec_path = h.list_from(dirs);
    let sym = h.intern("exec-path");
    let _ = h.set_value(&sym, exec_path);
    let shell = egetenv(h, "SHELL").unwrap_or_else(|| "/bin/sh".to_string());
    let shell = h.new_string(shell);
    let sym = h.intern("shell-file-name");
    let _ = h.set_value(&sym, shell);
}
fn special_variable_p(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(nil_or(h.symbol_special(&a[0])))
}
fn func_arity(h: &mut ElispHost, a: &[Value]) -> R {
    // Special forms and the intrinsic macros have no resolvable function cell,
    // so `resolve_function` would signal `void-function`. Emacs instead reports
    // their C-level arity: special forms as `(MIN . unevalled)`, macros as
    // `(MIN . many)`.
    if let Some(name) = h.sym_name(&a[0]) {
        let name = name.as_str().to_owned();
        if let Some((_, min)) = SPECIAL_FORMS.iter().find(|(sf, _)| *sf == name) {
            let unevalled = h.intern("unevalled");
            return Ok(h.cons(Value::Int(*min), unevalled));
        }
        if let Some((_, min)) = INTRINSIC_MACROS.iter().find(|(m, _)| *m == name) {
            let many = h.intern("many");
            return Ok(h.cons(Value::Int(*min), many));
        }
    }
    // eval.c `lambda_arity` for a `(lambda ARGLIST . BODY)` list.
    if let Some(fun) = h.indirect_lambda_list(&a[0]) {
        let arglist = match h.obj(&fun) {
            Some(Obj::Cons(_, rest)) => match h.obj(rest) {
                Some(Obj::Cons(args, _)) => args.clone(),
                _ => return Err(h.signal_invalid_function(&fun)),
            },
            _ => return Err(h.signal_invalid_function(&fun)),
        };
        let (mut min, mut max, mut optional) = (0i64, 0i64, false);
        let mut cur = arglist;
        while let Some(Obj::Cons(next, rest)) = h.obj(&cur) {
            let (next, rest) = (next.clone(), rest.clone());
            match h.sym_name(&next).as_deref() {
                None => return Err(h.signal_invalid_function(&fun)),
                Some("&rest") => {
                    let many = h.intern("many");
                    return Ok(h.cons(Value::Int(min), many));
                }
                Some("&optional") => optional = true,
                Some(_) => {
                    if !optional {
                        min += 1;
                    }
                    max += 1;
                }
            }
            cur = rest;
        }
        if !matches!(cur, Value::Undef | Value::Bool(false)) {
            return Err(h.signal_invalid_function(&fun));
        }
        return Ok(h.cons(Value::Int(min), Value::Int(max)));
    }
    let (min, max) = {
        match h.resolve_function(&a[0])? {
            Resolved::Subr { min, max, .. } => (min as i64, max.map(|m| m as i64)),
            Resolved::Closure { params, .. } => {
                let mn = params.required.len() as i64;
                if params.rest.is_some() {
                    (mn, None)
                } else {
                    (mn, Some(mn + params.optional.len() as i64))
                }
            }
        }
    };
    let maxv = match max {
        Some(m) => Value::Int(m),
        None => h.intern("many"),
    };
    Ok(h.cons(Value::Int(min), maxv))
}
/// sysdep.c `emacs_get_current_dir_name`: `$PWD` when it is absolute and names
/// the same file as `.` (same device and inode), else `getcwd`. So a shell
/// that entered a directory through a symlink keeps that spelling —
/// `/var/folders/…` on macOS, where `getcwd` answers `/private/var/folders/…`.
fn current_directory(h: &mut ElispHost, _a: &[Value]) -> R {
    use std::os::unix::fs::MetadataExt;
    let same_file =
        |a: &std::fs::Metadata, b: &std::fs::Metadata| a.dev() == b.dev() && a.ino() == b.ino();
    let from_pwd = std::env::var("PWD").ok().filter(|pwd| {
        pwd.starts_with('/')
            && match (std::fs::metadata(pwd), std::fs::metadata(".")) {
                (Ok(p), Ok(d)) => same_file(&p, &d),
                _ => false,
            }
    });
    Ok(h.new_string(from_pwd.unwrap_or_else(|| {
        std::env::current_dir()
            .map(|p| p.to_string_lossy().into_owned())
            .unwrap_or_else(|_| "/".to_string())
    })))
}

/// Emacs C `Vsystem_type` (emacs.c), computed at build/configure time. We derive
/// the same symbol from the running platform so a `.el` file gets the value it
/// would see under a native Emacs on this host. Mapping matches Emacs's
/// `s/*.h` `SYSTEM_TYPE` conventions: macOS -> `darwin`, Linux -> `gnu/linux`,
/// the BSDs -> `berkeley-unix`, Windows -> `windows-nt`.
fn system_type(h: &mut ElispHost, _a: &[Value]) -> R {
    let sym = match std::env::consts::OS {
        "macos" => "darwin",
        "linux" => "gnu/linux",
        "windows" => "windows-nt",
        "freebsd" | "openbsd" | "netbsd" | "dragonfly" => "berkeley-unix",
        "android" => "android",
        _ => "gnu/linux",
    };
    Ok(h.intern(sym))
}

// `system-name' (Fsystem_name, editfns.c): return the host name of the machine
// as a string. Emacs caches Vsystem_name from gethostname(2) at init; we query
// it directly. gethostname failure is effectively unreachable; the "unknown"
// fallback mirrors Emacs's own default when the host name is unavailable.
fn system_name(h: &mut ElispHost, _a: &[Value]) -> R {
    let mut buf = [0u8; 256];
    let rc = unsafe { libc::gethostname(buf.as_mut_ptr() as *mut libc::c_char, buf.len()) };
    if rc != 0 {
        return Ok(h.new_string("unknown"));
    }
    let end = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
    if end == 0 {
        return Ok(h.new_string("unknown"));
    }
    Ok(h.new_string(String::from_utf8_lossy(&buf[..end]).into_owned()))
}

/// editfns.c's UID argument decoding (`CONS_TO_INTEGER` into `uid_t`): a
/// natural number in range, an integral float, or `(HI . LO)` / `(HI LO)`
/// meaning HI * 2^16 + LO with LO below 2^16.
fn uid_arg(h: &ElispHost, v: &Value) -> Result<u32, String> {
    const MSG: &str = "error: Not an in-range integer, integral float, or cons of integers";
    let n = match v {
        Value::Int(n) => Some(*n),
        Value::Float(f) if f.fract() == 0.0 && *f >= 0.0 && *f <= u32::MAX as f64 => {
            Some(*f as i64)
        }
        _ => cons_parts(h, v).and_then(|(hi, lo)| {
            let lo = cons_parts(h, &lo).map_or(lo, |(car, _)| car);
            match (hi, lo) {
                (Value::Int(hi), Value::Int(lo)) if hi >= 0 && (0..1 << 16).contains(&lo) => {
                    hi.checked_mul(1 << 16).map(|v| v + lo)
                }
                _ => None,
            }
        }),
    };
    n.and_then(|n| u32::try_from(n).ok())
        .ok_or_else(|| MSG.to_string())
}

/// editfns.c `init_editfns`: the login name is `LOGNAME`, else `USER`, else
/// the name of the effective uid, else "unknown".
fn login_name_from_env() -> String {
    std::env::var("LOGNAME")
        .or_else(|_| std::env::var("USER"))
        .ok()
        .or_else(|| id_name(unsafe { libc::geteuid() }, false))
        .unwrap_or_else(|| "unknown".to_string())
}

/// `(user-login-name &optional UID)`: with UID, the name `getpwuid` records
/// for it, or nil; without, the login name from the environment.
fn user_login_name(h: &mut ElispHost, a: &[Value]) -> R {
    match a.first().filter(|v| !is_nil(v)) {
        Some(uid) => {
            let uid = uid_arg(h, uid)?;
            Ok(id_name(uid, false).map_or(Value::Undef, |s| h.new_string(s)))
        }
        None => Ok(h.new_string(login_name_from_env())),
    }
}

/// `(user-real-login-name)`: the name of the real uid, ignoring the
/// environment, or "unknown".
fn user_real_login_name(h: &mut ElispHost, _a: &[Value]) -> R {
    let name = id_name(unsafe { libc::getuid() }, false).unwrap_or_else(|| "unknown".to_string());
    Ok(h.new_string(name))
}

/// `(user-uid)`: the effective uid.
fn user_uid(_h: &mut ElispHost, _a: &[Value]) -> R {
    Ok(Value::Int(unsafe { libc::geteuid() } as i64))
}

/// `(user-real-uid)`: the real uid.
fn user_real_uid(_h: &mut ElispHost, _a: &[Value]) -> R {
    Ok(Value::Int(unsafe { libc::getuid() } as i64))
}

/// Raw temp-dir string behind Emacs C `Vtemporary_file_directory`
/// (callproc.c `init_callproc`). The caller wraps this in
/// `file-name-as-directory`, exactly as the C does (`build_string` then
/// `Ffile_name_as_directory`). Resolution order matches Emacs:
///   1. `$TMPDIR` if present in the environment — even when empty, so an empty
///      `TMPDIR` yields `""` which `file-name-as-directory` turns into `"./"`.
///   2. otherwise on macOS the per-user Darwin temp dir from
///      `confstr(_CS_DARWIN_USER_TEMP_DIR)` (e.g. `/var/folders/.../T/`).
///   3. otherwise `"/tmp/"`.
fn temp_directory(h: &mut ElispHost, _a: &[Value]) -> R {
    // `std::env::var` returns Ok("") when TMPDIR is set but empty, and
    // Err(NotPresent) only when it is absent — matching Emacs's `egetenv`
    // "non-NULL means present" test.
    if let Ok(v) = std::env::var("TMPDIR") {
        return Ok(h.new_string(v));
    }
    #[cfg(target_os = "macos")]
    {
        let mut buf = [0u8; 1024];
        let n = unsafe {
            libc::confstr(
                libc::_CS_DARWIN_USER_TEMP_DIR,
                buf.as_mut_ptr() as *mut libc::c_char,
                buf.len(),
            )
        };
        // confstr returns the byte length including the trailing NUL; 0 means
        // the name is unknown, > buf.len() means it was truncated.
        if n > 1 && n <= buf.len() {
            if let Ok(s) = std::str::from_utf8(&buf[..n - 1]) {
                return Ok(h.new_string(s.to_string()));
            }
        }
    }
    Ok(h.new_string("/tmp/".to_string()))
}

/// fileio.c `report_file_errno`: signal the failure of a file operation the
/// way Emacs does, as `(CONDITION STRING ERRSTRING NAME...)`.
///
/// `get_file_errno_data` picks the condition from errno — `file-missing` for
/// ENOENT, `permission-denied` for EACCES, `file-error` otherwise — and EEXIST
/// is `file-already-exists` with no STRING at all: `(make-directory-internal
/// "/tmp")` is `(file-already-exists "File exists" "/tmp")`. ERRSTRING is
/// `strerror`'s text, which is also what `io::Error` displays for an OS error
/// (minus its " (os error N)" suffix).
pub(crate) fn report_file_errno(
    h: &mut ElispHost,
    string: &str,
    names: &[&str],
    err: &std::io::Error,
) -> String {
    let errno = err.raw_os_error();
    let shown = err.to_string();
    let errstring = match shown.rfind(" (os error ") {
        Some(i) if errno.is_some() => shown[..i].to_string(),
        _ => shown,
    };
    let condition = match errno {
        Some(libc::EEXIST) => "file-already-exists",
        Some(libc::ENOENT) => "file-missing",
        Some(libc::EACCES) => "permission-denied",
        _ => "file-error",
    };
    let mut data = Vec::with_capacity(names.len() + 2);
    if errno != Some(libc::EEXIST) {
        data.push(h.new_string(string.to_string()));
    }
    data.push(h.new_string(errstring));
    data.extend(names.iter().map(|n| h.new_string(n.to_string())));
    let sym = h.intern(condition);
    let data = h.list_from(data);
    let obj = h.cons(sym, data);
    let msg = format!("{condition}: {}", h.print(&obj, true));
    h.set_pending_error(&msg, obj);
    msg
}

// ── filesystem (read-only queries) ──
/// The local file an already expanded file name (see `FILE_NAME_ARGS` in
/// host.rs) names. A quoted name "/:..." is the file it quotes, as
/// files.el's `file-name-non-special` handler hands it to the primitive.
fn fs_expand(s: &str) -> std::path::PathBuf {
    std::path::PathBuf::from(remove_slash_colon(s))
}
/// callproc.c / files.el `remove_slash_colon`: "/:" is "/", "/:REST" is REST.
fn remove_slash_colon(s: &str) -> &str {
    match s.strip_prefix("/:") {
        Some("") => "/",
        Some(rest) => rest,
        None => s,
    }
}
fn fs_access(p: &std::path::Path, mode: libc::c_int) -> bool {
    use std::os::unix::ffi::OsStrExt;
    match std::ffi::CString::new(p.as_os_str().as_bytes()) {
        Ok(c) => unsafe { libc::access(c.as_ptr(), mode) == 0 },
        Err(_) => false,
    }
}
fn file_exists_p(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(nil_or(fs_expand(&as_string(h, &a[0])?).exists()))
}
fn file_directory_p(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(nil_or(fs_expand(&as_string(h, &a[0])?).is_dir()))
}
fn file_regular_p(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(nil_or(fs_expand(&as_string(h, &a[0])?).is_file()))
}
fn file_readable_p(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(nil_or(fs_access(
        &fs_expand(&as_string(h, &a[0])?),
        libc::R_OK,
    )))
}
fn file_writable_p(h: &mut ElispHost, a: &[Value]) -> R {
    let p = fs_expand(&as_string(h, &a[0])?);
    // For a non-existent file, writability is the parent directory's.
    let target = if p.exists() {
        p.clone()
    } else {
        p.parent().map(|x| x.to_path_buf()).unwrap_or(p)
    };
    Ok(nil_or(fs_access(&target, libc::W_OK)))
}
fn file_symlink_p(h: &mut ElispHost, a: &[Value]) -> R {
    match std::fs::read_link(fs_expand(&as_string(h, &a[0])?)) {
        Ok(t) => Ok(h.new_string(t.to_string_lossy().into_owned())),
        Err(_) => Ok(Value::Undef),
    }
}
/// `file_attribute_errno` (fileio.c): a file that is not there (ENOENT, or a
/// non-directory in its leading part) answers nil; any other failure signals
/// `("Getting attributes" ERRSTRING FILE)`.
fn file_attribute_errno(h: &mut ElispHost, file: &str, err: &std::io::Error) -> R {
    match err.raw_os_error() {
        Some(libc::ENOENT) | Some(libc::ENOTDIR) => Ok(Value::Undef),
        _ => Err(report_file_errno(h, "Getting attributes", &[file], err)),
    }
}
/// timefns.c `make_lisp_time` in `current-time-list` form:
/// `(HIGH LOW USEC PSEC)`.
fn lisp_timestamp(h: &mut ElispHost, sec: i64, nsec: i64) -> Value {
    h.list_from(vec![
        Value::Int(sec >> 16),
        Value::Int(sec & 0xffff),
        Value::Int(nsec / 1000),
        Value::Int(nsec % 1000 * 1000),
    ])
}
/// Widen a `libc::mode_t` to `u32`: it is `u16` on macOS and `u32` on Linux,
/// so an `as u32` cast is a needed widening on one and a no-op on the other.
fn mode_bits<T: Into<u32>>(m: T) -> u32 {
    m.into()
}
/// filemode.c `filemodestring`: the ten-character `ls -l` mode string.
fn file_mode_string(mode: u32) -> String {
    let kind = match mode & mode_bits(libc::S_IFMT) {
        m if m == mode_bits(libc::S_IFREG) => '-',
        m if m == mode_bits(libc::S_IFDIR) => 'd',
        m if m == mode_bits(libc::S_IFBLK) => 'b',
        m if m == mode_bits(libc::S_IFCHR) => 'c',
        m if m == mode_bits(libc::S_IFLNK) => 'l',
        m if m == mode_bits(libc::S_IFIFO) => 'p',
        m if m == mode_bits(libc::S_IFSOCK) => 's',
        _ => '?',
    };
    let bit = |mask: u32, c: char| if mode & mask != 0 { c } else { '-' };
    // The execute slot also shows set-id / sticky: lower case when the
    // execute bit is set too, upper case when it is not.
    let exec =
        |x: u32, special: u32, set: char, unset: char| match (mode & x != 0, mode & special != 0) {
            (true, true) => set,
            (false, true) => unset,
            (true, false) => 'x',
            (false, false) => '-',
        };
    [
        kind,
        bit(0o400, 'r'),
        bit(0o200, 'w'),
        exec(0o100, 0o4000, 's', 'S'),
        bit(0o040, 'r'),
        bit(0o020, 'w'),
        exec(0o010, 0o2000, 's', 'S'),
        bit(0o004, 'r'),
        bit(0o002, 'w'),
        exec(0o001, 0o1000, 't', 'T'),
    ]
    .iter()
    .collect()
}
/// dired.c `stat_uname` / `stat_gname`: the user or group name of an id,
/// or None when the password or group database has no entry.
fn id_name(id: u32, group: bool) -> Option<String> {
    // SAFETY: the record getpwuid / getgrgid return is read at once, before
    // any other call could overwrite it.
    unsafe {
        let name = if group {
            let gr = libc::getgrgid(id);
            if gr.is_null() {
                return None;
            }
            (*gr).gr_name
        } else {
            let pw = libc::getpwuid(id);
            if pw.is_null() {
                return None;
            }
            (*pw).pw_name
        };
        if name.is_null() {
            return None;
        }
        Some(
            std::ffi::CStr::from_ptr(name)
                .to_string_lossy()
                .into_owned(),
        )
    }
}
/// dired.c `Ffile_attributes`: `lstat` FILENAME (expanded on the way in; a
/// name `expand-file-name` refuses, such as a non-string, answers nil) and
/// answer `(TYPE LINKS UID GID ATIME MTIME CTIME SIZE MODES t INODE
/// DEVICE)`. TYPE is t for a directory, the link's target for a symbolic
/// link, else nil. UID and GID are names when ID-FORMAT is non-nil and not
/// `integer` and the name is known, else numbers.
fn file_attributes(h: &mut ElispHost, a: &[Value]) -> R {
    use std::os::unix::fs::MetadataExt;
    let Some(name) = h.str_text(&a[0]).map(str::to_string) else {
        return Ok(Value::Undef);
    };
    let path = fs_expand(&name);
    let st = match std::fs::symlink_metadata(&path) {
        Ok(st) => st,
        Err(e) => return file_attribute_errno(h, &name, &e),
    };
    let ft = st.file_type();
    let kind = if ft.is_dir() {
        Value::Bool(true)
    } else if ft.is_symlink() {
        match std::fs::read_link(&path) {
            Ok(t) => h.new_string(t.to_string_lossy().into_owned()),
            Err(e) => return file_attribute_errno(h, &name, &e),
        }
    } else {
        Value::Undef
    };
    let by_name = match a.get(1) {
        Some(v) if !is_nil(v) => h.sym_name(v).is_none_or(|n| n.as_str() != "integer"),
        _ => false,
    };
    let id =
        |h: &mut ElispHost, n: u32, group: bool| match by_name.then(|| id_name(n, group)).flatten()
        {
            Some(s) => h.new_string(s),
            None => Value::Int(n as i64),
        };
    let uid = id(h, st.uid(), false);
    let gid = id(h, st.gid(), true);
    let size = h.make_integer(BigInt::from(st.size()));
    let atime = lisp_timestamp(h, st.atime(), st.atime_nsec());
    let mtime = lisp_timestamp(h, st.mtime(), st.mtime_nsec());
    let ctime = lisp_timestamp(h, st.ctime(), st.ctime_nsec());
    let modes = h.new_string(file_mode_string(st.mode()));
    let inode = h.make_integer(BigInt::from(st.ino()));
    let device = h.make_integer(BigInt::from(st.dev()));
    Ok(h.list_from(vec![
        kind,
        Value::Int(st.nlink() as i64),
        uid,
        gid,
        atime,
        mtime,
        ctime,
        size,
        modes,
        Value::Bool(true),
        inode,
        device,
    ]))
}
/// FLAG of `file-modes` / `set-file-modes`: `nofollow` acts on a symbolic
/// link itself.
fn nofollow_flag(h: &ElispHost, flag: Option<&Value>) -> bool {
    flag.and_then(|v| h.sym_name(v))
        .is_some_and(|n| n.as_str() == "nofollow")
}
/// fileio.c `Ffile_modes`: the permission bits (`st_mode & 07777`), nil
/// when FILENAME does not exist.
fn file_modes(h: &mut ElispHost, a: &[Value]) -> R {
    use std::os::unix::fs::MetadataExt;
    let name = as_string(h, &a[0])?;
    let path = fs_expand(&name);
    let st = if nofollow_flag(h, a.get(1)) {
        std::fs::symlink_metadata(&path)
    } else {
        std::fs::metadata(&path)
    };
    match st {
        Ok(st) => Ok(Value::Int((st.mode() & 0o7777) as i64)),
        Err(e) => file_attribute_errno(h, &name, &e),
    }
}
/// fileio.c `Fset_file_modes`: `fchmodat`, signalling `"Doing chmod"`.
fn set_file_modes(h: &mut ElispHost, a: &[Value]) -> R {
    let name = as_string(h, &a[0])?;
    let mode = as_fixnum_named(h, &a[1], "fixnump")?;
    let flags = if nofollow_flag(h, a.get(2)) {
        libc::AT_SYMLINK_NOFOLLOW
    } else {
        0
    };
    let Ok(c) = std::ffi::CString::new(remove_slash_colon(&name)) else {
        let e = std::io::Error::from_raw_os_error(libc::EINVAL);
        return Err(report_file_errno(h, "Doing chmod", &[&name], &e));
    };
    // SAFETY: `c` is a valid NUL-terminated path for the duration of the call.
    if unsafe { libc::fchmodat(libc::AT_FDCWD, c.as_ptr(), mode as libc::mode_t, flags) } != 0 {
        let e = std::io::Error::last_os_error();
        return Err(report_file_errno(h, "Doing chmod", &[&name], &e));
    }
    Ok(Value::Undef)
}
/// fileio.c `Ffile_newer_than_file_p`: nil when FILE1 does not exist, t
/// when only FILE2 does not, else whether FILE1's modification time is
/// later. Both names are expanded and lose a trailing slash
/// (`expand_and_dir_to_file`).
fn file_newer_than_file_p(h: &mut ElispHost, a: &[Value]) -> R {
    let mut names = Vec::with_capacity(2);
    for v in &a[..2] {
        as_string(h, v)?;
        let file = crate::fileio::directory_file_name(h, std::slice::from_ref(v))?;
        names.push(as_string(h, &file)?);
    }
    let mtime = |n: &str| {
        use std::os::unix::fs::MetadataExt;
        std::fs::metadata(fs_expand(n)).map(|m| (m.mtime(), m.mtime_nsec()))
    };
    let t1 = match mtime(&names[0]) {
        Ok(t) => t,
        Err(e) => return file_attribute_errno(h, &names[0], &e),
    };
    match mtime(&names[1]) {
        Ok(t2) => Ok(nil_or(t1 > t2)),
        Err(e) => {
            file_attribute_errno(h, &names[1], &e)?;
            Ok(Value::Bool(true))
        }
    }
}
/// fileio.c `Ffile_accessible_directory_p` / `file_accessible_directory_p`:
/// "DIR/." exists, so DIR is a directory that can be searched.
fn file_accessible_directory_p(h: &mut ElispHost, a: &[Value]) -> R {
    let name = as_string(h, &a[0])?;
    let dir = remove_slash_colon(&name);
    let probe = if dir.ends_with('/') {
        format!("{dir}.")
    } else {
        format!("{dir}/.")
    };
    Ok(nil_or(fs_access(std::path::Path::new(&probe), libc::F_OK)))
}
/// fileio.c `Fdelete_directory_internal`: one `rmdir`.
fn delete_directory_internal(h: &mut ElispHost, a: &[Value]) -> R {
    let name = as_string(h, &a[0])?;
    std::fs::remove_dir(fs_expand(&name))
        .map_err(|e| report_file_errno(h, "Removing directory", &[&name], &e))?;
    Ok(Value::Undef)
}
/// fileio.c `expand_cp_target` for a NEWNAME already expanded: a directory
/// name receives FILE's last component.
fn cp_target(file: &str, newname: &str) -> String {
    if newname.ends_with('/') {
        let base = file.rsplit('/').next().unwrap_or(file);
        format!("{newname}{base}")
    } else {
        newname.to_string()
    }
}
/// The link-making half of fileio.c `Fmake_symbolic_link` and
/// `Fadd_name_to_file`: MAKE creates NAMES' last element. When that exists
/// already, a non-nil OK-IF-ALREADY-EXISTS removes it and tries again, and
/// nil signals `(file-already-exists "File already exists" NEWNAME)`. (A
/// number, which asks the user in Emacs, is taken as nil: batch Emacs has
/// no one to ask either.) Other failures are `(STRING ERRSTRING NAMES...)`.
fn make_link(
    h: &mut ElispHost,
    string: &str,
    names: &[&str],
    ok_if_exists: Option<&Value>,
    make: impl Fn() -> std::io::Result<()>,
) -> Result<(), String> {
    let newname = names[names.len() - 1];
    let mut result = make();
    if matches!(&result, Err(e) if e.raw_os_error() == Some(libc::EEXIST)) {
        let replace = ok_if_exists.is_some_and(|v| !is_nil(v) && !matches!(v, Value::Int(_)));
        if !replace {
            let sym = h.intern("file-already-exists");
            let data = vec![
                h.new_string("File already exists".to_string()),
                h.new_string(newname.to_string()),
            ];
            let data = h.list_from(data);
            let obj = h.cons(sym, data);
            let msg = format!("file-already-exists: {}", h.print(&obj, true));
            h.set_pending_error(&msg, obj);
            return Err(msg);
        }
        // A failed `unlink` is not reported: the second attempt is.
        let _ = std::fs::remove_file(fs_expand(newname));
        result = make();
    }
    result.map_err(|e| report_file_errno(h, string, names, &e))
}
/// fileio.c `Fmake_symbolic_link`: TARGET is stored as written; LINKNAME
/// (expanded on the way in, `expand_cp_target`) is the link made. Errors
/// are `("Making symbolic link" ERRSTRING TARGET LINKNAME)`.
fn make_symbolic_link(h: &mut ElispHost, a: &[Value]) -> R {
    let target = as_string(h, &a[0])?;
    let link = cp_target(&target, &as_string(h, &a[1])?);
    let path = fs_expand(&link);
    make_link(
        h,
        "Making symbolic link",
        &[&target, &link],
        a.get(2),
        || std::os::unix::fs::symlink(&target, &path),
    )?;
    Ok(Value::Undef)
}
/// fileio.c `Fadd_name_to_file`: a hard link NEWNAME to FILE, both expanded
/// on the way in. Errors are `("Adding new name" ERRSTRING FILE NEWNAME)`.
fn add_name_to_file(h: &mut ElispHost, a: &[Value]) -> R {
    let file = as_string(h, &a[0])?;
    let newname = cp_target(&file, &as_string(h, &a[1])?);
    let (from, to) = (fs_expand(&file), fs_expand(&newname));
    make_link(h, "Adding new name", &[&file, &newname], a.get(2), || {
        std::fs::hard_link(&from, &to)
    })?;
    Ok(Value::Undef)
}
fn file_executable_p(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(nil_or(fs_access(
        &fs_expand(&as_string(h, &a[0])?),
        libc::X_OK,
    )))
}
/// Internal: absolute path of the running `elisp` binary, backing
/// `invocation-name'/`invocation-directory'/`exec-directory'. Falls back to the
/// bare name `"elisp"` if the OS cannot report the executable path.
fn invocation_file(h: &mut ElispHost, _a: &[Value]) -> R {
    Ok(h.new_string(
        std::env::current_exe()
            .map(|p| p.to_string_lossy().into_owned())
            .unwrap_or_else(|_| "elisp".to_string()),
    ))
}
fn directory_files_raw(h: &mut ElispHost, a: &[Value]) -> R {
    let raw = as_string(h, &a[0])?;
    let match_re = match a.get(1) {
        Some(v) if !is_nil(v) => Some(compile_cf(h, &as_string(h, v)?, false)?),
        _ => None,
    };
    let nosort = a.get(2).is_some_and(|v| !is_nil(v));
    let rd = std::fs::read_dir(fs_expand(&raw))
        .map_err(|e| report_file_errno(h, "Opening directory", &[&raw], &e))?;
    let mut names: Vec<String> = vec![".".into(), "..".into()];
    for e in rd.flatten() {
        names.push(e.file_name().to_string_lossy().into_owned());
    }
    if let Some(re) = match_re {
        names.retain(|n| re.is_match(n).unwrap_or(false));
    }
    if !nosort {
        names.sort();
    }
    Ok(h.list_from(names.into_iter().map(Value::str).collect()))
}

// ── buffer registry (named, live buffers over a global registry) ──
fn bufferp(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(nil_or(matches!(h.obj(&a[0]), Some(Obj::Buffer(_)))))
}
fn current_buffer_fn(h: &mut ElispHost, _a: &[Value]) -> R {
    Ok(h.current_buffer())
}
fn set_buffer_fn(h: &mut ElispHost, a: &[Value]) -> R {
    h.set_buffer(&a[0])
}
fn get_buffer(h: &mut ElispHost, a: &[Value]) -> R {
    // `Fget_buffer` returns a buffer *object* unchanged — live or killed — and
    // only the by-name branch can answer nil. See `ElispHost::get_buffer`.
    match h.get_buffer(&a[0])? {
        Some(idx) => Ok(h.buffers[idx].self_obj.clone()),
        None => Ok(Value::Undef),
    }
}
/// buffer.c `Fget_buffer_create`: `Fget_buffer` first, which hands a buffer
/// object back as it is — killed or not — so only a name can create one.
fn get_buffer_create(h: &mut ElispHost, a: &[Value]) -> R {
    if matches!(h.obj(&a[0]), Some(Obj::Buffer(_))) {
        return Ok(a[0].clone());
    }
    let name = as_string(h, &a[0])?;
    check_buffer_name(&name)?;
    let existed = h.find_buffer_by_name(&name).is_some();
    let buffer = h.get_buffer_create(&name);
    if !existed && a.get(1).is_some_and(|v| !is_nil(v)) {
        let idx = h.resolve_buffer(&buffer).expect("fresh buffer");
        h.buffers[idx].inhibit_hooks = true;
    }
    Ok(buffer)
}
/// buffer.c refuses the empty name outright rather than making an unnameable
/// buffer, in `get-buffer-create` and in `generate-new-buffer-name` alike.
fn check_buffer_name(name: &str) -> Result<(), String> {
    if name.is_empty() {
        return Err("error: Empty string for buffer name is not allowed".to_string());
    }
    Ok(())
}
fn generate_new_buffer(h: &mut ElispHost, a: &[Value]) -> R {
    let base = as_string(h, &a[0])?;
    check_buffer_name(&base)?;
    let name = h.generate_new_buffer_name(&base, None);
    // generate-new-buffer always makes a fresh buffer (the unique name is free).
    let buffer = h.get_buffer_create(&name);
    if a.get(1).is_some_and(|v| !is_nil(v)) {
        let idx = h.resolve_buffer(&buffer).expect("fresh buffer");
        h.buffers[idx].inhibit_hooks = true;
    }
    Ok(buffer)
}
fn generate_new_buffer_name(h: &mut ElispHost, a: &[Value]) -> R {
    let base = as_string(h, &a[0])?;
    // IGNORE (a name that may be reused even if taken) is only honored when it is
    // a string; `Fstring_equal` is guarded by `!NILP (ignore)` for NAME itself and
    // simply never matches a nil IGNORE inside the `<N>` loop.
    let ignore = match a.get(1) {
        Some(v) if !is_nil(v) => Some(as_string(h, v)?),
        _ => None,
    };
    Ok(h.new_string(h.generate_new_buffer_name(&base, ignore.as_deref())))
}
fn buffer_name(h: &mut ElispHost, a: &[Value]) -> R {
    let idx = match a.first() {
        Some(v) if !is_nil(v) => match h.resolve_buffer(v) {
            Some(i) => i,
            None => return Ok(Value::Undef),
        },
        _ => h.current,
    };
    Ok(match &h.buffers[idx].name {
        Some(n) => h.new_string(n.clone()),
        None => Value::Undef,
    })
}
fn buffer_live_p(h: &mut ElispHost, a: &[Value]) -> R {
    let ok = matches!(h.obj(&a[0]), Some(Obj::Buffer(idx))
        if h.buffers.get(*idx).is_some_and(|b| b.name.is_some()));
    Ok(nil_or(ok))
}
fn kill_buffer(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(h.kill_buffer(a.first()))
}
/// process.c `get-buffer-process`: elisprs runs no asynchronous processes,
/// so no buffer has one.
fn get_buffer_process(h: &mut ElispHost, a: &[Value]) -> R {
    if !is_nil(&a[0]) && h.resolve_buffer(&a[0]).is_none() && !h.is_string(&a[0]) {
        return Err(h.signal_wrong_type("stringp", &a[0]));
    }
    Ok(Value::Undef)
}
fn rename_buffer(h: &mut ElispHost, a: &[Value]) -> R {
    let newname = as_string(h, &a[0])?;
    let unique = a.get(1).is_some_and(|v| !is_nil(v));
    h.rename_buffer(&newname, unique)
}
fn buffer_list(h: &mut ElispHost, _a: &[Value]) -> R {
    Ok(h.buffer_list())
}

// ── mark ──
/// `(mark-marker)`. `mark` and `set-mark` are simple.el's, in the prelude.
fn mark_marker_fn(h: &mut ElispHost, _a: &[Value]) -> R {
    Ok(h.mark_marker())
}
/// editfns.c `region_limit`: in Transient Mark mode an inactive mark is
/// `mark-inactive` unless `mark-even-if-inactive`; the mark end is clipped to
/// the accessible portion.
fn region_limit(h: &mut ElispHost, beginningp: bool) -> R {
    let var = |h: &mut ElispHost, name: &str| {
        let sym = h.intern(name);
        h.get_dynamic_value(&sym)
            .map(|v| !is_nil(&v))
            .unwrap_or(false)
    };
    if var(h, "transient-mark-mode") && !var(h, "mark-even-if-inactive") && !var(h, "mark-active") {
        return Err("mark-inactive".to_string());
    }
    let m = h
        .mark_pos()
        .ok_or("error: The mark is not set now, so there is no region")?;
    let b = h.cur_buf_ref();
    Ok(Value::Int(if (b.point < m) == beginningp {
        b.point
    } else {
        m.clamp(b.begv, b.zv)
    } as i64))
}
fn region_beginning(h: &mut ElispHost, _a: &[Value]) -> R {
    region_limit(h, true)
}
fn region_end(h: &mut ElispHost, _a: &[Value]) -> R {
    region_limit(h, false)
}

// ── narrowing ──
/// `(narrow-to-region START END)` — port of `Fnarrow_to_region` (editfns.c).
///
/// An inverted pair is accepted and swapped, but a pair outside the BUFFER —
/// not outside the current restriction, which the call is about to replace — is
/// `(args-out-of-range START END)`, naming the arguments in the order they were
/// given rather than the swapped order. Clamping instead silently narrowed to
/// something the caller did not ask for.
fn narrow_to_region(h: &mut ElispHost, a: &[Value]) -> R {
    let (lo, hi) = narrow_bounds(h, &a[0], &a[1])?;
    h.narrow(lo, hi);
    Ok(Value::Undef)
}
/// `Fnarrow_to_region`'s argument check: positions in either order, inside the
/// WHOLE buffer (`BEG`..`Z`, not the current restriction), or
/// `(args-out-of-range START END)` naming the arguments as given.
fn narrow_bounds(h: &mut ElispHost, b: &Value, e: &Value) -> Result<(usize, usize), String> {
    let (s0, e0) = (fix_position(h, b)?, fix_position(h, e)?);
    let (lo, hi) = if e0 < s0 { (e0, s0) } else { (s0, e0) };
    let z = h.cur_buf_ref().text.len() as i64 + 1;
    if lo < 1 || hi > z {
        return Err(args_out_of_range_values(h, vec![b.clone(), e.clone()]));
    }
    Ok((lo as usize, hi as usize))
}
fn widen_fn(h: &mut ElispHost, _a: &[Value]) -> R {
    h.widen();
    Ok(Value::Undef)
}
/// `--se-push--`: record point as a save-excursion marker on the current buffer.
fn se_push(h: &mut ElispHost, _a: &[Value]) -> R {
    let p = h.cur_buf().point;
    h.cur_buf().se_markers.push(p);
    Ok(Value::Undef)
}
/// `--se-pop--`: restore point from (and drop) the current buffer's top
/// save-excursion marker.
fn se_pop(h: &mut ElispHost, _a: &[Value]) -> R {
    let buf = h.cur_buf();
    if let Some(m) = buf.se_markers.pop() {
        buf.point = m.clamp(buf.begv, buf.zv);
    }
    Ok(Value::Undef)
}
/// `--save-restriction--`: push the current `(begv, zv)` so it tracks edits.
fn save_restriction_push(h: &mut ElispHost, _a: &[Value]) -> R {
    let buf = h.cur_buf();
    let (lo, hi) = (buf.begv, buf.zv);
    buf.restrict_stack.push((lo, hi));
    Ok(Value::Undef)
}
/// `--restore-restriction--`: pop and reinstate the saved narrowing.
fn restore_restriction(h: &mut ElispHost, _a: &[Value]) -> R {
    let buf = h.cur_buf();
    if let Some((lo, hi)) = buf.restrict_stack.pop() {
        let maxzv = buf.text.len() + 1;
        buf.begv = lo.clamp(1, maxzv);
        buf.zv = hi.clamp(1, maxzv);
        buf.point = buf.point.clamp(buf.begv, buf.zv);
    }
    Ok(Value::Undef)
}
// ── buffer-local variables ──
fn make_local_variable(h: &mut ElispHost, a: &[Value]) -> R {
    h.make_local_variable(&a[0])
}
fn make_variable_buffer_local(h: &mut ElispHost, a: &[Value]) -> R {
    h.make_variable_buffer_local(&a[0])
}
fn check_symbol(h: &mut ElispHost, v: &Value) -> Result<(), String> {
    if !is_nil(&symbolp(h, std::slice::from_ref(v))?) {
        Ok(())
    } else {
        Err(h.signal_wrong_type("symbolp", v))
    }
}
/// data.c `Flocal_variable_p`: BUFFER is decoded before VARIABLE is checked.
fn local_variable_p(h: &mut ElispHost, a: &[Value]) -> R {
    let bi = decode_buffer(h, a.get(1))?;
    check_symbol(h, &a[0])?;
    Ok(nil_or(h.local_variable_p(&a[0], bi)))
}
/// data.c `Flocal_variable_if_set_p`: an automatically buffer-local variable
/// answers t for every buffer; otherwise it is `local-variable-p`, and a plain
/// variable answers nil before BUFFER is looked at.
fn local_variable_if_set_p(h: &mut ElispHost, a: &[Value]) -> R {
    check_symbol(h, &a[0])?;
    if h.is_auto_local_var(&a[0]) {
        return Ok(Value::Bool(true));
    }
    if !h.has_any_local(&a[0]) {
        return Ok(Value::Undef);
    }
    let bi = decode_buffer(h, a.get(1))?;
    Ok(nil_or(h.local_variable_p(&a[0], bi)))
}
fn kill_local_variable(h: &mut ElispHost, a: &[Value]) -> R {
    h.kill_local_variable(&a[0])
}
fn buffer_local_symbols_fn(h: &mut ElispHost, _a: &[Value]) -> R {
    Ok(h.buffer_local_symbols())
}
/// `(--make-always-local-- SYM INIT)`: SYM becomes an always-local per-buffer
/// slot. INIT is what a new buffer starts with: `:inherit` (the creating
/// buffer's value), `:undo-list` (t when the name starts with a space), or a
/// value.
fn make_always_local_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let init = match h.sym_name(&a[1]).as_deref() {
        Some(":inherit") => crate::host::SlotInit::Inherit,
        Some(":undo-list") => crate::host::SlotInit::UndoList,
        _ => crate::host::SlotInit::Value(a[1].clone()),
    };
    h.make_always_local(&a[0], init)
}
/// `(--early-declarations--)`: the `defun`/`defmacro` forms whose `declare`
/// was expanded before the prelude's declaration bridge existed, emptied as
/// they are handed over.
fn early_declarations_fn(h: &mut ElispHost, _a: &[Value]) -> R {
    let forms = std::mem::take(&mut h.early_declarations);
    Ok(h.list_from(forms))
}
/// `(--defvar-declare-- SYM)`: what a value-less `(defvar SYM)` does at run
/// time (see `ElispHost::declare_special_locally`). Returns SYM.
fn defvar_declare_fn(h: &mut ElispHost, a: &[Value]) -> R {
    h.declare_special_locally(&a[0]);
    Ok(a[0].clone())
}
/// `(--declare-special SYM)`: set SYM's `declared_special` flag, the part of
/// eval.c `internal--define-uninitialized-variable` that has no Lisp spelling.
fn declare_special_fn(h: &mut ElispHost, a: &[Value]) -> R {
    h.set_special(&a[0]);
    Ok(Value::Undef)
}
fn buffer_local_value_fn(h: &mut ElispHost, a: &[Value]) -> R {
    // BUFFER (a[1]) selects the buffer; default to the current one.
    let idx = match a.get(1) {
        Some(v) if !is_nil(v) => h
            .resolve_buffer(v)
            .ok_or_else(|| format!("wrong-type-argument: bufferp {}", h.print(v, true)))?,
        _ => h.current,
    };
    h.buffer_local_or_default(&a[0], idx)
}
/// `(default-value SYMBOL)` — SYMBOL's default (global) value, ignoring any
/// buffer-local binding. Signals `void-variable` when there is no default.
fn default_value_fn(h: &mut ElispHost, a: &[Value]) -> R {
    h.raw_global_value(&a[0])
}
/// `(set-default SYMBOL VALUE)` — set SYMBOL's default (global) value, bypassing
/// any buffer-local binding. Returns VALUE.
fn set_default_fn(h: &mut ElispHost, a: &[Value]) -> R {
    h.set_raw_global(&a[0], a[1].clone())?;
    Ok(a[1].clone())
}
// ── buffer-local keymap slot ──
fn use_local_map_fn(h: &mut ElispHost, a: &[Value]) -> R {
    h.use_local_map(a[0].clone());
    Ok(Value::Undef)
}
fn current_local_map_fn(h: &mut ElispHost, _a: &[Value]) -> R {
    Ok(h.current_local_map())
}
fn insert_chars(h: &ElispHost, v: &Value) -> Result<Vec<char>, String> {
    if let Some(s) = h.str_text(v) {
        return Ok(s.chars().collect());
    }
    match v {
        Value::Int(n) => Ok(vec![char::from_u32(*n as u32).unwrap_or('\u{fffd}')]),
        _ => Err(format!(
            "wrong-type-argument: char-or-string-p {}",
            h.print(v, true)
        )),
    }
}
fn insert_fn(h: &mut ElispHost, a: &[Value]) -> R {
    for v in a {
        let start = h.cur_buf_ref().point; // 1-based insertion position
        let chars = insert_chars(h, v)?;
        if !chars.is_empty() {
            h.barf_if_read_only()?;
        }
        let n = chars.len();
        h.cur_insert(chars, true);
        // A propertized string carries its intervals into the buffer
        // (`graft_intervals_into_buffer`).
        if let Some(arc) = h.str_arc(v) {
            h.buffer_graft_string_props(&arc, start - 1, n);
        }
    }
    Ok(Value::Undef)
}
/// `--insert-before-markers--`: insert one string/char, relocating markers at the
/// insertion point past the new text (the `insert-before-markers` primitive).
fn insert_before_markers_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let chunks = insert_chars(h, &a[0])?;
    if !chunks.is_empty() {
        h.barf_if_read_only()?;
    }
    h.cur_insert_before_markers(chunks);
    Ok(Value::Undef)
}
fn buffer_string(h: &mut ElispHost, _a: &[Value]) -> R {
    // Only the accessible (narrowed) portion `[begv, zv)`, carrying its text
    // properties (like Emacs `buffer-string`).
    let (begv, zv) = {
        let b = h.cur_buf_ref();
        (b.begv, b.zv)
    };
    let text: String = h.cur_buf_ref().text[(begv - 1)..(zv - 1)].iter().collect();
    let (out, arc) = h.new_string_keyed(text);
    h.string_from_buffer_props(&arc, begv - 1, zv - 1);
    Ok(out)
}
fn buffer_size(h: &mut ElispHost, _a: &[Value]) -> R {
    // The full buffer size, ignoring any narrowing (like Emacs `buffer-size`).
    Ok(Value::Int(h.cur_buf().text.len() as i64))
}
fn point_fn(h: &mut ElispHost, _a: &[Value]) -> R {
    Ok(Value::Int(h.cur_buf().point as i64))
}
fn point_min(h: &mut ElispHost, _a: &[Value]) -> R {
    Ok(Value::Int(h.cur_buf().begv as i64))
}
fn point_max(h: &mut ElispHost, _a: &[Value]) -> R {
    Ok(Value::Int(h.cur_buf().zv as i64))
}
fn goto_char(h: &mut ElispHost, a: &[Value]) -> R {
    let arg = as_int_or_marker(h, &a[0], "integer-or-marker-p")?;
    let buf = h.cur_buf();
    // Point is clamped to the accessible region, but `goto-char` returns its
    // POSITION argument unchanged — the marker object itself when it was given
    // one, not the position that marker held.
    buf.point = arg.clamp(buf.begv as i64, buf.zv as i64) as usize;
    Ok(a[0].clone())
}
/// `(position-bytes POSITION)` (editfns.c): the byte position of POSITION in
/// the whole buffer — the restriction does not apply — or nil outside it.
/// Bytes are counted in the internal UTF-8 encoding.
fn position_bytes(h: &mut ElispHost, a: &[Value]) -> R {
    let pos = fix_position(h, &a[0])?;
    let text = &h.cur_buf_ref().text;
    if !(1 <= pos && pos <= text.len() as i64 + 1) {
        return Ok(Value::Undef);
    }
    let bytes: usize = text[..pos as usize - 1].iter().map(|c| c.len_utf8()).sum();
    Ok(Value::Int(bytes as i64 + 1))
}
/// `(byte-to-position BYTEPOS)` (editfns.c): the character position whose
/// bytes include BYTEPOS, or nil outside the whole buffer.
fn byte_to_position(h: &mut ElispHost, a: &[Value]) -> R {
    let want = as_fixnum_named(h, &a[0], "fixnump")?;
    if want < 1 {
        return Ok(Value::Undef);
    }
    let mut byte = 1i64;
    for (i, c) in h.cur_buf_ref().text.iter().enumerate() {
        let next = byte + c.len_utf8() as i64;
        if want < next {
            return Ok(Value::Int(i as i64 + 1));
        }
        byte = next;
    }
    Ok(if want == byte {
        Value::Int(h.cur_buf_ref().text.len() as i64 + 1)
    } else {
        Value::Undef
    })
}
/// `decode_buffer` (buffer.c): nil is the current buffer; anything else must
/// be a buffer object, live or killed — a buffer NAME is not accepted.
fn decode_buffer(h: &mut ElispHost, v: Option<&Value>) -> Result<usize, String> {
    match v {
        None => Ok(h.current),
        Some(v) if is_nil(v) => Ok(h.current),
        Some(v) => match h.obj(v) {
            Some(Obj::Buffer(idx)) => Ok(*idx),
            _ => Err(h.signal_wrong_type("bufferp", v)),
        },
    }
}
/// `Fbuffer_modified_p`: nil when `SAVE_MODIFF >= MODIFF`, else `autosaved`
/// when the buffer was auto-saved since its last change, else t.
fn buffer_modified_p(h: &mut ElispHost, a: &[Value]) -> R {
    let bi = decode_buffer(h, a.first())?;
    let m = h.buffers[bi].mods;
    Ok(if m.save_modiff >= m.modiff {
        Value::Undef
    } else if m.autosave_modiff == m.modiff {
        h.intern("autosaved")
    } else {
        Value::Bool(true)
    })
}
/// `Frestore_buffer_modified_p`: FLAG nil marks the current buffer unmodified;
/// non-nil makes it modified (advancing `MODIFF` when it was not), and
/// `autosaved` also records it as auto-saved. Answers FLAG.
fn restore_buffer_modified_p(h: &mut ElispHost, a: &[Value]) -> R {
    let flag = a[0].clone();
    let autosaved = h
        .find_symbol("autosaved")
        .is_some_and(|s| h.values_eq(&s, &flag));
    let m = &mut h.cur_buf().mods;
    if is_nil(&flag) {
        m.save_modiff = m.modiff;
    } else {
        if m.save_modiff >= m.modiff {
            m.save_modiff = m.modiff;
            m.incr(1);
        }
        if autosaved {
            m.autosave_modiff = m.modiff;
        }
    }
    Ok(flag)
}
/// `set-buffer-modified-p`: `restore-buffer-modified-p` plus the file-lock and
/// mode-line bookkeeping batch has no use for; it answers nil.
fn set_buffer_modified_p(h: &mut ElispHost, a: &[Value]) -> R {
    restore_buffer_modified_p(h, a)?;
    Ok(Value::Undef)
}
/// `(buffer-modified-tick &optional BUFFER)`: BUFFER's `MODIFF`.
fn buffer_modified_tick(h: &mut ElispHost, a: &[Value]) -> R {
    let bi = decode_buffer(h, a.first())?;
    Ok(Value::Int(h.buffers[bi].mods.modiff))
}
/// `(buffer-chars-modified-tick &optional BUFFER)`: BUFFER's `CHARS_MODIFF`,
/// which text-property changes leave alone.
fn buffer_chars_modified_tick(h: &mut ElispHost, a: &[Value]) -> R {
    let bi = decode_buffer(h, a.first())?;
    Ok(Value::Int(h.buffers[bi].mods.chars_modiff))
}
fn erase_buffer(h: &mut ElispHost, _a: &[Value]) -> R {
    // Delete the whole buffer (ignoring narrowing) and remove the restriction.
    let len = h.cur_buf().text.len();
    if len > 0 {
        h.barf_if_read_only()?;
    }
    h.cur_delete(1, len + 1);
    h.widen();
    h.cur_buf().point = 1;
    Ok(Value::Undef)
}
/// editfns.c `Fchar_after`: POS is `fix_position`ed, so a non-position is
/// `(wrong-type-argument integer-or-marker-p POS)`.
fn char_after(h: &mut ElispHost, a: &[Value]) -> R {
    let arg = match a.first() {
        Some(v) if !is_nil(v) => Some(fix_position(h, v)?),
        _ => None,
    };
    let buf = h.cur_buf();
    let pos = arg.unwrap_or(buf.point as i64);
    // Only positions inside the accessible region `[begv, zv)` hold a char.
    Ok(if pos >= buf.begv as i64 && pos < buf.zv as i64 {
        Value::Int(buf.text[pos as usize - 1] as i64)
    } else {
        Value::Undef
    })
}
/// Shared core of `buffer-substring` (WITH-props) and `-no-properties`. Returns
/// the accessible-region-clamped `[lo, hi)` character range as a fresh string;
/// when `with_props`, the source characters' text properties are copied onto the
/// returned string (registered in the string-property side table).
/// `args_out_of_range_3 (Fcurrent_buffer (), START, END)` — the buffer *object*
/// leads the DATA, so the object is attached rather than rendered and re-read
/// (`#<buffer zb>` has no read syntax).
fn args_out_of_range_in_buffer(h: &mut ElispHost, start: i64, end: i64) -> String {
    let buf = h.current_buffer();
    let sym = h.intern("args-out-of-range");
    let data = h.list_from(vec![buf.clone(), Value::Int(start), Value::Int(end)]);
    let obj = h.cons(sym, data);
    let msg = format!("args-out-of-range: {} {start} {end}", h.print(&buf, true));
    h.set_pending_error(&msg, obj);
    msg
}

fn buffer_substring_core(h: &mut ElispHost, a: &[Value], with_props: bool) -> R {
    let s0 = as_int_or_marker(h, &a[0], "integer-or-marker-p")?;
    let e0 = as_int_or_marker(h, &a[1], "integer-or-marker-p")?;
    let buf = h.cur_buf_ref();
    let (lo0, hi0) = (buf.begv as i64, buf.zv as i64);
    // `validate_region`: swap first, then reject anything outside the accessible
    // portion. Clamping instead silently answered the whole buffer for
    // `(buffer-substring 1 999)`, where Emacs signals.
    let (lo, hi) = if s0 <= e0 { (s0, e0) } else { (e0, s0) };
    if lo < lo0 || hi > hi0 {
        return Err(args_out_of_range_in_buffer(h, s0, e0));
    }
    let text: String = buf.text[(lo - 1) as usize..(hi - 1) as usize]
        .iter()
        .collect();
    let (out, arc) = h.new_string_keyed(text);
    if with_props {
        // Copy the covered per-char plists (offset to the substring's indices).
        let plists: Vec<Value> = ((lo - 1) as usize..(hi - 1) as usize)
            .map(|i| {
                h.cur_buf_ref()
                    .props
                    .get(i)
                    .cloned()
                    .unwrap_or(Value::Undef)
            })
            .collect();
        if plists.iter().any(|p| !is_nil(p)) {
            let plists = h.copy_plist_runs(plists);
            h.string_set_props_vec(&arc, plists);
        }
    }
    Ok(out)
}
fn buffer_substring(h: &mut ElispHost, a: &[Value]) -> R {
    buffer_substring_core(h, a, true)
}
fn buffer_substring_no_properties(h: &mut ElispHost, a: &[Value]) -> R {
    buffer_substring_core(h, a, false)
}

// ── markers ──────────────────────────────────────────────────────────────
fn make_marker(h: &mut ElispHost, _a: &[Value]) -> R {
    Ok(h.alloc_marker(None, 0, false))
}
/// Port of `Finsert_buffer_substring` (editfns.c): insert BUFFER's text from
/// START to END (default its accessible region), with its text properties,
/// before point in the current buffer.
fn insert_buffer_substring(h: &mut ElispHost, a: &[Value]) -> R {
    let Some(bi) = h.get_buffer(&a[0])? else {
        return Err(h.nsberror(&a[0]));
    };
    if h.buffers[bi].name.is_none() {
        return Err("error: Selecting deleted buffer".to_string());
    }
    let (begv, zv) = (h.buffers[bi].begv as i64, h.buffers[bi].zv as i64);
    let b = match a.get(1) {
        Some(v) if !is_nil(v) => fix_position(h, v)?,
        _ => begv,
    };
    let e = match a.get(2) {
        Some(v) if !is_nil(v) => fix_position(h, v)?,
        _ => zv,
    };
    let (lo, hi) = if b > e { (e, b) } else { (b, e) };
    if !(begv <= lo && hi <= zv) {
        let data = vec![
            a.get(1).cloned().unwrap_or(Value::Undef),
            a.get(2).cloned().unwrap_or(Value::Undef),
        ];
        return Err(args_out_of_range_values(h, data));
    }
    let cur = h.current;
    h.current = bi;
    let text = buffer_substring_core(h, &[Value::Int(lo), Value::Int(hi)], true);
    h.current = cur;
    insert_fn(h, &[text?])?;
    Ok(Value::Undef)
}
/// `(point-min-marker)` / `(point-max-marker)`: a marker at the edge of the
/// accessible region.
fn point_min_marker(h: &mut ElispHost, _a: &[Value]) -> R {
    let (bi, p) = (h.current, h.cur_buf_ref().begv);
    Ok(h.alloc_marker(Some(bi), p, false))
}
fn point_max_marker(h: &mut ElispHost, _a: &[Value]) -> R {
    let (bi, p) = (h.current, h.cur_buf_ref().zv);
    Ok(h.alloc_marker(Some(bi), p, false))
}
/// Port of `Fdelete_and_extract_region` (editfns.c): delete START..END and
/// answer the deleted text, text properties included.
fn delete_and_extract_region(h: &mut ElispHost, a: &[Value]) -> R {
    let (lo, hi) = validate_region(h, &a[0], &a[1])?;
    if lo == hi {
        return Ok(h.new_string(String::new()));
    }
    let text = buffer_substring_core(h, &[Value::Int(lo as i64), Value::Int(hi as i64)], true)?;
    h.barf_if_read_only()?;
    h.cur_delete(lo, hi);
    Ok(text)
}
fn point_marker(h: &mut ElispHost, _a: &[Value]) -> R {
    let p = h.cur_buf_ref().point;
    let bi = h.current;
    Ok(h.alloc_marker(Some(bi), p, false))
}
fn markerp_fn(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(nil_or(h.is_marker(&a[0])))
}
fn require_marker(h: &ElispHost, v: &Value) -> Result<(), String> {
    if h.is_marker(v) {
        Ok(())
    } else {
        Err(format!("wrong-type-argument: markerp {}", h.print(v, true)))
    }
}
fn marker_position_fn(h: &mut ElispHost, a: &[Value]) -> R {
    require_marker(h, &a[0])?;
    Ok(match h.marker_position(&a[0]) {
        Some(p) => Value::Int(p as i64),
        None => Value::Undef,
    })
}
fn marker_buffer_fn(h: &mut ElispHost, a: &[Value]) -> R {
    require_marker(h, &a[0])?;
    Ok(h.marker_buffer(&a[0]).unwrap_or(Value::Undef))
}
fn marker_insertion_type_fn(h: &mut ElispHost, a: &[Value]) -> R {
    require_marker(h, &a[0])?;
    Ok(nil_or(h.marker_insertion_type(&a[0]).unwrap_or(false)))
}
fn set_marker_insertion_type_fn(h: &mut ElispHost, a: &[Value]) -> R {
    require_marker(h, &a[0])?;
    h.set_marker_insertion_type(&a[0], !is_nil(&a[1]));
    Ok(a[1].clone())
}
/// `(set-marker MARKER POSITION &optional BUFFER)` / `move-marker`.
fn set_marker_fn(h: &mut ElispHost, a: &[Value]) -> R {
    require_marker(h, &a[0])?;
    let pos_arg = a.get(1).cloned().unwrap_or(Value::Undef);
    if is_nil(&pos_arg) {
        h.set_marker_to(&a[0], None, 0)?;
        return Ok(a[0].clone());
    }
    let pos = as_int(h, &pos_arg)?;
    let bi = match a.get(2) {
        Some(v) if !is_nil(v) => h
            .resolve_buffer(v)
            .ok_or("error: Marker does not point anywhere")?,
        _ => h.current,
    };
    h.set_marker_to(&a[0], Some(bi), pos.max(1) as usize)?;
    Ok(a[0].clone())
}
/// `(copy-marker &optional POSITION TYPE)`.
fn copy_marker_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let itype = a.get(1).is_some_and(|v| !is_nil(v));
    let arg = a.first().cloned().unwrap_or(Value::Undef);
    if is_nil(&arg) {
        return Ok(h.alloc_marker(None, 0, itype));
    }
    if h.is_marker(&arg) {
        // Copy the source marker's buffer + position (detached when it is).
        if let (Some(p), Some(bufv)) = (h.marker_position(&arg), h.marker_buffer(&arg)) {
            let bi = h.resolve_buffer(&bufv).unwrap_or(h.current);
            return Ok(h.alloc_marker(Some(bi), p, itype));
        }
        return Ok(h.alloc_marker(None, 0, itype));
    }
    let pos = as_int(h, &arg)?;
    let bi = h.current;
    let size = h.cur_buf_ref().text.len();
    let p = (pos.max(1) as usize).min(size + 1);
    Ok(h.alloc_marker(Some(bi), p, itype))
}

// ── text properties ────────────────────────────────────────────────────────
/// A text-property OBJECT arg: a string (its Arc) or a buffer slot index.
/// `nil`/absent is the current buffer.
enum PropObj {
    Str(std::sync::Arc<String>),
    Buf(usize),
}
fn prop_object(h: &ElispHost, obj: Option<&Value>) -> Result<PropObj, String> {
    match obj {
        Some(v) if h.is_string(v) => Ok(PropObj::Str(h.str_arc(v).expect("checked stringp"))),
        None | Some(Value::Undef) | Some(Value::Bool(false)) => Ok(PropObj::Buf(h.current)),
        Some(v) => match h.resolve_buffer(v) {
            Some(bi) => Ok(PropObj::Buf(bi)),
            // Emacs's text-property fns validate OBJECT with `buffer-or-string-p`
            // (textprop.c validate_interval_range), not plain `bufferp`.
            None => Err(format!(
                "wrong-type-argument: buffer-or-string-p {}",
                h.print(v, true)
            )),
        },
    }
}
/// The plist at POS in OBJECT, validating range like Emacs (string idx `[0,len]`,
/// buffer pos `[begv,zv]`; the upper bound yields nil, past it errors).
fn plist_at_pos(h: &ElispHost, obj: &PropObj, pos: i64) -> Result<Value, String> {
    match obj {
        PropObj::Str(s) => {
            let len = s.chars().count() as i64;
            if pos < 0 || pos > len {
                return Err(format!("args-out-of-range: {pos} {pos}"));
            }
            if pos == len {
                return Ok(Value::Undef);
            }
            Ok(h.string_plist_at(s, pos as usize))
        }
        PropObj::Buf(bi) => {
            let (begv, zv) = h.buffer_begv_zv(*bi);
            if pos < begv as i64 || pos > zv as i64 {
                return Err(format!("args-out-of-range: {pos} {pos}"));
            }
            if pos == zv as i64 {
                return Ok(Value::Undef);
            }
            Ok(h.buffer_plist_at_idx(*bi, (pos - 1) as usize))
        }
    }
}
fn get_text_property_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let pos = as_int(h, &a[0])?;
    let obj = prop_object(h, a.get(2))?;
    let plist = plist_at_pos(h, &obj, pos)?;
    Ok(h.plist_get_eq(&plist, &a[1]))
}
fn text_properties_at_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let pos = as_int(h, &a[0])?;
    let obj = prop_object(h, a.get(1))?;
    plist_at_pos(h, &obj, pos)
}
/// Convert a text-property START/END pair to `(lo0, hi0)` character indices
/// (0-based, half-open) for OBJECT: strings index from 0, buffers from `begv`.
fn prop_range(
    obj: &PropObj,
    start: i64,
    end: i64,
    h: &ElispHost,
) -> Result<(usize, usize), String> {
    // validate_interval_range: START and END are swapped into order first, and
    // the error names them in that order.
    let (lo, hi) = if start <= end {
        (start, end)
    } else {
        (end, start)
    };
    let (min, max, base) = match obj {
        PropObj::Str(s) => (0, s.chars().count() as i64, 0),
        PropObj::Buf(bi) => {
            let (begv, zv) = h.buffer_begv_zv(*bi);
            (begv as i64, zv as i64, 1)
        }
    };
    if lo < min || hi > max {
        return Err(format!("args-out-of-range: {lo} {hi}"));
    }
    Ok(((lo - base) as usize, (hi - base) as usize))
}
/// Run `f` with the current buffer temporarily set to `bi` (restored after).
fn with_buffer<T>(h: &mut ElispHost, bi: usize, f: impl FnOnce(&mut ElispHost) -> T) -> T {
    let saved = h.current;
    h.current = bi;
    let r = f(h);
    h.current = saved;
    r
}
fn put_text_property_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let start = as_int(h, &a[0])?;
    let end = as_int(h, &a[1])?;
    let (prop, val) = (a[2].clone(), a[3].clone());
    let obj = prop_object(h, a.get(4))?;
    let (lo, hi) = prop_range(&obj, start, end, h)?;
    let changed = props_would_change(h, &obj, lo, hi, &[(prop.clone(), val.clone())], true);
    match obj {
        PropObj::Str(s) => h.string_put_prop(&s, lo, hi, &prop, &val),
        PropObj::Buf(bi) => {
            if changed {
                let pair = [(prop.clone(), val.clone())];
                record_prop_undo(h, bi, lo, hi, PropUndo::Add(&pair));
            }
            with_buffer(h, bi, |h| h.buffer_put_prop(lo, hi, &prop, &val));
            if changed {
                h.note_prop_change(bi);
            }
        }
    }
    Ok(Value::Undef)
}
fn set_text_properties_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let start = as_int(h, &a[0])?;
    let end = as_int(h, &a[1])?;
    let plist = a[2].clone();
    let obj = prop_object(h, a.get(3))?;
    let (lo, hi) = prop_range(&obj, start, end, h)?;
    // textprop.c `set_text_properties`: an empty range, or an object with no
    // intervals at all and nil PROPERTIES, returns nil without touching
    // anything; otherwise t. A buffer keeps its interval tree after its
    // properties are removed, until all of its text is deleted.
    let has_props = |h: &ElispHost| match &obj {
        PropObj::Str(s) => h
            .string_props_vec(s)
            .is_some_and(|v| v.iter().any(|p| !is_nil(p))),
        PropObj::Buf(bi) => h.buffers[*bi].has_intervals,
    };
    if lo == hi {
        return Ok(Value::Undef);
    }
    if is_nil(&plist) && !has_props(h) {
        return Ok(Value::Undef);
    }
    match obj {
        PropObj::Str(s) => h.string_set_props(&s, lo, hi, &plist),
        PropObj::Buf(bi) => {
            record_prop_undo(h, bi, lo, hi, PropUndo::Set(&plist));
            with_buffer(h, bi, |h| h.buffer_set_props(lo, hi, &plist));
            if lo < hi {
                h.note_prop_change(bi);
            }
        }
    }
    Ok(Value::Bool(true))
}
/// Apply each `(prop val)` pair of PROPS via `f` (for add/remove).
fn each_prop_pair(h: &ElispHost, props: &Value) -> Vec<(Value, Value)> {
    let mut out = Vec::new();
    let mut cur = props.clone();
    while let Some(Obj::Cons(k, d)) = h.obj(&cur) {
        let k = k.clone();
        let rest = d.clone();
        match h.obj(&rest) {
            Some(Obj::Cons(v, d2)) => {
                out.push((k, v.clone()));
                cur = d2.clone();
            }
            _ => break,
        }
    }
    out
}
/// The value PROP has in PLIST (`eq` keys), or `None` when PROP is absent —
/// a present nil value is `Some`.
fn plist_lookup(h: &ElispHost, plist: &Value, prop: &Value) -> Option<Value> {
    let mut cur = plist.clone();
    while let Some(Obj::Cons(k, d)) = h.obj(&cur) {
        let (k, d) = (k.clone(), d.clone());
        let Some(Obj::Cons(v, rest)) = h.obj(&d) else {
            return None;
        };
        if h.values_eq(&k, prop) {
            return Some(v.clone());
        }
        cur = rest.clone();
    }
    None
}
/// Whether any character in `[lo, hi)` of OBJ would change: textprop.c
/// `add_properties` (PROP absent or not `eq` to its new value) when ADD,
/// `remove_properties` (PROP present at all) otherwise. Their callers
/// return t exactly when this holds.
fn props_would_change(
    h: &ElispHost,
    obj: &PropObj,
    lo: usize,
    hi: usize,
    pairs: &[(Value, Value)],
    add: bool,
) -> bool {
    (lo..hi).any(|i| {
        let plist = match obj {
            PropObj::Str(s) => h.string_plist_at(s, i),
            PropObj::Buf(bi) => h.buffer_plist_at_idx(*bi, i),
        };
        pairs
            .iter()
            .any(|(prop, val)| match plist_lookup(h, &plist, prop) {
                Some(old) => !add || !h.values_eq(&old, val),
                None => add,
            })
    })
}
fn add_text_properties_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let start = as_int(h, &a[0])?;
    let end = as_int(h, &a[1])?;
    let obj = prop_object(h, a.get(3))?;
    let (lo, hi) = prop_range(&obj, start, end, h)?;
    let pairs = each_prop_pair(h, &a[2]);
    let changed = props_would_change(h, &obj, lo, hi, &pairs, true);
    match &obj {
        PropObj::Str(s) => {
            h.string_add_props(s, lo, hi, &pairs, crate::textprop::SetType::Replace);
        }
        PropObj::Buf(bi) => {
            let bi = *bi;
            record_prop_undo(h, bi, lo, hi, PropUndo::Add(&pairs));
            with_buffer(h, bi, |h| {
                h.buffer_add_props(lo, hi, &pairs, crate::textprop::SetType::Replace)
            });
        }
    }
    if let (true, PropObj::Buf(bi)) = (changed, &obj) {
        h.note_prop_change(*bi);
    }
    Ok(Value::Bool(changed))
}
fn remove_text_properties_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let start = as_int(h, &a[0])?;
    let end = as_int(h, &a[1])?;
    let obj = prop_object(h, a.get(3))?;
    let (lo, hi) = prop_range(&obj, start, end, h)?;
    let pairs = each_prop_pair(h, &a[2]);
    let changed = props_would_change(h, &obj, lo, hi, &pairs, false);
    match &obj {
        PropObj::Str(s) => {
            let names: Vec<Value> = pairs.iter().map(|(k, _)| k.clone()).collect();
            h.string_remove_props(s, lo, hi, &names);
        }
        PropObj::Buf(bi) => {
            let bi = *bi;
            let names: Vec<Value> = pairs.iter().map(|(k, _)| k.clone()).collect();
            record_prop_undo(h, bi, lo, hi, PropUndo::Remove(&names));
            with_buffer(h, bi, |h| h.buffer_remove_props(lo, hi, &names));
        }
    }
    if let (true, PropObj::Buf(bi)) = (changed, &obj) {
        h.note_prop_change(*bi);
    }
    Ok(Value::Bool(changed))
}
/// `(elisprs--replace-chars-in-place START END STRING)`: overwrite the text
/// from START to END with STRING's characters when it has exactly as many,
/// leaving text properties, markers and point where they are — what casefiddle.c
/// and `subst-char-in-region` do to the buffer through `modify_text`, which
/// counts one change of END - START characters. Answers nil, changing nothing,
/// when the lengths differ, so the Lisp caller can fall back to delete and
/// insert. An elisprs-internal primitive: Emacs does this in C.
fn replace_chars_in_place_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let (lo, hi) = validate_region(h, &a[0], &a[1])?;
    let new: Vec<char> = as_string(h, &a[2])?.chars().collect();
    if new.len() != hi - lo {
        return Ok(Value::Undef);
    }
    if lo < hi {
        h.barf_if_read_only()?;
        h.record_change(lo, hi - lo);
        h.note_text_change(hi - lo);
        h.cur_buf().text[lo - 1..hi - 1].copy_from_slice(&new);
    }
    Ok(Value::Bool(true))
}
/// `(transpose-regions STARTR1 ENDR1 STARTR2 ENDR2 &optional LEAVE-MARKERS)` —
/// editfns.c `Ftranspose_regions`. The span from the first region's start to
/// the second's end keeps its length: it becomes region 2, the text between,
/// region 1, each carrying its own text properties. Unless LEAVE-MARKERS,
/// point and every marker move with the text they were in
/// (`transpose_markers`); overlays are not moved.
///
/// Not followed: the before/after-change hooks and the undo record.
fn transpose_regions_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let (mut start1, mut end1) = validate_region(h, &a[0], &a[1])?;
    let (mut start2, mut end2) = validate_region(h, &a[2], &a[3])?;
    let (arg_start1, arg_end2) = (start1, end2);
    let leave_markers = a.get(4).is_some_and(|v| !is_nil(v));
    if start2 < end1 {
        std::mem::swap(&mut start1, &mut start2);
        std::mem::swap(&mut end1, &mut end2);
    }
    if start2 < end1 {
        return Err("error: Transposed regions overlap".to_string());
    }
    if (start1 == end1 || start2 == end2) && end1 == start2 {
        return Ok(Value::Undef);
    }
    h.barf_if_read_only()?;
    let (len1, len2) = (end1 - start1, end2 - start2);
    // The undo records: equal lengths are two changes, unless the regions
    // touch; otherwise one change over the whole span.
    if len1 == len2 && end1 != start2 {
        h.record_change(start1, len1);
        h.record_change(start2, len2);
    } else {
        h.record_change(start1, end2 - start1);
    }
    h.note_text_change(end2 - start1);
    // 0-based: region 1 [s1, e1), the text between [e1, s2), region 2 [s2, e2).
    let (s1, e1, s2, e2) = (start1 - 1, end1 - 1, start2 - 1, end2 - 1);
    // Where a 0-based position inside the span lands, as transpose_markers
    // computes it for a marker.
    let moved = |p: usize| {
        if p < s1 || p >= e2 {
            p
        } else if p < e1 {
            p + (e2 - s2) + (s2 - e1)
        } else if p < s2 {
            p + (e2 - s2) - (e1 - s1)
        } else {
            p - ((e1 - s1) + (s2 - e1))
        }
    };
    fn rearrange<T: Clone>(v: &mut Vec<T>, s1: usize, e1: usize, s2: usize, e2: usize) {
        let mut span: Vec<T> = v[s2..e2].to_vec();
        span.extend_from_slice(&v[e1..s2]);
        span.extend_from_slice(&v[s1..e1]);
        v.splice(s1..e2, span);
    }
    let b = h.cur_buf();
    rearrange(&mut b.text, s1, e1, s2, e2);
    rearrange(&mut b.props, s1, e1, s2, e2);
    // Intervals are positional: a boundary stays where it is while the text
    // moves under it. The C first clears the properties of the regions (when
    // they have equal lengths) or of the range from the FIRST argument pair's
    // start to the SECOND pair's end, as passed — the swap above does not
    // reach that call — and `set_text_properties_1` merges each cleared range
    // into one interval. It then grafts each piece's own intervals onto its
    // new place, splitting at the piece's edges.
    if b.has_intervals {
        let cleared: Vec<(usize, usize)> = if len1 == len2 {
            vec![(s1, e1), (s2, e2)]
        } else {
            vec![(arg_start1.min(arg_end2) - 1, arg_start1.max(arg_end2) - 1)]
        };
        let inside_cleared = |p: usize| cleared.iter().any(|&(lo, hi)| p > lo && p < hi);
        let mut bounds: Vec<u32> = b
            .prop_bounds
            .iter()
            .copied()
            .filter(|&p| !inside_cleared(p as usize))
            .collect();
        let mut split = |p: usize| bounds.push(p as u32);
        for &(lo, hi) in &cleared {
            split(lo);
            split(hi);
        }
        let mut pieces = vec![(s2, e2, s1), (s1, e1, e2 - len1)];
        if len1 != len2 {
            pieces.push((e1, s2, s1 + len2));
        }
        for (from, to, at) in pieces {
            split(at);
            split(at + (to - from));
            for &p in &b.prop_bounds {
                let p = p as usize;
                if p > from && p < to {
                    split(p - from + at);
                }
            }
        }
        bounds.retain(|&p| p != 0 && (p as usize) < b.text.len());
        bounds.sort_unstable();
        bounds.dedup();
        b.prop_bounds = bounds;
    }
    if !leave_markers {
        let pt = b.point - 1;
        b.point = moved(pt) + 1;
        for mk in &b.markers {
            let mut md = mk.borrow_mut();
            md.pos = moved(md.pos - 1) + 1;
        }
    }
    Ok(Value::Undef)
}
/// `(elisprs--carry-text-properties SRC DST)` — DST with SRC's per-character
/// text properties, when the two are the same length.
///
/// Emacs exposes no such function: its case and trimming primitives are written
/// in C and copy intervals internally. The ones written in elisp here — mainly
/// `capitalize`, which rebuilds its result character by character — need a way
/// to say the same thing, so this is an elisprs-internal primitive rather than
/// an Emacs one. Returns DST unchanged when the lengths differ or SRC has no
/// properties.
fn carry_text_properties_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let (Some(src), Some(dst)) = (h.str_arc(&a[0]), h.str_arc(&a[1])) else {
        return Ok(a[1].clone());
    };
    if src.chars().count() == dst.chars().count() {
        h.string_carry_all(&dst, &src);
    }
    Ok(a[1].clone())
}

/// `(propertize STRING &rest PROPS)` — a fresh copy of STRING carrying PROPS.
fn propertize_fn(h: &mut ElispHost, a: &[Value]) -> R {
    // Fpropertize: STRING plus PROP VALUE pairs; an even count is a stray PROP.
    if a.len().is_multiple_of(2) {
        let name = h.intern("propertize");
        return Err(h.signal_wrong_nargs_subject(name, a.len()));
    }
    let base = as_string(h, &a[0])?;
    let len = base.chars().count();
    let (out, arc) = h.new_string_keyed(base);
    // The plist is consed pair by pair from the last argument to the first, and
    // a property named twice keeps its first position with the earlier-in-the-
    // call value (`add_properties` overwrites in place).
    let mut flat: Vec<(Value, Value)> = Vec::new();
    for pair in a[1..].chunks(2).rev() {
        match flat.iter_mut().find(|(k, _)| el_eq(h, k, &pair[0])) {
            Some(slot) => slot.1 = pair[1].clone(),
            None => flat.insert(0, (pair[0].clone(), pair[1].clone())),
        }
    }
    if !flat.is_empty() {
        let items = flat.into_iter().flat_map(|(k, v)| [k, v]).collect();
        let plist = h.list_from(items);
        h.string_set_props(&arc, 0, len, &plist);
    }
    Ok(out)
}
/// Port of `fix_position` (editfns.c): an integer or marker as a buffer
/// position. A bignum is accepted and pinned to the fixnum range in its
/// direction, so it reaches the caller's range check and is reported there as
/// out of range rather than as the wrong type.
fn fix_position(h: &mut ElispHost, v: &Value) -> Result<i64, String> {
    if let Some(Obj::Bignum(b)) = h.obj(v) {
        return Ok(if b.sign() == num_bigint::Sign::Minus {
            -MOST_POSITIVE_FIXNUM - 1
        } else {
            MOST_POSITIVE_FIXNUM
        });
    }
    as_int_or_marker(h, v, "integer-or-marker-p")
}
/// Signal `(args-out-of-range ...DATA)` with DATA's objects as given.
fn args_out_of_range_values(h: &mut ElispHost, data: Vec<Value>) -> String {
    let sym = h.intern("args-out-of-range");
    let rendered: Vec<String> = data.iter().map(|v| h.print(v, true)).collect();
    let data = h.list_from(data);
    let obj = h.cons(sym, data);
    let msg = format!("args-out-of-range: {}", rendered.join(" "));
    h.set_pending_error(&msg, obj);
    msg
}
/// Port of `validate_region` (buffer.c): START and END in either order, both
/// inside the accessible portion, or `(args-out-of-range BUFFER START END)`.
pub(crate) fn validate_region(
    h: &mut ElispHost,
    b: &Value,
    e: &Value,
) -> Result<(usize, usize), String> {
    let (s0, e0) = (fix_position(h, b)?, fix_position(h, e)?);
    let (lo, hi) = if e0 < s0 { (e0, s0) } else { (s0, e0) };
    let buf = h.cur_buf_ref();
    if !(buf.begv as i64 <= lo && hi <= buf.zv as i64) {
        let cur = h.current_buffer();
        return Err(args_out_of_range_values(h, vec![cur, b.clone(), e.clone()]));
    }
    Ok((lo as usize, hi as usize))
}
pub(crate) fn delete_region(h: &mut ElispHost, a: &[Value]) -> R {
    let (lo, hi) = validate_region(h, &a[0], &a[1])?;
    if lo < hi {
        h.barf_if_read_only()?;
    }
    h.cur_delete(lo, hi);
    Ok(Value::Undef)
}
fn insert_file_contents(h: &mut ElispHost, a: &[Value]) -> R {
    let raw = as_string(h, &a[0])?;
    let mut file = std::fs::File::open(fs_expand(&raw))
        .map_err(|e| report_file_errno(h, "Opening input file", &[&raw], &e))?;
    let mut content = String::new();
    std::io::Read::read_to_string(&mut file, &mut content)
        .map_err(|e| report_file_errno(h, "Read error", &[&raw], &e))?;
    let chars: Vec<char> = content.chars().collect();
    let n = chars.len() as i64;
    h.cur_insert(chars, false); // leaves point at the beginning of the inserted text
    let raw = h.new_string(raw);
    Ok(h.list_from(vec![raw, Value::Int(n)]))
}

// ── buffer motion ──
/// Move point by DELTA characters, faithful to `Fforward_char` (cmds.c): on
/// overshoot, point is set to the boundary (BEGV/ZV) *and* the corresponding
/// `beginning-of-buffer`/`end-of-buffer` condition is signaled.
fn move_point_by(h: &mut ElispHost, delta: i64) -> R {
    let buf = h.cur_buf();
    let target = buf.point as i64 + delta;
    if target < buf.begv as i64 {
        buf.point = buf.begv;
        return Err("beginning-of-buffer".to_string());
    }
    if target > buf.zv as i64 {
        buf.point = buf.zv;
        return Err("end-of-buffer".to_string());
    }
    buf.point = target as usize;
    Ok(Value::Undef)
}
fn forward_char(h: &mut ElispHost, a: &[Value]) -> R {
    let n = match a.first() {
        Some(v) if !is_nil(v) => as_fixnum_named(h, v, "fixnump")?,
        _ => 1,
    };
    move_point_by(h, n)
}
fn backward_char(h: &mut ElispHost, a: &[Value]) -> R {
    let n = match a.first() {
        Some(v) if !is_nil(v) => as_fixnum_named(h, v, "fixnump")?,
        _ => 1,
    };
    move_point_by(h, -n)
}
/// Port of `find_newline` (search.c) over the accessible region: scan from
/// START towards the limit for COUNT newlines (backwards when COUNT < 0).
///
/// Answers the position just past the COUNT-th newline found — in either
/// direction, `find_newline` lands AFTER the newline — or the limit (`zv`
/// forwards, `begv` backwards) when there are fewer. The second value is the
/// number found, negative when scanning backwards, like `*counted`.
fn find_newline(t: &[char], start: usize, count: i64, begv: usize, zv: usize) -> (usize, i64) {
    let mut p = start;
    let mut found = 0i64;
    if count > 0 {
        while p < zv {
            p += 1;
            if t[p - 2] == '\n' {
                found += 1;
                if found == count {
                    return (p, found);
                }
            }
        }
        (zv, found)
    } else {
        while p > begv {
            if t[p - 2] == '\n' {
                found += 1;
                if found == -count {
                    return (p, -found);
                }
            }
            p -= 1;
        }
        (begv, -found)
    }
}
/// Port of `scan_newline_from_point`: COUNT <= 0 scans back for `1 - COUNT`
/// newlines, so 0 is the start of point's own line.
fn scan_newline_from_point(buf: &crate::host::EditBuffer, count: i64) -> (usize, i64) {
    let cnt = if count <= 0 { count - 1 } else { count };
    find_newline(&buf.text, buf.point, cnt, buf.begv, buf.zv)
}
/// An optional line-count argument: nil is DEFAULT, a fixnum is taken as is, and
/// a bignum stands for "more lines than any buffer has" in its direction, as
/// `bol`/`eol` clip it to `BUF_BYTES_MAX`. Anything else is not an integer.
fn line_count_arg(h: &ElispHost, a: &[Value], default: i64) -> Result<i64, String> {
    const HUGE: i64 = i64::MAX / 4;
    match a.first() {
        None => Ok(default),
        Some(v) if is_nil(v) => Ok(default),
        Some(v) => match h.obj(v) {
            Some(Obj::Bignum(b)) => Ok(if b.sign() == num_bigint::Sign::Minus {
                -HUGE
            } else {
                HUGE
            }),
            _ => as_integer(h, v),
        },
    }
}
/// Port of `bol` (editfns.c): the start of the line N - 1 lines from point's.
fn bol_n(h: &mut ElispHost, a: &[Value]) -> Result<usize, String> {
    let n = line_count_arg(h, a, 1)?;
    Ok(scan_newline_from_point(h.cur_buf(), n.saturating_sub(1)).0)
}
/// Port of `eol` (editfns.c) via `find_before_next_newline`: the end of the
/// line N - 1 lines from point's. A scan that found every newline it wanted
/// stops ON the last one; a short scan stops at the limit.
fn eol_n(h: &mut ElispHost, a: &[Value]) -> Result<usize, String> {
    let n = line_count_arg(h, a, 1)?;
    let cnt = n - (n <= 0) as i64;
    let buf = h.cur_buf();
    let (pos, counted) = find_newline(&buf.text, buf.point, cnt, buf.begv, buf.zv);
    Ok(if counted == cnt { pos - 1 } else { pos })
}
/// cmds.c `Fbeginning_of_line` / `Fend_of_line`: N nil is 1, anything else
/// must be a fixnum.
fn check_line_motion_arg(h: &mut ElispHost, a: &[Value]) -> Result<(), String> {
    match a.first() {
        Some(v) if !is_nil(v) => as_fixnum_named(h, v, "fixnump").map(|_| ()),
        _ => Ok(()),
    }
}
fn beginning_of_line(h: &mut ElispHost, a: &[Value]) -> R {
    check_line_motion_arg(h, a)?;
    let p = bol_n(h, a)?;
    h.cur_buf().point = p;
    Ok(Value::Undef)
}
fn end_of_line(h: &mut ElispHost, a: &[Value]) -> R {
    check_line_motion_arg(h, a)?;
    let p = eol_n(h, a)?;
    h.cur_buf().point = p;
    Ok(Value::Undef)
}
fn line_beginning_position(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(Value::Int(bol_n(h, a)? as i64))
}
fn line_end_position(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(Value::Int(eol_n(h, a)? as i64))
}
fn bolp(h: &mut ElispHost, _a: &[Value]) -> R {
    let buf = h.cur_buf();
    Ok(nil_or(
        buf.point == buf.begv || buf.text[buf.point - 2] == '\n',
    ))
}
fn eolp(h: &mut ElispHost, _a: &[Value]) -> R {
    let buf = h.cur_buf();
    Ok(nil_or(
        buf.point == buf.zv || buf.text[buf.point - 1] == '\n',
    ))
}
fn bobp(h: &mut ElispHost, _a: &[Value]) -> R {
    let buf = h.cur_buf();
    Ok(nil_or(buf.point == buf.begv))
}
fn eobp(h: &mut ElispHost, _a: &[Value]) -> R {
    let buf = h.cur_buf();
    Ok(nil_or(buf.point == buf.zv))
}
fn forward_line(h: &mut ElispHost, a: &[Value]) -> R {
    // Port of `Fforward_line` (cmds.c).
    let count = line_count_arg(h, a, 1)?;
    let buf = h.cur_buf();
    let opoint = buf.point;
    let (pos, counted) = scan_newline_from_point(buf, count);
    buf.point = pos;
    let mut shortage = count - (count <= 0) as i64 - counted;
    if shortage != 0 {
        // A non-empty last line counts as a line moved across.
        shortage -= if count <= 0 {
            -1
        } else {
            (buf.begv < buf.zv && pos != opoint && buf.text[pos - 2] != '\n') as i64
        };
    }
    // A bignum N was scanned as a clipped COUNT; report against N itself.
    match a.first().and_then(|v| h.obj(v)).and_then(|o| match o {
        Obj::Bignum(b) => Some(b.clone()),
        _ => None,
    }) {
        Some(n) => Ok(h.make_integer(n + (shortage - count))),
        None => Ok(Value::Int(shortage)),
    }
}

// ── buffer search (sets buffer-position match data) ──
/// Record SPANS (0-based buffer offsets) as a match in the current buffer, which
/// becomes `last_thing_searched`.
fn set_buf_match(h: &mut ElispHost, spans0: &[Option<(usize, usize)>]) {
    let spans = spans0
        .iter()
        .map(|o| o.map(|(b, e)| (b + 1, e + 1)))
        .collect();
    h.match_data = Some(MatchData {
        subject: String::new(),
        spans,
        from_buffer: true,
        buffer: Some(h.current),
    });
}
/// The four search commands, driven COUNT times — a port of `search_command`
/// (search.c).
///
/// COUNT is not a decoration: `(search-forward "a" nil t 2)` finds the SECOND
/// occurrence, COUNT 0 searches not at all and answers point, and a NEGATIVE
/// COUNT searches the other way — `search-forward` with -1 is a backward
/// search.
///
/// BOUND must lie on the side of point the search goes (`Invalid search
/// bound`), and is then clipped to the accessible region; the search never
/// looks outside that region, narrowed or not.
///
/// Failure is per `search_command`: with NOERROR nil it signals; with NOERROR
/// `t` it answers nil and leaves point WHERE IT WAS; with any other non-nil
/// NOERROR it answers nil and moves point to the limit.
fn search_with_count(
    h: &mut ElispHost,
    a: &[Value],
    forward: bool,
    fwd: SearchStep,
    bwd: SearchStep,
) -> R {
    let noerror = a.get(2).cloned().unwrap_or(Value::Undef);
    let count = match a.get(3) {
        Some(v) if !is_nil(v) => as_fixnum_named(h, v, "fixnump")?,
        _ => 1,
    };
    let n = if forward { count } else { -count };
    let pat = as_string(h, &a[0])?;
    let (point, begv, zv) = {
        let b = h.cur_buf_ref();
        (b.point, b.begv, b.zv)
    };
    let lim = match a.get(1) {
        Some(v) if !is_nil(v) => {
            let lim = fix_position(h, v)?;
            if if n > 0 {
                lim < point as i64
            } else {
                lim > point as i64
            } {
                return Err("error: Invalid search bound (wrong side of point)".to_string());
            }
            lim.clamp(begv as i64, zv as i64) as usize
        }
        _ if n > 0 => zv,
        _ => begv,
    };
    if n == 0 {
        return Ok(Value::Int(point as i64));
    }
    let step = if count > 0 { fwd } else { bwd };
    let mut last = None;
    for _ in 0..count.unsigned_abs() {
        match step(h, &pat, lim)? {
            Some(p) => last = Some(p),
            None => {
                h.cur_buf().point = point;
                if is_nil(&noerror) {
                    return Err(format!("search-failed: {pat}"));
                }
                if !matches!(noerror, Value::Bool(true)) {
                    h.cur_buf().point = lim;
                }
                return Ok(Value::Undef);
            }
        }
    }
    Ok(Value::Int(last.unwrap_or(point as i64)))
}
/// One search from point to LIM: answers the new point, having moved there
/// and recorded the match, or `None` without touching either.
type SearchStep = fn(&mut ElispHost, &str, usize) -> Result<Option<i64>, String>;
fn search_forward(h: &mut ElispHost, a: &[Value]) -> R {
    search_with_count(h, a, true, search_forward_once, search_backward_once)
}
fn search_backward(h: &mut ElispHost, a: &[Value]) -> R {
    search_with_count(h, a, false, search_backward_once, search_forward_once)
}
fn re_search_forward(h: &mut ElispHost, a: &[Value]) -> R {
    search_with_count(h, a, true, re_search_forward_once, re_search_backward_once)
}
fn re_search_backward(h: &mut ElispHost, a: &[Value]) -> R {
    search_with_count(h, a, false, re_search_backward_once, re_search_forward_once)
}
/// A literal search is a regexp search for the quoted string: Emacs folds case
/// in both through the same `case-fold-search` translation.
fn literal_regexp(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        if matches!(c, '.' | '*' | '+' | '?' | '[' | '^' | '$' | '\\') {
            out.push('\\');
        }
        out.push(c);
    }
    out
}
fn search_forward_once(h: &mut ElispHost, s: &str, lim: usize) -> Result<Option<i64>, String> {
    re_search_forward_once(h, &literal_regexp(s), lim)
}
fn search_backward_once(h: &mut ElispHost, s: &str, lim: usize) -> Result<Option<i64>, String> {
    re_search_backward_once(h, &literal_regexp(s), lim)
}
/// The current buffer's accessible portion as a string, with the 0-based
/// buffer offset of its first character. Every buffer regexp operation runs
/// on this, never on the whole text: Emacs hands `re_search_2` exactly the
/// region `BEGV`..`ZV`, so `\`` and `^` match at `BEGV`, `\'` and `$` at
/// `ZV`, and nothing outside the restriction can match.
fn accessible_text(h: &ElispHost) -> (String, usize) {
    let b = h.cur_buf_ref();
    (b.text[b.begv - 1..b.zv - 1].iter().collect(), b.begv - 1)
}
/// A match of RE starting exactly at char S of TEXT whose end is at most
/// STOP — `re_match_2_internal` with STOP as `stop`.
///
/// fancy-regex has no stop position, so this is two attempts. Matched against
/// the whole text, a match that already ends by STOP is the one Emacs finds:
/// a stop only prunes paths, so it cannot change which path succeeds first
/// when the first success never reaches it. Only when that match runs past
/// STOP is the text cut there — and then an end-of-text assertion (`\'`,
/// `$`, `\b`) right at STOP sees an end Emacs would not.
fn match_within(
    re: &CompiledRe,
    text: &str,
    s: usize,
    stop: usize,
    anchored: bool,
) -> Option<Spans> {
    let ok = |spans: &Spans| match spans[0] {
        Some((b, e)) => (!anchored || b == s) && e <= stop,
        None => false,
    };
    let m = run_match(re, text, s)?;
    if ok(&m) {
        return Some(m);
    }
    let first = m[0]?.0;
    if anchored && first != s || first > stop {
        return None;
    }
    let cut = &text[..byte_of_char(text, stop)];
    run_match(re, cut, s).filter(ok)
}
type Spans = Vec<Option<(usize, usize)>>;
/// `fast_looking_at`'s match: RE matched at char S of TEXT, ending by STOP.
pub(crate) fn match_at(re: &CompiledRe, text: &str, s: usize, stop: usize) -> Option<Spans> {
    match_within(re, text, s, stop, true)
}
/// Record SPANS (offsets into the accessible text starting at buffer offset
/// OFF) as the current buffer's match data, and answer them rebased.
fn record_buf_match(h: &mut ElispHost, spans: Spans, off: usize) -> Spans {
    let spans: Spans = spans
        .into_iter()
        .map(|o| o.map(|(b, e)| (b + off, e + off)))
        .collect();
    set_buf_match(h, &spans);
    spans
}
fn re_search_forward_once(h: &mut ElispHost, pat: &str, lim: usize) -> Result<Option<i64>, String> {
    let re = compile_cf_buf(h, pat, case_fold_search(h))?;
    let (text, off) = accessible_text(h);
    let p = h.cur_buf_ref().point - 1 - off;
    let Some(m) = match_within(&re, &text, p, lim - 1 - off, false) else {
        return Ok(None);
    };
    let spans = record_buf_match(h, m, off);
    let end = spans[0].map_or(p + off, |(_, e)| e) + 1;
    h.cur_buf().point = end;
    Ok(Some(end as i64))
}
/// `(re-search-backward REGEXP &optional BOUND NOERROR COUNT)`.
///
/// A backward search is not "the last forward match before point". Emacs tries
/// START positions from point downwards and takes the FIRST that matches, and
/// it stops the match at the position the search started from — so for `a+` in
/// `"aaa"` with point at 4 the answer is a one-character match at 3, not the
/// three-character match at 1 that a forward scan finds first:
///
/// ```text
/// (with-temp-buffer (insert "aaa") (goto-char 4)
///   (list (re-search-backward "a+" nil t) (match-beginning 0) (match-end 0)))
///   => (3 3 4)
/// (with-temp-buffer (insert "aaa") (goto-char 3) …)   => (2 2 3)
/// ```
///
/// The second line is the end bound: at start 2 an unbounded `a+` would reach
/// 4, past where the search began. Collecting non-overlapping forward matches
/// instead answered 1 for the first and nil for the second, and ignored BOUND
/// entirely.
fn re_search_backward_once(
    h: &mut ElispHost,
    pat: &str,
    lim: usize,
) -> Result<Option<i64>, String> {
    let re = compile_cf_buf(h, pat, case_fold_search(h))?;
    let (text, off) = accessible_text(h);
    let p = h.cur_buf_ref().point - 1 - off;
    let lower = lim - 1 - off;
    let mut s = p + 1;
    while s > lower {
        s -= 1;
        if let Some(m) = match_within(&re, &text, s, p, true) {
            let spans = record_buf_match(h, m, off);
            let begin = spans[0].map_or(s + off, |(b, _)| b) + 1;
            h.cur_buf().point = begin;
            return Ok(Some(begin as i64));
        }
    }
    Ok(None)
}
fn looking_at(h: &mut ElispHost, a: &[Value]) -> R {
    let re = compile_cf_buf(h, &as_string(h, &a[0])?, case_fold_search(h))?;
    let (text, off) = accessible_text(h);
    let p = h.cur_buf_ref().point - 1 - off;
    let stop = text.chars().count();
    match match_within(&re, &text, p, stop, true) {
        Some(m) => {
            record_buf_match(h, m, off);
            Ok(Value::Bool(true))
        }
        None => Ok(Value::Undef),
    }
}
fn looking_at_p(h: &mut ElispHost, a: &[Value]) -> R {
    let saved = h.match_data.take();
    let r = looking_at(h, a);
    h.match_data = saved;
    r
}
/// Expand NEWTEXT's `\&` (whole match), `\N` (group N), and `\\` escapes using
/// GT, an accessor returning the text of group N.
///
/// A backslash before anything else — including the end of the string — is an
/// error, not a character to drop: `search.c`'s `Freplace_match` signals
/// `Invalid use of ‘\’ in replacement text` there, so `\q` and a trailing `\`
/// both fail rather than quietly producing `q` and nothing.
fn expand_repl(
    newtext: &str,
    gt: &dyn Fn(usize) -> String,
    in_string: bool,
) -> Result<String, String> {
    const BAD: &str = "error: Invalid use of ‘\\’ in replacement text";
    let chars: Vec<char> = newtext.chars().collect();
    let mut out = String::new();
    let mut i = 0;
    while i < chars.len() {
        if chars[i] == '\\' {
            let Some(&c) = chars.get(i + 1) else {
                return Err(BAD.to_string());
            };
            match c {
                '&' => out.push_str(&gt(0)),
                '0'..='9' => out.push_str(&gt(c as usize - '0' as usize)),
                '\\' => out.push(c),
                // `\?` (meaningful only to `query-replace-regexp`) is kept as
                // is in a string, and is an error in a buffer: search.c's
                // string loop lets `?` through, its buffer loop does not.
                '?' if in_string => out.push_str("\\?"),
                _ => return Err(BAD.to_string()),
            }
            i += 2;
        } else {
            out.push(chars[i]);
            i += 1;
        }
    }
    Ok(out)
}
/// `(replace-match NEWTEXT &optional FIXEDCASE LITERAL STRING SUBEXP)`. With a
/// STRING argument, returns a new string with the last `string-match` of STRING
/// replaced; otherwise edits the current buffer and leaves point after the
/// replacement. Expands `\&`/`\N`/`\\` unless LITERAL, adapts case unless
/// FIXEDCASE.
/// search.c's `(error "replace-match subexpression does not exist" SUBEXP)`.
/// Two DATA elements, so the render-and-re-read path every other error helper
/// uses cannot express it — the object is attached directly.
fn no_such_subexp(h: &mut ElispHost, subexp: usize) -> String {
    let sym = h.intern("error");
    let text = h.new_string("replace-match subexpression does not exist");
    let data = h.list_from(vec![text, Value::Int(subexp as i64)]);
    let obj = h.cons(sym, data);
    let msg = format!("error: replace-match subexpression does not exist: {subexp}");
    h.set_pending_error(&msg, obj);
    msg
}

/// search.c `Fmatch_data__translate`: add N to every recorded position,
/// flooring each at 0. `replace-regexp-in-string` uses it to aim the match
/// data at the matched substring instead of matching REGEXP a second time.
fn match_data_translate(h: &mut ElispHost, a: &[Value]) -> R {
    let n = as_fixnum_named(h, &a[0], "fixnump")?;
    if let Some(md) = h.match_data.as_mut() {
        for (b, e) in md.spans.iter_mut().flatten() {
            *b = (*b as i64 + n).max(0) as usize;
            *e = (*e as i64 + n).max(0) as usize;
        }
    }
    Ok(Value::Undef)
}
fn replace_match(h: &mut ElispHost, a: &[Value]) -> R {
    let newtext = as_string(h, &a[0])?;
    let fixedcase = !matches!(
        a.get(1),
        Some(Value::Undef) | Some(Value::Bool(false)) | None
    );
    let literal = !matches!(
        a.get(2),
        Some(Value::Undef) | Some(Value::Bool(false)) | None
    );
    let subexp = match a.get(4) {
        Some(v) if !is_nil(v) => as_int(h, v)?.max(0) as usize,
        _ => 0,
    };
    let spans = {
        let md = h
            .match_data
            .as_ref()
            .ok_or("args-out-of-range: no match data".to_string())?;
        md.spans.clone()
    };
    // STRING mode: spans are 0-based char indices into STRING; return a new string.
    if let Some(s) = a.get(3).and_then(|v| h.str_text(v)).map(str::to_string) {
        let subject: Vec<char> = s.chars().collect();
        let Some((b, e)) = spans.get(subexp).copied().flatten() else {
            return Err(no_such_subexp(h, subexp));
        };
        // `Freplace_match` bounds-checks the span against STRING before touching
        // it: match data is global and outlives the string it was set from, so
        // the span routinely points past a *different* string. Indexing without
        // this check panicked the interpreter thread.
        if e > subject.len() || b > e {
            return Err(format!("args-out-of-range: {b} {e}"));
        }
        let gt = |n: usize| -> String {
            spans
                .get(n)
                .copied()
                .flatten()
                .filter(|(gb, ge)| *ge <= subject.len() && gb <= ge)
                .map(|(gb, ge)| subject[gb..ge].iter().collect::<String>())
                .unwrap_or_default()
        };
        let matched = gt(subexp);
        let rep = if literal {
            newtext
        } else {
            expand_repl(&newtext, &gt, true)?
        };
        let rep = if fixedcase {
            rep
        } else {
            adapt_replacement_case(&matched, rep)
        };
        let mut out: String = subject[..b].iter().collect();
        out.push_str(&rep);
        out.extend(&subject[e..]);
        let rep_len = rep.chars().count();
        // The result is SUBJECT before and after the match plus NEWTEXT, whose
        // `\&` / `\N` pieces are substrings of SUBJECT: each piece keeps the
        // text properties of the string it was cut from.
        let (new_arc, subj_arc) = (h.str_arc(&a[0]), a.get(3).and_then(|v| h.str_arc(v)));
        let (res, key) = h.new_string_keyed(out);
        if new_arc.is_some() || subj_arc.is_some() {
            let mut pieces: Vec<(Option<std::sync::Arc<String>>, usize, usize)> = Vec::new();
            pieces.push((subj_arc.clone(), 0, b));
            let mut produced = 0;
            if literal {
                pieces.push((new_arc.clone(), 0, rep_len));
                produced = rep_len;
            } else if let Some(na) = &new_arc {
                let nc: Vec<char> = na.chars().collect();
                let mut i = 0;
                while i < nc.len() {
                    if nc[i] == '\\' && i + 1 < nc.len() {
                        let c = nc[i + 1];
                        let group = match c {
                            '&' => Some(0),
                            '0'..='9' => Some(c as usize - '0' as usize),
                            _ => None,
                        };
                        match group {
                            Some(g) => {
                                if let Some((gb, ge)) = spans.get(g).copied().flatten() {
                                    if ge <= subject.len() && gb <= ge {
                                        pieces.push((subj_arc.clone(), gb, ge - gb));
                                        produced += ge - gb;
                                    }
                                }
                            }
                            None => {
                                let len = if c == '?' { 2 } else { 1 };
                                pieces.push((Some(na.clone()), i + 2 - len, len));
                                produced += len;
                            }
                        }
                        i += 2;
                    } else {
                        pieces.push((Some(na.clone()), i, 1));
                        produced += 1;
                        i += 1;
                    }
                }
            }
            pieces.push((subj_arc, e, subject.len() - e));
            if produced == rep_len {
                h.string_carry_props(&key, &pieces);
            }
        }
        return Ok(res);
    }
    let text: Vec<char> = h.cur_buf().text.clone();
    let (begv, zv) = (h.cur_buf().begv, h.cur_buf().zv);
    let Some((b, e)) = spans.get(subexp).copied().flatten() else {
        return Err(no_such_subexp(h, subexp));
    };
    // `! (BEGV <= sub_start && sub_end <= ZV)` => args_out_of_range, exactly as
    // search.c does. The global match data survives the buffer it was set in, so
    // without the check a stale span indexed past the buffer text and panicked.
    if b < begv || e > zv || b > e {
        return Err(format!("args-out-of-range: {b} {e}"));
    }
    let gt = |n: usize| -> String {
        spans
            .get(n)
            .copied()
            .flatten()
            .filter(|(gb, ge)| *gb >= begv && *ge <= zv && gb <= ge)
            .map(|(gb, ge)| text[(gb - 1)..(ge - 1)].iter().collect::<String>())
            .unwrap_or_default()
    };
    let matched = gt(subexp);
    let rep = if literal {
        newtext
    } else {
        expand_repl(&newtext, &gt, false)?
    };
    let rep = if fixedcase {
        rep
    } else {
        adapt_replacement_case(&matched, rep)
    };
    let rep_chars: Vec<char> = rep.chars().collect();
    h.barf_if_read_only()?;
    // Delete the matched span, then insert the replacement at its start (point is
    // left after the replacement, matching Emacs and adjusting markers/narrowing).
    h.cur_buf().point = b;
    h.cur_delete(b, e);
    h.cur_insert(rep_chars, true);
    Ok(Value::Undef)
}

// ── overlays ──
//
// An overlay is a buffer range carrying a property list. It differs from a text
// property in that it is an OBJECT: it survives the text under it changing, both
// of its ends move with edits like markers, and deleting it detaches it rather
// than clearing anything. `host::OverlayData` holds the range and the two
// advance flags; the owning buffer holds the same `Rc`, which is what lets
// `adjust_for_insert`/`adjust_for_delete` move every overlay in one pass.

/// The shared data behind an overlay object, or None if `v` is not one.
fn ov_rc(h: &ElispHost, v: &Value) -> Option<Rc<RefCell<crate::host::OverlayData>>> {
    match h.obj(v) {
        Some(Obj::Overlay(o)) => Some(o.clone()),
        _ => None,
    }
}
fn ov_of(h: &mut ElispHost, v: &Value) -> Result<Rc<RefCell<crate::host::OverlayData>>, String> {
    ov_rc(h, v).ok_or_else(|| h.signal_wrong_type("overlayp", v))
}
fn overlayp(h: &mut ElispHost, a: &[Value]) -> R {
    Ok(nil_or(ov_rc(h, &a[0]).is_some()))
}
/// `(make-overlay BEG END &optional BUFFER FRONT-ADVANCE REAR-ADVANCE)`.
///
/// An inverted pair is accepted and swapped, and both ends are clamped into the
/// buffer, so `(make-overlay 4 2)` is the same overlay as `(make-overlay 2 4)`.
fn make_overlay(h: &mut ElispHost, a: &[Value]) -> R {
    let bi = match a.get(2) {
        Some(v) if !is_nil(v) => h
            .resolve_buffer(v)
            .ok_or_else(|| h.signal_wrong_type("buffer-or-string-p", v))?,
        _ => h.current,
    };
    let z = h.buffers[bi].text.len() as i64 + 1;
    let clamp = |n: i64| n.clamp(1, z) as usize;
    let b0 = clamp(as_int(h, &a[0])?);
    let e0 = clamp(as_int(h, &a[1])?);
    let (start, end) = if b0 <= e0 { (b0, e0) } else { (e0, b0) };
    let od = Rc::new(RefCell::new(crate::host::OverlayData {
        buffer: Some(bi),
        start,
        end,
        front_advance: a.get(3).is_some_and(|v| !is_nil(v)),
        rear_advance: a.get(4).is_some_and(|v| !is_nil(v)),
        props: Vec::new(),
    }));
    h.buffers[bi].overlays.push(od.clone());
    Ok(h.alloc(Obj::Overlay(od)))
}
fn overlay_start(h: &mut ElispHost, a: &[Value]) -> R {
    let od = ov_of(h, &a[0])?;
    let od = od.borrow();
    Ok(match od.buffer {
        Some(_) => Value::Int(od.start as i64),
        None => Value::Undef,
    })
}
fn overlay_end(h: &mut ElispHost, a: &[Value]) -> R {
    let od = ov_of(h, &a[0])?;
    let od = od.borrow();
    Ok(match od.buffer {
        Some(_) => Value::Int(od.end as i64),
        None => Value::Undef,
    })
}
fn overlay_buffer(h: &mut ElispHost, a: &[Value]) -> R {
    let od = ov_of(h, &a[0])?;
    let bi = od.borrow().buffer;
    Ok(match bi {
        Some(i) => h.buffer_object(i),
        None => Value::Undef,
    })
}
fn overlay_get(h: &mut ElispHost, a: &[Value]) -> R {
    let od = ov_of(h, &a[0])?;
    let od = od.borrow();
    Ok(od
        .props
        .iter()
        .find(|(k, _)| el_eq(h, k, &a[1]))
        .map(|(_, v)| v.clone())
        .unwrap_or(Value::Undef))
}
/// `(overlay-put OV PROP VALUE)`. A property set twice keeps its original
/// position in the list, which is why `overlay-properties` is newest-first only
/// for properties that are new.
fn overlay_put(h: &mut ElispHost, a: &[Value]) -> R {
    let od = ov_of(h, &a[0])?;
    let existing = od
        .borrow()
        .props
        .iter()
        .position(|(k, _)| el_eq(h, k, &a[1]));
    let mut od = od.borrow_mut();
    match existing {
        Some(i) => od.props[i].1 = a[2].clone(),
        None => od.props.insert(0, (a[1].clone(), a[2].clone())),
    }
    Ok(a[2].clone())
}
fn overlay_properties(h: &mut ElispHost, a: &[Value]) -> R {
    let od = ov_of(h, &a[0])?;
    let flat: Vec<Value> = od
        .borrow()
        .props
        .iter()
        .flat_map(|(k, v)| [k.clone(), v.clone()])
        .collect();
    Ok(h.list_from(flat))
}
/// `(delete-overlay OV)` — detach it. The object stays an overlay; its ends and
/// buffer read as nil, and `move-overlay` can put it back.
fn delete_overlay(h: &mut ElispHost, a: &[Value]) -> R {
    let od = ov_of(h, &a[0])?;
    let was = od.borrow().buffer;
    if let Some(bi) = was {
        h.buffers[bi].overlays.retain(|o| !Rc::ptr_eq(o, &od));
    }
    od.borrow_mut().buffer = None;
    Ok(Value::Undef)
}
/// `(move-overlay OV BEG END &optional BUFFER)` — also re-attaches a deleted
/// overlay, to BUFFER or to the current buffer.
fn move_overlay(h: &mut ElispHost, a: &[Value]) -> R {
    let od = ov_of(h, &a[0])?;
    let old = od.borrow().buffer;
    let bi = match a.get(3) {
        Some(v) if !is_nil(v) => h
            .resolve_buffer(v)
            .ok_or_else(|| h.signal_wrong_type("buffer-or-string-p", v))?,
        _ => old.unwrap_or(h.current),
    };
    let z = h.buffers[bi].text.len() as i64 + 1;
    let clamp = |n: i64| n.clamp(1, z) as usize;
    let b0 = clamp(as_int(h, &a[1])?);
    let e0 = clamp(as_int(h, &a[2])?);
    if old != Some(bi) {
        if let Some(o) = old {
            h.buffers[o].overlays.retain(|x| !Rc::ptr_eq(x, &od));
        }
        h.buffers[bi].overlays.push(od.clone());
    }
    {
        let mut m = od.borrow_mut();
        m.buffer = Some(bi);
        m.start = b0.min(e0);
        m.end = b0.max(e0);
    }
    Ok(a[0].clone())
}
/// Overlays of the current buffer whose range satisfies `keep`, in creation
/// order — which is the order `overlays-in` reports.
fn overlays_where(
    h: &mut ElispHost,
    keep: impl Fn(usize, usize) -> bool,
) -> Vec<Rc<RefCell<crate::host::OverlayData>>> {
    h.buffers[h.current]
        .overlays
        .iter()
        .filter(|o| {
            let od = o.borrow();
            keep(od.start, od.end)
        })
        .cloned()
        .collect()
}
fn overlays_to_list(h: &mut ElispHost, ovs: Vec<Rc<RefCell<crate::host::OverlayData>>>) -> R {
    let items: Vec<Value> = ovs.into_iter().map(|o| h.alloc(Obj::Overlay(o))).collect();
    Ok(h.list_from(items))
}
/// `(overlays-at POS)` — those that COVER POS, i.e. `start <= POS < end`. An
/// overlay ending at POS does not cover it, so `(overlays-at 3)` is nil for an
/// overlay from 1 to 3.
fn overlays_at(h: &mut ElispHost, a: &[Value]) -> R {
    let pos = as_int(h, &a[0])? as usize;
    let ovs = overlays_where(h, |s, e| s <= pos && pos < e);
    overlays_to_list(h, ovs)
}
/// `(overlays-in BEG END)` — those overlapping the range. An EMPTY overlay is
/// included when it sits inside it, including when BEG equals END.
fn overlays_in(h: &mut ElispHost, a: &[Value]) -> R {
    let beg = as_int(h, &a[0])? as usize;
    let end = as_int(h, &a[1])? as usize;
    let ovs = overlays_where(h, |s, e| {
        if s == e {
            beg <= s && s <= end
        } else {
            s < end && e > beg
        }
    });
    overlays_to_list(h, ovs)
}
/// `(next-overlay-change POS)` — the next position after POS where an overlay
/// begins or ends, or `point-max` when there is none.
fn next_overlay_change(h: &mut ElispHost, a: &[Value]) -> R {
    let pos = as_int(h, &a[0])? as usize;
    let zv = h.cur_buf_ref().zv;
    let mut best = zv;
    for o in h.buffers[h.current].overlays.iter() {
        let od = o.borrow();
        for p in [od.start, od.end] {
            if p > pos && p < best {
                best = p;
            }
        }
    }
    Ok(Value::Int(best as i64))
}
/// `(previous-overlay-change POS)` — the previous such position, or `point-min`.
fn previous_overlay_change(h: &mut ElispHost, a: &[Value]) -> R {
    let pos = as_int(h, &a[0])? as usize;
    let begv = h.cur_buf_ref().begv;
    let mut best = begv;
    for o in h.buffers[h.current].overlays.iter() {
        let od = o.borrow();
        for p in [od.start, od.end] {
            if p < pos && p > best {
                best = p;
            }
        }
    }
    Ok(Value::Int(best as i64))
}

// ── filesystem writes / mutations ──
fn write_region(h: &mut ElispHost, a: &[Value]) -> R {
    let append = a.get(3).is_some_and(|v| !is_nil(v));
    // START may be a string (write it directly) or a buffer position.
    let content: String = match h.str_text(&a[0]).map(str::to_string) {
        Some(s) => s,
        None => {
            let len = h.cur_buf_ref().text.len() as i64;
            let s = as_int(h, &a[0])?.clamp(1, len + 1);
            let e = match a.get(1) {
                Some(v) if !is_nil(v) => as_int(h, v)?.clamp(1, len + 1),
                _ => len + 1,
            };
            let buf = h.cur_buf();
            let (lo, hi) = if s <= e { (s, e) } else { (e, s) };
            buf.text[(lo - 1) as usize..(hi - 1) as usize]
                .iter()
                .collect()
        }
    };
    let filename = as_string(h, &a[2])?;
    let path = fs_expand(&filename);
    let res = if append {
        use std::io::Write;
        std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(&path)
            .and_then(|mut f| f.write_all(content.as_bytes()))
    } else {
        std::fs::write(&path, content.as_bytes())
    };
    res.map_err(|e| report_file_errno(h, "Opening output file", &[&filename], &e))?;
    Ok(Value::Undef)
}
/// fileio.c `Fdelete_file_internal`: one `unlink`; a file that is already
/// gone is not an error. `delete-file` is files.el's.
fn delete_file_internal(h: &mut ElispHost, a: &[Value]) -> R {
    let f = as_string(h, &a[0])?;
    match std::fs::remove_file(fs_expand(&f)) {
        Err(e) if e.raw_os_error() != Some(libc::ENOENT) => {
            Err(report_file_errno(h, "Removing old name", &[&f], &e))
        }
        _ => Ok(Value::Undef),
    }
}
/// `(make-directory-internal DIR)` — fileio.c: one `mkdir`, no parents.
/// `make-directory` itself is files.el's, in the prelude.
fn make_directory_internal(h: &mut ElispHost, a: &[Value]) -> R {
    let f = as_string(h, &a[0])?;
    std::fs::create_dir(fs_expand(&f))
        .map_err(|e| report_file_errno(h, "Creating directory", &[&f], &e))?;
    Ok(Value::Undef)
}
fn rename_file(h: &mut ElispHost, a: &[Value]) -> R {
    let (o, n) = (as_string(h, &a[0])?, as_string(h, &a[1])?);
    std::fs::rename(fs_expand(&o), fs_expand(&n))
        .map_err(|e| report_file_errno(h, "Renaming", &[&o, &n], &e))?;
    Ok(Value::Undef)
}
fn copy_file(h: &mut ElispHost, a: &[Value]) -> R {
    let (o, n) = (as_string(h, &a[0])?, as_string(h, &a[1])?);
    // fileio.c `Fcopy_file`: an existing NEWNAME is refused before FILE is
    // even opened, unless OK-IF-ALREADY-EXISTS is non-nil (and not a number).
    let ok_if_exists = a
        .get(2)
        .is_some_and(|v| !is_nil(v) && !matches!(v, Value::Int(_)));
    if !ok_if_exists && std::fs::symlink_metadata(fs_expand(&n)).is_ok() {
        let sym = h.intern("file-already-exists");
        let data = vec![
            h.new_string("File already exists".to_string()),
            h.new_string(n.clone()),
        ];
        let data = h.list_from(data);
        let obj = h.cons(sym, data);
        let msg = format!("file-already-exists: {}", h.print(&obj, true));
        h.set_pending_error(&msg, obj);
        return Err(msg);
    }
    std::fs::File::open(fs_expand(&o))
        .map_err(|e| report_file_errno(h, "Opening input file", &[&o], &e))?;
    std::fs::copy(fs_expand(&o), fs_expand(&n))
        .map_err(|e| report_file_errno(h, "Opening output file", &[&n], &e))?;
    Ok(Value::Undef)
}

// ── subprocesses ──
/// Where `call-process` sends the child's standard output (callproc.c's
/// reading of DESTINATION).
pub(crate) enum ProcOutput {
    /// nil: discarded, waited for.
    Discard,
    /// A number: discarded, not waited for; `call-process` answers nil.
    NoWait,
    /// t, a buffer or a buffer name: inserted at that buffer's point.
    Buffer(Value),
    /// `(:file FILE)`: written to FILE (expanded), truncated first.
    File(String),
}
/// Where the child's standard error goes: the second element of a list
/// DESTINATION. Without one it is mixed with the output.
pub(crate) enum ProcStderr {
    Discard,
    Mix,
    File(String),
}
/// The car and cdr of V when it is a cons.
fn cons_parts(h: &ElispHost, v: &Value) -> Option<(Value, Value)> {
    match h.obj(v) {
        Some(Obj::Cons(a, d)) => Some((a.clone(), d.clone())),
        _ => None,
    }
}
/// callproc.c `call_process`'s decoding of DESTINATION. A buffer name is
/// `get-buffer-create`d; a killed buffer is `Selecting deleted buffer`; a
/// file name is expanded against `default-directory`.
pub(crate) fn process_destination(
    h: &mut ElispHost,
    dest: Option<&Value>,
) -> Result<(ProcOutput, ProcStderr), String> {
    let Some(dest) = dest.cloned() else {
        return Ok((ProcOutput::Discard, ProcStderr::Mix));
    };
    let mut stderr = ProcStderr::Mix;
    let mut buffer = dest.clone();
    if let Some((car, cdr)) = cons_parts(h, &dest) {
        if h.sym_name(&car).is_some_and(|n| n.as_str() == ":file") {
            let file = cons_parts(h, &cdr).map(|(file, _)| file);
            let file = file.unwrap_or(Value::Undef);
            let file = crate::fileio::expand_file_name(h, &[file])?;
            return Ok((ProcOutput::File(as_string(h, &file)?), stderr));
        }
        if let Some((err, _)) = cons_parts(h, &cdr) {
            stderr = if is_nil(&err) {
                ProcStderr::Discard
            } else if matches!(err, Value::Bool(true)) {
                ProcStderr::Mix
            } else {
                let file = crate::fileio::expand_file_name(h, &[err])?;
                ProcStderr::File(as_string(h, &file)?)
            };
        }
        buffer = car;
    }
    let out = match buffer {
        Value::Undef => ProcOutput::Discard,
        Value::Bool(false) => ProcOutput::Discard,
        Value::Bool(true) => ProcOutput::Buffer(h.cur_buf_ref().self_obj.clone()),
        Value::Int(_) => ProcOutput::NoWait,
        v => {
            let b = get_buffer_create(h, &[v])?;
            if h.resolve_buffer(&b)
                .is_none_or(|i| h.buffers[i].name.is_none())
            {
                return Err("error: Selecting deleted buffer".to_string());
            }
            ProcOutput::Buffer(b)
        }
    };
    Ok((out, stderr))
}
/// callproc.c: a child killed by a signal answers `strsignal`'s text.
fn exit_value(h: &mut ElispHost, status: std::process::ExitStatus) -> Value {
    use std::os::unix::process::ExitStatusExt;
    if let Some(sig) = status.signal() {
        // SAFETY: strsignal returns a pointer to a static or thread-local
        // string, read at once.
        let text = unsafe {
            let p = libc::strsignal(sig);
            if p.is_null() {
                "unknown".to_string()
            } else {
                std::ffi::CStr::from_ptr(p).to_string_lossy().into_owned()
            }
        };
        return h.new_string(text);
    }
    Value::Int(status.code().unwrap_or(0) as i64)
}
/// `open (FILE, O_WRONLY | O_CREAT | O_TRUNC, 0666)` for the child's output
/// or error file; STRING names the failure.
fn create_output_file(
    h: &mut ElispHost,
    file: &str,
    string: &str,
) -> Result<std::fs::File, String> {
    std::fs::File::create(fs_expand(file)).map_err(|e| report_file_errno(h, string, &[file], &e))
}
/// callproc.c `call_process` with DISPLAY ignored (batch Emacs never
/// redisplays). The checks run in Emacs's order: INFILE's type, PROGRAM and
/// ARGS, DESTINATION, `default-directory`, INFILE opened (`/dev/null` when
/// nil), PROGRAM on `exec-path`, then the output and error files. Output is
/// decoded as UTF-8. Answers the exit status, `strsignal`'s description of
/// the signal that killed the child, or nil for a numeric DESTINATION.
pub(crate) fn run_process(
    h: &mut ElispHost,
    program: &Value,
    infile: Option<&Value>,
    dest: Option<&Value>,
    args: &[Value],
) -> R {
    use std::process::Stdio;
    let infile = match infile {
        Some(v) if !is_nil(v) => {
            let f = crate::fileio::expand_file_name(h, std::slice::from_ref(v))?;
            Some(as_string(h, &f)?)
        }
        _ => None,
    };
    let program = as_string(h, program)?;
    let args: Vec<String> = args
        .iter()
        .map(|v| as_string(h, v))
        .collect::<Result<_, _>>()?;
    let (out, stderr) = process_destination(h, dest)?;
    let cwd = subprocess_directory(h)?;
    let stdin = match &infile {
        Some(f) => Stdio::from(
            std::fs::File::open(fs_expand(f))
                .map_err(|e| report_file_errno(h, "Opening process input file", &[f], &e))?,
        ),
        None => Stdio::null(),
    };
    let path = find_program(h, &program)?;
    let mut cmd = std::process::Command::new(path);
    cmd.args(&args)
        .current_dir(&cwd)
        .env_clear()
        .envs(child_environment(h, &cwd))
        .stdin(stdin);
    // The pipe both streams share when the output is captured and the error
    // is mixed in, so the two interleave as the child wrote them.
    let mut reader = None;
    let stdout_file = match &out {
        ProcOutput::File(f) => Some(create_output_file(h, f, "Opening process output file")?),
        _ => None,
    };
    let stderr_file = match &stderr {
        ProcStderr::File(f) => Some(create_output_file(h, f, "Cannot redirect stderr")?),
        _ => None,
    };
    let to_stdout: Stdio = match (&out, &stdout_file) {
        (ProcOutput::Buffer(_), _) => {
            let (r, w) = std::io::pipe().map_err(|e| e.to_string())?;
            reader = Some(r);
            if matches!(stderr, ProcStderr::Mix) {
                cmd.stderr(w.try_clone().map_err(|e| e.to_string())?);
            }
            w.into()
        }
        (_, Some(f)) => {
            if matches!(stderr, ProcStderr::Mix) {
                cmd.stderr(f.try_clone().map_err(|e| e.to_string())?);
            }
            f.try_clone().map_err(|e| e.to_string())?.into()
        }
        _ => Stdio::null(),
    };
    cmd.stdout(to_stdout);
    match (stderr_file, &stderr) {
        (Some(f), _) => {
            cmd.stderr(f);
        }
        (None, ProcStderr::Discard) => {
            cmd.stderr(Stdio::null());
        }
        (None, _) if reader.is_none() && stdout_file.is_none() => {
            cmd.stderr(Stdio::null());
        }
        _ => {}
    }
    let mut child = cmd
        .spawn()
        .map_err(|e| report_file_errno(h, "Searching for program", &[&program], &e))?;
    // The parent's copies of the pipe's write end go with the Command.
    drop(cmd);
    if matches!(out, ProcOutput::NoWait) {
        return Ok(Value::Undef);
    }
    let mut bytes = Vec::new();
    if let Some(mut r) = reader {
        std::io::Read::read_to_end(&mut r, &mut bytes)
            .map_err(|e| report_file_errno(h, "Read error", &[&program], &e))?;
    }
    let status = child.wait().map_err(|e| e.to_string())?;
    if let ProcOutput::Buffer(buffer) = &out {
        if !bytes.is_empty() {
            let saved = h.cur_buf_ref().self_obj.clone();
            h.set_buffer(buffer)?;
            let inserted = h.barf_if_read_only().map(|()| {
                let chars: Vec<char> = String::from_utf8_lossy(&bytes).chars().collect();
                h.cur_insert(chars, true);
            });
            h.set_buffer(&saved)?;
            inserted?;
        }
    }
    Ok(exit_value(h, status))
}
/// simple.el `shell-command-to-string`, which runs `shell-command` into a
/// temporary buffer: `(call-process shell-file-name nil t nil
/// shell-command-switch COMMAND)`, standard error mixed into the output.
fn shell_command_to_string(h: &mut ElispHost, a: &[Value]) -> R {
    as_string(h, &a[0])?;
    let shell = symbol_value_or_nil(h, "shell-file-name");
    let switch = symbol_value_or_nil(h, "shell-command-switch");
    let saved = h.cur_buf_ref().self_obj.clone();
    let name = h.generate_new_buffer_name(" *temp*", None);
    let temp = h.get_buffer_create(&name);
    if let Some(i) = h.resolve_buffer(&temp) {
        h.buffers[i].inhibit_hooks = true;
    }
    let dest = Value::Bool(true);
    h.set_buffer(&temp)?;
    let result = run_process(h, &shell, None, Some(&dest), &[switch, a[0].clone()]);
    let text: String = h.cur_buf_ref().text.iter().collect();
    h.set_buffer(&saved)?;
    h.kill_buffer(Some(&temp));
    result?;
    Ok(h.new_string(text))
}
/// `(call-process PROGRAM &optional INFILE DESTINATION DISPLAY &rest ARGS)`.
fn call_process(h: &mut ElispHost, a: &[Value]) -> R {
    run_process(h, &a[0], a.get(1), a.get(2), a.get(4..).unwrap_or(&[]))
}

// ── more buffer editing/motion ──
/// editfns.c `Fchar_before`: POS is `fix_position`ed like `char-after`'s.
fn char_before(h: &mut ElispHost, a: &[Value]) -> R {
    let arg = match a.first() {
        Some(v) if !is_nil(v) => Some(fix_position(h, v)?),
        _ => None,
    };
    let buf = h.cur_buf();
    let pos = arg.unwrap_or(buf.point as i64);
    // The char at pos-1, only when pos-1 is inside the accessible region.
    Ok(if pos > buf.begv as i64 && pos <= buf.zv as i64 {
        Value::Int(buf.text[pos as usize - 2] as i64)
    } else {
        Value::Undef
    })
}
/// cmds.c `Fdelete_char`: N characters past either end of the accessible
/// portion signal `beginning-of-buffer`/`end-of-buffer` instead of deleting
/// what is there. (KILLFLAG, which routes through `kill-forward-chars`, is
/// not honoured: a subr cannot call back into Lisp here.)
fn delete_char(h: &mut ElispHost, a: &[Value]) -> R {
    let n = as_fixnum_named(h, &a[0], "fixnump")?;
    let (point, begv, zv) = {
        let b = h.cur_buf_ref();
        (b.point as i64, b.begv as i64, b.zv as i64)
    };
    let pos = point + n;
    let (lo, hi) = if n < 0 {
        if pos < begv {
            return Err("beginning-of-buffer".to_string());
        }
        (pos, point)
    } else {
        if pos > zv {
            return Err("end-of-buffer".to_string());
        }
        (point, pos)
    };
    if lo < hi {
        h.barf_if_read_only()?;
    }
    h.cur_delete(lo as usize, hi as usize);
    Ok(Value::Undef)
}
pub(crate) fn insert_char(h: &mut ElispHost, a: &[Value]) -> R {
    let c = char::from_u32(as_int(h, &a[0])? as u32).unwrap_or('\u{fffd}');
    let count = match a.get(1) {
        Some(v) if !is_nil(v) => as_int(h, v)?.max(0) as usize,
        _ => 1,
    };
    if count > 0 {
        h.barf_if_read_only()?;
    }
    h.cur_insert(vec![c; count], true);
    Ok(Value::Undef)
}
fn count_lines(h: &mut ElispHost, a: &[Value]) -> R {
    // simple.el narrows to START..END first, so the bounds are narrow-to-region's.
    let (lo, hi) = narrow_bounds(h, &a[0], &a[1])?;
    let buf = h.cur_buf();
    let region = &buf.text[lo - 1..hi - 1];
    let nl = region.iter().filter(|&&c| c == '\n').count();
    // Count the final partial line (region non-empty and not ending in newline).
    let extra = if !region.is_empty() && region[region.len() - 1] != '\n' {
        1
    } else {
        0
    };
    Ok(Value::Int((nl + extra) as i64))
}
fn line_number_at_pos(h: &mut ElispHost, a: &[Value]) -> R {
    let arg = match a.first() {
        Some(v) if !is_nil(v) => Some(as_int(h, v)? as usize),
        _ => None,
    };
    let buf = h.cur_buf();
    let pos = arg.unwrap_or(buf.point);
    let upto = (pos.saturating_sub(1)).min(buf.text.len());
    let n = buf.text[..upto].iter().filter(|&&c| c == '\n').count();
    Ok(Value::Int(n as i64 + 1))
}
/// `SANE_TAB_WIDTH` (buffer.h): `tab-width` when it is an integer in
/// 1..=1000, else 8.
fn sane_tab_width(h: &ElispHost) -> i64 {
    match h
        .find_symbol("tab-width")
        .and_then(|s| h.get_value(&s).ok())
    {
        Some(Value::Int(n)) if (1..=1000).contains(&n) => n,
        _ => 8,
    }
}
/// The columns character C advances from column COL: a tab to the next tab
/// stop, anything else its `char-width`.
fn advance_column(c: char, col: i64, tab_width: i64) -> i64 {
    if c == '\t' {
        (col / tab_width + 1) * tab_width
    } else {
        col + char_display_width(c as u32) as i64
    }
}
/// Port of `scan_for_column` (indent.c) without display properties or
/// invisibility: walk from the start of point's line towards END, stopping at a
/// newline or once column GOAL is reached. Answers `(pos, col, prev_pos,
/// prev_col)`, the `prev_` pair naming the last character stepped over.
pub(crate) fn scan_for_column(h: &ElispHost, end: usize, goal: i64) -> (usize, i64, usize, i64) {
    let tab_width = sane_tab_width(h);
    let buf = h.cur_buf_ref();
    let mut pos = find_newline(&buf.text, buf.point, -1, buf.begv, buf.zv).0;
    let (mut col, mut prev_pos, mut prev_col) = (0i64, pos, 0i64);
    while pos < end {
        if col >= goal {
            break;
        }
        let c = buf.text[pos - 1];
        if c == '\n' {
            break;
        }
        prev_pos = pos;
        prev_col = col;
        col = advance_column(c, col, tab_width);
        pos += 1;
    }
    (pos, col, prev_pos, prev_col)
}
/// `(current-column)`: the display column of point.
fn current_column(h: &mut ElispHost, _a: &[Value]) -> R {
    let point = h.cur_buf_ref().point;
    Ok(Value::Int(scan_for_column(h, point, i64::MAX).1))
}
/// Port of `Fcurrent_indentation` / `position_indentation` (indent.c): the
/// column of the first character on point's line that is not a space or tab.
fn current_indentation(h: &mut ElispHost, _a: &[Value]) -> R {
    let tab_width = sane_tab_width(h);
    let buf = h.cur_buf_ref();
    let mut pos = find_newline(&buf.text, buf.point, -1, buf.begv, buf.zv).0;
    let mut col = 0i64;
    while pos < buf.zv && matches!(buf.text[pos - 1], ' ' | '\t') {
        col = advance_column(buf.text[pos - 1], col, tab_width);
        pos += 1;
    }
    Ok(Value::Int(col))
}
/// Port of `Findent_to` (indent.c): pad from point's column to COLUMN (and at
/// least MINIMUM columns), with tabs where `indent-tabs-mode` allows, and
/// answer the column reached.
/// What `Findent_to` inserts at point: `(MINCOL, TABS, SPACES)`. Nothing to
/// insert when point is already at MINCOL; otherwise the buffer must be
/// writable.
pub(crate) fn indent_to_plan(
    h: &mut ElispHost,
    a: &[Value],
) -> Result<(i64, usize, usize), String> {
    let column = as_fixnum_named(h, &a[0], "fixnump")?;
    let minimum = match a.get(1) {
        Some(v) if !is_nil(v) => as_fixnum_named(h, v, "fixnump")?,
        _ => 0,
    };
    let tab_width = sane_tab_width(h);
    let point = h.cur_buf_ref().point;
    let mut fromcol = scan_for_column(h, point, i64::MAX).1;
    let mincol = (fromcol + minimum).max(column);
    if fromcol == mincol {
        return Ok((mincol, 0, 0));
    }
    h.barf_if_read_only()?;
    let tabs_mode = h
        .find_symbol("indent-tabs-mode")
        .and_then(|s| h.get_value(&s).ok())
        .is_some_and(|v| !is_nil(&v));
    let mut tabs = 0;
    if tabs_mode {
        let n = mincol / tab_width - fromcol / tab_width;
        if n != 0 {
            tabs = n.max(0) as usize;
            fromcol = (mincol / tab_width) * tab_width;
        }
    }
    Ok((mincol, tabs, (mincol - fromcol).max(0) as usize))
}
/// `(indent-to COLUMN &optional MINIMUM)` — indent.c. Its two insertions are
/// `insert-char` calls with INHERIT, so `crate::modhooks` routes them
/// through the change hooks and property inheritance; this body is what
/// runs when neither applies.
pub(crate) fn indent_to(h: &mut ElispHost, a: &[Value]) -> R {
    let (mincol, tabs, spaces) = indent_to_plan(h, a)?;
    h.cur_insert(vec!['\t'; tabs], true);
    h.cur_insert(vec![' '; spaces], true);
    Ok(Value::Int(mincol))
}
/// Port of `Fmove_to_column` (indent.c): move to COLUMN on the current line,
/// or as close as the line allows. FORCE non-nil splits a tab that straddles
/// COLUMN into spaces; FORCE `t` also pads a line too short to reach it.
fn move_to_column(h: &mut ElispHost, a: &[Value]) -> R {
    let goal = match &a[0] {
        Value::Int(n) if *n >= 0 => *n,
        other => return Err(h.signal_wrong_type("wholenump", other)),
    };
    let force = a.get(1).cloned().unwrap_or(Value::Undef);
    let zv = h.cur_buf_ref().zv;
    let (pos, mut col, prev_pos, prev_col) = scan_for_column(h, zv, goal);
    h.cur_buf().point = pos;
    if !is_nil(&force) && col > goal {
        let c = h.cur_buf_ref().text[prev_pos - 1];
        if c == '\t' && prev_col < goal && prev_pos < pos {
            h.cur_buf().point = prev_pos;
            h.cur_insert(vec![' '; (goal - prev_col) as usize], true);
            let at = h.cur_buf_ref().point;
            h.cur_delete(at, at + 1);
            indent_to(h, &[Value::Int(col)])?;
            h.cur_buf().point = at;
            col = goal;
        }
    }
    if col < goal && matches!(force, Value::Bool(true)) {
        col = goal;
        indent_to(h, &[Value::Int(col)])?;
    }
    Ok(Value::Int(col))
}
/// One member of a `skip-chars-forward` set: an inclusive character range, or
/// an ISO C class (`[:alpha:]`), tested through the regexp engine's class
/// translation so the two agree character for character.
enum SkipItem {
    Range(char, char),
    Class(Rc<CompiledRe>),
}
/// A parsed `skip-chars-forward`/`-backward` set (syntax.c `skip_chars`).
struct SkipSet {
    negate: bool,
    items: Vec<SkipItem>,
}
impl SkipSet {
    /// syntax.c `skip_chars`'s parse: a leading `^` negates; `[:NAME:]` is a
    /// character class (an unknown NAME is an error, a malformed one is plain
    /// characters); `\` quotes the next character; `A-B` is a range only when a
    /// character follows the `-`, and an inverted range is empty.
    fn parse(h: &ElispHost, spec: &str) -> Result<SkipSet, String> {
        let chars: Vec<char> = spec.chars().collect();
        let negate = chars.first() == Some(&'^');
        let mut i = usize::from(negate);
        let mut items = Vec::new();
        while i < chars.len() {
            let mut c = chars[i];
            i += 1;
            if c == '[' && chars.get(i) == Some(&':') {
                let beg = i + 1;
                let mut end = beg;
                while end + 1 < chars.len()
                    && !(chars[end] as u32 >= 0o200
                        || chars[end] as u32 <= 0o40
                        || (chars[end] == ':' && chars[end + 1] == ']'))
                {
                    end += 1;
                }
                if end > beg && chars.get(end) == Some(&':') && chars.get(end + 1) == Some(&']') {
                    let name: String = chars[beg..end].iter().collect();
                    if !crate::regexp::is_class_name(&name) {
                        return Err("error: Invalid ISO C character class".to_string());
                    }
                    items.push(SkipItem::Class(compile_cf(
                        h,
                        &format!("[[:{name}:]]"),
                        false,
                    )?));
                    i = end + 2;
                    continue;
                }
            }
            if c == '\\' {
                match chars.get(i) {
                    Some(&q) => {
                        c = q;
                        i += 1;
                    }
                    None => break,
                }
            }
            if i + 1 < chars.len() && chars[i] == '-' {
                let mut c2 = chars[i + 1];
                i += 2;
                if c2 == '\\' && i < chars.len() {
                    c2 = chars[i];
                    i += 1;
                }
                if c <= c2 {
                    items.push(SkipItem::Range(c, c2));
                }
            } else {
                items.push(SkipItem::Range(c, c));
            }
        }
        Ok(SkipSet { negate, items })
    }
    fn contains(&self, c: char) -> bool {
        let hit = self.items.iter().any(|item| match item {
            SkipItem::Range(a, b) => (*a..=*b).contains(&c),
            SkipItem::Class(re) => re.is_match(c.encode_utf8(&mut [0; 4])).unwrap_or(false),
        });
        hit != self.negate
    }
}
/// syntax.c `skip_chars`: LIM nil is ZV (forward) / BEGV (backward), and any
/// LIM is clamped to the accessible portion — so a narrowing bounds the scan
/// and point already past LIM does not move. Returns the distance moved.
fn skip_chars(h: &mut ElispHost, a: &[Value], forward: bool) -> R {
    let set = SkipSet::parse(h, &as_string(h, &a[0])?)?;
    let lim = match a.get(1) {
        Some(v) if !is_nil(v) => Some(as_int_or_marker(h, v, "integer-or-marker-p")?),
        _ => None,
    };
    let buf = h.cur_buf();
    let (begv, zv) = (buf.begv as i64, buf.zv as i64);
    let lim = lim
        .unwrap_or(if forward { zv } else { begv })
        .clamp(begv, zv) as usize;
    let start = buf.point;
    if forward {
        while buf.point < lim && set.contains(buf.text[buf.point - 1]) {
            buf.point += 1;
        }
    } else {
        while buf.point > lim && set.contains(buf.text[buf.point - 2]) {
            buf.point -= 1;
        }
    }
    Ok(Value::Int(buf.point as i64 - start as i64))
}
fn skip_chars_forward(h: &mut ElispHost, a: &[Value]) -> R {
    skip_chars(h, a, true)
}
fn skip_chars_backward(h: &mut ElispHost, a: &[Value]) -> R {
    skip_chars(h, a, false)
}
/// Port of `scan_words` (syntax.c): the position COUNT words from FROM, or
/// `None` when the accessible region ends first.
///
/// A word is a run of word-syntax characters in the buffer's syntax table
/// (plus escape / char-quote characters under `words-include-escapes`).
/// Not ported: `word_boundary_p`'s script and category split, so a run that
/// changes script mid-word (`abcαβγ`) is one word here and two in Emacs; and
/// `find-word-boundary-function-table`.
fn scan_words(h: &ElispHost, from: usize, mut count: i64) -> Option<usize> {
    let escapes = h
        .find_symbol("words-include-escapes")
        .and_then(|s| h.get_value(&s).ok())
        .is_some_and(|v| !is_nil(&v));
    let buf = h.cur_buf_ref();
    let is_word = |c: char| {
        let code = h.syntax_class_of(c);
        code == 'w' || (escapes && (code == '\\' || code == '/'))
    };
    let mut from = from;
    while count > 0 {
        loop {
            if from == buf.zv {
                return None;
            }
            from += 1;
            if is_word(buf.text[from - 2]) {
                break;
            }
        }
        while from < buf.zv && is_word(buf.text[from - 1]) {
            from += 1;
        }
        count -= 1;
    }
    while count < 0 {
        loop {
            if from == buf.begv {
                return None;
            }
            from -= 1;
            if is_word(buf.text[from - 1]) {
                break;
            }
        }
        while from > buf.begv && is_word(buf.text[from - 2]) {
            from -= 1;
        }
        count += 1;
    }
    Some(from)
}
/// Port of `Fforward_word` (syntax.c): move over ARG words; on running out of
/// buffer, stop at the limit and answer nil.
fn forward_word(h: &mut ElispHost, a: &[Value]) -> R {
    let n = match a.first() {
        Some(v) if !is_nil(v) => as_fixnum_named(h, v, "fixnump")?,
        _ => 1,
    };
    let found = scan_words(h, h.cur_buf_ref().point, n);
    let buf = h.cur_buf();
    buf.point = found.unwrap_or(if n > 0 { buf.zv } else { buf.begv });
    Ok(nil_or(found.is_some()))
}
/// `backward-word` (simple.el): `(forward-word (- (or arg 1)))`.
fn backward_word(h: &mut ElispHost, a: &[Value]) -> R {
    let arg = match a.first() {
        Some(v) if !is_nil(v) => v.clone(),
        _ => Value::Int(1),
    };
    let neg = match arg {
        Value::Int(n) => Value::Int(-n),
        Value::Float(f) => Value::Float(-f),
        other => {
            return Err(format!(
                "wrong-type-argument: number-or-marker-p {}",
                h.print(&other, true)
            ))
        }
    };
    forward_word(h, &[neg])
}

/// Install the primitive subr set.
pub fn install(h: &mut ElispHost) {
    crate::window::install(h);
    crate::window::install_frame_geometry(h);
    crate::window::install_window_display(h);
    let mut s = |n: &str, min: usize, max: Option<usize>, f: crate::host::SubrFn| {
        h.defsubr(n, min, max, f);
    };
    // arithmetic
    s("+", 0, None, add);
    s("-", 0, None, sub);
    s("*", 0, None, mul);
    s("/", 1, None, div);
    s("%", 2, Some(2), modulo);
    s("mod", 2, Some(2), mod_fn);
    s("1+", 1, Some(1), one_plus);
    s("1-", 1, Some(1), one_minus);
    s("=", 1, None, num_eq);
    s("<", 1, None, lt);
    s(">", 1, None, gt);
    s("<=", 1, None, le);
    s(">=", 1, None, ge);
    // equality / predicates
    s("eq", 2, Some(2), eq_fn);
    s("eql", 2, Some(2), eql_fn);
    s("equal", 2, Some(2), equal_fn);
    // fns.c list search. These were prelude `defun`s, which made `subrp` nil where
    // Emacs says t, named the closure in a wrong-arity signal, and — because a
    // `while (consp l)` loop has no cycle check — did not terminate on a circular
    // list at all.
    s("memq", 2, Some(2), memq_fn);
    s("memql", 2, Some(2), memql_fn);
    s("member", 2, Some(2), member_fn);
    s("assq", 2, Some(2), assq_fn);
    s("rassq", 2, Some(2), rassq_fn);
    s("rassoc", 2, Some(2), rassoc_fn);
    s("null", 1, Some(1), null_fn);
    s("consp", 1, Some(1), consp);
    s("listp", 1, Some(1), listp);
    s("atom", 1, Some(1), atom);
    s("symbolp", 1, Some(1), symbolp);
    s("stringp", 1, Some(1), stringp);
    s("natnump", 1, Some(1), natnump_fn);
    s("nlistp", 1, Some(1), nlistp_fn);
    s("numberp", 1, Some(1), numberp);
    s("integerp", 1, Some(1), integerp);
    s("max", 1, None, max_fn);
    s("min", 1, None, min_fn);
    s("fixnump", 1, Some(1), fixnump);
    s("bignump", 1, Some(1), bignump);
    s("floatp", 1, Some(1), floatp);
    s("vectorp", 1, Some(1), vectorp);
    // NOTE: `zerop` is deliberately NOT a subr: in Emacs it is a byte-compiled
    // defsubst from subr.el ((subrp (symbol-function 'zerop)) => nil) whose
    // arity error is (wrong-number-of-arguments (1 . 1) N), so it is defined in
    // the prelude. Registering it here would also lose the prelude's shadowing
    // definition on a bytecode-cache HIT, since builtin-range symbols' function
    // cells are not part of the exported heap image.
    // lists
    s("cons", 2, Some(2), cons_fn);
    s("car", 1, Some(1), car);
    s("cdr", 1, Some(1), cdr);
    s("setcar", 2, Some(2), setcar);
    s("setcdr", 2, Some(2), setcdr);
    s("car-less-than-car", 2, Some(2), car_less_than_car);
    s("list", 0, None, list_fn);
    s("append", 0, None, append_fn);
    s("reverse", 1, Some(1), reverse_fn);
    s("length", 1, Some(1), length_fn);
    s("nth", 2, Some(2), nth_fn);
    s("nthcdr", 2, Some(2), nthcdr_fn);
    // c[ad]+r compositions, two to four letters, plus the cl-lib prefixed
    // two-letter names (the prelude aliases the three- and four-letter ones).
    for (name, f) in CXR_SUBRS {
        s(name, 1, Some(1), *f);
    }
    s("cl-caar", 1, Some(1), caar);
    s("cl-cadr", 1, Some(1), cadr);
    s("cl-cdar", 1, Some(1), cdar);
    s("cl-cddr", 1, Some(1), cddr);
    // vectors
    s("vector", 0, None, vector_fn);
    s("make-vector", 2, Some(2), make_vector);
    s("make-list", 2, Some(2), make_list);
    s("record", 1, None, record_fn);
    s("make-record", 3, Some(3), make_record);
    s("make-bool-vector", 2, Some(2), make_bool_vector);
    s("bool-vector", 0, None, bool_vector_fn);
    s("bool-vector-p", 1, Some(1), bool_vector_p);
    s(
        "bool-vector-count-population",
        1,
        Some(1),
        bool_vector_count_population,
    );
    s("bool-vector-subsetp", 2, Some(2), bool_vector_subsetp);
    s("bool-vector-not", 1, Some(2), bool_vector_not);
    s(
        "bool-vector-exclusive-or",
        2,
        Some(3),
        bool_vector_exclusive_or,
    );
    s("bool-vector-union", 2, Some(3), bool_vector_union);
    s(
        "bool-vector-intersection",
        2,
        Some(3),
        bool_vector_intersection,
    );
    s(
        "bool-vector-set-difference",
        2,
        Some(3),
        bool_vector_set_difference,
    );
    s(
        "bool-vector-count-consecutive",
        3,
        Some(3),
        bool_vector_count_consecutive,
    );
    s("elt", 2, Some(2), elt_fn);
    s("aref", 2, Some(2), aref);
    s("aset", 3, Some(3), aset);
    // overlays
    s("make-overlay", 2, Some(5), make_overlay);
    s("overlayp", 1, Some(1), overlayp);
    s("overlay-start", 1, Some(1), overlay_start);
    s("overlay-end", 1, Some(1), overlay_end);
    s("overlay-buffer", 1, Some(1), overlay_buffer);
    s("overlay-get", 2, Some(2), overlay_get);
    s("overlay-put", 3, Some(3), overlay_put);
    s("overlay-properties", 1, Some(1), overlay_properties);
    s("delete-overlay", 1, Some(1), delete_overlay);
    s("move-overlay", 3, Some(4), move_overlay);
    s("overlays-at", 1, Some(2), overlays_at);
    s("overlays-in", 2, Some(2), overlays_in);
    s("next-overlay-change", 1, Some(1), next_overlay_change);
    s(
        "previous-overlay-change",
        1,
        Some(1),
        previous_overlay_change,
    );
    s("--note-compiler-macro", 1, Some(1), note_compiler_macro);
    s("store-substring", 3, Some(3), store_substring);
    s("clear-string", 1, Some(1), clear_string);
    s("fillarray", 2, Some(2), fillarray);
    s("make-char-table--new", 3, Some(3), make_char_table_new);
    s("elisprs--copy-char-table", 1, Some(1), copy_char_table);
    s("elisprs--copy-string", 1, Some(1), copy_string);
    s("elisprs--char-table-runs", 1, Some(1), char_table_runs);
    s("optimize-char-table", 1, Some(2), optimize_char_table);
    s("char-table-p", 1, Some(1), char_table_p);
    s("char-table-subtype", 1, Some(1), char_table_subtype);
    s("char-table-parent", 1, Some(1), char_table_parent);
    s("set-char-table-parent", 2, Some(2), set_char_table_parent);
    s("char-table-extra-slot", 2, Some(2), char_table_extra_slot);
    s(
        "set-char-table-extra-slot",
        3,
        Some(3),
        set_char_table_extra_slot,
    );
    s("char-table-range", 2, Some(2), char_table_range);
    s("set-char-table-range", 3, Some(3), set_char_table_range);
    s("--char-table-run-end--", 3, Some(3), char_table_run_end);
    // symbols
    s("symbol-name", 1, Some(1), symbol_name);
    s("intern", 1, Some(2), intern_fn);
    s("obarray-make", 0, Some(1), obarray_make_fn);
    s("obarrayp", 1, Some(1), obarrayp_fn);
    s("unintern", 1, Some(2), unintern_fn);
    s("make-symbol", 1, Some(1), make_symbol_fn);
    s("set", 2, Some(2), set_fn);
    s("symbol-value", 1, Some(1), symbol_value);
    s("keywordp", 1, Some(1), keywordp);
    s("boundp", 1, Some(1), boundp);
    s("default-boundp", 1, Some(1), default_boundp);
    s("default-toplevel-value", 1, Some(1), default_toplevel_value);
    s("bare-symbol-p", 1, Some(1), bare_symbol_p);
    s("makunbound", 1, Some(1), makunbound);
    s("defvaralias", 2, Some(3), defvaralias);
    s("indirect-variable", 1, Some(1), indirect_variable);
    s("sha1", 1, Some(4), sha1_fn);
    s("md5", 1, Some(5), md5_fn);
    s("secure-hash", 2, Some(5), secure_hash);
    s("secure-hash-algorithms", 0, Some(0), secure_hash_algorithms);
    s("base64-encode-string", 1, Some(2), base64_encode_string);
    s("base64-decode-string", 1, Some(3), base64_decode_string);
    s(
        "base64url-encode-string",
        1,
        Some(2),
        base64url_encode_string,
    );
    s(
        "base64url-decode-string",
        1,
        Some(2),
        base64url_decode_string,
    );
    s("url-hexify-string", 1, Some(2), url_hexify_string);
    s("url-unhex-string", 1, Some(2), url_unhex_string);
    s("fset", 2, Some(2), fset);
    s("fboundp", 1, Some(1), fboundp);
    s("fmakunbound", 1, Some(1), fmakunbound);
    // json.c
    s("json-parse-string", 1, None, crate::json::json_parse_string);
    s("json-parse-buffer", 0, None, crate::json::json_parse_buffer);
    s("json-serialize", 1, None, crate::json::json_serialize);
    s("json-insert", 1, None, crate::json::json_insert);
    s(
        "json-available-p",
        0,
        Some(0),
        crate::json::json_available_p,
    );
    s("indirect-function", 1, Some(2), indirect_function);
    // The higher-order primitives run in `host::call_function`, which intercepts
    // them by name *before* any function-cell lookup so they never execute
    // inside a host borrow. That left them with no function cell at all, so
    // `(fboundp 'mapcar)`, `(functionp 'eval)`, `(func-arity 'funcall)`,
    // `(indirect-function 'apply)` and `(symbol-function 'load)` all answered as
    // though the name were undefined, where Emacs reports `#<subr NAME>`.
    // Registering the cell here restores every one of those answers; the bodies
    // below are unreachable, because `call_function` matches the name first —
    // for a bare symbol and, since this change, for the subr object too, so
    // `(funcall (symbol-function 'mapcar) …)` routes to the intercept as well.
    // `intercepted_subr` is what runs if that ever stops being true, and it says
    // so rather than answering wrongly.
    //
    // NAMED boundary: `macroexpand-1` and `macroexpand-all` are byte-compiled
    // Lisp in Emacs (macroexp.el), not subrs, so `(subrp (symbol-function
    // 'macroexpand-1))` is nil there and t here. The other four observables
    // agree; they are native here, and there is no Lisp definition to point at.
    s("funcall", 1, None, intercepted_subr);
    s("apply", 1, None, intercepted_subr);
    s("mapcar", 2, Some(2), intercepted_subr);
    s("mapc", 2, Some(2), intercepted_subr);
    // `assoc` calls TESTFN and `mapconcat` calls FUNCTION, so both re-enter elisp
    // and both are driven from `host::call_function`. Registering the cell keeps
    // `subrp` / `subr-name` / `func-arity` / `symbol-function` answering as Emacs
    // does for a C subr in fns.c.
    s("assoc", 2, Some(3), intercepted_subr);
    s("mapconcat", 2, Some(3), intercepted_subr);
    s("maphash", 2, Some(2), intercepted_subr);
    s("mapatoms", 1, Some(2), intercepted_subr);
    s("load", 1, Some(5), intercepted_subr);
    s("eval", 1, Some(2), intercepted_subr);
    s("macroexpand", 1, Some(2), intercepted_subr);
    s("macroexpand-1", 1, Some(2), intercepted_subr);
    s("macroexpand-all", 1, Some(2), intercepted_subr);
    s("sort", 1, None, intercepted_subr);
    s("identity", 1, Some(1), identity);
    s("terpri", 0, Some(2), terpri);
    s("write-char", 1, Some(2), write_char_fn);
    s("backquote-process", 1, Some(2), backquote_process_fn);
    s("print", 1, Some(2), print_fn);
    s("prin1-to-string", 1, Some(3), prin1_to_string);
    // nonlocal exits (catch/unwind-protect/condition-case are compiler intrinsics)
    s("throw", 2, Some(2), throw_fn);
    s("error", 1, None, error_fn);
    s("user-error", 1, None, user_error_fn);
    s("signal", 1, Some(2), signal_fn);
    // hash tables (maphash is intercepted in host::call_function)
    // Intercepted: resolving a `define-hash-table-test` name reads an elisp
    // plist, which cannot happen inside a host borrow.
    s("make-hash-table", 0, None, intercepted_subr);
    // Intercepted: a `define-hash-table-test` table's test and hash functions
    // are elisp, so a lookup on one has to run outside the host borrow.
    s("gethash", 2, Some(3), intercepted_subr);
    s("puthash", 3, Some(3), intercepted_subr);
    s("remhash", 2, Some(2), intercepted_subr);
    s("clrhash", 1, Some(1), clrhash);
    s("hash-table-count", 1, Some(1), hash_table_count);
    s("hash-table-test", 1, Some(1), hash_table_test);
    s("hash-table-size", 1, Some(1), hash_table_size);
    s("hash-table-weakness", 1, Some(1), hash_table_weakness);
    s("hash-table-p", 1, Some(1), hash_table_p);
    s("hash-table-keys", 1, Some(1), hash_table_keys);
    s("hash-table-values", 1, Some(1), hash_table_values);
    s("copy-hash-table", 1, Some(1), copy_hash_table);
    // time
    s("getenv-internal", 1, Some(2), getenv_internal);
    s("set-time-zone-rule", 1, Some(1), set_time_zone_rule);
    s("undo-boundary", 0, Some(0), undo_boundary_fn);
    s("subst-char-in-region", 4, Some(5), subst_char_in_region);
    s("recent-auto-save-p", 0, Some(0), recent_auto_save_p);
    s("special-variable-p", 1, Some(1), special_variable_p);
    s("func-arity", 1, Some(1), func_arity);
    s("subr-arity", 1, Some(1), func_arity);
    s("subr-name", 1, Some(1), subr_name);
    s("--current-directory--", 0, Some(0), current_directory);
    s(
        "file-name-directory",
        1,
        Some(1),
        crate::fileio::file_name_directory,
    );
    s(
        "file-name-nondirectory",
        1,
        Some(1),
        crate::fileio::file_name_nondirectory,
    );
    s(
        "file-name-as-directory",
        1,
        Some(1),
        crate::fileio::file_name_as_directory,
    );
    s(
        "directory-file-name",
        1,
        Some(1),
        crate::fileio::directory_file_name,
    );
    s(
        "directory-name-p",
        1,
        Some(1),
        crate::fileio::directory_name_p,
    );
    s("file-name-concat", 1, None, crate::fileio::file_name_concat);
    s(
        "file-name-absolute-p",
        1,
        Some(1),
        crate::fileio::file_name_absolute_p,
    );
    s(
        "expand-file-name",
        1,
        Some(2),
        crate::fileio::expand_file_name,
    );
    s(
        "file-name-case-insensitive-p",
        1,
        Some(1),
        crate::fileio::file_name_case_insensitive_p,
    );
    s("--system-type--", 0, Some(0), system_type);
    s("--build-time--", 0, Some(0), build_time);
    s("system-name", 0, Some(0), system_name);
    s("user-login-name", 0, Some(1), user_login_name);
    s("user-real-login-name", 0, Some(0), user_real_login_name);
    s("user-uid", 0, Some(0), user_uid);
    s("user-real-uid", 0, Some(0), user_real_uid);
    s("--temp-directory--", 0, Some(0), temp_directory);
    s("file-exists-p", 1, Some(1), file_exists_p);
    s("file-directory-p", 1, Some(1), file_directory_p);
    s("file-regular-p", 1, Some(1), file_regular_p);
    s("file-readable-p", 1, Some(1), file_readable_p);
    s("file-writable-p", 1, Some(1), file_writable_p);
    s("file-symlink-p", 1, Some(1), file_symlink_p);
    s("file-attributes", 1, Some(2), file_attributes);
    s("file-modes", 1, Some(2), file_modes);
    s("set-file-modes", 2, Some(3), set_file_modes);
    s("file-newer-than-file-p", 2, Some(2), file_newer_than_file_p);
    s(
        "file-accessible-directory-p",
        1,
        Some(1),
        file_accessible_directory_p,
    );
    s(
        "delete-directory-internal",
        1,
        Some(1),
        delete_directory_internal,
    );
    s("make-symbolic-link", 2, Some(3), make_symbolic_link);
    s("add-name-to-file", 2, Some(3), add_name_to_file);
    s("file-executable-p", 1, Some(1), file_executable_p);
    s("--invocation-file--", 0, Some(0), invocation_file);
    s("--directory-files--", 1, Some(3), directory_files_raw);
    // buffer registry
    s("bufferp", 1, Some(1), bufferp);
    s("current-buffer", 0, Some(0), current_buffer_fn);
    s("set-buffer", 1, Some(1), set_buffer_fn);
    s("get-buffer", 1, Some(1), get_buffer);
    s("get-buffer-create", 1, Some(2), get_buffer_create);
    s("generate-new-buffer", 1, Some(3), generate_new_buffer);
    s(
        "generate-new-buffer-name",
        1,
        Some(2),
        generate_new_buffer_name,
    );
    s("buffer-name", 0, Some(1), buffer_name);
    s("buffer-live-p", 1, Some(1), buffer_live_p);
    s("kill-buffer", 0, Some(1), kill_buffer);
    s("get-buffer-process", 1, Some(1), get_buffer_process);
    s("rename-buffer", 1, Some(2), rename_buffer);
    s("buffer-list", 0, Some(1), buffer_list);
    // mark + narrowing
    s("mark-marker", 0, Some(0), mark_marker_fn);
    s("region-beginning", 0, Some(0), region_beginning);
    s("region-end", 0, Some(0), region_end);
    s("narrow-to-region", 2, Some(2), narrow_to_region);
    s("widen", 0, Some(0), widen_fn);
    s("--se-push--", 0, Some(0), se_push);
    s("--se-pop--", 0, Some(0), se_pop);
    s("--save-restriction--", 0, Some(0), save_restriction_push);
    s("--restore-restriction--", 0, Some(0), restore_restriction);
    // buffer-local variables
    s("make-local-variable", 1, Some(1), make_local_variable);
    s(
        "make-variable-buffer-local",
        1,
        Some(1),
        make_variable_buffer_local,
    );
    s("local-variable-p", 1, Some(2), local_variable_p);
    s(
        "local-variable-if-set-p",
        1,
        Some(2),
        local_variable_if_set_p,
    );
    s("kill-local-variable", 1, Some(1), kill_local_variable);
    s(
        "--buffer-local-symbols--",
        0,
        Some(0),
        buffer_local_symbols_fn,
    );
    s("--make-always-local--", 2, Some(2), make_always_local_fn);
    s("--early-declarations--", 0, Some(0), early_declarations_fn);
    s("--defvar-declare--", 1, Some(1), defvar_declare_fn);
    s("--declare-special", 1, Some(1), declare_special_fn);
    s("buffer-local-value", 2, Some(2), buffer_local_value_fn);
    s("default-value", 1, Some(1), default_value_fn);
    s("set-default", 2, Some(2), set_default_fn);
    s("use-local-map", 1, Some(1), use_local_map_fn);
    s("current-local-map", 0, Some(0), current_local_map_fn);
    s("insert", 0, None, insert_fn);
    s(
        "insert-buffer-substring",
        1,
        Some(3),
        insert_buffer_substring,
    );
    s("point-min-marker", 0, Some(0), point_min_marker);
    s("point-max-marker", 0, Some(0), point_max_marker);
    s(
        "delete-and-extract-region",
        2,
        Some(2),
        delete_and_extract_region,
    );
    s("buffer-string", 0, Some(0), buffer_string);
    s("buffer-size", 0, Some(1), buffer_size);
    s("point", 0, Some(0), point_fn);
    s("point-min", 0, Some(0), point_min);
    s("point-max", 0, Some(0), point_max);
    s("goto-char", 1, Some(1), goto_char);
    s("erase-buffer", 0, Some(0), erase_buffer);
    s("buffer-modified-p", 0, Some(1), buffer_modified_p);
    s("position-bytes", 1, Some(1), position_bytes);
    s("byte-to-position", 1, Some(1), byte_to_position);
    s(
        "restore-buffer-modified-p",
        1,
        Some(1),
        restore_buffer_modified_p,
    );
    s("set-buffer-modified-p", 1, Some(1), set_buffer_modified_p);
    s("buffer-modified-tick", 0, Some(1), buffer_modified_tick);
    s(
        "buffer-chars-modified-tick",
        0,
        Some(1),
        buffer_chars_modified_tick,
    );
    s("char-after", 0, Some(1), char_after);
    s("buffer-substring", 2, Some(2), buffer_substring);
    s(
        "buffer-substring-no-properties",
        2,
        Some(2),
        buffer_substring_no_properties,
    );
    s("delete-region", 2, Some(2), delete_region);
    // markers
    s("make-marker", 0, Some(0), make_marker);
    s("point-marker", 0, Some(0), point_marker);
    s("markerp", 1, Some(1), markerp_fn);
    s("marker-position", 1, Some(1), marker_position_fn);
    s("marker-buffer", 1, Some(1), marker_buffer_fn);
    s(
        "marker-insertion-type",
        1,
        Some(1),
        marker_insertion_type_fn,
    );
    s(
        "set-marker-insertion-type",
        2,
        Some(2),
        set_marker_insertion_type_fn,
    );
    s("set-marker", 2, Some(3), set_marker_fn);
    s("move-marker", 2, Some(3), set_marker_fn);
    s("copy-marker", 0, Some(2), copy_marker_fn);
    // text properties
    s("next-property-change", 1, Some(3), next_property_change_fn);
    s(
        "next-single-property-change",
        2,
        Some(4),
        next_single_property_change_fn,
    );
    s(
        "previous-property-change",
        1,
        Some(3),
        previous_property_change_fn,
    );
    s(
        "previous-single-property-change",
        2,
        Some(4),
        previous_single_property_change_fn,
    );
    s("object-intervals", 1, Some(1), object_intervals_fn);
    s(
        "elisprs--inside-interval-p",
        1,
        Some(1),
        inside_interval_p_fn,
    );
    s("elisprs--inherit-props", 5, Some(6), inherit_props_fn);
    s(
        "add-face-text-property",
        3,
        Some(5),
        add_face_text_property_fn,
    );
    s("get-text-property", 2, Some(3), get_text_property_fn);
    s("text-properties-at", 1, Some(2), text_properties_at_fn);
    s("put-text-property", 4, Some(5), put_text_property_fn);
    s("set-text-properties", 3, Some(4), set_text_properties_fn);
    s("add-text-properties", 3, Some(4), add_text_properties_fn);
    s(
        "remove-text-properties",
        3,
        Some(4),
        remove_text_properties_fn,
    );
    s("propertize", 1, None, propertize_fn);
    s("transpose-regions", 4, Some(5), transpose_regions_fn);
    s(
        "elisprs--replace-chars-in-place",
        3,
        Some(3),
        replace_chars_in_place_fn,
    );
    s(
        "elisprs--carry-text-properties",
        2,
        Some(2),
        carry_text_properties_fn,
    );
    s(
        "--insert-before-markers--",
        1,
        Some(1),
        insert_before_markers_fn,
    );
    s("insert-file-contents", 1, None, insert_file_contents);
    s("forward-char", 0, Some(1), forward_char);
    s("backward-char", 0, Some(1), backward_char);
    s("beginning-of-line", 0, Some(1), beginning_of_line);
    s("end-of-line", 0, Some(1), end_of_line);
    s(
        "line-beginning-position",
        0,
        Some(1),
        line_beginning_position,
    );
    s("line-end-position", 0, Some(1), line_end_position);
    s("pos-bol", 0, Some(1), line_beginning_position);
    s("pos-eol", 0, Some(1), line_end_position);
    s("bolp", 0, Some(0), bolp);
    s("eolp", 0, Some(0), eolp);
    s("bobp", 0, Some(0), bobp);
    s("eobp", 0, Some(0), eobp);
    s("forward-line", 0, Some(1), forward_line);
    s("search-forward", 1, Some(4), search_forward);
    s("re-search-forward", 1, Some(4), re_search_forward);
    s("looking-at", 1, Some(2), looking_at);
    s(
        "current-bidi-paragraph-direction",
        0,
        Some(1),
        crate::bidi::current_bidi_paragraph_direction,
    );
    s("looking-at-p", 1, Some(1), looking_at_p);
    s("replace-match", 1, Some(5), replace_match);
    // filesystem writes / mutations
    s("write-region", 3, Some(7), write_region);
    s("delete-file-internal", 1, Some(1), delete_file_internal);
    s(
        "make-directory-internal",
        1,
        Some(1),
        make_directory_internal,
    );
    s("rename-file", 2, Some(3), rename_file);
    s("copy-file", 2, Some(6), copy_file);
    s(
        "shell-command-to-string",
        1,
        Some(1),
        shell_command_to_string,
    );
    s("call-process", 1, None, call_process);
    s("char-before", 0, Some(1), char_before);
    s("delete-char", 1, Some(2), delete_char);
    s("insert-char", 1, Some(3), insert_char);
    s("count-lines", 2, Some(3), count_lines);
    s("line-number-at-pos", 0, Some(2), line_number_at_pos);
    s("current-column", 0, Some(0), current_column);
    s("current-indentation", 0, Some(0), current_indentation);
    s("indent-to", 1, Some(2), indent_to);
    s("move-to-column", 1, Some(2), move_to_column);
    s("search-backward", 1, Some(4), search_backward);
    s("re-search-backward", 1, Some(4), re_search_backward);
    s("skip-chars-forward", 1, Some(2), skip_chars_forward);
    s("skip-chars-backward", 1, Some(2), skip_chars_backward);
    s("forward-word", 0, Some(1), forward_word);
    s("backward-word", 0, Some(1), backward_word);
    s("random", 0, Some(1), random_fn);
    s("float-time", 0, Some(1), float_time);
    s("sleep-for", 1, Some(2), sleep_for);
    s("current-time", 0, Some(0), current_time);
    s("format-time-string", 1, Some(3), format_time_string);
    s("current-time-string", 0, Some(2), current_time_string);
    s("decode-time", 0, Some(3), decode_time);
    s("encode-time", 1, None, encode_time);
    s("time--decode", 1, Some(1), crate::timefns::time_decode_fn);
    // strings
    s("substring", 1, Some(3), substring);
    s(
        "substring-no-properties",
        1,
        Some(3),
        substring_no_properties_fn,
    );
    s("split-string", 1, Some(4), split_string);
    s("string-prefix-p", 2, Some(3), string_prefix_p);
    s("string-suffix-p", 2, Some(3), string_suffix_p);
    s("string-empty-p", 1, Some(1), string_empty_p);
    s("string-join", 1, Some(2), string_join);
    s("char-to-string", 1, Some(1), char_to_string);
    s("string-to-char", 1, Some(1), string_to_char);
    s("make-string", 2, Some(3), make_string);
    s("string", 0, None, string_fn);
    s("string-to-list", 1, Some(1), string_to_list);
    s("string-search", 2, Some(3), string_search);
    // regexp
    s("string-match", 2, Some(3), string_match);
    s("string-match-p", 2, Some(3), string_match_p);
    s("match-beginning", 1, Some(1), match_beginning);
    s("match-end", 1, Some(1), match_end);
    s("match-string", 1, Some(2), match_string);
    s("match-data", 0, Some(3), match_data_fn);
    s("set-match-data", 1, Some(2), set_match_data);
    s("match-data--translate", 1, Some(1), match_data_translate);
    s("regexp-quote", 1, Some(1), regexp_quote);
    // `replace-regexp-in-string` is Lisp in Emacs (subr.el) and Lisp here — see
    // the prelude, which mirrors that definition.
    // strings / IO
    s("concat", 0, None, concat_fn);
    s("format", 1, None, format_fn);
    s("message", 1, None, message_fn);
    s("princ", 1, Some(2), princ_fn);
    s("prin1", 1, Some(2), prin1_fn);
    s("number-to-string", 1, Some(1), number_to_string);
    // numeric: float→int rounding + integer bit ops
    s("floor", 1, Some(2), floor_fn);
    s("ceiling", 1, Some(2), ceiling_fn);
    s("round", 1, Some(2), round_fn);
    s("truncate", 1, Some(2), truncate_fn);
    s("float", 1, Some(1), float_fn);
    s("logand", 0, None, logand_fn);
    s("logior", 0, None, logior_fn);
    s("logxor", 0, None, logxor_fn);
    s("lognot", 1, Some(1), lognot_fn);
    s("ash", 2, Some(2), ash_fn);
    s("lsh", 2, Some(2), lsh_fn);
    // parity: float math / parsing / introspection
    s("expt", 2, Some(2), expt_fn);
    s("sqrt", 1, Some(1), sqrt_fn);
    s("exp", 1, Some(1), exp_fn);
    s("log", 1, Some(2), log_fn);
    s("sin", 1, Some(1), sin_fn);
    s("cos", 1, Some(1), cos_fn);
    s("tan", 1, Some(1), tan_fn);
    s("asin", 1, Some(1), asin_fn);
    s("acos", 1, Some(1), acos_fn);
    s("atan", 1, Some(2), atan_fn);
    s("ldexp", 2, Some(2), ldexp_fn);
    s("copysign", 2, Some(2), copysign_fn);
    s("frexp", 1, Some(1), frexp_fn);
    s("isnan", 1, Some(1), isnan_fn);
    s("fround", 1, Some(1), fround_fn);
    s("ffloor", 1, Some(1), ffloor_fn);
    s("fceiling", 1, Some(1), fceiling_fn);
    s("ftruncate", 1, Some(1), ftruncate_fn);
    s("string-to-number", 1, Some(2), string_to_number);
    s("downcase", 1, Some(1), downcase_fn);
    s("upcase", 1, Some(1), upcase_fn);
    s("--char-titlecase--", 1, Some(1), char_titlecase);
    s("type-of", 1, Some(1), type_of);
    s("recordp", 1, Some(1), recordp);
    s("closurep", 1, Some(1), closurep_fn);
    s(
        "elisprs--prelude-closure-p",
        1,
        Some(1),
        prelude_closure_p_fn,
    );
    s("oclosure--fix-type", 4, Some(4), oclosure_fix_type);
    s("oclosure-type", 1, Some(1), oclosure_type_fn);
    s("oclosure--get", 3, Some(3), oclosure_get_fn);
    s("oclosure--set", 3, Some(3), oclosure_set_fn);
    s("oclosure--copy", 2, None, oclosure_copy_fn);
    s("sxhash-equal", 1, Some(1), sxhash_equal_fn);
    s("sxhash", 1, Some(1), sxhash_equal_fn);
    s("sxhash-eq", 1, Some(1), sxhash_eq_fn);
    s("sxhash-eql", 1, Some(1), sxhash_eql_fn);
    s("cl-struct-p", 1, Some(1), recordp);
    s("functionp", 1, Some(1), functionp);
    s("char-or-string-p", 1, Some(1), char_or_string_p);
    s("char-equal", 2, Some(2), char_equal);
    s("char-width", 1, Some(1), char_width_fn);
    s("vconcat", 0, None, vconcat_fn);
    s("string-to-vector", 1, Some(1), string_to_vector);
    s("abs", 1, Some(1), abs_fn);
    s("logcount", 1, Some(1), logcount_fn);
    s("symbol-function", 1, Some(1), symbol_function);
    s(
        "--set-intrinsic-macro-cell",
        2,
        Some(2),
        set_intrinsic_macro_cell,
    );
    s("intern-soft", 1, Some(2), intern_soft);
    s("subrp", 1, Some(1), subrp);
    s("--set-subr-intspec", 2, Some(2), set_subr_intspec);
    s("--subr-intspec", 1, Some(1), subr_intspec);
    s("macrop", 1, Some(1), macrop);
    s("special-form-p", 1, Some(1), special_form_p);
    s("char-uppercase-p", 1, Some(1), char_uppercase_p);
    s("string-distance", 2, Some(3), string_distance);
    s("logb", 1, Some(1), logb_fn);
    s("max-char", 0, Some(1), max_char);
    s("byteorder", 0, Some(0), byteorder);
    s("char-resolve-modifiers", 1, Some(1), char_resolve_modifiers);
    s("text-char-description", 1, Some(1), text_char_description);
    s(
        "unibyte-char-to-multibyte",
        1,
        Some(1),
        unibyte_char_to_multibyte,
    );
    s(
        "multibyte-char-to-unibyte",
        1,
        Some(1),
        multibyte_char_to_unibyte,
    );
    s("decode-char", 2, Some(2), decode_char);
    s("emacs-pid", 0, Some(0), emacs_pid);
    s("load-average", 0, Some(1), load_average);
    s("read", 0, Some(1), read_fn);
    s("read-from-string", 1, Some(3), read_from_string);
    s("read-from-minibuffer", 1, Some(7), read_from_minibuffer);
    s("read-string", 1, Some(5), read_string);
    s("kill-emacs", 0, Some(2), intercepted_subr);
    s("compare-strings", 6, Some(7), compare_strings);
    // Emacs 28 alias for split-string with identical semantics (direct forwarder).
    s("string-split", 1, Some(4), split_string);
    s("member-ignore-case", 2, Some(2), member_ignore_case);
    // `not` is `(defalias 'not #'null)` in Emacs (subr.el), not a subr of its
    // own: `(symbol-function 'not)` is the symbol `null`, and an arity error
    // through `#'not` names `#<subr null>`. Alias the symbol rather than
    // registering a second subr so both render exactly that way.
    let null_sym = h.intern("null");
    h.set_function("not", null_sym);
    install_special_form_cells(h);
    // AOP pattern-intercept layer (elisprs extension, ported from zshrs). Registers
    // the `intercept*` subrs and marks its context variables special.
    crate::intercepts::install(h);
}

/// Whether NAME is one of Emacs's special forms.
pub(crate) fn is_special_form(name: &str) -> bool {
    SPECIAL_FORMS.iter().any(|(sf, _)| *sf == name)
}

/// The body of the subr that stands for a special form.
///
/// Unreachable: evaluating `if`/`let`/`progn` goes through the compiler, and
/// calling one goes through `host::call_function`, which refuses it exactly as
/// Emacs's `funcall` refuses a subr whose `max_args` is `UNEVALLED`. Getting here
/// means a call site bypassed that check.
fn special_form_body(_h: &mut ElispHost, _a: &[Value]) -> R {
    Err(
        "internal: a special form's subr body was called; host::call_function \
         should have signalled invalid-function"
            .to_string(),
    )
}

/// Give every special form the `#<subr NAME>` function cell Emacs gives it.
///
/// In Emacs a special form is an ordinary subr whose `max_args` is `UNEVALLED`,
/// so it answers `fboundp`, `symbol-function`, `indirect-function`, `subrp` and
/// `subr-name` exactly like `car` does — `(fboundp 'if)` is `t` and
/// `(symbol-function 'if)` prints `#<subr if>`. elisprs lowers these forms in the
/// compiler and so had no function cell at all for them, which made all five
/// answer as though `if` were undefined.
///
/// The cell goes in the introspection side table rather than the symbol's real
/// function cell: `resolve_function` must keep failing for it, because
/// `(functionp 'if)` is nil in Emacs and `(funcall 'if …)` is an error, not a
/// call.
fn install_special_form_cells(h: &mut ElispHost) {
    for (name, min) in SPECIAL_FORMS {
        let subr = h.alloc(Obj::Subr {
            name: (*name).to_string(),
            min: *min as usize,
            max: None,
            f: special_form_body,
        });
        let sym = h.intern(name);
        h.set_intrinsic_macro_cell(&sym, subr);
    }
}

// ── text-property queries over intervals (textprop.c) ──────────────────────
/// The intervals of a text-property OBJECT as `(START, END, PLIST)` in the
/// object's own coordinates (strings count from 0, buffers from 1), or `None`
/// when it has none.
fn object_runs(h: &ElispHost, obj: &PropObj) -> Option<Vec<(i64, i64, Value)>> {
    match obj {
        PropObj::Str(s) => {
            let runs = h.string_intervals(s);
            if runs.is_empty() {
                None
            } else {
                Some(
                    runs.into_iter()
                        .map(|(a, b, p)| (a as i64, b as i64, p))
                        .collect(),
                )
            }
        }
        PropObj::Buf(bi) => {
            let b = &h.buffers[*bi];
            if !b.has_intervals || b.props.is_empty() {
                return None;
            }
            Some(
                h.tp_runs(&b.props, &b.prop_bounds)
                    .into_iter()
                    .map(|(a, e)| (a as i64 + 1, e as i64 + 1, b.props[a].clone()))
                    .collect(),
            )
        }
    }
}

/// `validate_interval_range` for a single POSITION: the position, as an
/// integer, checked against the object's accessible range.
fn single_position(h: &ElispHost, obj: &PropObj, pos: &Value) -> Result<i64, String> {
    let p = match h.marker_position(pos) {
        Some(p) => p as i64,
        None => match pos {
            Value::Int(n) => *n,
            other => {
                return Err(format!(
                    "wrong-type-argument: integer-or-marker-p {}",
                    h.print(other, true)
                ))
            }
        },
    };
    let (min, max) = match obj {
        PropObj::Str(s) => (0, s.chars().count() as i64),
        PropObj::Buf(bi) => {
            let (begv, zv) = h.buffer_begv_zv(*bi);
            (begv as i64, zv as i64)
        }
    };
    if p < min || p > max {
        return Err(format!("args-out-of-range: {p} {p}"));
    }
    Ok(p)
}

/// `textget`: PROP in PLIST, falling back to the `category` symbol's plist.
fn textget(h: &mut ElispHost, plist: &Value, prop: &Value) -> Value {
    if let Some(v) = h.plist_lookup(plist, prop) {
        return v;
    }
    let category = h.intern("category");
    match h.plist_lookup(plist, &category) {
        Some(cat) if h.sym_name(&cat).is_some() => {
            let table_sym = h.intern("symbol-plist--table");
            match h.get_dynamic_value(&table_sym) {
                Ok(table) => {
                    let plist = gethash(h, &[cat, table]).unwrap_or(Value::Undef);
                    h.plist_get_eq(&plist, prop)
                }
                Err(_) => Value::Undef,
            }
        }
        _ => Value::Undef,
    }
}

/// Where the text properties of OBJECT end: its length or `zv`.
fn object_end(h: &ElispHost, obj: &PropObj) -> i64 {
    match obj {
        PropObj::Str(s) => s.chars().count() as i64,
        PropObj::Buf(bi) => h.buffer_begv_zv(*bi).1 as i64,
    }
}
fn object_begin(h: &ElispHost, obj: &PropObj) -> i64 {
    match obj {
        PropObj::Str(_) => 0,
        PropObj::Buf(bi) => h.buffer_begv_zv(*bi).0 as i64,
    }
}

/// The LIMIT argument: nil, `t`, or an integer/marker.
fn limit_arg(h: &ElispHost, v: Option<&Value>) -> Result<Value, String> {
    match v {
        None => Ok(Value::Undef),
        Some(v) if is_nil(v) || matches!(v, Value::Bool(true)) => Ok(v.clone()),
        Some(v) => match h.marker_position(v) {
            Some(p) => Ok(Value::Int(p as i64)),
            None => match v {
                Value::Int(_) => Ok(v.clone()),
                other => Err(format!(
                    "wrong-type-argument: integer-or-marker-p {}",
                    h.print(other, true)
                )),
            },
        },
    }
}

fn limit_int(limit: &Value) -> Option<i64> {
    match limit {
        Value::Int(n) => Some(*n),
        _ => None,
    }
}

/// `(next-property-change POSITION &optional OBJECT LIMIT)`.
fn next_property_change_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let obj = prop_object(h, a.get(1))?;
    let limit = limit_arg(h, a.get(2))?;
    let pos = single_position(h, &obj, &a[0])?;
    let runs = object_runs(h, &obj);
    let end = object_end(h, &obj);
    let Some(runs) = runs else {
        return Ok(limit);
    };
    let i = runs
        .iter()
        .position(|&(s, e, _)| s <= pos && pos < e)
        .unwrap_or(runs.len() - 1);
    if matches!(limit, Value::Bool(true)) {
        return Ok(Value::Int(runs.get(i + 1).map_or(end, |r| r.0)));
    }
    let lim = limit_int(&limit);
    let mut next = i + 1;
    while next < runs.len()
        && h.plist_struct_eq(&runs[i].2, &runs[next].2)
        && lim.is_none_or(|l| runs[next].0 < l)
    {
        next += 1;
    }
    match runs.get(next) {
        Some(r) if r.0 < lim.unwrap_or(end) => Ok(Value::Int(r.0)),
        _ => Ok(limit),
    }
}

/// `(next-single-property-change POSITION PROP &optional OBJECT LIMIT)`.
fn next_single_property_change_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let obj = prop_object(h, a.get(2))?;
    let limit = limit_arg(h, a.get(3))?;
    if matches!(limit, Value::Bool(true)) {
        // The C code only does CHECK_FIXNUM_COERCE_MARKER on LIMIT.
        return Err(format!(
            "wrong-type-argument: integer-or-marker-p {}",
            h.print(&limit, true)
        ));
    }
    let pos = single_position(h, &obj, &a[0])?;
    let end = object_end(h, &obj);
    let Some(runs) = object_runs(h, &obj) else {
        return Ok(limit);
    };
    let i = runs
        .iter()
        .position(|&(s, e, _)| s <= pos && pos < e)
        .unwrap_or(runs.len() - 1);
    let here = textget(h, &runs[i].2, &a[1]);
    let lim = limit_int(&limit);
    let mut next = i + 1;
    while next < runs.len()
        && {
            let v = textget(h, &runs[next].2, &a[1]);
            h.values_eq(&here, &v)
        }
        && lim.is_none_or(|l| runs[next].0 < l)
    {
        next += 1;
    }
    match runs.get(next) {
        Some(r) if r.0 < lim.unwrap_or(end) => Ok(Value::Int(r.0)),
        _ => Ok(limit),
    }
}

/// `(previous-property-change POSITION &optional OBJECT LIMIT)`.
fn previous_property_change_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let obj = prop_object(h, a.get(1))?;
    let limit = limit_arg(h, a.get(2))?;
    let pos = single_position(h, &obj, &a[0])?;
    let begin = object_begin(h, &obj);
    let Some(runs) = object_runs(h, &obj) else {
        return Ok(limit);
    };
    let mut i = runs
        .iter()
        .position(|&(s, e, _)| s <= pos && pos < e)
        .unwrap_or(runs.len() - 1);
    // Start with the interval containing the char before POSITION.
    if runs[i].0 == pos {
        if i == 0 {
            return Ok(limit);
        }
        i -= 1;
    }
    let lim = limit_int(&limit);
    let mut prev = i as i64 - 1;
    while prev >= 0
        && h.plist_struct_eq(&runs[prev as usize].2, &runs[i].2)
        && lim.is_none_or(|l| runs[prev as usize].1 > l)
    {
        prev -= 1;
    }
    if prev < 0 || runs[prev as usize].1 <= lim.unwrap_or(begin) {
        return Ok(limit);
    }
    Ok(Value::Int(runs[prev as usize].1))
}

/// `(previous-single-property-change POSITION PROP &optional OBJECT LIMIT)`.
fn previous_single_property_change_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let obj = prop_object(h, a.get(2))?;
    let limit = limit_arg(h, a.get(3))?;
    let pos = single_position(h, &obj, &a[0])?;
    let begin = object_begin(h, &obj);
    let Some(runs) = object_runs(h, &obj) else {
        return Ok(limit);
    };
    let mut i = runs
        .iter()
        .position(|&(s, e, _)| s <= pos && pos < e)
        .unwrap_or(runs.len() - 1);
    if runs[i].0 == pos {
        if i == 0 {
            return Ok(limit);
        }
        i -= 1;
    }
    let here = textget(h, &runs[i].2, &a[1]);
    let lim = limit_int(&limit);
    let mut prev = i as i64 - 1;
    while prev >= 0
        && {
            let v = textget(h, &runs[prev as usize].2, &a[1]);
            h.values_eq(&here, &v)
        }
        && lim.is_none_or(|l| runs[prev as usize].1 > l)
    {
        prev -= 1;
    }
    if prev < 0 || runs[prev as usize].1 <= lim.unwrap_or(begin) {
        return Ok(limit);
    }
    Ok(Value::Int(runs[prev as usize].1))
}

/// `(object-intervals OBJECT)`: `((BEG END PLIST) …)`, 0-based, nil intervals
/// included.
fn object_intervals_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let obj = match &a[0] {
        v if h.is_string(v) => PropObj::Str(h.str_arc(v).expect("checked stringp")),
        v => match h.resolve_buffer(v) {
            Some(bi) if matches!(h.obj(v), Some(Obj::Buffer(_))) => PropObj::Buf(bi),
            _ => {
                return Err(format!(
                    "wrong-type-argument: buffer-or-string-p {}",
                    h.print(v, true)
                ))
            }
        },
    };
    let base = if matches!(obj, PropObj::Buf(_)) { 1 } else { 0 };
    let runs = object_runs(h, &obj).unwrap_or_default();
    let items = runs
        .into_iter()
        .map(|(s, e, p)| h.list_from(vec![Value::Int(s - base), Value::Int(e - base), p]))
        .collect();
    Ok(h.list_from(items))
}

/// `(add-face-text-property START END FACE &optional APPENDP OBJECT)`.
fn add_face_text_property_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let start = as_int(h, &a[0])?;
    let end = as_int(h, &a[1])?;
    let append = a.get(3).is_some_and(|v| !is_nil(v));
    let obj = prop_object(h, a.get(4))?;
    let (lo, hi) = prop_range(&obj, start, end, h)?;
    let face = h.intern("face");
    let pairs = [(face, a[2].clone())];
    let set_type = if append {
        crate::textprop::SetType::Append
    } else {
        crate::textprop::SetType::Prepend
    };
    match &obj {
        PropObj::Str(s) => {
            h.string_add_props(s, lo, hi, &pairs, set_type);
        }
        PropObj::Buf(bi) => {
            let bi = *bi;
            record_prop_undo(h, bi, lo, hi, PropUndo::Add(&pairs));
            let changed = with_buffer(h, bi, |h| h.buffer_add_props(lo, hi, &pairs, set_type));
            if changed {
                h.note_prop_change(bi);
            }
        }
    }
    Ok(Value::Undef)
}

/// `(elisprs--inside-interval-p POS)`: the characters around buffer position
/// POS belong to one interval.
fn inside_interval_p_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let pos = as_int(h, &a[0])?.max(0) as usize;
    Ok(nil_or(h.buffer_inside_interval(pos)))
}

/// `(elisprs--inherit-props START END PLIST PLEFT PRIGHT INSIDE)`: see
/// [`ElispHost::buffer_inherit_props`].
fn inherit_props_fn(h: &mut ElispHost, a: &[Value]) -> R {
    let start = as_int(h, &a[0])?.max(1) as usize;
    let end = as_int(h, &a[1])?.max(1) as usize;
    let inside = a.get(5).is_some_and(|v| !is_nil(v));
    h.buffer_inherit_props(start, end, &a[2], inside);
    Ok(Value::Undef)
}

/// `(undo-boundary)` — undo.c `Fundo_boundary` (see `ElispHost::undo_boundary`).
fn undo_boundary_fn(h: &mut ElispHost, _a: &[Value]) -> R {
    h.undo_boundary();
    Ok(Value::Undef)
}

/// What a text-property change does to each interval, for its undo records.
enum PropUndo<'a> {
    /// `add_properties`: PAIRS are added or replace differing values.
    Add(&'a [(Value, Value)]),
    /// `remove_properties`: the properties named are removed.
    Remove(&'a [Value]),
    /// `set_properties`: the interval's plist becomes PLIST.
    Set(&'a Value),
}

/// The undo records textprop.c's `add_properties`, `remove_properties` and
/// `set_properties` make for the 0-based span `[lo, hi)` of buffer BI before
/// changing it: one `(nil PROP OLD-VALUE BEG . END)` per interval (clipped to
/// the span) and per property whose value changes, OLD-VALUE nil for a
/// property the interval lacks.
fn record_prop_undo(h: &mut ElispHost, bi: usize, lo: usize, hi: usize, change: PropUndo) {
    if lo >= hi {
        return;
    }
    let (props, bounds) = {
        let b = &h.buffers[bi];
        (b.props.clone(), b.prop_bounds.clone())
    };
    let runs = h.tp_runs(&props, &bounds);
    let mut records: Vec<(usize, usize, Value, Value)> = Vec::new();
    for (rs, re) in runs {
        let (s, e) = (rs.max(lo), re.min(hi));
        if s >= e {
            continue;
        }
        let plist = props[rs].clone();
        match &change {
            PropUndo::Add(pairs) => {
                for (prop, val) in pairs.iter() {
                    match plist_lookup(h, &plist, prop) {
                        Some(old) if h.values_eq(&old, val) => {}
                        Some(old) => records.push((s, e, prop.clone(), old)),
                        None => records.push((s, e, prop.clone(), Value::Undef)),
                    }
                }
            }
            PropUndo::Remove(names) => {
                for name in names.iter() {
                    if let Some(old) = plist_lookup(h, &plist, name) {
                        records.push((s, e, name.clone(), old));
                    }
                }
            }
            PropUndo::Set(new) => {
                for (prop, old) in each_prop_pair(h, &plist) {
                    let same = plist_lookup(h, new, &prop).is_some_and(|v| h.values_eq(&v, &old));
                    if !same {
                        records.push((s, e, prop, old));
                    }
                }
                for (prop, _) in each_prop_pair(h, new) {
                    if plist_lookup(h, &plist, &prop).is_none() {
                        records.push((s, e, prop, Value::Undef));
                    }
                }
            }
        }
    }
    for (s, e, prop, old) in records {
        h.record_property_change(bi, s + 1, e - s, prop, old);
    }
}

/// `(recent-auto-save-p)` — fileio.c: whether the buffer was auto-saved since
/// it was last saved (`SAVE_MODIFF < BUF_AUTOSAVE_MODIFF`).
fn recent_auto_save_p(h: &mut ElispHost, _a: &[Value]) -> R {
    let m = &h.cur_buf_ref().mods;
    Ok(nil_or(m.save_modiff < m.autosave_modiff))
}

/// For `crate::modhooks`: the buffer and 1-based span `[BEG, END)` a call
/// of the text-property primitive NAME with ARGS changes, `None` when it is
/// a string, the arguments are invalid, or nothing would change (textprop.c
/// returns before `modify_text_properties` then). OBJECT is `args[object]`.
pub(crate) fn text_prop_change_span(
    h: &mut ElispHost,
    name: &str,
    args: &[Value],
    object: usize,
) -> Option<(usize, usize, usize)> {
    let (Value::Int(start), Value::Int(end)) = (args.first()?.clone(), args.get(1)?.clone()) else {
        return None;
    };
    let obj = prop_object(h, args.get(object)).ok()?;
    let PropObj::Buf(bi) = obj else {
        return None;
    };
    let (lo, hi) = prop_range(&obj, start, end, h).ok()?;
    if lo >= hi {
        return None;
    }
    let changes = match name {
        "put-text-property" => {
            let pair = [(args.get(2)?.clone(), args.get(3)?.clone())];
            props_would_change(h, &obj, lo, hi, &pair, true)
        }
        "add-text-properties" => {
            let pairs = each_prop_pair(h, args.get(2)?);
            props_would_change(h, &obj, lo, hi, &pairs, true)
        }
        "remove-text-properties" => {
            let pairs = each_prop_pair(h, args.get(2)?);
            props_would_change(h, &obj, lo, hi, &pairs, false)
        }
        "add-face-text-property" => {
            let face = h.intern("face");
            let pair = [(face, args.get(2)?.clone())];
            props_would_change(h, &obj, lo, hi, &pair, true)
        }
        // `set_text_properties`: nil PROPERTIES on text with no intervals.
        _ => !(args.get(2).is_none_or(is_nil) && !h.buffers[bi].has_intervals),
    };
    changes.then_some((bi, lo + 1, hi + 1))
}

/// The positions `subst-char-in-region` changes: `(START END FIRST LAST)`
/// with FIRST the first character equal to FROMCHAR and LAST one past the
/// last; `None` when the arguments are invalid or nothing matches.
pub(crate) fn subst_char_span(
    h: &mut ElispHost,
    a: &[Value],
) -> Option<(usize, usize, usize, usize)> {
    let (lo, hi) = validate_region(h, &a[0], &a[1]).ok()?;
    let from = char::from_u32(check_character(h, &a[2]).ok()? as u32)?;
    check_character(h, &a[3]).ok()?;
    let text = &h.cur_buf_ref().text[lo - 1..hi - 1];
    let first = text.iter().position(|&c| c == from)?;
    let last = text.iter().rposition(|&c| c == from)?;
    Some((lo, hi, lo + first, lo + last + 1))
}

/// `(subst-char-in-region START END FROMCHAR TOCHAR &optional NOUNDO)` —
/// editfns.c. Each FROMCHAR from START to END becomes TOCHAR in place:
/// one `modify_text` from the first one to END, a `record_change` per
/// character unless NOUNDO, and with NOUNDO a buffer unmodified before stays
/// so when only this change modified it. The change hooks are
/// `crate::modhooks`'s.
fn subst_char_in_region(h: &mut ElispHost, a: &[Value]) -> R {
    let (lo, hi) = validate_region(h, &a[0], &a[1])?;
    let from = check_character(h, &a[2])?;
    let to = check_character(h, &a[3])?;
    let noundo = a.get(4).is_some_and(|v| !is_nil(v));
    let (from, to) = (
        char::from_u32(from as u32).unwrap_or('\u{fffd}'),
        char::from_u32(to as u32).unwrap_or('\u{fffd}'),
    );
    let positions: Vec<usize> = (lo..hi)
        .filter(|&p| h.cur_buf_ref().text[p - 1] == from)
        .collect();
    let Some(&first) = positions.first() else {
        return Ok(Value::Undef);
    };
    h.barf_if_read_only()?;
    {
        let m = &h.cur_buf_ref().mods;
        if m.modiff <= m.save_modiff {
            h.record_first_change_if_undo();
        }
    }
    h.note_text_change(hi - first);
    if noundo {
        let m = &mut h.cur_buf().mods;
        if m.save_modiff == m.modiff - 1 {
            m.save_modiff = m.modiff;
        }
        if m.autosave_modiff == m.modiff - 1 {
            m.autosave_modiff = m.modiff;
        }
    }
    for p in positions {
        if !noundo {
            h.record_change(p, 1);
        }
        h.cur_buf().text[p - 1] = to;
    }
    Ok(Value::Undef)
}

#[cfg(test)]
mod tests {
    use crate::{eval_str, print, reset_host};

    fn eval(src: &str) -> String {
        reset_host();
        let v = eval_str(src).expect("eval failed");
        print(&v, true)
    }

    fn eval_err(src: &str) -> String {
        reset_host();
        eval_str(src).unwrap_err()
    }

    #[test]
    fn cadr_family_composition() {
        // caadr = (car (car (cdr X)))
        assert_eq!(eval("(caadr '(1 (2 3) 4))"), "2");
        // cadar = (car (cdr (car X)))
        assert_eq!(eval("(cadar '((1 2 3) 4))"), "2");
        // cdaar = (cdr (car (car X)))
        assert_eq!(eval("(cdaar '(((1 2) 3) 4))"), "(2)");
        // cdadr = (cdr (car (cdr X)))
        assert_eq!(eval("(cdadr '(1 (2 3) 4))"), "(3)");
        // cddar = (cdr (cdr (car X)))
        assert_eq!(eval("(cddar '((1 2 3) 4))"), "(3)");
    }

    #[test]
    fn cadr_family_nil_edges() {
        // Intermediate nil propagates to nil (no error) on short lists.
        assert_eq!(eval("(caadr '(1))"), "nil");
        assert_eq!(eval("(cadar '(nil))"), "nil");
        assert_eq!(eval("(cddar '((1)))"), "nil");
        // A non-nil non-cons intermediate signals wrong-type-argument listp.
        assert!(eval_err("(caadr '(1 2 3))").contains("listp"));
    }

    #[test]
    fn cl_two_level_aliases() {
        assert_eq!(eval("(cl-caar '((1 2) 3))"), "1");
        assert_eq!(eval("(cl-cadr '(1 2 3))"), "2");
        assert_eq!(eval("(cl-cdar '((1 2) 3))"), "(2)");
        assert_eq!(eval("(cl-cddr '(1 2 3 4))"), "(3 4)");
        // Short/nil lists yield nil.
        assert_eq!(eval("(cl-cadr '(1))"), "nil");
        assert_eq!(eval("(cl-cddr '(1))"), "nil");
    }

    #[test]
    fn string_split_forwards_to_split_string() {
        // Default separators: whitespace, omit-nulls implicitly on.
        assert_eq!(eval("(string-split \"  a  b c \")"), "(\"a\" \"b\" \"c\")");
        // Empty string with default separators -> nil.
        assert_eq!(eval("(string-split \"\")"), "nil");
        // Explicit separator regexp, omit-nulls default off keeps empty fields.
        assert_eq!(eval("(string-split \"a,,b\" \",\")"), "(\"a\" \"\" \"b\")");
        // An empty separator regexp matches at every position, INCLUDING before
        // the first character and after the last, so Emacs 30.2 answers
        // ("" "a" "b" "c" "") — verified against `emacs -Q --batch`. This
        // assertion previously encoded elisprs's own (leading/trailing-less)
        // output rather than Emacs's.
        assert_eq!(
            eval("(string-split \"abc\" \"\")"),
            "(\"\" \"a\" \"b\" \"c\" \"\")"
        );
    }

    #[test]
    fn member_ignore_case_semantics() {
        // Returns the tail beginning at the first case-insensitive string match.
        assert_eq!(
            eval("(member-ignore-case \"b\" '(\"A\" \"B\" \"C\"))"),
            "(\"B\" \"C\")"
        );
        // No match -> nil.
        assert_eq!(eval("(member-ignore-case \"z\" '(\"a\" \"b\"))"), "nil");
        // Non-string elements are skipped, never match.
        assert_eq!(eval("(member-ignore-case \"b\" '(1 2 \"B\"))"), "(\"B\")");
        // Empty list -> nil.
        assert_eq!(eval("(member-ignore-case \"a\" nil)"), "nil");
    }
}