neovm-core 0.0.2

Core runtime structures for NeoVM
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
//! Context — special forms, function application, and dispatch.

use std::cell::RefCell;
use std::collections::{HashMap, HashSet, VecDeque};
use std::hash::{Hash, Hasher};
use std::rc::Rc;
use std::sync::OnceLock;

use smallvec::SmallVec;

use super::abbrev::AbbrevManager;
use super::advice::VariableWatcherList;
use super::autoload::AutoloadManager;
use super::bookmark::BookmarkManager;
use super::builtins;
use super::coding::CodingSystemManager;
use super::custom::CustomManager;
use super::doc::{STARTUP_VARIABLE_DOC_STRING_PROPERTIES, STARTUP_VARIABLE_DOC_STUBS};
use super::error::*;
use super::interactive::InteractiveRegistry;
use super::intern::{
    NameId, SymId, intern, intern_uninterned, is_canonical_id, is_keyword_id, resolve_name,
    resolve_sym, resolve_sym_metadata, symbol_name_id,
};
use super::keymap::{
    list_keymap_define, list_keymap_set_parent, make_list_keymap, make_sparse_list_keymap,
};
use super::kmacro::KmacroManager;
use super::minibuffer::MinibufferManager;
use super::mode::ModeRegistry;
use super::process::ProcessManager;
use super::rect::RectangleState;
use super::regex::MatchData;
use super::register::RegisterManager;
use super::symbol::Obarray;
use super::threads::ThreadManager;
use super::timer::TimerManager;
use super::value::*;
use crate::buffer::BufferManager;
use crate::face::{Face as RuntimeFace, FaceTable, FontSlant, FontWeight, FontWidth};
use crate::gc_trace::GcTrace;
use crate::tagged::header::{CLOSURE_ARGLIST, SubrDispatchKind, SubrFn, SubrObj};
use crate::window::FrameManager;

const EVAL_STACK_RED_ZONE: usize = 128 * 1024;
const EVAL_STACK_SEGMENT: usize = 2 * 1024 * 1024;
const STACK_GROWTH_PROBE_START_DEPTH: usize = 16;
const STACK_GROWTH_PROBE_INTERVAL: usize = 16;
/// Capacity of the per-Context cache mapping symbol → resolved call
/// target.  The cache is keyed by `function_epoch` and invalidated
/// whenever the obarray's function cells change.  GNU Emacs has no such
/// cache (its dispatcher walks the symbol's function cell directly per
/// call), but in NeoMacs's debug build a fast path that avoids
/// `resolve_sym`/`intern` lock acquisitions per call is a major win
/// for byte-compiler workloads.  4096 entries comfortably covers the
/// distinct functions called during batch-byte-compile so the cache
/// never thrashes once warmed.
const NAMED_CALL_CACHE_CAPACITY: usize = 4096;
const LEXENV_ASSQ_CACHE_CAPACITY: usize = 16;
const LEXENV_SPECIAL_CACHE_CAPACITY: usize = 16;
const GC_DEFAULT_THRESHOLD_BYTES: usize = 1_000_000 * std::mem::size_of::<usize>();
const GC_THRESHOLD_FLOOR_BYTES: usize = GC_DEFAULT_THRESHOLD_BYTES / 10;
const GC_HI_THRESHOLD_BYTES: usize = (i64::MAX as usize) / 2;
const GC_PERCENT_SCALE: u64 = 1_000_000;
pub(crate) const INTERNAL_COMPILER_FUNCTION_OVERRIDES: &str =
    "internal--compiler-function-overrides";

#[derive(Clone, Debug, PartialEq, Eq)]
struct RedisplaySignature {
    selected_frame: Option<u64>,
    selected_window: Option<u64>,
    current_buffer: Option<u64>,
    current_message: Option<crate::heap_types::LispString>,
    active_minibuffer_window: Option<u64>,
    minibuffer_selected_window: Option<u64>,
    face_change_count: u64,
    obarray_function_epoch: u64,
    redisplay_generation: u64,
    frame: Option<RedisplayFrameSignature>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct RedisplayFrameSignature {
    id: u64,
    width: u32,
    height: u32,
    char_width: u32,
    char_height: u32,
    font_pixel_size: u32,
    visible: bool,
    selected_window: u64,
    window_state_change: bool,
    windows: Vec<RedisplayWindowSignature>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct RedisplayWindowSignature {
    id: u64,
    buffer_id: u64,
    bounds: (u32, u32, u32, u32),
    window_start: usize,
    window_end_pos: usize,
    window_end_bytepos: usize,
    window_end_vpos: usize,
    window_end_valid: bool,
    point: usize,
    old_point: usize,
    hscroll: usize,
    vscroll: i32,
    preserve_vscroll_p: bool,
    buffer: Option<RedisplayBufferSignature>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct RedisplayBufferSignature {
    id: u64,
    modified_tick: i64,
    chars_modified_tick: i64,
    save_modified_tick: i64,
    autosave_modified_tick: i64,
    point: usize,
    point_byte: usize,
    begv: usize,
    begv_byte: usize,
    zv: usize,
    zv_byte: usize,
    total_chars: usize,
    total_bytes: usize,
    last_window_start: usize,
    last_selected_window: Option<u64>,
}

fn redisplay_f32_bits(value: f32) -> u32 {
    if value == 0.0 {
        0.0f32.to_bits()
    } else {
        value.to_bits()
    }
}

/// Static subr entry — lives in global table, not on the tagged heap.
/// Replaces the heap-allocated SubrObj for builtin function metadata.
#[derive(Clone, Copy)]
pub(crate) struct SubrEntry {
    pub(crate) function: Option<crate::tagged::header::SubrFn>,
    pub(crate) min_args: u16,
    pub(crate) max_args: Option<u16>,
    pub(crate) dispatch_kind: crate::tagged::header::SubrDispatchKind,
    pub(crate) name_id: crate::emacs_core::intern::NameId,
}

thread_local! {
    // Static subrs are encoded directly from `SymId`, so the registry should
    // be indexed by that dense id rather than hashed again at dispatch time.
    static GLOBAL_SUBR_TABLE: RefCell<Vec<Option<SubrEntry>>> = const { RefCell::new(Vec::new()) };

    /// Thread-local handle to the active `Context::quit_requested`
    /// atomic. Installed by `Context::setup_thread_locals`, read by
    /// leaf functions (e.g. the regex matcher) that need a cheap quit
    /// check without threading `&mut Context` through their signature.
    /// Mirrors the call site shape of GNU's `maybe_quit()` — reachable
    /// from anywhere without an explicit context pointer.
    static QUIT_REQUESTED_TLS: RefCell<Option<std::sync::Arc<std::sync::atomic::AtomicBool>>> = const { RefCell::new(None) };
}

/// Check whether a quit is pending without needing `&mut Context`.
/// The regex matcher calls this at jump/fail sites, mirroring GNU's
/// `regex-emacs.c:4901,5236`. When it returns `true`, the caller
/// should unwind its work so the next `maybe_quit()` poll can promote
/// the pending flag to a `quit` signal.
pub(crate) fn tls_quit_pending() -> bool {
    QUIT_REQUESTED_TLS.with(|cell| {
        cell.borrow()
            .as_ref()
            .is_some_and(|flag| flag.load(std::sync::atomic::Ordering::Relaxed))
    })
}

/// Register a subr entry in the global static table.
pub(crate) fn register_global_subr_entry(sym_id: SymId, entry: SubrEntry) {
    GLOBAL_SUBR_TABLE.with(|table| {
        let idx = sym_id.0 as usize;
        let mut table = table.borrow_mut();
        if table.len() <= idx {
            table.resize_with(idx + 1, || None);
        }
        table[idx] = Some(entry);
    });
    crate::tagged::value::update_static_subr_object_entry(
        sym_id,
        entry.function,
        entry.min_args,
        entry.max_args,
        entry.dispatch_kind,
    );
}

/// Look up a subr entry by SymId.
pub(crate) fn lookup_global_subr_entry(sym_id: SymId) -> Option<SubrEntry> {
    GLOBAL_SUBR_TABLE.with(|table| table.borrow().get(sym_id.0 as usize).copied().flatten())
}

#[inline(always)]
fn subr_entry_from_value(function: Value) -> Option<(SymId, SubrEntry)> {
    let ptr = function.as_veclike_ptr()?;
    let header = unsafe { &*ptr };
    if header.type_tag != VecLikeType::Subr {
        return None;
    }
    let subr = unsafe { &*(ptr as *const SubrObj) };
    if subr.function.is_none() && subr.dispatch_kind == SubrDispatchKind::Builtin {
        return None;
    }
    Some((
        subr.sym_id,
        SubrEntry {
            function: subr.function,
            min_args: subr.min_args,
            max_args: subr.max_args,
            dispatch_kind: subr.dispatch_kind,
            name_id: subr.name,
        },
    ))
}

/// Access a subr entry by reference (avoids cloning).
pub(crate) fn with_global_subr_entry<R>(
    sym_id: SymId,
    f: impl FnOnce(&SubrEntry) -> R,
) -> Option<R> {
    GLOBAL_SUBR_TABLE.with(|table| {
        table
            .borrow()
            .get(sym_id.0 as usize)
            .and_then(|entry| entry.as_ref().map(f))
    })
}

/// Clear all subr entries (used during heap reset).
pub(crate) fn clear_global_subr_table() {
    GLOBAL_SUBR_TABLE.with(|table| table.borrow_mut().clear());
}

/// Cached SymId for `internal--compiler-function-overrides`.
///
/// `compiler_function_overrides_active_in_obarray` is called from
/// `resolve_named_call_target_by_id` on every funcall.  The previous
/// implementation re-interned the string each call, which acquires the
/// global interner write lock — even after `parking_lot::RwLock`, that
/// is many extra atomic ops per call and shows up as the dominant cost
/// in debug-build batch-byte-compile profiles.  Cache the SymId once
/// and use the `_id`-suffixed obarray accessor that bypasses intern.
fn internal_compiler_function_overrides_sym() -> SymId {
    static SYM: OnceLock<SymId> = OnceLock::new();
    *SYM.get_or_init(|| intern(INTERNAL_COMPILER_FUNCTION_OVERRIDES))
}

#[inline]
fn internal_make_interpreted_closure_function_symbol() -> SymId {
    static SYM: OnceLock<SymId> = OnceLock::new();
    *SYM.get_or_init(|| intern("internal-make-interpreted-closure-function"))
}

#[inline]
fn cconv_make_interpreted_closure_symbol() -> SymId {
    static SYM: OnceLock<SymId> = OnceLock::new();
    *SYM.get_or_init(|| intern("cconv-make-interpreted-closure"))
}

#[inline]
fn load_in_progress_symbol() -> SymId {
    static SYM: OnceLock<SymId> = OnceLock::new();
    *SYM.get_or_init(|| intern("load-in-progress"))
}

#[inline]
fn macroexpand_all_environment_symbol() -> SymId {
    static SYM: OnceLock<SymId> = OnceLock::new();
    *SYM.get_or_init(|| intern("macroexpand-all-environment"))
}

#[inline]
fn throw_symbol() -> SymId {
    static SYM: OnceLock<SymId> = OnceLock::new();
    *SYM.get_or_init(|| intern("throw"))
}

pub(crate) fn compiler_function_override_in_obarray(
    obarray: &Obarray,
    sym_id: SymId,
) -> Option<Value> {
    let overrides_sym = internal_compiler_function_overrides_sym();
    let mut cursor = obarray.symbol_value_id_or_nil(overrides_sym);
    while cursor.is_cons() {
        let entry = cursor.cons_car();
        cursor = cursor.cons_cdr();
        if entry.is_cons() && entry.cons_car().as_symbol_id() == Some(sym_id) {
            return Some(entry.cons_cdr());
        }
    }
    None
}

pub(crate) fn compiler_function_overrides_active_in_obarray(obarray: &Obarray) -> bool {
    let overrides_sym = internal_compiler_function_overrides_sym();
    obarray.symbol_value_id_or_nil(overrides_sym).is_cons()
}

#[derive(Clone, Debug)]
struct ExecutingKbdMacroRuntimeScope {
    snapshot: crate::keyboard::ExecutingKbdMacroRuntimeSnapshot,
    real_this_command: Value,
}

/// A single entry on the specpdl (special binding stack).
/// Matches GNU Emacs's `union specbinding` SPECPDL_LET / SPECPDL_LET_LOCAL.
#[derive(Clone, Debug)]
pub(crate) enum SpecBinding {
    /// Plain dynamic let-binding: saves old obarray (global/default) value.
    Let {
        sym_id: SymId,
        old_value: Option<Value>,
    },
    /// Buffer-local let-binding: saves old buffer-local value and which buffer.
    /// On unbind, restores the value in that specific buffer (if still live).
    /// Matches GNU's SPECPDL_LET_LOCAL.
    LetLocal {
        sym_id: SymId,
        old_value: Value,
        buffer_id: crate::buffer::BufferId,
    },
    /// Default-value let-binding for buffer-local variables without a local
    /// binding in the current buffer. Saves/restores the obarray default value.
    /// Matches GNU's SPECPDL_LET_DEFAULT.
    LetDefault {
        sym_id: SymId,
        old_value: Option<Value>,
    },
    /// Lexical environment save/restore. Mirrors GNU's
    /// `specbind(Qinternal_interpreter_environment, ...)` which saves
    /// the current `Vinternal_interpreter_environment` on the specpdl.
    /// `unbind_to` restores `self.lexenv` to this value.
    LexicalEnv { old_lexenv: Value },
    /// Temporary GC root carried on the specpdl itself, mirroring GNU's
    /// use of specpdl-owned runtime state for unwind/helper temporaries.
    GcRoot { value: Value },
    /// Call frame for backtrace. Matches GNU SPECPDL_BACKTRACE.
    /// unbind_to discards these (no-op).
    ///
    /// `args == BacktraceArgs::Unevalled(_)` mirrors GNU's
    /// `nargs == UNEVALLED` marker (eval.c:2585 for special forms).
    /// In that shape, the payload is the original cons list of
    /// un-evaluated argument forms. The walker emits
    /// `(nil FUNC FORMS FLAGS)` for these (`backtrace_frame_apply`,
    /// eval.c:3993-3994).
    Backtrace {
        function: Value,
        args: BacktraceArgs,
        debug_on_exit: bool,
    },
    /// unwind-protect cleanup. Matches GNU SPECPDL_UNWIND.
    /// For interpreter: forms is a cons list, unbind_to calls sf_progn_value.
    /// For VM: forms is a callable (bytecode fn), unbind_to calls apply.
    UnwindProtect { forms: Value, lexenv: Value },
    /// save-excursion state. Matches GNU SPECPDL_UNWIND_EXCURSION.
    SaveExcursion {
        buffer_id: crate::buffer::BufferId,
        marker_id: u64,
        marker: Value,
    },
    /// save-current-buffer state. Matches GNU record_unwind_current_buffer.
    SaveCurrentBuffer { buffer_id: crate::buffer::BufferId },
    /// save-restriction state. Matches GNU SPECPDL_UNWIND with save_restriction_restore.
    SaveRestriction {
        state: crate::buffer::SavedRestrictionState,
    },
    /// Placeholder. Matches GNU SPECPDL_NOP.
    Nop,
}

#[derive(Clone, Debug)]
pub(crate) enum BacktraceArgs {
    Unevalled(Value),
    Evaluated(LispArgVec),
}

impl BacktraceArgs {
    #[inline]
    pub(crate) fn is_unevalled(&self) -> bool {
        matches!(self, Self::Unevalled(_))
    }

    #[inline]
    pub(crate) fn as_slice(&self) -> &[Value] {
        match self {
            Self::Unevalled(value) => std::slice::from_ref(value),
            Self::Evaluated(args) => args.as_slice(),
        }
    }
}

#[derive(Clone, Debug, Default)]
pub(crate) struct VmRootFrame {
    pub(crate) roots: LispArgVec,
}

impl VmRootFrame {
    fn new() -> Self {
        Self {
            roots: LispArgVec::new(),
        }
    }
}

#[derive(Clone, Debug)]
pub(crate) struct PendingSafeFuncall {
    pub(crate) function: Value,
    pub(crate) args: LispArgVec,
}

pub(crate) type LispArgVec = SmallVec<[Value; 8]>;
type LetBindingVec = SmallVec<[(SymId, Value); 8]>;

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct GnuTimerTimestamp {
    pub(crate) high_seconds: i64,
    pub(crate) low_seconds: i64,
    pub(crate) usecs: i64,
    pub(crate) psecs: i64,
}

impl GnuTimerTimestamp {
    pub(crate) fn now() -> Self {
        use std::time::{SystemTime, UNIX_EPOCH};

        let (secs, usecs) = match SystemTime::now().duration_since(UNIX_EPOCH) {
            Ok(dur) => (dur.as_secs() as i64, dur.subsec_micros() as i64),
            Err(err) => {
                let dur = err.duration();
                (-(dur.as_secs() as i64), -(dur.subsec_micros() as i64))
            }
        };

        Self {
            high_seconds: secs >> 16,
            low_seconds: secs & 0xFFFF,
            usecs,
            psecs: 0,
        }
    }

    fn unix_seconds(self) -> i64 {
        (self.high_seconds << 16) + self.low_seconds
    }

    pub(crate) fn duration_until(self, now: Self) -> std::time::Duration {
        use std::time::Duration;

        if self <= now {
            return Duration::ZERO;
        }

        let mut secs = self.unix_seconds() - now.unix_seconds();
        let mut usecs = self.usecs - now.usecs;
        let mut psecs = self.psecs - now.psecs;

        if psecs < 0 {
            psecs += 1_000_000;
            usecs -= 1;
        }
        if usecs < 0 {
            usecs += 1_000_000;
            secs -= 1;
        }
        if secs < 0 {
            return Duration::ZERO;
        }

        let mut secs = secs as u64;
        let mut nanos = (usecs as u32) * 1_000 + ((psecs.max(0) as u32) + 999) / 1_000;
        if nanos >= 1_000_000_000 {
            secs += 1;
            nanos -= 1_000_000_000;
        }

        Duration::new(secs, nanos)
    }

    pub(crate) fn overdue_duration(self, now: Self) -> std::time::Duration {
        use std::time::Duration;

        if self >= now {
            return Duration::ZERO;
        }

        let mut secs = now.unix_seconds() - self.unix_seconds();
        let mut usecs = now.usecs - self.usecs;
        let mut psecs = now.psecs - self.psecs;

        if psecs < 0 {
            psecs += 1_000_000;
            usecs -= 1;
        }
        if usecs < 0 {
            usecs += 1_000_000;
            secs -= 1;
        }

        let nanos = ((usecs as u32) * 1_000) + (psecs as u32 / 1_000);
        Duration::new(secs as u64, nanos)
    }

    pub(crate) fn from_duration(duration: std::time::Duration) -> Self {
        let secs = duration.as_secs() as i64;
        let usecs = duration.subsec_micros() as i64;
        Self {
            high_seconds: secs >> 16,
            low_seconds: secs & 0xFFFF,
            usecs,
            psecs: 0,
        }
    }
}

#[derive(Clone, Copy, Debug)]
pub(crate) struct PendingGnuTimer {
    pub(crate) timer: Value,
    pub(crate) when: GnuTimerTimestamp,
}

fn runtime_tail_fingerprint(tail: &[Value]) -> u64 {
    use std::hash::{Hash, Hasher};
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    let mut seen = std::collections::HashSet::new();
    tail.len().hash(&mut hasher);
    for (i, value) in tail.iter().enumerate() {
        i.hash(&mut hasher);
        value_fingerprint(*value, &mut hasher, 3, &mut seen);
    }
    hasher.finish()
}

fn value_fingerprint(
    value: Value,
    hasher: &mut impl std::hash::Hasher,
    depth: usize,
    seen: &mut std::collections::HashSet<usize>,
) {
    use std::hash::Hash;
    match value.kind() {
        ValueKind::Nil => 0u8.hash(hasher),
        ValueKind::T => 1u8.hash(hasher),
        ValueKind::Fixnum(n) => {
            2u8.hash(hasher);
            n.hash(hasher);
        }
        ValueKind::Float => {
            3u8.hash(hasher);
            value.as_float().unwrap().to_bits().hash(hasher);
        }
        ValueKind::Symbol(id) => {
            4u8.hash(hasher);
            id.0.hash(hasher);
        }
        ValueKind::String => {
            5u8.hash(hasher);
            let key = value.bits() as usize;
            if depth == 0 || !seen.insert(key) {
                key.hash(hasher);
                return;
            }
            let string = match value.as_lisp_string() {
                Some(string) => string,
                None => {
                    key.hash(hasher);
                    return;
                }
            };
            string.is_multibyte().hash(hasher);
            string.schars().hash(hasher);
            string.sbytes().hash(hasher);
            for byte in string.as_bytes().iter().take(32) {
                byte.hash(hasher);
            }
        }
        ValueKind::Cons => {
            6u8.hash(hasher);
            let key = value.bits() as usize;
            if depth == 0 || !seen.insert(key) {
                key.hash(hasher);
                return;
            }
            let mut cursor = value;
            let mut count = 0usize;
            while count < 4 && cursor.is_cons() {
                count.hash(hasher);
                value_fingerprint(cursor.cons_car(), hasher, depth - 1, seen);
                cursor = cursor.cons_cdr();
                count += 1;
            }
            value_fingerprint(cursor, hasher, depth - 1, seen);
        }
        ValueKind::Veclike(VecLikeType::Vector) => {
            7u8.hash(hasher);
            let key = value.bits() as usize;
            if depth == 0 || !seen.insert(key) {
                key.hash(hasher);
                return;
            }
            let items = value.as_vector_data().unwrap();
            items.len().hash(hasher);
            for item in items.iter().take(4) {
                value_fingerprint(*item, hasher, depth - 1, seen);
            }
        }
        ValueKind::Subr(sym_id) => {
            8u8.hash(hasher);
            sym_id.0.hash(hasher);
        }
        ValueKind::Veclike(VecLikeType::Subr) => {
            8u8.hash(hasher);
            value.as_subr_id().unwrap().0.hash(hasher);
        }
        _ => {
            9u8.hash(hasher);
            value.bits().hash(hasher);
        }
    }
}

fn interpreted_closure_env_entries(lexenv: Value) -> Vec<InterpretedClosureEnvEntry> {
    let mut cursor = lexenv;
    let mut entries = Vec::new();
    loop {
        match cursor.kind() {
            ValueKind::Cons => {
                let pair_car = cursor.cons_car();
                let pair_cdr = cursor.cons_cdr();
                match pair_car.kind() {
                    ValueKind::T => entries.push(InterpretedClosureEnvEntry::TopLevelSentinel),
                    ValueKind::Symbol(sym) => {
                        entries.push(InterpretedClosureEnvEntry::Special(sym))
                    }
                    ValueKind::Cons => {
                        let inner_car = pair_car.cons_car();
                        if let Some(sym) = binding_symbol_id(inner_car) {
                            entries.push(InterpretedClosureEnvEntry::Binding(sym));
                        }
                    }
                    _ => {}
                }
                cursor = pair_cdr;
            }
            _ => return entries,
        }
    }
}

fn binding_symbol_id(value: Value) -> Option<SymId> {
    match value.kind() {
        ValueKind::Symbol(sym) => Some(sym),
        ValueKind::T => Some(intern("t")),
        ValueKind::Nil => Some(intern("nil")),
        _ => None,
    }
}

fn interpreted_closure_trim_fingerprint(
    params_value: Value,
    body_value: Value,
    iform_value: Value,
    env_shape: &[InterpretedClosureEnvEntry],
) -> u64 {
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    let mut seen = std::collections::HashSet::new();
    value_fingerprint(params_value, &mut hasher, 8, &mut seen);
    value_fingerprint(body_value, &mut hasher, 8, &mut seen);
    value_fingerprint(iform_value, &mut hasher, 8, &mut seen);
    env_shape.hash(&mut hasher);
    hasher.finish()
}

fn interpreted_closure_env_shape_hash(env_shape: &[InterpretedClosureEnvEntry]) -> u64 {
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    env_shape.hash(&mut hasher);
    hasher.finish()
}

fn rebuild_trimmed_interpreted_closure_env(
    source_env: Value,
    template: &[InterpretedClosureEnvEntry],
) -> Value {
    let mut entries = Vec::with_capacity(template.len());
    for entry in template {
        match entry {
            InterpretedClosureEnvEntry::TopLevelSentinel => entries.push(Value::T),
            InterpretedClosureEnvEntry::Special(sym) => entries.push(Value::from_sym_id(*sym)),
            InterpretedClosureEnvEntry::Binding(sym) => {
                let cell = lexenv_assq(source_env, *sym)
                    .expect("cached interpreted-closure env binding should exist");
                entries.push(cell);
            }
        }
    }
    Value::list(entries)
}

#[derive(Clone, Debug)]
enum NamedCallTarget {
    Obarray(Value),
    Subr(Value),
    Void,
}

#[derive(Clone, Debug)]
struct NamedCallCacheEntry {
    function_epoch: u64,
    target: NamedCallTarget,
}

#[derive(Clone, Copy, Debug)]
struct LexenvAssqCacheEntry {
    lexenv_bits: usize,
    symbol: SymId,
    cell: Value,
}

#[derive(Clone, Debug, Default)]
struct LexenvAssqCache {
    entries: [Option<LexenvAssqCacheEntry>; LEXENV_ASSQ_CACHE_CAPACITY],
}

impl LexenvAssqCache {
    #[inline]
    fn slot(lexenv_bits: usize, sym_id: SymId) -> usize {
        let mixed = lexenv_bits.rotate_left(7) ^ (sym_id.0 as usize).wrapping_mul(0x9E37_79B1);
        mixed & (LEXENV_ASSQ_CACHE_CAPACITY - 1)
    }

    #[inline]
    fn find(&self, lexenv_bits: usize, sym_id: SymId) -> Option<Value> {
        let entry = self.entries[Self::slot(lexenv_bits, sym_id)]?;
        (entry.lexenv_bits == lexenv_bits && entry.symbol == sym_id).then_some(entry.cell)
    }

    #[inline]
    fn push(&mut self, entry: LexenvAssqCacheEntry) {
        let index = Self::slot(entry.lexenv_bits, entry.symbol);
        self.entries[index] = Some(entry);
    }
}

#[derive(Clone, Copy, Debug)]
struct LexenvSpecialCacheEntry {
    lexenv_bits: usize,
    symbol: SymId,
    declared_special: bool,
}

#[derive(Clone, Debug, Default)]
struct LexenvSpecialCache {
    entries: [Option<LexenvSpecialCacheEntry>; LEXENV_SPECIAL_CACHE_CAPACITY],
}

impl LexenvSpecialCache {
    #[inline]
    fn slot(lexenv_bits: usize, sym_id: SymId) -> usize {
        let mixed = lexenv_bits.rotate_left(7) ^ (sym_id.0 as usize).wrapping_mul(0x9E37_79B1);
        mixed & (LEXENV_SPECIAL_CACHE_CAPACITY - 1)
    }

    #[inline]
    fn find(&self, lexenv_bits: usize, sym_id: SymId) -> Option<bool> {
        let entry = self.entries[Self::slot(lexenv_bits, sym_id)]?;
        (entry.lexenv_bits == lexenv_bits && entry.symbol == sym_id)
            .then_some(entry.declared_special)
    }

    #[inline]
    fn push(&mut self, entry: LexenvSpecialCacheEntry) {
        let index = Self::slot(entry.lexenv_bits, entry.symbol);
        self.entries[index] = Some(entry);
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum InterpretedClosureEnvEntry {
    TopLevelSentinel,
    Special(SymId),
    Binding(SymId),
}

#[derive(Clone, Debug)]
pub(crate) struct RuntimeMacroExpansionCacheEntry {
    function: Value,
    expanded: Value,
    fingerprint: u64,
}

impl RuntimeMacroExpansionCacheEntry {
    fn new(function: Value, expanded: Value, fingerprint: u64) -> Self {
        Self {
            function,
            expanded,
            fingerprint,
        }
    }
}

#[derive(Clone, Copy, Debug, Default)]
struct MacroPerfCounter {
    calls: u64,
    total_us: u64,
    max_us: u64,
}

impl MacroPerfCounter {
    fn note_duration(&mut self, duration: std::time::Duration) {
        let elapsed_us = duration.as_micros() as u64;
        self.calls = self.calls.saturating_add(1);
        self.total_us = self.total_us.saturating_add(elapsed_us);
        self.max_us = self.max_us.max(elapsed_us);
    }

    fn summary(&self, label: &str) -> Option<String> {
        if self.calls == 0 {
            return None;
        }
        let avg_us = self.total_us / self.calls.max(1);
        Some(format!(
            "{label}=count:{} total:{:.2}ms avg:{:.3}ms max:{:.3}ms",
            self.calls,
            self.total_us as f64 / 1000.0,
            avg_us as f64 / 1000.0,
            self.max_us as f64 / 1000.0
        ))
    }
}

#[derive(Clone, Debug, Default)]
struct MacroPerfStats {
    scope_enter: MacroPerfCounter,
    scope_exit: MacroPerfCounter,
    macro_apply: MacroPerfCounter,
    cache_lookup: MacroPerfCounter,
    cache_store: MacroPerfCounter,
    expand_macro: MacroPerfCounter,
    eager_step1: MacroPerfCounter,
    eager_step3: MacroPerfCounter,
    eager_step4: MacroPerfCounter,
}

#[derive(Clone, Debug)]
struct InterpretedClosureTrimCacheEntry {
    params_value: Value,
    body_value: Value,
    iform_value: Value,
    env_shape: Vec<InterpretedClosureEnvEntry>,
    trimmed_params_value: Value,
    trimmed_body_value: Value,
    trimmed_env_template: Vec<InterpretedClosureEnvEntry>,
}

impl InterpretedClosureTrimCacheEntry {
    fn matches(
        &self,
        params_value: Value,
        body_value: Value,
        iform_value: Value,
        env_shape: &[InterpretedClosureEnvEntry],
    ) -> bool {
        equal_value(&self.params_value, &params_value, 0)
            && equal_value(&self.body_value, &body_value, 0)
            && equal_value(&self.iform_value, &iform_value, 0)
            && self.env_shape == env_shape
    }
}

#[derive(Clone, Debug)]
struct InterpretedClosureValueCacheEntry {
    source_function: Value,
    env_shape: Vec<InterpretedClosureEnvEntry>,
    trimmed_params_value: Value,
    trimmed_body_value: Value,
    trimmed_env_template: Vec<InterpretedClosureEnvEntry>,
}

impl InterpretedClosureValueCacheEntry {
    fn matches(&self, source_function: Value, env_shape: &[InterpretedClosureEnvEntry]) -> bool {
        equal_value(&self.source_function, &source_function, 0) && self.env_shape == env_shape
    }
}

fn value_from_symbol_id(sym_id: SymId) -> Value {
    if is_canonical_id(sym_id) {
        if sym_id == nil_symbol() {
            return Value::NIL;
        }
        if sym_id == t_symbol() {
            return Value::T;
        }
        if is_keyword_id(sym_id) {
            return Value::from_kw_id(sym_id);
        }
    }
    Value::from_sym_id(sym_id)
}

fn hidden_internal_interpreter_environment_symbol() -> SymId {
    static HIDDEN_SYMBOL: OnceLock<SymId> = OnceLock::new();
    *HIDDEN_SYMBOL.get_or_init(|| intern_uninterned("internal-interpreter-environment"))
}

fn default_directory_symbol() -> SymId {
    static SYMBOL: OnceLock<SymId> = OnceLock::new();
    *SYMBOL.get_or_init(|| intern("default-directory"))
}

fn lexical_binding_symbol() -> SymId {
    static SYMBOL: OnceLock<SymId> = OnceLock::new();
    *SYMBOL.get_or_init(|| intern("lexical-binding"))
}

fn nil_symbol() -> SymId {
    static SYMBOL: OnceLock<SymId> = OnceLock::new();
    *SYMBOL.get_or_init(|| intern("nil"))
}

fn t_symbol() -> SymId {
    static SYMBOL: OnceLock<SymId> = OnceLock::new();
    *SYMBOL.get_or_init(|| intern("t"))
}

fn buffer_undo_list_symbol() -> SymId {
    static SYMBOL: OnceLock<SymId> = OnceLock::new();
    *SYMBOL.get_or_init(|| intern("buffer-undo-list"))
}

fn macroexp_dynvars_symbol() -> SymId {
    static SYMBOL: OnceLock<SymId> = OnceLock::new();
    *SYMBOL.get_or_init(|| intern("macroexp--dynvars"))
}

macro_rules! cached_symbol_id {
    ($fn_name:ident, $name:literal) => {
        #[inline(always)]
        fn $fn_name() -> SymId {
            static SYMBOL: OnceLock<SymId> = OnceLock::new();
            if let Some(id) = SYMBOL.get() {
                *id
            } else {
                *SYMBOL.get_or_init(|| intern($name))
            }
        }
    };
}

cached_symbol_id!(quote_symbol, "quote");
cached_symbol_id!(function_symbol, "function");
cached_symbol_id!(let_symbol, "let");
cached_symbol_id!(let_star_symbol, "let*");
cached_symbol_id!(setq_symbol, "setq");
cached_symbol_id!(if_symbol, "if");
cached_symbol_id!(and_symbol, "and");
cached_symbol_id!(or_symbol, "or");
cached_symbol_id!(cond_symbol, "cond");
cached_symbol_id!(while_symbol, "while");
cached_symbol_id!(progn_symbol, "progn");
cached_symbol_id!(prog1_symbol, "prog1");
cached_symbol_id!(defvar_symbol, "defvar");
cached_symbol_id!(defconst_symbol, "defconst");
cached_symbol_id!(catch_symbol, "catch");
cached_symbol_id!(unwind_protect_symbol, "unwind-protect");
cached_symbol_id!(condition_case_symbol, "condition-case");
cached_symbol_id!(save_excursion_symbol, "save-excursion");
cached_symbol_id!(save_current_buffer_symbol, "save-current-buffer");
cached_symbol_id!(save_restriction_symbol, "save-restriction");
cached_symbol_id!(interactive_symbol_id, "interactive");
cached_symbol_id!(lambda_symbol, "lambda");
cached_symbol_id!(closure_symbol, "closure");
cached_symbol_id!(declare_symbol, "declare");
cached_symbol_id!(macro_symbol, "macro");
cached_symbol_id!(byte_code_literal_symbol, "byte-code-literal");
cached_symbol_id!(byte_code_symbol, "byte-code");
cached_symbol_id!(gc_cons_threshold_symbol, "gc-cons-threshold");
cached_symbol_id!(gc_cons_percentage_symbol, "gc-cons-percentage");
cached_symbol_id!(memory_full_symbol, "memory-full");
cached_symbol_id!(gc_elapsed_symbol, "gc-elapsed");
cached_symbol_id!(gcs_done_symbol, "gcs-done");

fn is_lambda_like_symbol_id(id: SymId) -> bool {
    id == lambda_symbol() || id == closure_symbol()
}

fn cons_head_symbol_id(value: &Value) -> Option<SymId> {
    if value.is_cons() {
        let car = value.cons_car();
        // Try bare symbol first, then transparently unwrap symbol-with-pos.
        car.as_symbol_id().or_else(|| {
            car.as_symbol_with_pos_sym()
                .and_then(|sym| sym.as_symbol_id())
        })
    } else {
        None
    }
}

struct CoreEvalSymbols {
    internal_interpreter_environment_symbol: SymId,
    quit_flag_symbol: SymId,
    inhibit_quit_symbol: SymId,
    throw_on_input_symbol: SymId,
    kill_emacs_symbol: SymId,
    noninteractive_symbol: SymId,
    symbols_with_pos_enabled_symbol: SymId,
    print_symbols_bare_symbol: SymId,
}

fn install_core_eval_symbols(obarray: &mut Obarray, reset_runtime_values: bool) -> CoreEvalSymbols {
    obarray.intern("internal-interpreter-environment");
    let internal_interpreter_environment_symbol = hidden_internal_interpreter_environment_symbol();
    obarray.set_symbol_value_id(internal_interpreter_environment_symbol, Value::NIL);
    obarray.make_special_id(internal_interpreter_environment_symbol);

    let quit_flag_symbol = intern("quit-flag");
    if reset_runtime_values {
        obarray.set_symbol_value_id(quit_flag_symbol, Value::NIL);
    }
    obarray.make_special_id(quit_flag_symbol);

    let inhibit_quit_symbol = intern("inhibit-quit");
    if reset_runtime_values {
        obarray.set_symbol_value_id(inhibit_quit_symbol, Value::NIL);
    }
    obarray.make_special_id(inhibit_quit_symbol);

    let throw_on_input_symbol = intern("throw-on-input");
    if reset_runtime_values {
        obarray.set_symbol_value_id(throw_on_input_symbol, Value::NIL);
    }
    obarray.make_special_id(throw_on_input_symbol);

    let kill_emacs_symbol = intern("kill-emacs");
    let noninteractive_symbol = intern("noninteractive");
    let symbols_with_pos_enabled_symbol = intern("symbols-with-pos-enabled");
    let print_symbols_bare_symbol = intern("print-symbols-bare");

    CoreEvalSymbols {
        internal_interpreter_environment_symbol,
        quit_flag_symbol,
        inhibit_quit_symbol,
        throw_on_input_symbol,
        kill_emacs_symbol,
        noninteractive_symbol,
        symbols_with_pos_enabled_symbol,
        print_symbols_bare_symbol,
    }
}

fn is_runtime_dynamically_special(obarray: &Obarray, sym_id: SymId) -> bool {
    obarray.is_special_id(sym_id) && !obarray.is_constant_id(sym_id)
}

fn symbol_sets_constant_error(sym_id: SymId) -> Option<&'static str> {
    match resolve_sym(sym_id) {
        "nil" => Some("nil"),
        "t" => Some("t"),
        _ => None,
    }
}

pub(crate) fn sync_features_variable_in_state(obarray: &mut Obarray, features: &[SymId]) {
    let values: Vec<Value> = features.iter().map(|id| Value::from_sym_id(*id)).collect();
    obarray.set_symbol_value("features", Value::list(values));
}

pub(crate) fn refresh_features_from_variable_in_state(
    obarray: &Obarray,
    features: &mut Vec<SymId>,
) {
    let current = obarray
        .symbol_value("features")
        .cloned()
        .unwrap_or(Value::NIL);
    let mut parsed = Vec::new();
    if let Some(items) = list_to_vec(&current) {
        for item in items {
            if let Some(id) = item.as_symbol_id() {
                parsed.push(id);
            }
        }
    }
    *features = parsed;
}

pub(crate) fn feature_present_in_state(
    obarray: &Obarray,
    features: &mut Vec<SymId>,
    name: &str,
) -> bool {
    refresh_features_from_variable_in_state(obarray, features);
    let id = intern(name);
    features.iter().any(|feature| *feature == id)
}

pub(crate) fn add_feature_in_state(obarray: &mut Obarray, features: &mut Vec<SymId>, name: &str) {
    refresh_features_from_variable_in_state(obarray, features);
    let id = intern(name);
    if features.iter().any(|feature| *feature == id) {
        return;
    }
    // Emacs pushes newly-provided features at the front.
    features.insert(0, id);
    sync_features_variable_in_state(obarray, features);
}

pub(crate) fn remove_feature_in_state(
    obarray: &mut Obarray,
    features: &mut Vec<SymId>,
    name: &str,
) {
    refresh_features_from_variable_in_state(obarray, features);
    let id = intern(name);
    features.retain(|feature| *feature != id);
    sync_features_variable_in_state(obarray, features);
}

pub(crate) fn provide_value_in_state(
    obarray: &mut Obarray,
    features: &mut Vec<SymId>,
    feature: Value,
    subfeatures: Option<Value>,
) -> EvalResult {
    // Use symbol_id to transparently handle symbol-with-pos wrappers.
    let sym_id = super::builtins::symbols::symbol_id(&feature).ok_or_else(|| {
        signal(
            "wrong-type-argument",
            vec![Value::symbol("symbolp"), feature],
        )
    })?;
    let name = resolve_sym(sym_id).to_owned();
    if let Some(value) = subfeatures {
        obarray.put_property(&name, "subfeatures", value)?;
    }
    add_feature_in_state(obarray, features, &name);
    Ok(feature)
}

/// Limit for stored recent input events to match GNU Emacs: 300 entries.
pub(crate) const RECENT_INPUT_EVENT_LIMIT: usize = 300;

thread_local! {
    static SCRATCH_GC_ROOTS: RefCell<Vec<Value>> = const { RefCell::new(Vec::new()) };
}

/// Collect GC roots from all thread-local statics that hold Values.
///
/// Thread-local statics are invisible to the normal GC root scan (which
/// only walks the Evaluator struct and its sub-managers).  This function
/// calls each module's `collect_*_gc_roots` helper to ensure those Values
/// are marked as live during garbage collection.
fn collect_thread_local_gc_roots(roots: &mut Vec<Value>) {
    super::syntax::collect_syntax_gc_roots(roots);
    super::casetab::collect_casetab_gc_roots(roots);
    super::category::collect_category_gc_roots(roots);
    super::value_reader::collect_value_reader_gc_roots(roots);
    super::terminal::pure::collect_terminal_gc_roots(roots);
    super::font::collect_font_gc_roots(roots);
    super::charset::collect_charset_gc_roots(roots);
    super::ccl::collect_ccl_gc_roots(roots);
    SCRATCH_GC_ROOTS.with(|scratch| roots.extend(scratch.borrow().iter().copied()));
}

pub fn save_scratch_gc_roots() -> usize {
    SCRATCH_GC_ROOTS.with(|scratch| scratch.borrow().len())
}

pub fn push_scratch_gc_root(value: Value) {
    SCRATCH_GC_ROOTS.with(|scratch| scratch.borrow_mut().push(value));
}

pub fn restore_scratch_gc_roots(saved_len: usize) {
    SCRATCH_GC_ROOTS.with(|scratch| scratch.borrow_mut().truncate(saved_len));
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GuiFrameHostRequest {
    pub frame_id: crate::window::FrameId,
    pub width: u32,
    pub height: u32,
    pub title: crate::heap_types::LispString,
    pub geometry_hints: crate::window::GuiFrameGeometryHints,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct GuiFrameHostSize {
    pub width: u32,
    pub height: u32,
}

#[derive(Clone, Debug)]
pub struct FontResolveRequest {
    pub frame_id: crate::window::FrameId,
    pub character: char,
    pub face: RuntimeFace,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FontSpecResolveRequest {
    pub frame_id: crate::window::FrameId,
    pub family: Option<crate::heap_types::LispString>,
    pub registry: Option<crate::heap_types::LispString>,
    pub lang: Option<crate::heap_types::LispString>,
    pub weight: Option<FontWeight>,
    pub slant: Option<FontSlant>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ResolvedFontMatch {
    pub family: crate::heap_types::LispString,
    pub foundry: Option<crate::heap_types::LispString>,
    pub weight: FontWeight,
    pub slant: FontSlant,
    pub width: FontWidth,
    pub postscript_name: Option<crate::heap_types::LispString>,
}

#[derive(Clone, Debug, PartialEq)]
pub struct ResolvedFrameFont {
    pub family: crate::heap_types::LispString,
    pub foundry: Option<crate::heap_types::LispString>,
    pub weight: FontWeight,
    pub slant: FontSlant,
    pub width: FontWidth,
    pub postscript_name: Option<crate::heap_types::LispString>,
    pub font_size_px: f32,
    pub char_width: f32,
    pub line_height: f32,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ResolvedFontSpecMatch {
    pub family: crate::heap_types::LispString,
    pub registry: Option<crate::heap_types::LispString>,
    pub weight: Option<FontWeight>,
    pub slant: Option<FontSlant>,
    pub width: Option<FontWidth>,
    pub spacing: Option<i32>,
    pub postscript_name: Option<crate::heap_types::LispString>,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum ImageResolveSource {
    File(crate::heap_types::LispString),
    Data(Vec<u8>),
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ImageResolveRequest {
    pub source: ImageResolveSource,
    pub max_width: u32,
    pub max_height: u32,
    pub fg_color: u32,
    pub bg_color: u32,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ResolvedImage {
    pub image_id: u32,
    pub width: u32,
    pub height: u32,
}

pub trait DisplayHost {
    fn realize_gui_frame(&mut self, request: GuiFrameHostRequest) -> Result<(), String>;
    fn resize_gui_frame(&mut self, request: GuiFrameHostRequest) -> Result<(), String>;
    fn set_gui_frame_geometry_hints(
        &mut self,
        _frame_id: crate::window::FrameId,
        _geometry_hints: crate::window::GuiFrameGeometryHints,
    ) -> Result<(), String> {
        Ok(())
    }
    fn set_gui_frame_title(
        &mut self,
        _frame_id: crate::window::FrameId,
        _title: crate::heap_types::LispString,
    ) -> Result<(), String> {
        Ok(())
    }
    fn opening_gui_frame_pending(&self) -> bool {
        false
    }
    fn current_primary_window_size(&self) -> Option<GuiFrameHostSize> {
        None
    }
    fn resolve_font_for_char(
        &mut self,
        _request: FontResolveRequest,
    ) -> Result<Option<ResolvedFontMatch>, String> {
        Ok(None)
    }
    fn resolve_frame_font(
        &mut self,
        _frame_id: crate::window::FrameId,
        _face: RuntimeFace,
    ) -> Result<Option<ResolvedFrameFont>, String> {
        Ok(None)
    }
    fn resolve_font_for_spec(
        &mut self,
        _request: FontSpecResolveRequest,
    ) -> Result<Option<ResolvedFontSpecMatch>, String> {
        Ok(None)
    }
    fn resolve_image(
        &self,
        _request: ImageResolveRequest,
    ) -> Result<Option<ResolvedImage>, String> {
        Ok(None)
    }
    fn set_cursor_blink(&mut self, _enabled: bool, _interval_ms: u32) -> Result<(), String> {
        Ok(())
    }
}

/// The Elisp evaluator.
///
/// # Safety: Send
/// Evaluator is inherently single-threaded (uses thread-local heap and caches).
/// # Safety: Send
/// Context is inherently single-threaded (uses thread-local heap and caches).
/// `neovm-worker` moves the Context to a worker thread inside
/// `Arc<Mutex<..>>`, which ensures exclusive access.
// SAFETY: Rc is !Send only because it uses non-atomic refcounting.
// Since Context is always used single-threaded (guarded by Mutex when
// transferred between threads), this is safe.
unsafe impl Send for Context {}

#[derive(Clone, Debug, PartialEq, Eq)]
#[allow(dead_code)]
pub(crate) enum ResumeTarget {
    CommandLoopExit,
    CommandLoopTopLevel,
    InterpreterCatch,
    InterpreterConditionCase {
        handler_index: usize,
        condition_stack_base: usize,
    },
    VmCatch {
        resume_id: u64,
        target: u32,
        stack_len: usize,
        spec_depth: usize,
        bind_stack_len: usize,
    },
    VmConditionCase {
        resume_id: u64,
        target: u32,
        stack_len: usize,
        spec_depth: usize,
        bind_stack_len: usize,
    },
}

#[derive(Clone, Debug)]
#[allow(dead_code)]
pub(crate) enum ConditionFrame {
    Catch {
        tag: Value,
        resume: ResumeTarget,
    },
    ConditionCase {
        conditions: Value,
        resume: ResumeTarget,
    },
    HandlerBind {
        conditions: Value,
        handler: Value,
        mute_span: usize,
    },
    SkipConditions {
        remaining: usize,
    },
}

fn condition_value_contains_debug(value: &Value) -> bool {
    match value.kind() {
        ValueKind::Symbol(id) => resolve_sym(id) == "debug",
        ValueKind::Cons => {
            list_to_vec(value).is_some_and(|items| items.iter().any(condition_value_contains_debug))
        }
        _ => false,
    }
}

fn wants_debugger(setting: &Value, conditions: &Value) -> bool {
    if setting.is_nil() {
        return false;
    }
    let Some(entries) = list_to_vec(setting) else {
        return true;
    };
    let signal_conditions = list_to_vec(conditions).unwrap_or_else(|| vec![*conditions]);
    entries
        .iter()
        .any(|entry| signal_conditions.iter().any(|condition| condition == entry))
}

fn signal_hook_payload_value(sig: &SignalData) -> Value {
    if let Some(raw) = &sig.raw_data {
        *raw
    } else if sig.data.is_empty() {
        Value::NIL
    } else {
        Value::list(sig.data.clone())
    }
}

/// Metadata for a single active bytecode frame in the contiguous `bc_buf`.
pub(crate) struct BcFrame {
    /// Index in `Context::bc_buf` where this frame's stack region starts.
    pub base: usize,
    /// The function value — keeps the bytecode object (and its constants)
    /// reachable by GC.
    pub fun: Value,
}

pub struct Context {
    /// Tagged pointer heap — sole GC and allocator.
    pub(crate) tagged_heap: Box<crate::tagged::gc::TaggedHeap>,
    /// Mmap-backed pdump image that owns any mapped heap payloads borrowed by
    /// this evaluator's Lisp objects.
    pub(crate) pdump_image: Option<super::pdump::mmap_image::LoadedMmapImage>,
    /// The obarray — unified symbol table with value cells, function cells, plists.
    pub(crate) obarray: Obarray,
    /// Specpdl — special binding stack that writes directly to the obarray.
    /// Matches GNU Emacs's specpdl design.
    pub(crate) specpdl: Vec<SpecBinding>,
    /// Lexical environment: flat cons alist mirroring GNU Emacs's
    /// `Vinternal_interpreter_environment`.
    pub(crate) lexenv: Value,
    /// GNU `eval.c` keeps `Vinternal_interpreter_environment` on a hidden
    /// symbol object by `Funintern`ing the public name from the obarray.
    /// NeoVM keeps the actual evaluator-owned symbol identity here so the
    /// public `internal-interpreter-environment` symbol can stay visible
    /// while remaining unbound and non-special.
    pub(crate) internal_interpreter_environment_symbol: SymId,
    /// GNU `eval.c` hot-path DEFVARs exposed via direct globals like
    /// `Vquit_flag`, `Vinhibit_quit`, and `Vthrow_on_input`.
    ///
    /// NeoVM still stores their values in the obarray's symbol cells so Lisp
    /// sees ordinary variables, but evaluator boundaries keep their symbol
    /// identities cached here to avoid repeated name interning/lookups.
    quit_flag_symbol: SymId,
    inhibit_quit_symbol: SymId,
    throw_on_input_symbol: SymId,
    kill_emacs_symbol: SymId,
    quit_flag: Value,
    inhibit_quit: Value,
    noninteractive_symbol: SymId,
    noninteractive: bool,
    symbols_with_pos_enabled_symbol: SymId,
    /// When true, `symbolp`/`eq`/hash operations transparently unwrap
    /// symbol-with-pos objects. Bound to `t` by the byte-compiler.
    pub(crate) symbols_with_pos_enabled: bool,
    print_symbols_bare_symbol: SymId,
    /// When true, the printer outputs bare symbol names for symbol-with-pos.
    pub(crate) print_symbols_bare: bool,
    /// Features list (for require/provide).
    pub(crate) features: Vec<SymId>,
    /// Features currently being resolved through `require`.
    pub(crate) require_stack: Vec<SymId>,
    /// Files currently being loaded (mirrors `Vloads_in_progress` in lread.c).
    pub(crate) loads_in_progress: Vec<crate::heap_types::LispString>,
    /// Buffer manager — owns all live buffers and tracks current buffer.
    pub buffers: BufferManager,
    /// Match data from the last successful search/match operation.
    pub(crate) match_data: Option<MatchData>,
    /// Process manager — owns all tracked processes.
    pub(crate) processes: ProcessManager,
    /// Network manager — owns network connections, filters, and sentinels.
    /// Timer manager — owns all timers.
    pub(crate) timers: TimerManager,
    /// Variable watcher list — callbacks on variable changes.
    pub(crate) watchers: VariableWatcherList,
    /// Canonical Lisp object returned by `standard-syntax-table`.
    ///
    /// GNU Emacs stores this in `Vstandard_syntax_table`; NeoVM keeps the
    /// authoritative identity here and mirrors it into thread-local state for
    /// no-evaluator syntax builtins.
    pub(crate) standard_syntax_table: Value,
    /// Canonical Lisp object returned by `standard-category-table`.
    ///
    /// Like `standard_syntax_table`, this is mirrored into thread-local state
    /// because the category-table helpers currently expose some no-evaluator
    /// entry points.
    pub(crate) standard_category_table: Value,
    /// Current buffer-local keymap (set by `use-local-map`).
    pub(crate) current_local_map: Value,
    /// Register manager — quick storage and retrieval of text, positions, etc.
    pub(crate) registers: RegisterManager,
    /// Bookmark manager — persistent named positions.
    pub(crate) bookmarks: BookmarkManager,
    /// Abbreviation manager — text abbreviation expansion.
    pub(crate) abbrevs: AbbrevManager,
    /// Autoload manager — deferred function loading.
    pub(crate) autoloads: AutoloadManager,
    /// Custom variable manager — defcustom/defgroup system.
    pub(crate) custom: CustomManager,
    /// Rectangle state — stores the last killed rectangle for yank-rectangle.
    pub(crate) rectangle: RectangleState,
    /// Interactive command registry — tracks interactive commands.
    pub(crate) interactive: InteractiveRegistry,
    /// Tree-sitter runtime manager — loaded grammars, parser state, node handles,
    /// and compiled queries backing `treesit-*` builtins.
    pub(crate) treesit: super::treesit::TreeSitterManager,
    /// Minibuffer runtime state — active minibuffer stack, prompt metadata, and history.
    pub(crate) minibuffers: MinibufferManager,
    /// Count of completed minibuffer reads observed by the evaluator.
    pub(crate) interactive_minibuffer_read_count: u64,
    /// Current echo-area message text, mirroring GNU `current-message`.
    pub(crate) current_message: Option<crate::heap_types::LispString>,
    /// Window that was selected when the active minibuffer session began.
    pub(crate) minibuffer_selected_window: Option<crate::window::WindowId>,
    /// Currently active minibuffer window, if any.
    pub(crate) active_minibuffer_window: Option<crate::window::WindowId>,
    /// Pending orderly shutdown requested by GNU C-owned primitives such as
    /// `kill-emacs`.
    pub(crate) shutdown_request: Option<ShutdownRequest>,
    /// Batch-compatible input-mode interrupt flag for `current-input-mode`.
    pub(crate) input_mode_interrupt: bool,
    /// Lisp-visible `quit_char` used by `current-input-mode` and low-level
    /// keyboard quit detection.
    pub(crate) quit_char: i64,
    /// True while the command loop is blocked waiting for external input.
    pub(crate) waiting_for_user_input: bool,
    /// Frame manager — owns all frames and windows.
    pub(crate) frames: FrameManager,
    /// Mode registry — major/minor modes.
    pub(crate) modes: ModeRegistry,
    /// Thread manager — cooperative threading primitives.
    pub(crate) threads: ThreadManager,
    /// Keyboard macro metadata — ring/counter state layered above the
    /// keyboard-owned live recording/playback runtime.
    pub(crate) kmacro: KmacroManager,
    /// Command loop state — event queue, prefix args, kbd macros, quit flag.
    /// Used by the interactive command loop (recursive-edit → command_loop).
    pub(crate) command_loop: crate::keyboard::CommandLoop,
    /// Input event receiver from the display/render thread.
    /// `None` in batch mode (tests, non-interactive evaluation).
    /// When `Some`, `read_char()` blocks on this channel for interactive input.
    pub input_rx: Option<crossbeam_channel::Receiver<crate::keyboard::InputEvent>>,
    /// Wakeup file descriptor — the read end of a pipe that the render thread
    /// writes to when input is available.  Used by `wait_for_input()` with
    /// `pselect()`/`poll()` to multiplex input with process I/O and timers.
    /// `None` in batch mode.
    #[cfg(unix)]
    pub wakeup_fd: Option<std::os::unix::io::RawFd>,
    /// Cross-thread quit signal. The input-bridge thread flips this to
    /// `true` when it observes a `quit-char` keystroke; the evaluator
    /// drains it from `maybe_quit` into `Vquit_flag` on its next poll.
    ///
    /// GNU handles this case with `sys_longjmp` from the signal or
    /// keystroke handler straight into `read_char`'s `setjmp` target
    /// (`keyboard.c:12738`, `keyboard.c:3812`). Rust can't do that
    /// across owned borrows, so we use an atomic flag and rely on
    /// `maybe_quit` polling from `eval_sub` / `Ffuncall` / the bytecode
    /// VM to pick it up.
    pub quit_requested: std::sync::Arc<std::sync::atomic::AtomicBool>,
    /// Redisplay callback — called before blocking for input in `read_char()`.
    ///
    /// In GNU Emacs, `read_char()` calls `redisplay()` directly (keyboard.c
    /// calls xdisp.c, both in the same binary). In our crate structure,
    /// `neomacs-layout-engine` depends on `neovm-core`, so neovm-core cannot
    /// call the layout engine directly (circular dependency). Instead,
    /// `neomacs-bin` sets this callback to run the layout engine and send
    /// the resulting `FrameGlyphBuffer` to the render thread.
    ///
    /// `None` in batch mode (no display).
    pub redisplay_fn: Option<Box<dyn FnMut(&mut Self)>>,
    /// Host-display bridge for GUI frame realization.
    pub display_host: Option<Box<dyn DisplayHost>>,
    /// Coding system manager — encoding/decoding registry.
    pub(crate) coding_systems: CodingSystemManager,
    /// Face table — global registry of named face definitions.
    pub(crate) face_table: FaceTable,
    /// Incremented when any face attribute changes; layout engine uses
    /// this to invalidate its resolved face cache.
    pub face_change_count: u64,
    /// Explicit redisplay invalidation generation, used for state that GNU
    /// marks with update_mode_lines/window redisplay flags.
    redisplay_generation: u64,
    /// Last visible state submitted to redisplay.  Mirrors GNU's fast
    /// `needs_no_redisplay` path by skipping layout when none of the visible
    /// inputs changed.
    last_redisplay_signature: Option<RedisplaySignature>,
    /// Recursion depth counter.
    pub(crate) depth: usize,
    eval_counter: u64,
    /// Maximum recursion depth.
    pub(crate) max_depth: usize,
    /// Set when allocation crosses the GC threshold; cleared by `gc_collect`.
    pub(crate) gc_pending: bool,
    /// Total number of GC collections performed.
    pub(crate) gc_count: u64,
    /// Nested depth of explicit GC inhibition scopes.
    pub(crate) gc_inhibit_depth: usize,
    /// Stress-test mode: force GC at every safe point regardless of threshold.
    pub(crate) gc_stress: bool,
    /// Cached Lisp-visible GC tuning variables used on every safe point.
    ///
    /// GNU updates its low-level GC tuning state when the watched variables
    /// change, then keeps `maybe_gc` itself cheap.  Mirror that split here:
    /// refresh the cache on the mutation sites, and let safe points combine
    /// the cached values with current heap usage.
    gc_runtime_settings_cache: GcRuntimeSettingsCache,
    /// Active VM-local root frames. Mirrors GNU's model more closely than a
    /// single save/truncate side vector by keeping VM dynamic roots in explicit
    /// nested frames.
    vm_root_frames: Vec<VmRootFrame>,
    /// Contiguous bytecode stack buffer, matching GNU Emacs's bc_thread_state.
    /// All bytecode frames share this single buffer. GC scans it directly.
    pub(crate) bc_buf: Vec<Value>,
    /// Frame metadata for each active bytecode invocation.
    /// Each entry records where the frame's stack region starts in bc_buf
    /// and the function object (so GC can trace its constants).
    pub(crate) bc_frames: Vec<BcFrame>,
    /// Shared condition runtime mirror for active catch/condition handlers.
    pub(crate) condition_stack: Vec<ConditionFrame>,
    /// Stable identity source for VM resume targets stored in the shared
    /// condition runtime.
    next_resume_id: u64,
    /// GNU `pending_funcalls` equivalent for internal no-Lisp teardown paths.
    pub(crate) pending_safe_funcalls: Vec<PendingSafeFuncall>,
    /// Hot cache for named callable resolution in `funcall`/`apply`.
    /// Keyed by symbol id; entries are validated against the obarray's
    /// `function_epoch` so that any `defalias` / `fset` / autoload
    /// installation immediately invalidates stale lookups.
    named_call_cache: HashMap<SymId, NamedCallCacheEntry>,
    /// Small hot cache for GNU-shaped lexical env alist lookups.
    lexenv_assq_cache: RefCell<LexenvAssqCache>,
    /// Small hot cache for GNU-shaped lexical special declarations.
    lexenv_special_cache: RefCell<LexenvSpecialCache>,
    /// Nested depth of active macro-expansion scopes.
    macro_expansion_scope_depth: usize,
    /// Monotonic counter for Lisp-visible mutations performed while a macro
    /// expander is running. Eager-load caches use this to preserve GNU
    /// `eval-and-compile` side effects during replay.
    macro_expansion_mutation_epoch: u64,
    /// Diagnostic counters for macro expansion cache.
    pub(crate) macro_cache_hits: u64,
    pub(crate) macro_cache_misses: u64,
    pub(crate) macro_expand_total_us: u64,
    /// When true, skip cache lookups (still populate cache for timing).
    pub(crate) macro_cache_disabled: bool,
    /// Value-side eager-load macro cache used by `macroexpand`/
    /// `internal-macroexpand-for-load`.
    ///
    /// Keyed by macro identity plus a structural fingerprint of the runtime
    /// argument tail, so equivalent cons trees rebuilt from cached/bootstrap
    /// forms can reuse the same expansion.
    pub(crate) runtime_macro_expansion_cache:
        HashMap<(usize, usize, u64), RuntimeMacroExpansionCacheEntry>,
    /// When true, collect detailed timing counters for macro/eager-load paths.
    macro_perf_enabled: bool,
    macro_perf_stats: MacroPerfStats,
    /// Bootstrapped standard interpreted-closure filter function object.
    /// Used to memoize the GNU cconv closure-trimming path without changing
    /// semantics when users later rebind/advice the hook.
    interpreted_closure_filter_fn: Option<Value>,
    /// Cache of standard cconv interpreted-closure trimming results keyed by
    /// lambda syntax plus lexical-environment shape. The cached data stores
    /// only the selected env template and trimmed body, so captured values are
    /// always rebuilt from the current runtime environment on a hit.
    interpreted_closure_trim_cache: HashMap<u64, Vec<InterpretedClosureTrimCacheEntry>>,
    /// Value-native cache for runtime callable-cons lambda instantiation.
    /// Keyed by a shallow Value fingerprint of the source callable plus the
    /// lexical environment shape.
    interpreted_closure_value_cache: HashMap<(u64, u64), Vec<InterpretedClosureValueCacheEntry>>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ShutdownRequest {
    pub exit_code: i32,
    pub restart: bool,
}

#[derive(Clone, Copy, Debug)]
struct GcRuntimeSettingsCache {
    gc_cons_threshold_bytes: usize,
    gc_cons_percentage_scaled: Option<u64>,
    memory_full: bool,
}

impl Default for GcRuntimeSettingsCache {
    fn default() -> Self {
        Self {
            gc_cons_threshold_bytes: GC_DEFAULT_THRESHOLD_BYTES,
            gc_cons_percentage_scaled: Some(100_000),
            memory_full: false,
        }
    }
}

pub(crate) enum RequirePlan {
    Return(Value),
    Load {
        sym_id: SymId,
        name: String,
        path: std::path::PathBuf,
    },
}

pub(crate) fn plan_require_in_state(
    obarray: &Obarray,
    features: &mut Vec<SymId>,
    require_stack: &[SymId],
    feature: Value,
    filename: Option<Value>,
    noerror: Option<Value>,
) -> Result<RequirePlan, Flow> {
    refresh_features_from_variable_in_state(obarray, features);
    // Use symbol_id to transparently handle symbol-with-pos wrappers.
    let sym_id = super::builtins::symbols::symbol_id(&feature).ok_or_else(|| {
        signal(
            "wrong-type-argument",
            vec![Value::symbol("symbolp"), feature],
        )
    })?;
    let name = resolve_sym(sym_id).to_owned();
    if features.contains(&sym_id) {
        return Ok(RequirePlan::Return(Value::symbol(&name)));
    }

    // GNU Emacs fns.c:Frequire tracks recursive requires in
    // require_nesting_list, but it does not treat an in-progress require as a
    // provided feature.  Recursive require is legitimate up to GNU's guard.
    let nesting = require_stack
        .iter()
        .filter(|stacked_sym_id| **stacked_sym_id == sym_id)
        .count();
    if nesting > 3 {
        return Err(signal(
            "error",
            vec![Value::string(format!(
                "Recursive `require' for feature `{name}'"
            ))],
        ));
    }

    let filename = match filename {
        Some(v) if v.is_nil() => name.clone(),
        Some(v) if v.is_string() => runtime_string_value(v),
        Some(other) => {
            return Err(signal(
                "wrong-type-argument",
                vec![Value::symbol("stringp"), other],
            ));
        }
        None => name.clone(),
    };
    let filename = super::load::expand_tilde(&filename);

    let load_path = super::load::get_load_path(obarray);
    match super::load::find_file_in_load_path(&filename, &load_path) {
        Some(path) => Ok(RequirePlan::Load { sym_id, name, path }),
        None => {
            if noerror.is_some_and(|value| value.is_truthy()) {
                return Ok(RequirePlan::Return(Value::NIL));
            }
            Err(signal(
                "file-missing",
                vec![Value::string(format!(
                    "Cannot open load file: no such file or directory, {}",
                    name
                ))],
            ))
        }
    }
}

pub(crate) fn finish_require_in_state(features: &[SymId], sym_id: SymId, name: &str) -> EvalResult {
    if features.contains(&sym_id) {
        Ok(Value::symbol(name))
    } else {
        Err(signal(
            "error",
            vec![Value::string(format!(
                "Required feature '{}' was not provided",
                name
            ))],
        ))
    }
}

pub(crate) fn parse_eval_lexical_arg(arg: Option<Value>) -> Result<(bool, Option<Value>), Flow> {
    // GNU eval.c Feval (src/eval.c:2527):
    //   specbind(Qinternal_interpreter_environment,
    //            CONSP(lexical) || NILP(lexical) ? lexical : list_of_t);
    //
    // GNU ALWAYS specbinds — no case leaves the environment untouched.
    // We must always return Some(...) so the caller saves/restores lexenv.
    let Some(arg) = arg else {
        // No LEXICAL arg: clear lexical env (dynamic mode).
        return Ok((false, Some(Value::NIL)));
    };
    if arg.is_nil() {
        // LEXICAL is nil: clear lexical env (dynamic mode).
        return Ok((false, Some(Value::NIL)));
    }

    // Non-nil atom (like t) => lexical mode, env = (t)  [the list!]
    if !arg.is_cons() {
        return Ok((true, Some(Value::list(vec![Value::T]))));
    };

    // Cons (alist) => lexical mode, env = the alist
    if list_to_vec(&arg).is_none() {
        return Err(signal(
            "wrong-type-argument",
            vec![Value::symbol("listp"), arg],
        ));
    }

    Ok((true, Some(arg)))
}

fn lexical_binding_in_obarray(obarray: &Obarray) -> bool {
    obarray
        .symbol_value_id(lexical_binding_symbol())
        .is_some_and(|v| v.is_truthy())
}

#[inline]
fn top_level_lexenv_sentinel() -> Value {
    Value::list(vec![Value::T])
}

#[inline]
fn lexenv_is_active(lexenv: Value) -> bool {
    !lexenv.is_nil()
}

#[inline]
fn is_top_level_lexenv_sentinel(lexenv: Value) -> bool {
    lexenv.is_cons() && lexenv.cons_car().is_t() && lexenv.cons_cdr().is_nil()
}

pub(crate) struct ActiveEvalLexicalArgState {
    specpdl_count: usize,
}

pub(crate) fn begin_eval_with_lexical_arg_in_state(
    _obarray: &mut Obarray,
    lexenv: &mut Value,
    specpdl: &mut Vec<SpecBinding>,
    lexical_arg: Option<Value>,
) -> Result<ActiveEvalLexicalArgState, Flow> {
    let (_use_lexical, lexenv_value) = parse_eval_lexical_arg(lexical_arg)?;
    // Mirrors GNU eval.c Feval:
    //   specbind(Qinternal_interpreter_environment, new_env);
    //   return unbind_to(count, eval_sub(form));
    //
    // We push a SpecBinding::LexicalEnv entry (saving the old lexenv)
    // and set lexenv to the new value. unbind_to restores it
    // automatically, providing unwind-safe cleanup on non-local exits.
    let specpdl_count = specpdl.len();
    if let Some(env) = lexenv_value {
        specpdl.push(SpecBinding::LexicalEnv {
            old_lexenv: *lexenv,
        });
        *lexenv = env;
    }
    Ok(ActiveEvalLexicalArgState { specpdl_count })
}

pub(crate) fn finish_eval_with_lexical_arg_in_state(
    _obarray: &mut Obarray,
    lexenv: &mut Value,
    specpdl: &mut Vec<SpecBinding>,
    state: ActiveEvalLexicalArgState,
) {
    // Mirrors GNU: unbind_to(count, result) which pops the
    // SpecBinding::LexicalEnv entry and restores self.lexenv.
    while specpdl.len() > state.specpdl_count {
        let binding = specpdl.pop().unwrap();
        match binding {
            SpecBinding::LexicalEnv { old_lexenv } => {
                *lexenv = old_lexenv;
            }
            other => {
                // Should not happen — begin only pushes LexicalEnv.
                // Put it back if it does.
                specpdl.push(other);
                break;
            }
        }
    }
}

pub(crate) struct ActiveLambdaCallState {
    specpdl_count: usize,
}

pub(crate) struct ActiveMacroExpansionScopeState {
    saved_specpdl_len: usize,
    old_lexical: bool,
    old_dynvars: Value,
}

#[derive(Clone, Copy, Debug)]
pub(crate) struct VmRootScopeState {
    pushed_vm_root_frame: bool,
    saved_vm_root_frame_len: Option<usize>,
}

#[derive(Clone, Copy, Debug)]
pub(crate) struct SpecpdlRootScopeState {
    saved_len: usize,
}

fn bind_lexical_value_rooted_in_specpdl(
    lexenv: &mut Value,
    specpdl: &mut Vec<SpecBinding>,
    sym: SymId,
    value: Value,
) {
    specpdl.push(SpecBinding::GcRoot { value });
    let binding = Value::make_cons(lexenv_binding_symbol_value(sym), value);
    match specpdl.last_mut() {
        Some(SpecBinding::GcRoot { value }) => *value = binding,
        other => panic!("expected temporary specpdl gc root entry, got {other:?}"),
    }
    *lexenv = Value::make_cons(binding, *lexenv);
    match specpdl.pop() {
        Some(SpecBinding::GcRoot { .. }) => {}
        other => panic!("expected temporary specpdl gc root entry, got {other:?}"),
    }
}

fn prepend_lexical_binding_in_specpdl_rooted_env(
    lexenv: &mut Value,
    specpdl: &mut Vec<SpecBinding>,
    env_root_index: usize,
    sym: SymId,
    value: Value,
) {
    specpdl.push(SpecBinding::GcRoot { value });
    let current_env = match specpdl.get(env_root_index) {
        Some(SpecBinding::GcRoot { value }) => *value,
        other => panic!("expected specpdl gc root entry for lexical env, got {other:?}"),
    };
    let binding = Value::make_cons(lexenv_binding_symbol_value(sym), value);
    match specpdl.last_mut() {
        Some(SpecBinding::GcRoot { value }) => *value = binding,
        other => panic!("expected temporary specpdl gc root entry, got {other:?}"),
    }
    let new_env = Value::make_cons(binding, current_env);
    match specpdl.get_mut(env_root_index) {
        Some(SpecBinding::GcRoot { value }) => *value = new_env,
        other => panic!("expected mutable specpdl gc root entry for lexical env, got {other:?}"),
    }
    *lexenv = new_env;
    match specpdl.pop() {
        Some(SpecBinding::GcRoot { .. }) => {}
        other => panic!("expected temporary specpdl gc root entry, got {other:?}"),
    }
}

/// Build a `(MIN . MAX)` cons cell representing the arity of a lambda/closure,
/// matching the format GNU Emacs uses in `wrong-number-of-arguments` errors.
/// `MAX` is the symbol `many` when the function accepts `&rest`.
fn lambda_arity_cons(params: &LambdaParams) -> Value {
    let min_val = Value::fixnum(params.min_arity() as i64);
    let max_val = match params.max_arity() {
        Some(n) => Value::fixnum(n as i64),
        None => Value::symbol("many"),
    };
    Value::cons(min_val, max_val)
}

fn begin_lambda_call_in_state(
    obarray: &mut Obarray,
    specpdl: &mut Vec<SpecBinding>,
    lexenv: &mut Value,
    params: &LambdaParams,
    env: Option<Value>,
    args: &[Value],
) -> Result<ActiveLambdaCallState, Flow> {
    if args.len() < params.min_arity() {
        let arity_val = lambda_arity_cons(params);
        return Err(signal(
            "wrong-number-of-arguments",
            vec![arity_val, Value::fixnum(args.len() as i64)],
        ));
    }
    if let Some(max) = params.max_arity()
        && args.len() > max
    {
        let arity_val = lambda_arity_cons(params);
        return Err(signal(
            "wrong-number-of-arguments",
            vec![arity_val, Value::fixnum(args.len() as i64)],
        ));
    }

    let specpdl_count = specpdl.len();

    if let Some(env) = env {
        // Debug: detect malformed env (bare t instead of list (t))
        if env.is_t() {
            tracing::error!(
                "Lambda called with env=t (should be (t))! params={:?}",
                params
            );
        }
        let old = std::mem::replace(lexenv, env);
        // Mirrors GNU funcall_lambda:
        //   specbind(Qinternal_interpreter_environment, lexenv);
        specpdl.push(SpecBinding::LexicalEnv { old_lexenv: old });

        let env_root_index = specpdl.len();
        specpdl.push(SpecBinding::GcRoot { value: env });

        let mut arg_idx = 0;
        for param in &params.required {
            prepend_lexical_binding_in_specpdl_rooted_env(
                lexenv,
                specpdl,
                env_root_index,
                *param,
                args[arg_idx],
            );
            arg_idx += 1;
        }
        for param in &params.optional {
            if arg_idx < args.len() {
                prepend_lexical_binding_in_specpdl_rooted_env(
                    lexenv,
                    specpdl,
                    env_root_index,
                    *param,
                    args[arg_idx],
                );
                arg_idx += 1;
            } else {
                prepend_lexical_binding_in_specpdl_rooted_env(
                    lexenv,
                    specpdl,
                    env_root_index,
                    *param,
                    Value::NIL,
                );
            }
        }
        if let Some(rest_name) = params.rest {
            let rest_value = Value::list_from_slice(&args[arg_idx..]);
            prepend_lexical_binding_in_specpdl_rooted_env(
                lexenv,
                specpdl,
                env_root_index,
                rest_name,
                rest_value,
            );
        }
    } else {
        // Dynamic binding: use specbind to write directly to obarray.
        let mut arg_idx = 0;
        for param in &params.required {
            specbind_in_state(obarray, specpdl, *param, args[arg_idx]);
            arg_idx += 1;
        }
        for param in &params.optional {
            if arg_idx < args.len() {
                specbind_in_state(obarray, specpdl, *param, args[arg_idx]);
                arg_idx += 1;
            } else {
                specbind_in_state(obarray, specpdl, *param, Value::NIL);
            }
        }
        if let Some(rest_name) = params.rest {
            let rest_value = Value::list_from_slice(&args[arg_idx..]);
            specbind_in_state(obarray, specpdl, rest_name, rest_value);
        }
    }

    // GNU never writes `lexical-binding` during lambda/closure calls.
    // The closure's captured env is installed in self.lexenv (above),
    // which is the single source of truth for "is lexical mode active?"
    // via lexical_binding() -> !self.lexenv.is_nil().

    Ok(ActiveLambdaCallState { specpdl_count })
}

fn finish_lambda_call_in_state(
    obarray: &mut Obarray,
    specpdl: &mut Vec<SpecBinding>,
    lexenv: &mut Value,
    state: ActiveLambdaCallState,
) {
    // Unwind all specpdl entries back to the count saved at begin.
    // For lexical closures, this pops the SpecBinding::LexicalEnv
    // entry (restoring self.lexenv) plus any dynamic bindings.
    // For dynamic lambdas, this pops the specbind entries.
    // Mirrors GNU: unbind_to(count, val) in funcall_lambda.
    while specpdl.len() > state.specpdl_count {
        let binding = specpdl.pop().unwrap();
        match binding {
            SpecBinding::LexicalEnv { old_lexenv } => {
                *lexenv = old_lexenv;
            }
            SpecBinding::Let { sym_id, old_value } => match old_value {
                Some(val) => obarray.set_symbol_value_id(sym_id, val),
                None => obarray.makunbound_id(sym_id),
            },
            SpecBinding::GcRoot { .. } => {}
            SpecBinding::Backtrace { .. } => {}
            other => {
                // LetLocal/LetDefault shouldn't appear here in the
                // standalone path, but handle gracefully.
                specpdl.push(other);
                break;
            }
        }
    }
}

fn begin_macro_expansion_scope_in_state(
    obarray: &mut Obarray,
    specpdl: &mut Vec<SpecBinding>,
    buffers: &mut BufferManager,
    custom: &CustomManager,
    lexenv: Value,
) -> ActiveMacroExpansionScopeState {
    let saved_specpdl_len = specpdl.len();
    let old_lexical = obarray
        .symbol_value_id(lexical_binding_symbol())
        .is_some_and(|value| value.is_truthy());
    let old_dynvars = obarray
        .symbol_value_id(macroexp_dynvars_symbol())
        .cloned()
        .unwrap_or(Value::NIL);

    let dynvars_root_index = specpdl.len();
    specpdl.push(SpecBinding::GcRoot { value: old_dynvars });
    let mut dynvars = old_dynvars;
    // GNU eval.c walks Vinternal_interpreter_environment directly and only
    // extends `macroexp--dynvars` for bare symbols. Dynamic specpdl bindings
    // are not part of this macro-expansion state.
    let mut cursor = lexenv;
    while cursor.is_cons() {
        let entry = cursor.cons_car();
        if let Some(sym) = entry.as_symbol_id() {
            dynvars = Value::cons(Value::from_sym_id(sym), dynvars);
            match specpdl.get_mut(dynvars_root_index) {
                Some(SpecBinding::GcRoot { value }) => *value = dynvars,
                other => panic!("expected macro-expansion dynvars gc root, got {other:?}"),
            }
        }
        cursor = cursor.cons_cdr();
    }
    obarray.set_symbol_value_id(lexical_binding_symbol(), Value::bool_val(!lexenv.is_nil()));
    set_runtime_binding(
        obarray,
        buffers,
        custom,
        specpdl,
        macroexp_dynvars_symbol(),
        dynvars,
    );

    ActiveMacroExpansionScopeState {
        saved_specpdl_len,
        old_lexical,
        old_dynvars,
    }
}

fn finish_macro_expansion_scope_in_state(
    obarray: &mut Obarray,
    specpdl: &mut Vec<SpecBinding>,
    buffers: &mut BufferManager,
    custom: &CustomManager,
    state: ActiveMacroExpansionScopeState,
) {
    set_runtime_binding(
        obarray,
        buffers,
        custom,
        specpdl,
        macroexp_dynvars_symbol(),
        state.old_dynvars,
    );
    obarray.set_symbol_value_id(lexical_binding_symbol(), Value::bool_val(state.old_lexical));
    specpdl.truncate(state.saved_specpdl_len);
}

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

impl Context {
    #[inline]
    pub(crate) fn subr_dispatch_kind(&self, sym_id: SymId) -> Option<SubrDispatchKind> {
        lookup_global_subr_entry(sym_id).map(|e| e.dispatch_kind)
    }

    #[inline]
    pub(crate) fn subr_dispatch_kind_or_compat(&self, sym_id: SymId) -> SubrDispatchKind {
        self.subr_dispatch_kind(sym_id)
            .unwrap_or_else(|| super::subr_info::compat_subr_dispatch_kind(resolve_sym(sym_id)))
    }

    #[inline]
    fn subr_is_special_form_id(&self, sym_id: SymId) -> bool {
        self.subr_dispatch_kind_or_compat(sym_id) == SubrDispatchKind::SpecialForm
    }

    #[inline]
    fn subr_is_context_callable_id(&self, sym_id: SymId) -> bool {
        self.subr_dispatch_kind_or_compat(sym_id) == SubrDispatchKind::ContextCallable
    }

    #[inline]
    fn has_registered_subr(&self, sym_id: SymId) -> bool {
        lookup_global_subr_entry(sym_id).is_some_and(|e| e.function.is_some())
    }

    pub fn new() -> Self {
        let mut ctx = Self::new_inner(true);
        ctx.initialize_gc_stack_bottom();
        // Register builtins AFTER new_inner returns — the function is too
        // large (1500+ lines) for reliable codegen in debug mode when
        // combined with init_builtins (1162 defsubr calls in the same frame).
        builtins::init_builtins(&mut ctx);
        ctx
    }

    #[cfg(test)]
    pub(crate) fn new_vm_runtime_harness() -> Self {
        // GNU bytecode executes inside the same callable runtime surface as the
        // ordinary evaluator. Keep the default VM harness on that full surface.
        Self::new()
    }

    #[cfg(test)]
    pub(crate) fn new_minimal_vm_harness() -> Self {
        // Keep this reduced constructor only for low-level VM/opcode tests
        // that intentionally do not depend on the full builtin surface.
        let mut ev = Self::new_inner(true);
        ev.obarray = Obarray::new();
        super::errors::init_standard_errors(&mut ev.obarray);
        ev.obarray
            .set_symbol_value("most-positive-fixnum", Value::fixnum(i64::MAX >> 2));
        ev.obarray
            .set_symbol_value("most-negative-fixnum", Value::fixnum(-(i64::MAX >> 2) - 1));
        ev.specpdl.clear();
        ev.lexenv = Value::NIL;
        ev.features.clear();
        ev.require_stack.clear();
        ev.loads_in_progress.clear();
        ev.buffers = BufferManager::new();
        ev.match_data = None;
        ev.processes = ProcessManager::new();
        ev.timers = TimerManager::new();
        ev.watchers = VariableWatcherList::new();
        ev.current_local_map = Value::NIL;
        ev.registers = RegisterManager::new();
        ev.bookmarks = BookmarkManager::new();
        ev.abbrevs = AbbrevManager::new();
        ev.autoloads = AutoloadManager::new();
        ev.custom = CustomManager::new();
        ev.rectangle = RectangleState::new();
        ev.interactive = InteractiveRegistry::new();
        ev.input_mode_interrupt = false;
        ev.frames = FrameManager::new();
        ev.modes = ModeRegistry::new();
        ev.threads = ThreadManager::new();
        ev.kmacro = KmacroManager::new();
        ev.command_loop = crate::keyboard::CommandLoop::default();
        ev.input_rx = None;
        #[cfg(unix)]
        {
            ev.wakeup_fd = None;
        }
        ev.redisplay_fn = None;
        ev.display_host = None;
        ev.coding_systems = CodingSystemManager::new();
        ev.face_table = FaceTable::new();
        ev.face_change_count = 0;
        ev.redisplay_generation = 0;
        ev.last_redisplay_signature = None;
        ev.depth = 0;
        ev.max_depth = 1600;
        ev.gc_pending = false;
        ev.gc_count = 0;
        ev.gc_stress = false;
        ev.condition_stack.clear();
        ev.next_resume_id = 1;
        ev.named_call_cache.clear();

        ev.runtime_macro_expansion_cache.clear();
        ev.macro_cache_hits = 0;
        ev.macro_cache_misses = 0;
        ev.macro_expand_total_us = 0;
        ev.macro_cache_disabled = false;
        ev.macro_perf_enabled = std::env::var_os("NEOVM_TRACE_MACRO_PERF").is_some();
        ev.macro_perf_stats = MacroPerfStats::default();
        ev.interpreted_closure_filter_fn = None;
        ev.interpreted_closure_trim_cache.clear();
        ev.materialize_public_evaluator_function_cells();
        ev.finish_runtime_activation(false);
        ev
    }

    pub(crate) fn push_condition_frame(&mut self, frame: ConditionFrame) {
        self.condition_stack.push(frame);
    }

    pub(crate) fn pop_condition_frame(&mut self) -> Option<ConditionFrame> {
        self.condition_stack.pop()
    }

    pub(crate) fn truncate_condition_stack(&mut self, len: usize) {
        self.condition_stack.truncate(len);
    }

    pub(crate) fn condition_stack_len(&self) -> usize {
        self.condition_stack.len()
    }

    pub(crate) fn allocate_resume_id(&mut self) -> u64 {
        let resume_id = self.next_resume_id;
        self.next_resume_id += 1;
        resume_id
    }

    pub(crate) fn matching_catch_resume(&self, tag: &Value) -> Option<ResumeTarget> {
        if tag.is_nil() {
            return None;
        }

        self.condition_stack
            .iter()
            .rev()
            .find_map(|frame| match frame {
                ConditionFrame::Catch {
                    tag: catch_tag,
                    resume,
                } if eq_value(catch_tag, tag) => Some(resume.clone()),
                _ => None,
            })
    }

    pub(crate) fn has_active_catch(&self, tag: &Value) -> bool {
        self.matching_catch_resume(tag).is_some()
    }

    pub(crate) fn dispatch_signal_if_needed(
        &mut self,
        sig: Box<SignalData>,
    ) -> Result<Box<SignalData>, Flow> {
        if sig.search_complete {
            return Ok(sig);
        }
        self.dispatch_signal(*sig).map(Box::new)
    }

    pub(crate) fn dispatch_signal_result_if_needed(&mut self, result: EvalResult) -> EvalResult {
        match result {
            Err(Flow::Signal(sig)) => match self.dispatch_signal_if_needed(sig) {
                Ok(dispatched) => Err(Flow::Signal(dispatched)),
                Err(flow) => Err(flow),
            },
            other => other,
        }
    }

    fn dispatch_signal(&mut self, mut sig: SignalData) -> Result<SignalData, Flow> {
        if sig.symbol == self.kill_emacs_symbol {
            return Err(Flow::Signal(Box::new(sig)));
        }
        self.run_signal_hook(&sig)?;
        sig = self.canonicalize_signal_symbol(sig);

        let mut idx = self.condition_stack.len();
        let mut seen_condition_entries = 0usize;

        while let Some(next_idx) = idx.checked_sub(1) {
            idx = next_idx;
            match self.condition_stack[idx].clone() {
                ConditionFrame::Catch { .. } => {}
                ConditionFrame::SkipConditions { remaining } => {
                    let mut to_skip = remaining;
                    while idx > 0 && to_skip > 0 {
                        idx -= 1;
                        if matches!(
                            self.condition_stack[idx],
                            ConditionFrame::ConditionCase { .. }
                                | ConditionFrame::HandlerBind { .. }
                        ) {
                            to_skip -= 1;
                        }
                    }
                }
                ConditionFrame::ConditionCase { conditions, resume } => {
                    seen_condition_entries += 1;
                    if crate::emacs_core::errors::signal_matches_condition_value(
                        &self.obarray,
                        sig.symbol_name(),
                        &conditions,
                    ) {
                        self.maybe_call_debugger_for_signal(&sig, Some(&conditions))?;
                        sig.selected_resume = Some(resume);
                        sig.search_complete = true;
                        return Ok(sig);
                    }
                }
                ConditionFrame::HandlerBind {
                    conditions,
                    handler,
                    mute_span,
                } => {
                    seen_condition_entries += 1;
                    if !crate::emacs_core::errors::signal_matches_condition_value(
                        &self.obarray,
                        sig.symbol_name(),
                        &conditions,
                    ) {
                        continue;
                    }

                    let specpdl_root_scope = self.save_specpdl_roots();
                    for value in &sig.data {
                        self.push_specpdl_root(*value);
                    }
                    if let Some(raw) = &sig.raw_data {
                        self.push_specpdl_root(*raw);
                    }

                    self.push_condition_frame(ConditionFrame::SkipConditions {
                        remaining: seen_condition_entries + mute_span,
                    });

                    let handler_result = self.apply(handler, vec![make_signal_binding_value(&sig)]);

                    match handler_result {
                        Ok(_) => {
                            self.pop_condition_frame();
                            self.restore_specpdl_roots(specpdl_root_scope);
                            continue;
                        }
                        Err(Flow::Signal(next_sig)) => {
                            let dispatched =
                                self.dispatch_signal_if_needed(next_sig).map(|sig| *sig);
                            self.pop_condition_frame();
                            self.restore_specpdl_roots(specpdl_root_scope);
                            return dispatched;
                        }
                        Err(flow @ Flow::Throw { .. }) => {
                            self.pop_condition_frame();
                            self.restore_specpdl_roots(specpdl_root_scope);
                            return Err(flow);
                        }
                    }
                }
            }
        }

        self.maybe_call_debugger_for_signal(&sig, None)?;
        sig.search_complete = true;
        sig.selected_resume = None;
        Ok(sig)
    }

    fn run_signal_hook(&mut self, sig: &SignalData) -> Result<(), Flow> {
        if sig.suppress_signal_hook {
            return Ok(());
        }

        let hook = self
            .obarray
            .symbol_value("signal-hook-function")
            .copied()
            .unwrap_or(Value::NIL);
        if hook.is_nil() {
            return Ok(());
        }

        self.apply(
            hook,
            vec![
                Value::from_sym_id(sig.symbol),
                signal_hook_payload_value(sig),
            ],
        )
        .map(|_| ())
    }

    fn canonicalize_signal_symbol(&self, sig: SignalData) -> SignalData {
        let sym_name = sig.symbol_name();
        if sym_name == "error" || sym_name == "quit" {
            return sig;
        }
        if self
            .obarray
            .get_property(sym_name, "error-conditions")
            .is_some()
        {
            return sig;
        }

        SignalData {
            symbol: intern("error"),
            data: vec![
                Value::string("Invalid error symbol"),
                Value::from_sym_id(sig.symbol),
            ],
            raw_data: None,
            suppress_signal_hook: sig.suppress_signal_hook,
            selected_resume: None,
            search_complete: false,
        }
    }

    fn maybe_call_debugger_for_signal(
        &mut self,
        sig: &SignalData,
        matched_clause: Option<&Value>,
    ) -> Result<(), Flow> {
        if self
            .obarray
            .symbol_value("inhibit-debugger")
            .is_some_and(|value| !value.is_nil())
        {
            return Ok(());
        }

        let debug_on_signal = self
            .obarray
            .symbol_value("debug-on-signal")
            .is_some_and(|value| !value.is_nil());
        let should_consider_debugger = debug_on_signal
            || matched_clause.is_none()
            || matched_clause.is_some_and(condition_value_contains_debug);
        if !should_consider_debugger {
            return Ok(());
        }

        let conditions = self.signal_conditions_value(sig);
        let debug_setting = if crate::emacs_core::errors::signal_matches_hierarchical(
            &self.obarray,
            sig.symbol_name(),
            "quit",
        ) {
            self.obarray
                .symbol_value("debug-on-quit")
                .copied()
                .unwrap_or(Value::NIL)
        } else {
            self.obarray
                .symbol_value("debug-on-error")
                .copied()
                .unwrap_or(Value::NIL)
        };
        if !wants_debugger(&debug_setting, &conditions) {
            return Ok(());
        }
        if self.skip_debugger(sig, &conditions)? {
            return Ok(());
        }

        self.call_debugger_for_signal(sig)
    }

    fn signal_conditions_value(&self, sig: &SignalData) -> Value {
        self.obarray
            .get_property(sig.symbol_name(), "error-conditions")
            .unwrap_or_else(|| Value::list(vec![Value::from_sym_id(sig.symbol)]))
    }

    fn skip_debugger(&mut self, sig: &SignalData, conditions: &Value) -> Result<bool, Flow> {
        let ignored = self
            .obarray
            .symbol_value("debug-ignored-errors")
            .copied()
            .unwrap_or(Value::NIL);
        let Some(entries) = list_to_vec(&ignored) else {
            return Ok(false);
        };
        if entries.is_empty() {
            return Ok(false);
        }

        let mut error_message = None;
        let error_data = make_signal_binding_value(sig);
        let signal_conditions = list_to_vec(conditions).unwrap_or_else(|| vec![*conditions]);

        for entry in entries {
            if entry.is_string() {
                let message = if let Some(message) = error_message {
                    message
                } else {
                    let rendered = crate::emacs_core::errors::builtin_error_message_string(
                        self,
                        vec![error_data],
                    )?;
                    error_message = Some(rendered);
                    rendered
                };

                if builtins::search::builtin_string_match_p_with_case_fold(
                    false,
                    &[entry, message],
                )?
                .as_fixnum()
                .is_some()
                {
                    return Ok(true);
                }
                continue;
            }

            if signal_conditions.iter().any(|item| *item == entry) {
                return Ok(true);
            }
        }

        Ok(false)
    }

    fn call_debugger_for_signal(&mut self, sig: &SignalData) -> Result<(), Flow> {
        let debugger = self
            .obarray
            .symbol_value("debugger")
            .copied()
            .unwrap_or(Value::NIL);
        let specpdl_count = self.specpdl.len();
        self.specbind(intern("debugger-may-continue"), Value::T);
        self.specbind(intern("inhibit-debugger"), Value::T);
        let result = self.apply(
            debugger,
            vec![Value::symbol("error"), make_signal_binding_value(sig)],
        );
        self.unbind_to(specpdl_count);
        result.map(|_| ())
    }

    fn new_inner(reset_thread_locals: bool) -> Self {
        // Create the heap and set thread-locals so tagged constructors work
        // during evaluator initialization.
        let mut tagged_heap = Box::new(crate::tagged::gc::TaggedHeap::new());
        crate::tagged::gc::set_tagged_heap(&mut tagged_heap);

        // Clear any caches that hold heap-allocated Values (tagged pointers) from a
        // previous heap. Critical for test isolation when multiple Contexts
        // are created sequentially on the same thread.
        if reset_thread_locals {
            super::pdump::runtime::reset_runtime_for_new_heap(
                super::pdump::runtime::HeapResetMode::FreshContext,
            );
        }

        let mut obarray = Obarray::new();
        // Builtin names are interned by defsubr() during init_builtins(),
        // which runs after Context construction.
        let default_directory = std::env::current_dir()
            .ok()
            .and_then(|p| p.to_str().map(|s| s.to_string()))
            .map(|mut s| {
                if !s.ends_with('/') {
                    s.push('/');
                }
                s
            })
            .unwrap_or_else(|| "./".to_string());
        // Create all keymaps as Emacs-compatible cons-list values
        let completion_in_region_mode_map = make_sparse_list_keymap();
        let completion_list_mode_map = make_sparse_list_keymap();
        let minibuffer_local_map = make_sparse_list_keymap();
        // Keep only the base minibuffer map here. GNU Lisp defines
        // `read-expression-map` / `read--expression-map` itself in simple.el via
        // `defvar-keymap`; prebinding them here causes those definitions to be
        // skipped, which leaves RET/C-j handling diverged from GNU Emacs.
        // Standard keymaps required by loadup.el files (normally created by C code)
        // `global-map`, `esc-map`, `ctl-x-map`, and `help-map` are defined in GNU Lisp,
        // so keep them unbound here and let the Lisp `defvar` / `defvar-keymap`
        // initializers run.  Prebinding them here causes GNU definitions like
        // help.el's `defvar-keymap help-map ...` to skip installing their real
        // bindings.
        let special_event_map = make_sparse_list_keymap();
        let mode_line_window_dedicated_keymap = make_sparse_list_keymap();
        let indent_rigidly_map = make_sparse_list_keymap();
        let text_mode_map = make_sparse_list_keymap();
        let image_slice_map = make_sparse_list_keymap();
        let tool_bar_map = make_sparse_list_keymap();
        let key_translation_map = make_sparse_list_keymap();
        let function_key_map = make_sparse_list_keymap();
        let input_decode_map = make_sparse_list_keymap();
        let local_function_key_map = make_sparse_list_keymap();
        // GNU Emacs: local-function-key-map inherits from function-key-map
        // (keyboard.c:13097). Without this, bindings in function-key-map
        // (like [backspace] → [?\C-?]) are not found during key translation.
        list_keymap_set_parent(local_function_key_map, function_key_map);
        // GNU keyboard.c seeds special-event-map with delete-frame and focus
        // handlers at C bootstrap time and leaves hook semantics to frame.el.
        list_keymap_define(
            special_event_map,
            Value::symbol("delete-frame"),
            Value::symbol("handle-delete-frame"),
        );
        list_keymap_define(
            special_event_map,
            Value::symbol("focus-in"),
            Value::symbol("handle-focus-in"),
        );
        list_keymap_define(
            special_event_map,
            Value::symbol("focus-out"),
            Value::symbol("handle-focus-out"),
        );

        let standard_syntax_table = super::syntax::builtin_standard_syntax_table(Vec::new())
            .expect("startup seeding requires standard syntax table");
        let standard_category_table = super::category::ensure_standard_category_table_object()
            .expect("startup seeding requires standard category table");

        // Set up standard global variables
        // Match GNU Emacs: MOST_POSITIVE_FIXNUM = EMACS_INT_MAX >> INTTYPEBITS (>> 2)
        // These are SYMBOL_NOWRITE constants in GNU Emacs (cannot be setq'd).
        obarray.set_symbol_value("most-positive-fixnum", Value::fixnum(i64::MAX >> 2));
        obarray.set_constant("most-positive-fixnum");
        obarray.set_symbol_value("most-negative-fixnum", Value::fixnum(-(i64::MAX >> 2) - 1));
        obarray.set_constant("most-negative-fixnum");
        // Mathematical constants (defconst in float-sup.el)
        obarray.set_symbol_value("float-e", Value::make_float(std::f64::consts::E));
        obarray.set_symbol_value("float-pi", Value::make_float(std::f64::consts::PI));
        obarray.set_symbol_value("pi", Value::make_float(std::f64::consts::PI));
        obarray.set_symbol_value("emacs-version", Value::string("31.0.50"));
        obarray.set_symbol_value(
            "emacs-copyright",
            Value::string("Copyright (C) 2026 Free Software Foundation, Inc."),
        );
        obarray.set_symbol_value("emacs-major-version", Value::fixnum(31));
        obarray.set_symbol_value("emacs-minor-version", Value::fixnum(0));
        obarray.set_symbol_value("emacs-build-number", Value::fixnum(1));
        obarray.set_symbol_value("system-type", Value::symbol("gnu/linux"));
        obarray.set_symbol_value("system-uses-terminfo", Value::T);
        // GNU Emacs uses unibyte for default-directory during dump because
        // the locale isn't set up yet (see init_buffer in buffer.c).
        obarray.set_symbol_value(
            "default-directory",
            Value::unibyte_string(default_directory.clone()),
        );
        obarray.set_symbol_value(
            "command-line-default-directory",
            Value::unibyte_string(default_directory),
        );
        let obarray_object = Value::vector(vec![Value::NIL]);
        obarray.set_symbol_value("obarray", obarray_object);
        obarray.set_symbol_value("neovm--obarray-object", obarray_object);
        obarray.make_special("obarray");
        obarray.set_symbol_value("standard-input", Value::T);
        obarray.make_special("standard-input");
        obarray.set_symbol_value(
            "command-line-args",
            Value::list(vec![
                Value::string("neovm-worker"),
                Value::string("--batch"),
            ]),
        );
        obarray.set_symbol_value("command-line-args-left", Value::NIL);
        obarray.set_symbol_value("command-line-functions", Value::NIL);
        obarray.set_symbol_value("command-line-processed", Value::T);
        obarray.set_symbol_value("command-switch-alist", Value::NIL);
        obarray.set_symbol_value(
            "pdumper-fingerprint",
            Value::string(crate::emacs_core::pdump::fingerprint_hex()),
        );
        obarray.make_special("pdumper-fingerprint");
        // GNU emacs.c: set from argv[0]. NeoVM uses current exe path.
        let exe_path = std::env::current_exe()
            .ok()
            .and_then(|p| p.canonicalize().ok());
        let invocation_name = exe_path
            .as_ref()
            .and_then(|p| p.file_name())
            .map(|n| n.to_string_lossy().to_string())
            .unwrap_or_else(|| "neomacs".to_string());
        let invocation_directory = exe_path
            .as_ref()
            .and_then(|p| p.parent())
            .map(|d| format!("{}/", d.to_string_lossy()))
            .unwrap_or_else(|| "./".to_string());
        obarray.set_symbol_value("invocation-name", Value::string(invocation_name));
        obarray.set_symbol_value("invocation-directory", Value::string(invocation_directory));
        obarray.set_symbol_value("installation-directory", Value::NIL);
        obarray.set_symbol_value("configure-info-directory", Value::NIL);
        // GNU keyboard.c: internal--top-level-message for command loop entry
        obarray.set_symbol_value(
            "internal--top-level-message",
            Value::string("Back to top level"),
        );
        obarray.set_symbol_value("charset-map-path", Value::NIL);
        obarray.set_symbol_value("doc-directory", Value::NIL);
        // warnings.el defcustom — needed before warnings.el loads
        obarray.set_symbol_value("warning-minimum-log-level", Value::keyword(":warning"));
        obarray.set_symbol_value("warning-minimum-level", Value::keyword(":warning"));
        // GNU callproc.c defines these with DEFVAR_LISP, so lexical-binding
        // Lisp must treat them as dynamically scoped special variables.
        obarray.set_symbol_value("process-environment", Value::NIL);
        obarray.make_special("process-environment");
        obarray.set_symbol_value("initial-environment", Value::NIL);
        obarray.make_special("initial-environment");
        for (name, program) in [
            ("ctags-program-name", "ctags"),
            ("etags-program-name", "etags"),
            ("hexl-program-name", "hexl"),
            ("emacsclient-program-name", "emacsclient"),
            ("movemail-program-name", "movemail"),
            ("ebrowse-program-name", "ebrowse"),
            ("rcs2log-program-name", "rcs2log"),
        ] {
            obarray.set_symbol_value(name, Value::unibyte_string(program));
            obarray.make_special(name);
        }
        obarray.set_symbol_value("path-separator", Value::string(":"));
        obarray.set_symbol_value("shared-game-score-directory", Value::NIL);
        obarray.set_symbol_value("system-messages-locale", Value::NIL);
        obarray.set_symbol_value("system-time-locale", Value::NIL);
        obarray.set_symbol_value("before-init-time", Value::NIL);
        obarray.set_symbol_value("after-init-time", Value::NIL);
        obarray.set_symbol_value(
            "system-configuration",
            super::builtins_extra::system_configuration_value(),
        );
        obarray.set_symbol_value(
            "system-configuration-options",
            super::builtins_extra::system_configuration_options_value(),
        );
        obarray.set_symbol_value(
            "system-configuration-features",
            super::builtins_extra::system_configuration_features_value(),
        );
        obarray.set_symbol_value("system-name", Value::string("localhost"));
        obarray.set_symbol_value("user-full-name", Value::string("unknown"));
        obarray.set_symbol_value("user-login-name", Value::string("unknown"));
        obarray.set_symbol_value("user-real-login-name", Value::string("unknown"));
        obarray.set_symbol_value(
            "operating-system-release",
            super::builtins_extra::operating_system_release_value(),
        );
        obarray.set_symbol_value("delayed-warnings-list", Value::NIL);
        // GNU `keyboard.c:14070` (`DEFVAR_LISP ("delayed-warnings-hook", ...)`)
        // — Lisp callers `display-warning` etc. expect this symbol
        // to exist as a hook list. Keyboard audit Finding 17 in
        // `drafts/keyboard-command-loop-audit.md`.
        obarray.set_symbol_value("delayed-warnings-hook", Value::NIL);
        obarray.set_symbol_value(
            "command-line-ns-option-alist",
            Value::list(vec![Value::list(vec![
                Value::string("-NSOpen"),
                Value::fixnum(1),
                Value::symbol("ns-handle-nxopen"),
            ])]),
        );
        obarray.set_symbol_value(
            "command-line-x-option-alist",
            Value::list(vec![Value::list(vec![
                Value::string("-display"),
                Value::fixnum(1),
                Value::symbol("x-handle-display"),
            ])]),
        );
        obarray.set_symbol_value("load-path", Value::NIL);
        obarray.make_special("load-path");
        obarray.set_symbol_value("load-history", Value::NIL);
        obarray.set_symbol_value(
            "fontset-alias-alist",
            super::builtins::symbols::fontset_alias_alist_startup_value(),
        );
        // GNU Emacs: load-suffixes defaults to (".elc" ".el").
        // NeoVM matches this — prefer compiled bytecode, fall back to source.
        obarray.set_symbol_value(
            "load-suffixes",
            Value::list(vec![Value::string(".elc"), Value::string(".el")]),
        );
        obarray.make_special("load-suffixes");
        obarray.set_symbol_value("module-file-suffix", Value::NIL);
        obarray.make_special("module-file-suffix");
        obarray.set_symbol_value(
            "dynamic-library-suffixes",
            Value::list(vec![Value::string(std::env::consts::DLL_SUFFIX)]),
        );
        obarray.make_special("dynamic-library-suffixes");
        // load-file-rep-suffixes: suffixes for alternate representations of
        // the same file (e.g., compressed ".gz").  Default is just ("").
        obarray.set_symbol_value(
            "load-file-rep-suffixes",
            Value::list(vec![Value::string("")]),
        );
        obarray.make_special("load-file-rep-suffixes");
        // file-coding-system-alist: needed by jka-cmpr-hook.el and others.
        obarray.set_symbol_value("file-coding-system-alist", Value::NIL);
        obarray.set_symbol_value("features", Value::NIL);
        obarray.set_symbol_value_id(lexical_binding_symbol(), Value::NIL);
        obarray.set_symbol_value("load-prefer-newer", Value::NIL);
        obarray.set_symbol_value("load-file-name", Value::NIL);
        obarray.make_special("load-file-name");
        obarray.set_symbol_value("noninteractive", Value::T);
        obarray.set_symbol_value("inhibit-quit", Value::NIL);
        obarray.set_symbol_value("symbols-with-pos-enabled", Value::NIL);
        obarray.make_special("symbols-with-pos-enabled");
        obarray.set_symbol_value("print-symbols-bare", Value::NIL);
        obarray.make_special("print-symbols-bare");
        // GNU Emacs print.c: all print-* variables are DEFVAR_BOOL or
        // DEFVAR_LISP, making them dynamically scoped (special).
        // This is essential so `(let ((print-escape-newlines t)) ...)`
        // affects the C print code via dynamic binding.
        for name in [
            "print-length",
            "print-level",
            "print-circle",
            "print-quoted",
            "print-escape-newlines",
            "print-escape-control-characters",
            "print-escape-nonascii",
            "print-escape-multibyte",
            "print-gensym",
            "print-continuous-numbering",
            "print-number-table",
            "print-charset-text-property",
            "print-integers-as-characters",
            "print-unreadable-function",
        ] {
            obarray.set_symbol_value(name, Value::NIL);
            obarray.make_special(name);
        }
        obarray.set_symbol_value("print-quoted", Value::T);
        obarray.set_symbol_value("text-quoting-style", Value::NIL);
        // GNU DEFVAR_LISP variables needed by loadup.el and early .el files.
        obarray.set_symbol_value("char-code-property-alist", Value::NIL);
        obarray.set_symbol_value("redisplay--inhibit-bidi", Value::NIL);
        obarray.set_symbol_value("resize-mini-windows", Value::NIL);

        // GNU C variables checked by cus-start.el during bootstrap.
        // 178 DEFVAR_LISP/DEFVAR_INT/DEFVAR_BOOL variables extracted from
        // GNU Emacs -Q. Default values match GNU's init_*() functions.
        for name in [
            "alter-fullscreen-frames",
            "auto-save-no-message",
            "auto-save-visited-file-name",
            "blink-cursor-alist",
            "composition-break-at-point",
            "debug-on-quit",
            "debugger-stack-frame-as-list",
            "default-frame-alist",
            "delete-by-moving-to-trash",
            "display-fill-column-indicator",
            "display-fill-column-indicator-character",
            "display-line-numbers",
            "display-line-numbers-widen",
            "display-line-numbers-width",
            "display-raw-bytes-as-hex",
            "echo-keystrokes-help",
            "enable-character-translation",
            "enable-recursive-minibuffers",
            "fast-but-imprecise-scrolling",
            "focus-follows-mouse",
            "font-use-system-font",
            "frame-resize-pixelwise",
            "garbage-collection-messages",
            "highlight-nonselected-windows",
            "history-delete-duplicates",
            "inhibit-eol-conversion",
            "inverse-video",
            "kill-buffer-delete-auto-save-files",
            "line-number-display-limit",
            "make-pointer-invisible",
            "menu-bar-mode",
            "minibuffer-auto-raise",
            "mode-line-compact",
            "mouse-autoselect-window",
            "mouse-prefer-closest-glyph",
            "no-redraw-on-reenter",
            "parse-sexp-ignore-comments",
            "read-buffer-completion-ignore-case",
            "record-all-keys",
            "resize-mini-frames",
            "ring-bell-function",
            "scalable-fonts-allowed",
            "scroll-preserve-screen-position",
            "show-trailing-whitespace",
            "tab-bar-mode",
            "tab-bar-position",
            "temp-buffer-show-function",
            "tool-bar-mode",
            "tool-bar-style",
            "tooltip-reuse-hidden-frame",
            "treesit-extra-load-path",
            "treesit-auto-install-grammar",
            "treesit-enabled-modes",
            "treesit-language-remap-alist",
            "treesit-language-source-alist",
            "treesit-load-name-override-list",
            "treesit-languages-require-line-column-tracking",
            "treesit-major-mode-remap-alist",
            "treesit-thing-settings",
            "undo-outer-limit",
            "unibyte-display-via-language-environment",
            "use-short-answers",
            "visible-bell",
            "window-combination-resize",
            "window-resize-pixelwise",
            "word-wrap-by-category",
            "words-include-escapes",
            "x-dnd-disable-motif-drag",
            "x-gtk-show-hidden-files",
            "x-gtk-use-native-input",
            "x-gtk-use-old-file-dialog",
            "x-stretch-cursor",
            "x-underline-at-descent-line",
            "x-use-underline-position-properties",
            // Mouse pointer shapes — GNU defines these in
            // src/xfns.c (and parallel files w32fns.c, pgtkfns.c,
            // haikufns.c, androidfns.c) as integer Lisp_Object
            // variables that hold X cursor font codes. neomacs has
            // no native window-system bindings for these yet, so
            // they default to nil. Cursor audit Finding 9 in
            // drafts/cursor-audit.md flagged the symbols as
            // missing entirely; Lisp code that tried
            // (setq x-pointer-shape ...) hit void-variable.
            "x-pointer-shape",
            "x-nontext-pointer-shape",
            "x-mode-pointer-shape",
            "x-sensitive-text-pointer-shape",
            "x-hourglass-pointer-shape",
            "x-window-horizontal-drag-cursor",
            "x-window-vertical-drag-cursor",
            "x-window-left-edge-cursor",
            "x-window-top-left-corner-cursor",
            "x-window-top-edge-cursor",
            "x-window-top-right-corner-cursor",
            "x-window-right-edge-cursor",
            "x-window-bottom-right-corner-cursor",
            "x-window-bottom-edge-cursor",
            "x-window-bottom-left-corner-cursor",
            "x-cursor-fore-pixel",
        ] {
            obarray.set_symbol_value(name, Value::NIL);
        }
        // GNU `frame.c` initializes these global minor-mode variables in C:
        //   Vmenu_bar_mode = Qt
        //   Vtool_bar_mode = Qt   (when built with window-system support)
        // neomacs is a window-system-capable build, so match GNU's defaults
        // instead of starting graphical sessions with both modes forced off.
        obarray.set_symbol_value("menu-bar-mode", Value::T);
        obarray.set_symbol_value("tool-bar-mode", Value::T);
        for name in [
            "auto-hscroll-mode",
            "create-lockfiles",
            "delete-auto-save-files",
            "delete-exited-processes",
            "display-fill-column-indicator-column",
            "display-hourglass",
            "display-line-numbers-current-absolute",
            "make-cursor-line-fully-visible",
            "menu-prompting",
            "mode-line-in-non-selected-windows",
            "mouse-highlight",
            "open-paren-in-column-0-is-defun-start",
            "overflow-newline-into-fringe",
            "read-minibuffer-restore-windows",
            "scroll-bar-adjust-thumb-portion",
            "select-active-regions",
            "translate-upper-case-key-bindings",
            "use-dialog-box",
            "use-file-dialog",
            "use-system-tooltips",
            "visible-cursor",
            "x-gtk-file-dialog-help-text",
            "x-select-enable-clipboard-manager",
        ] {
            obarray.set_symbol_value(name, Value::T);
        }
        obarray.set_symbol_value("auto-save-interval", Value::fixnum(300));
        obarray.set_symbol_value("auto-save-timeout", Value::fixnum(30));
        obarray.set_symbol_value("display-line-numbers-major-tick", Value::fixnum(0));
        obarray.set_symbol_value("display-line-numbers-minor-tick", Value::fixnum(0));
        obarray.set_symbol_value("double-click-fuzz", Value::fixnum(3));
        obarray.set_symbol_value("double-click-time", Value::fixnum(500));
        obarray.set_symbol_value("echo-keystrokes", Value::fixnum(1));
        obarray.set_symbol_value("gc-cons-threshold", Value::fixnum(8_000_000));
        obarray.set_symbol_value("help-char", Value::fixnum(8));
        obarray.set_symbol_value("hourglass-delay", Value::fixnum(1));
        obarray.set_symbol_value("hscroll-margin", Value::fixnum(5));
        obarray.set_symbol_value("hscroll-step", Value::fixnum(0));
        obarray.set_symbol_value("line-number-display-limit-width", Value::fixnum(200));
        obarray.set_symbol_value("maximum-scroll-margin", Value::fixnum(25));
        obarray.set_symbol_value("message-log-max", Value::fixnum(1000));
        obarray.set_symbol_value("meta-prefix-char", Value::fixnum(27));
        obarray.set_symbol_value("next-screen-context-lines", Value::fixnum(2));
        obarray.set_symbol_value("overline-margin", Value::fixnum(2));
        obarray.set_symbol_value("polling-period", Value::fixnum(2));
        obarray.set_symbol_value("process-error-pause-time", Value::fixnum(1));
        obarray.set_symbol_value("scroll-conservatively", Value::fixnum(0));
        obarray.set_symbol_value("scroll-margin", Value::fixnum(0));
        obarray.set_symbol_value("scroll-step", Value::fixnum(0));
        obarray.set_symbol_value("tool-bar-max-label-size", Value::fixnum(10));
        obarray.set_symbol_value("truncate-partial-width-windows", Value::fixnum(50));
        obarray.set_symbol_value("underline-minimum-offset", Value::fixnum(1));
        obarray.set_symbol_value("undo-limit", Value::fixnum(160000));
        obarray.set_symbol_value("undo-strong-limit", Value::fixnum(240000));
        obarray.set_symbol_value("eol-mnemonic-dos", Value::string("\\"));
        obarray.set_symbol_value("eol-mnemonic-mac", Value::string("/"));
        obarray.set_symbol_value("eol-mnemonic-undecided", Value::string(":"));
        obarray.set_symbol_value("eol-mnemonic-unix", Value::string(":"));
        obarray.set_symbol_value(
            "report-emacs-bug-address",
            Value::string("bug-gnu-emacs@gnu.org"),
        );
        obarray.set_symbol_value("yes-or-no-prompt", Value::string("(yes or no) "));
        // Float-valued C variables
        obarray.set_symbol_value("gc-cons-percentage", Value::make_float(0.1));
        obarray.set_symbol_value("max-mini-window-height", Value::make_float(0.25));
        obarray.set_symbol_value("image-scaling-factor", Value::make_float(1.0));
        // Display engine C variables (xdisp.c)
        obarray.set_symbol_value("global-mode-string", Value::NIL);
        // File loading C variables (lread.c)
        obarray.set_symbol_value("load-in-progress", Value::NIL);
        // Process/daemon C variables (process.c)
        obarray.set_symbol_value("internal--daemon-sockname", Value::NIL);
        // Byte compiler variables (bytecomp.el defcustom, but referenced
        // at runtime by legacy packages like evil-escape via ad-add-advice)
        obarray.set_symbol_value("byte-compile-warnings", Value::T);
        // Other missing C variables cus-start.el checks
        obarray.set_symbol_value("history-length", Value::fixnum(100));
        obarray.set_symbol_value("minibuffer-follows-selected-frame", Value::T);
        obarray.set_symbol_value("recenter-redisplay", Value::symbol("tty"));
        obarray.set_symbol_value("iconify-child-frame", Value::symbol("iconify-top-level"));
        obarray.set_symbol_value("frame-inhibit-implied-resize", Value::NIL);
        obarray.set_symbol_value("mark-even-if-inactive", Value::T);
        obarray.set_symbol_value("read-buffer-function", Value::NIL);
        obarray.set_symbol_value("minibuffer-prompt-properties", Value::NIL);
        obarray.set_symbol_value("help-event-list", Value::NIL);
        // GNU `keyboard.c:14127`:
        //   DEFVAR_LISP ("prefix-help-command", Vprefix_help_command, ...);
        //   Vprefix_help_command = intern_c_string ("describe-prefix-bindings");
        // The default is consulted by `read_key_sequence` when the
        // help-char fires after a prefix. Keyboard audit Finding 5
        // in `drafts/keyboard-command-loop-audit.md`.
        obarray.set_symbol_value(
            "prefix-help-command",
            Value::symbol("describe-prefix-bindings"),
        );
        obarray.set_symbol_value("debug-ignored-errors", Value::NIL);
        obarray.set_symbol_value("debug-on-event", Value::NIL);
        obarray.set_symbol_value("debug-on-signal", Value::NIL);
        // Remaining cus-start.el variables (general + platform stubs)
        for name in [
            "imagemagick-render-type",
            "window-combination-limit",
            "void-text-area-pointer",
            "x-bitmap-file-path",
            "x-gtk-use-system-tooltips",
            "x-scroll-event-delta-factor",
            "x-auto-preserve-selections",
            "xwidget-internal",
            "temporary-file-directory",
            "vertical-centering-font-regexp",
            "ns-control-modifier",
            "ns-right-control-modifier",
            "ns-command-modifier",
            "ns-right-command-modifier",
            "ns-alternate-modifier",
            "ns-right-alternate-modifier",
            "ns-function-modifier",
            "ns-antialias-text",
            "ns-auto-hide-menu-bar",
            "ns-confirm-quit",
            "ns-use-native-fullscreen",
            "ns-use-fullscreen-animation",
            "ns-use-srgb-colorspace",
            "ns-scroll-event-delta-factor",
            "ns-click-through",
            "w32-follow-system-dark-mode",
            "dos-display-scancodes",
            "dos-hyper-key",
            "dos-super-key",
            "dos-keypad-mode",
            "dos-unsupported-char-glyph",
            "haiku-debug-on-fatal-error",
            "haiku-use-system-tooltips",
            "xwidget-webkit-disable-javascript",
        ] {
            obarray.set_symbol_value(name, Value::NIL);
        }

        // GNU DEFVAR_LISP variables from lread.c that must be bound to nil
        // before any Elisp runs (code may test `boundp` or read them directly).
        //
        // Keep GNU's exception for `values`: `lread.c` defines it via
        // `DEFVAR_LISP` and then explicitly clears the declared-special bit,
        // so it remains an ordinary variable even under lexical binding.
        obarray.set_symbol_value("values", Value::NIL);
        obarray.set_symbol_value("eval-buffer-list", Value::NIL);
        obarray.make_special("eval-buffer-list");
        obarray.set_symbol_value("lread--unescaped-character-literals", Value::NIL);
        obarray.make_special("lread--unescaped-character-literals");
        obarray.set_symbol_value("load-read-function", Value::symbol("read"));
        obarray.make_special("load-read-function");
        obarray.set_symbol_value("load-source-file-function", Value::NIL);
        obarray.make_special("load-source-file-function");
        obarray.set_symbol_value("load-true-file-name", Value::NIL);
        obarray.make_special("load-true-file-name");
        obarray.set_symbol_value("user-init-file", Value::NIL);
        obarray.make_special("user-init-file");
        obarray.set_symbol_value("source-directory", Value::NIL);
        obarray.make_special("source-directory");
        obarray.set_symbol_value("after-load-alist", Value::NIL);
        obarray.make_special("after-load-alist");
        obarray.set_symbol_value("load-history", Value::NIL);
        obarray.make_special("load-history");
        obarray.set_symbol_value("current-load-list", Value::NIL);
        obarray.make_special("current-load-list");
        obarray.set_symbol_value("preloaded-file-list", Value::NIL);
        obarray.make_special("preloaded-file-list");
        obarray.set_symbol_value("byte-boolean-vars", Value::NIL);
        obarray.make_special("byte-boolean-vars");
        obarray.set_symbol_value(
            "bytecomp-version-regexp",
            Value::string(r#"^;;;.\(in Emacs version\|bytecomp version FSF\)"#),
        );
        obarray.make_special("bytecomp-version-regexp");
        obarray.set_symbol_value("load-path-filter-function", Value::NIL);
        obarray.make_special("load-path-filter-function");
        obarray.set_symbol_value("internal--get-default-lexical-binding-function", Value::NIL);
        obarray.make_special("internal--get-default-lexical-binding-function");
        obarray.set_symbol_value("read-symbol-shorthands", Value::NIL);
        obarray.make_special("read-symbol-shorthands");
        obarray.set_symbol_value("macroexp--dynvars", Value::NIL);
        obarray.make_special("macroexp--dynvars");
        // GNU DEFVAR_LISP variables from eval.c / keyboard.c.
        let core_eval_symbols = install_core_eval_symbols(&mut obarray, true);
        obarray.set_symbol_value("inhibit-debugger", Value::NIL);
        obarray.make_special("inhibit-debugger");
        obarray.set_symbol_value("debug-on-error", Value::NIL);
        obarray.make_special("debug-on-error");
        obarray.set_symbol_value("debug-on-quit", Value::NIL);
        obarray.make_special("debug-on-quit");
        obarray.set_symbol_value("debug-on-signal", Value::NIL);
        obarray.make_special("debug-on-signal");
        obarray.set_symbol_value("debug-ignored-errors", Value::NIL);
        obarray.make_special("debug-ignored-errors");
        obarray.set_symbol_value("debugger-may-continue", Value::NIL);
        obarray.make_special("debugger-may-continue");
        obarray.set_symbol_value("internal-when-entered-debugger", Value::fixnum(-1));
        obarray.make_special("internal-when-entered-debugger");
        obarray.set_symbol_value("signal-hook-function", Value::NIL);
        obarray.make_special("signal-hook-function");
        // GNU `eval.c` defines `internal-interpreter-environment` and then
        // immediately `Funintern`s that symbol, so Lisp-visible lookup sees a
        // separate ordinary symbol while the evaluator keeps a hidden special
        // variable for its own lexical-environment bookkeeping.
        obarray.set_symbol_value("internal-make-interpreted-closure-function", Value::NIL);
        obarray.make_special("internal-make-interpreted-closure-function");
        // GNU seeds `debugger` from eval.c before Lisp startup.
        // `eval-expression` relies on it.
        obarray.set_symbol_value("debugger", Value::symbol("debug-early"));
        obarray.make_special("debugger");
        obarray.set_symbol_value("standard-output", Value::T);
        // GNU DEFVAR_INT from dispnew.c — used by bytecomp.el
        obarray.set_symbol_value("baud-rate", Value::fixnum(38400));
        obarray.set_symbol_value("search-slow-speed", Value::fixnum(1200));
        // GNU startup.el sets these based on --debug-init
        obarray.set_symbol_value("init-file-debug", Value::NIL);
        // GNU callproc.c: exec-path is built from PATH env var.
        // exec-directory is the directory containing helper programs.
        let exec_path: Vec<Value> = std::env::var("PATH")
            .unwrap_or_default()
            .split(':')
            .map(|s| Value::unibyte_string(s.to_string()))
            .collect();
        obarray.set_symbol_value("exec-path", Value::list(exec_path));
        obarray.set_symbol_value(
            "exec-directory",
            Value::unibyte_string(
                std::env::current_exe()
                    .ok()
                    .and_then(|p| p.parent().map(|d| d.to_string_lossy().to_string()))
                    .unwrap_or_else(|| "/usr/bin/".to_string()),
            ),
        );
        obarray.set_symbol_value(
            "exec-suffixes",
            Value::list(vec![Value::unibyte_string("")]),
        );
        obarray.set_symbol_value("buffer-read-only", Value::NIL);
        obarray.set_symbol_value("left-margin-width", Value::NIL);
        obarray.set_symbol_value("right-margin-width", Value::NIL);
        obarray.set_symbol_value("left-fringe-width", Value::NIL);
        obarray.set_symbol_value("right-fringe-width", Value::NIL);
        obarray.set_symbol_value("fringes-outside-margins", Value::NIL);
        obarray.set_symbol_value("scroll-bar-width", Value::NIL);
        obarray.set_symbol_value("scroll-bar-height", Value::NIL);
        obarray.set_symbol_value("vertical-scroll-bar", Value::T);
        obarray.set_symbol_value("horizontal-scroll-bar", Value::T);
        obarray.set_symbol_value("kill-ring", Value::NIL);
        obarray.set_symbol_value("kill-ring-yank-pointer", Value::NIL);
        obarray.set_symbol_value("last-command", Value::NIL);
        obarray.set_symbol_value("current-fill-column--has-warned", Value::NIL);
        obarray.set_symbol_value("current-input-method", Value::NIL);
        obarray.set_symbol_value("current-input-method-title", Value::NIL);
        obarray.set_symbol_value("current-iso639-language", Value::NIL);
        obarray.set_symbol_value("current-key-remap-sequence", Value::NIL);
        obarray.set_symbol_value("current-language-environment", Value::string("UTF-8"));
        obarray.set_symbol_value(
            "current-load-list",
            Value::list(vec![
                Value::symbol("comp--no-native-compile"),
                Value::cons(
                    Value::symbol("defun"),
                    Value::symbol("load--fixup-all-elns"),
                ),
                Value::symbol("load--eln-dest-dir"),
                Value::symbol("load--bin-dest-dir"),
            ]),
        );
        obarray.set_symbol_value("current-locale-environment", Value::string("C.UTF-8"));
        obarray.set_symbol_value("current-minibuffer-command", Value::NIL);
        obarray.set_symbol_value("current-time-list", Value::T);
        obarray.set_symbol_value("current-transient-input-method", Value::NIL);
        obarray.set_symbol_value("real-last-command", Value::NIL);
        obarray.set_symbol_value("last-repeatable-command", Value::NIL);
        obarray.set_symbol_value("this-original-command", Value::NIL);
        obarray.set_symbol_value("prefix-arg", Value::NIL);
        obarray.set_symbol_value("defining-kbd-macro", Value::NIL);
        obarray.set_symbol_value("executing-kbd-macro", Value::NIL);
        obarray.set_symbol_value("executing-kbd-macro-index", Value::fixnum(0));
        obarray.set_symbol_value("kbd-macro-termination-hook", Value::NIL);
        obarray.set_symbol_value("command-history", Value::NIL);
        obarray.set_symbol_value("extended-command-history", Value::NIL);
        obarray.set_symbol_value("completion-ignore-case", Value::NIL);
        obarray.set_symbol_value("read-buffer-completion-ignore-case", Value::NIL);
        obarray.set_symbol_value("read-file-name-completion-ignore-case", Value::NIL);
        obarray.set_symbol_value("completion-regexp-list", Value::NIL);
        obarray.set_symbol_value("completion--all-sorted-completions-location", Value::NIL);
        obarray.set_symbol_value("completion--capf-misbehave-funs", Value::NIL);
        obarray.set_symbol_value("completion--capf-safe-funs", Value::NIL);
        obarray.set_symbol_value(
            "completion--embedded-envvar-re",
            Value::string(
                "\\(?:^\\|[^$]\\(?:\\$\\$\\)*\\)\\$\\([[:alnum:]_]*\\|{\\([^}]*\\)\\)\\'",
            ),
        );
        obarray.set_symbol_value("completion--flex-score-last-md", Value::NIL);
        obarray.set_symbol_value("completion-all-sorted-completions", Value::NIL);
        obarray.set_symbol_value(
            "completion--cycling-threshold-type",
            Value::list(vec![Value::symbol("choice")]),
        );
        obarray.set_symbol_value(
            "completion--styles-type",
            Value::list(vec![Value::symbol("repeat")]),
        );
        obarray.set_symbol_value(
            "completion-at-point-functions",
            Value::list(vec![Value::symbol("tags-completion-at-point-function")]),
        );
        obarray.set_symbol_value(
            "completion-setup-hook",
            Value::list(vec![Value::symbol("completion-setup-function")]),
        );
        obarray.set_symbol_value(
            "completion-in-region-mode-map",
            completion_in_region_mode_map,
        );
        obarray.set_symbol_value("completion-list-mode-map", completion_list_mode_map);
        obarray.set_symbol_value("completion-list-mode-syntax-table", standard_syntax_table);
        obarray.set_symbol_value(
            "completion-list-mode-abbrev-table",
            Value::symbol("completion-list-mode-abbrev-table"),
        );
        obarray.set_symbol_value("completion-list-mode-hook", Value::NIL);
        obarray.set_symbol_value(
            "completion-ignored-extensions",
            Value::list(vec![
                Value::string(".o"),
                Value::string("~"),
                Value::string(".elc"),
            ]),
        );
        obarray.set_symbol_value(
            "completion-styles",
            Value::list(vec![
                Value::symbol("basic"),
                Value::symbol("partial-completion"),
                Value::symbol("emacs22"),
            ]),
        );
        obarray.set_symbol_value(
            "completion-category-defaults",
            Value::list(vec![
                Value::list(vec![
                    Value::symbol("buffer"),
                    Value::list(vec![
                        Value::symbol("styles"),
                        Value::symbol("basic"),
                        Value::symbol("substring"),
                    ]),
                ]),
                Value::list(vec![
                    Value::symbol("unicode-name"),
                    Value::list(vec![
                        Value::symbol("styles"),
                        Value::symbol("basic"),
                        Value::symbol("substring"),
                    ]),
                ]),
                Value::list(vec![
                    Value::symbol("project-file"),
                    Value::list(vec![Value::symbol("styles"), Value::symbol("substring")]),
                ]),
                Value::list(vec![
                    Value::symbol("xref-location"),
                    Value::list(vec![Value::symbol("styles"), Value::symbol("substring")]),
                ]),
                Value::list(vec![
                    Value::symbol("info-menu"),
                    Value::list(vec![
                        Value::symbol("styles"),
                        Value::symbol("basic"),
                        Value::symbol("substring"),
                    ]),
                ]),
                Value::list(vec![
                    Value::symbol("symbol-help"),
                    Value::list(vec![
                        Value::symbol("styles"),
                        Value::symbol("basic"),
                        Value::symbol("shorthand"),
                        Value::symbol("substring"),
                    ]),
                ]),
                Value::list(vec![
                    Value::symbol("calendar-month"),
                    Value::cons(
                        Value::symbol("display-sort-function"),
                        Value::symbol("identity"),
                    ),
                ]),
            ]),
        );
        // Do NOT hardcode completion-styles-alist here.
        // GNU defines it via (defvar completion-styles-alist ...)
        // in lisp/minibuffer.el:1158 with all 8 styles including
        // flex, substring, initials, shorthand. defvar only sets
        // the value when the symbol is void, so pre-setting it
        // here would shadow the Lisp definition and lose styles
        // like flex — breaking fido-vertical-mode which requires
        // the flex completion style.
        obarray.set_symbol_value("completion-category-overrides", Value::NIL);
        obarray.set_symbol_value("completion-cycle-threshold", Value::NIL);
        obarray.set_symbol_value("completions-detailed", Value::NIL);
        obarray.set_symbol_value("completions-format", Value::symbol("horizontal"));
        obarray.set_symbol_value("completions-group", Value::NIL);
        obarray.set_symbol_value("completions-group-format", Value::string("     %s  "));
        obarray.set_symbol_value("completions-group-sort", Value::NIL);
        obarray.set_symbol_value(
            "completions-header-format",
            Value::string("%s possible completions:\n"),
        );
        obarray.set_symbol_value(
            "completions-highlight-face",
            Value::symbol("completions-highlight"),
        );
        obarray.set_symbol_value("completions-max-height", Value::NIL);
        obarray.set_symbol_value("completions-sort", Value::symbol("alphabetical"));
        obarray.set_symbol_value("completion-auto-help", Value::T);
        obarray.set_symbol_value("completion-auto-deselect", Value::T);
        obarray.set_symbol_value("completion-auto-select", Value::NIL);
        obarray.set_symbol_value("completion-auto-wrap", Value::T);
        obarray.set_symbol_value("completion-base-position", Value::NIL);
        obarray.set_symbol_value("completion-cycling", Value::NIL);
        obarray.set_symbol_value("completion-extra-properties", Value::NIL);
        obarray.set_symbol_value("completion-fail-discreetly", Value::NIL);
        obarray.set_symbol_value("completion-flex-nospace", Value::NIL);
        obarray.set_symbol_value("completion-in-region--data", Value::NIL);
        obarray.set_symbol_value(
            "completion-in-region-function",
            Value::symbol("completion--in-region"),
        );
        obarray.set_symbol_value("completion-in-region-functions", Value::NIL);
        obarray.set_symbol_value("completion-in-region-mode", Value::NIL);
        obarray.set_symbol_value("completion-in-region-mode--predicate", Value::NIL);
        obarray.set_symbol_value("completion-in-region-mode-hook", Value::NIL);
        obarray.set_symbol_value("completion-in-region-mode-predicate", Value::NIL);
        obarray.set_symbol_value("completion-show-help", Value::T);
        obarray.set_symbol_value("completion-show-inline-help", Value::T);
        obarray.set_symbol_value("completion-lazy-hilit", Value::NIL);
        obarray.set_symbol_value("completion-lazy-hilit-fn", Value::NIL);
        obarray.set_symbol_value(
            "completion-list-insert-choice-function",
            Value::symbol("completion--replace"),
        );
        obarray.set_symbol_value("completion-no-auto-exit", Value::NIL);
        obarray.set_symbol_value(
            "completion-pcm--delim-wild-regex",
            Value::string("[-_./:| *]"),
        );
        obarray.set_symbol_value("completion-pcm--regexp", Value::NIL);
        obarray.set_symbol_value(
            "completion-pcm-complete-word-inserts-delimiters",
            Value::NIL,
        );
        obarray.set_symbol_value("completion-pcm-word-delimiters", Value::string("-_./:| "));
        obarray.set_symbol_value("completion-reference-buffer", Value::NIL);
        obarray.set_symbol_value("completion-tab-width", Value::NIL);
        obarray.set_symbol_value("enable-recursive-minibuffers", Value::NIL);
        obarray.set_symbol_value("history-length", Value::fixnum(100));
        obarray.set_symbol_value("history-delete-duplicates", Value::NIL);
        obarray.set_symbol_value("history-add-new-input", Value::T);
        obarray.set_symbol_value("read-buffer-function", Value::NIL);
        obarray.set_symbol_value(
            "read-file-name-function",
            Value::symbol("read-file-name-default"),
        );
        obarray.set_symbol_value("read-expression-history", Value::NIL);
        obarray.set_symbol_value("read-number-history", Value::NIL);
        obarray.set_symbol_value("read-char-history", Value::NIL);
        obarray.set_symbol_value("read-answer-short", Value::symbol("auto"));
        obarray.set_symbol_value("read-char-by-name-sort", Value::NIL);
        obarray.set_symbol_value("read-char-choice-use-read-key", Value::NIL);
        obarray.set_symbol_value("read-circle", Value::T);
        obarray.make_special("read-circle");
        obarray.set_symbol_value("read-envvar-name-history", Value::NIL);
        obarray.set_symbol_value("read-face-name-sample-text", Value::string("SAMPLE"));
        obarray.set_symbol_value("read-key-delay", Value::make_float(0.01));
        obarray.set_symbol_value(
            "read-answer-map--memoize",
            Value::hash_table(HashTableTest::Equal),
        );
        obarray.set_symbol_value("read-extended-command-mode", Value::NIL);
        obarray.set_symbol_value("read-extended-command-mode-hook", Value::NIL);
        obarray.set_symbol_value("read-extended-command-predicate", Value::NIL);
        obarray.set_symbol_value("read-hide-char", Value::NIL);
        obarray.set_symbol_value("read-mail-command", Value::symbol("rmail"));
        obarray.set_symbol_value("read-minibuffer-restore-windows", Value::T);
        obarray.set_symbol_value("read-only-mode-hook", Value::NIL);
        obarray.set_symbol_value("read-process-output-max", Value::fixnum(65536));
        obarray.set_symbol_value("read-quoted-char-radix", Value::fixnum(8));
        obarray.set_symbol_value("read-regexp--case-fold", Value::NIL);
        obarray.set_symbol_value("read-regexp-defaults-function", Value::NIL);
        obarray.set_symbol_value("read-symbol-shorthands", Value::NIL);
        obarray.set_symbol_value(
            "minibuffer-frame-alist",
            Value::list(vec![
                Value::cons(Value::symbol("width"), Value::fixnum(80)),
                Value::cons(Value::symbol("height"), Value::fixnum(2)),
            ]),
        );
        obarray.set_symbol_value(
            "minibuffer-inactive-mode-abbrev-table",
            Value::symbol("minibuffer-inactive-mode-abbrev-table"),
        );
        obarray.set_symbol_value("minibuffer-inactive-mode-hook", Value::NIL);
        obarray.set_symbol_value(
            "minibuffer-inactive-mode-syntax-table",
            standard_syntax_table,
        );
        obarray.set_symbol_value(
            "minibuffer-mode-abbrev-table",
            Value::symbol("minibuffer-mode-abbrev-table"),
        );
        obarray.set_symbol_value("minibuffer-mode-hook", Value::NIL);
        obarray.set_symbol_value("minibuffer-local-map", minibuffer_local_map);
        obarray.set_symbol_value("minibuffer-local-filename-syntax", standard_syntax_table);
        obarray.set_symbol_value("minibuffer-history", Value::NIL);
        obarray.set_symbol_value(
            "minibuffer-history-variable",
            Value::symbol("minibuffer-history"),
        );
        obarray.set_symbol_value("minibuffer-history-position", Value::NIL);
        obarray.set_symbol_value("minibuffer-history-isearch-message-overlay", Value::NIL);
        obarray.set_symbol_value("minibuffer-history-search-history", Value::NIL);
        obarray.set_symbol_value("minibuffer-history-sexp-flag", Value::NIL);
        obarray.set_symbol_value("minibuffer-default", Value::NIL);
        obarray.set_symbol_value("minibuffer-default-add-done", Value::NIL);
        obarray.set_symbol_value(
            "minibuffer-default-add-function",
            Value::symbol("minibuffer-default-add-completions"),
        );
        obarray.set_symbol_value("minibuffer--original-buffer", Value::NIL);
        obarray.set_symbol_value("minibuffer--regexp-primed", Value::NIL);
        obarray.set_symbol_value(
            "minibuffer--regexp-prompt-regexp",
            Value::string(
                "\\(?:Posix search\\|RE search\\|Search for regexp\\|Query replace regexp\\)",
            ),
        );
        obarray.set_symbol_value("minibuffer--require-match", Value::NIL);
        obarray.set_symbol_value("minibuffer-auto-raise", Value::NIL);
        obarray.set_symbol_value("minibuffer-follows-selected-frame", Value::T);
        obarray.set_symbol_value(
            "minibuffer-exit-hook",
            Value::list(vec![
                Value::symbol("minibuffer--regexp-exit"),
                Value::symbol("minibuffer-exit-on-screen-keyboard"),
                Value::symbol("minibuffer-restore-windows"),
            ]),
        );
        obarray.set_symbol_value("minibuffer-completion-table", Value::NIL);
        obarray.set_symbol_value("minibuffer-completion-predicate", Value::NIL);
        obarray.set_symbol_value("minibuffer-completion-confirm", Value::NIL);
        obarray.set_symbol_value("minibuffer-completion-auto-choose", Value::T);
        obarray.set_symbol_value("minibuffer-completion-base", Value::NIL);
        obarray.set_symbol_value("minibuffer-help-form", Value::NIL);
        obarray.set_symbol_value("minibuffer-completing-file-name", Value::NIL);
        obarray.set_symbol_value("minibuffer-regexp-mode", Value::T);
        obarray.set_symbol_value("minibuffer-regexp-mode-hook", Value::NIL);
        obarray.set_symbol_value(
            "minibuffer-regexp-prompts",
            Value::list(vec![
                Value::string("Posix search"),
                Value::string("RE search"),
                Value::string("Search for regexp"),
                Value::string("Query replace regexp"),
            ]),
        );
        obarray.set_symbol_value("minibuffer-message-clear-timeout", Value::NIL);
        obarray.set_symbol_value("minibuffer-message-overlay", Value::NIL);
        obarray.set_symbol_value("minibuffer-message-properties", Value::NIL);
        obarray.set_symbol_value("minibuffer-message-timeout", Value::fixnum(2));
        obarray.set_symbol_value("minibuffer-message-timer", Value::NIL);
        obarray.set_symbol_value("minibuffer-lazy-count-format", Value::string("%s "));
        obarray.set_symbol_value("minibuffer-text-before-history", Value::NIL);
        obarray.set_symbol_value(
            "minibuffer-prompt-properties",
            Value::list(vec![
                Value::symbol("read-only"),
                Value::T,
                Value::symbol("face"),
                Value::symbol("minibuffer-prompt"),
            ]),
        );
        obarray.set_symbol_value("minibuffer-allow-text-properties", Value::NIL);
        obarray.set_symbol_value("minibuffer-scroll-window", Value::NIL);
        obarray.make_special("minibuffer-scroll-window");
        obarray.set_symbol_value("other-window-scroll-buffer", Value::NIL);
        obarray.make_special("other-window-scroll-buffer");
        obarray.set_symbol_value("other-window-scroll-default", Value::NIL);
        obarray.make_special("other-window-scroll-default");
        obarray.set_symbol_value("minibuffer-visible-completions", Value::NIL);
        obarray.set_symbol_value("minibuffer-visible-completions--always-bind", Value::NIL);
        obarray.set_symbol_value("minibuffer-depth-indicate-mode", Value::NIL);
        obarray.set_symbol_value(
            "minibuffer-default-prompt-format",
            Value::string(" (default %s)"),
        );
        obarray.set_symbol_value("minibuffer-beginning-of-buffer-movement", Value::NIL);
        obarray.set_symbol_value("minibuffer-electric-default-mode", Value::NIL);
        obarray.set_symbol_value("minibuffer-temporary-goal-position", Value::NIL);
        obarray.set_symbol_value(
            "minibuffer-confirm-exit-commands",
            Value::list(vec![
                Value::symbol("completion-at-point"),
                Value::symbol("minibuffer-complete"),
                Value::symbol("minibuffer-complete-word"),
            ]),
        );
        obarray.set_symbol_value("minibuffer-history-case-insensitive-variables", Value::NIL);
        obarray.set_symbol_value("minibuffer-on-screen-keyboard-displayed", Value::NIL);
        obarray.set_symbol_value("minibuffer-on-screen-keyboard-timer", Value::NIL);
        obarray.set_symbol_value(
            "minibuffer-setup-hook",
            Value::list(vec![
                Value::symbol("rfn-eshadow-setup-minibuffer"),
                Value::symbol("minibuffer--regexp-setup"),
                Value::symbol("minibuffer-setup-on-screen-keyboard"),
                Value::symbol("minibuffer-error-initialize"),
                Value::symbol("minibuffer-history-isearch-setup"),
                Value::symbol("minibuffer-history-initialize"),
            ]),
        );
        obarray.set_symbol_value("regexp-search-ring", Value::NIL);
        obarray.set_symbol_value("regexp-search-ring-max", Value::fixnum(16));
        obarray.set_symbol_value("regexp-search-ring-yank-pointer", Value::NIL);
        obarray.set_symbol_value("search-ring", Value::NIL);
        obarray.set_symbol_value("search-ring-max", Value::fixnum(16));
        obarray.set_symbol_value("search-ring-update", Value::NIL);
        obarray.set_symbol_value("search-ring-yank-pointer", Value::NIL);
        obarray.set_symbol_value("last-abbrev", Value::NIL);
        obarray.set_symbol_value("last-abbrev-location", Value::fixnum(0));
        obarray.set_symbol_value("last-abbrev-text", Value::NIL);
        obarray.set_symbol_value("last-command-event", Value::NIL);
        // last-event-frame is set by keyboard::pure::register_bootstrap_vars
        obarray.set_symbol_value("last-event-device", Value::NIL);
        obarray.set_symbol_value("last-input-event", Value::NIL);
        obarray.set_symbol_value("last-nonmenu-event", Value::NIL);
        obarray.set_symbol_value("last-prefix-arg", Value::NIL);
        obarray.set_symbol_value("last-kbd-macro", Value::NIL);
        obarray.set_symbol_value("last-code-conversion-error", Value::NIL);
        obarray.set_symbol_value("last-coding-system-specified", Value::NIL);
        obarray.set_symbol_value("last-coding-system-used", Value::symbol("undecided-unix"));
        obarray.set_symbol_value("last-next-selection-coding-system", Value::NIL);
        obarray.set_symbol_value("command-debug-status", Value::NIL);
        obarray.set_symbol_value(
            "command-error-function",
            Value::symbol("help-command-error-confusable-suggestions"),
        );
        obarray.set_symbol_value("key-substitution-in-progress", Value::NIL);
        obarray.set_symbol_value("this-command", Value::NIL);
        obarray.set_symbol_value("real-this-command", Value::NIL);
        obarray.set_symbol_value("this-command-keys-shift-translated", Value::NIL);
        obarray.set_symbol_value("current-prefix-arg", Value::NIL);
        obarray.set_symbol_value("track-mouse", Value::NIL);
        obarray.make_special("track-mouse");
        obarray.set_symbol_value(
            "while-no-input-ignore-events",
            Value::list(vec![
                Value::symbol("thread-event"),
                Value::symbol("file-notify"),
                Value::symbol("dbus-event"),
                Value::symbol("select-window"),
                Value::symbol("help-echo"),
                Value::symbol("move-frame"),
                Value::symbol("iconify-frame"),
                Value::symbol("make-frame-visible"),
                Value::symbol("focus-in"),
                Value::symbol("focus-out"),
                Value::symbol("config-changed-event"),
                Value::symbol("selection-request"),
                Value::symbol("monitors-changed"),
            ]),
        );
        obarray.make_special("while-no-input-ignore-events");
        obarray.set_symbol_value("input-pending-p-filter-events", Value::T);
        obarray.make_special("input-pending-p-filter-events");
        obarray.set_symbol_value("deactivate-mark", Value::T);
        obarray.set_symbol_value("mark-active", Value::NIL);
        obarray.set_symbol_value("mark-even-if-inactive", Value::T);
        obarray.set_symbol_value("mark-ring", Value::NIL);
        obarray.set_symbol_value("mark-ring-max", Value::fixnum(16));
        // saved-region-selection is set by keyboard::pure::register_bootstrap_vars
        obarray.set_symbol_value("transient-mark-mode", Value::NIL);
        obarray.set_symbol_value("transient-mark-mode-hook", Value::NIL);
        obarray.set_symbol_value("post-select-region-hook", Value::NIL);
        obarray.set_symbol_value("echo-area-clear-hook", Value::NIL);
        obarray.set_symbol_value("display-monitors-changed-functions", Value::NIL);
        obarray.set_symbol_value("delete-terminal-functions", Value::NIL);
        obarray.set_symbol_value("suspend-tty-functions", Value::NIL);
        obarray.set_symbol_value("resume-tty-functions", Value::NIL);
        obarray.set_symbol_value("overriding-local-map", Value::NIL);
        obarray.make_special("overriding-local-map");
        obarray.set_symbol_value("overriding-local-map-menu-flag", Value::NIL);
        obarray.make_special("overriding-local-map-menu-flag");
        obarray.set_symbol_value("overriding-plist-environment", Value::NIL);
        obarray.set_symbol_value("overriding-terminal-local-map", Value::NIL);
        // GNU uses DEFVAR_KBOARD here. NeoVM does not yet split keyboard state
        // per terminal, so model it as a dynamically scoped runtime variable.
        obarray.make_special("overriding-terminal-local-map");
        obarray.set_symbol_value("overriding-text-conversion-style", Value::symbol("lambda"));

        // ---- C-level bootstrap variables required by loadup.el files ----

        // Standard keymaps (C creates these in keyboard.c:init_kboard)
        obarray.set_symbol_value("special-event-map", special_event_map);
        obarray.set_symbol_value(
            "mode-line-window-dedicated-keymap",
            mode_line_window_dedicated_keymap,
        );
        obarray.set_symbol_value("indent-rigidly-map", indent_rigidly_map);
        obarray.set_symbol_value("text-mode-map", text_mode_map);
        obarray.set_symbol_value("image-slice-map", image_slice_map);
        obarray.set_symbol_value("tool-bar-map", tool_bar_map);
        obarray.set_symbol_value("key-translation-map", key_translation_map);
        obarray.set_symbol_value("function-key-map", function_key_map);
        obarray.set_symbol_value("input-decode-map", input_decode_map);
        obarray.make_special("input-decode-map");
        obarray.set_symbol_value("local-function-key-map", local_function_key_map);
        obarray.make_special("local-function-key-map");
        obarray.set_symbol_value("keyboard-translate-table", Value::NIL);

        // Core eval variables (stay in eval.rs)
        obarray.set_symbol_value("purify-flag", Value::NIL);
        // GNU Emacs defaults to 1600 but only increments lisp_eval_depth in
        // eval_sub() and Ffuncall(). NeoVM increments depth for every
        // sub-expression including primitive calls (get, fboundp, etc.), so
        // the same Elisp code uses ~5x more depth units. Use 10000 to match
        // effective GNU depth capacity.
        obarray.set_symbol_value("max-lisp-eval-depth", Value::fixnum(2400));
        obarray.set_symbol_value("max-specpdl-size", Value::fixnum(1800));
        obarray.set_symbol_value("inhibit-load-charset-map", Value::NIL);

        // Terminal/display variables (C-level DEFVAR in official Emacs)
        obarray.set_symbol_value("standard-display-table", Value::NIL);
        obarray.set_symbol_value(
            "image-load-path",
            Value::list(vec![
                Value::string("/usr/share/emacs/30.1/etc/images/"),
                Value::symbol("data-directory"),
            ]),
        );
        obarray.set_symbol_value("image-scaling-factor", Value::make_float(1.0));

        // User init / startup (C DEFVAR in official Emacs)
        obarray.set_symbol_value("user-init-file", Value::NIL);
        obarray.set_symbol_value("user-emacs-directory", Value::string("~/.emacs.d/"));

        // Frame parameters (C DEFVAR in official Emacs)
        obarray.set_symbol_value("frame--special-parameters", Value::NIL);

        // Initialize distributed bootstrap variables
        super::alloc::register_bootstrap_vars(&mut obarray);
        super::load::register_bootstrap_vars(&mut obarray);
        super::fileio::register_bootstrap_vars(&mut obarray);
        super::window_cmds::register_bootstrap_vars(&mut obarray);
        super::keyboard::pure::register_bootstrap_vars(&mut obarray);
        super::composite::register_bootstrap_vars(&mut obarray);
        super::coding::register_bootstrap_vars(&mut obarray);
        super::xdisp::register_bootstrap_vars(&mut obarray);
        super::textprop::register_bootstrap_vars(&mut obarray);
        super::xfaces::register_bootstrap_vars(&mut obarray);
        super::frame_vars::register_bootstrap_vars(&mut obarray);
        super::buffer_vars::register_bootstrap_vars(&mut obarray);

        // ---- end C-level bootstrap variables ----

        obarray.set_symbol_value("unread-input-method-events", Value::NIL);
        obarray.set_symbol_value("unread-post-input-method-events", Value::NIL);
        obarray.set_symbol_value("input-method-alist", Value::NIL);
        obarray.set_symbol_value("input-method-activate-hook", Value::NIL);
        obarray.set_symbol_value("input-method-after-insert-chunk-hook", Value::NIL);
        obarray.set_symbol_value("input-method-deactivate-hook", Value::NIL);
        obarray.set_symbol_value("input-method-exit-on-first-char", Value::NIL);
        obarray.set_symbol_value("input-method-exit-on-invalid-key", Value::NIL);
        // GNU `keyboard.c:14147` initialises `Vinput_method_function`
        // to `Qlist` as a placeholder, but that is a C-side
        // representation of "no function". The observable default
        // at the Lisp level is `nil` (checked via `(null
        // input-method-function)` in `lisp/international/mule.el`
        // and countless input-method packages). Keyboard audit
        // Finding 10 in `drafts/keyboard-command-loop-audit.md`.
        obarray.set_symbol_value("input-method-function", Value::NIL);
        obarray.set_symbol_value("input-method-highlight-flag", Value::T);
        obarray.set_symbol_value("input-method-history", Value::NIL);
        // input-method-previous-message is set by keyboard::pure::register_bootstrap_vars
        obarray.set_symbol_value("input-method-use-echo-area", Value::NIL);
        obarray.set_symbol_value("input-method-verbose-flag", Value::symbol("default"));
        obarray.set_symbol_value("unread-command-events", Value::NIL);
        // GNU Emacs seeds core startup vars with integer
        // `variable-documentation` offsets in the DOC table.
        for &(name, _) in STARTUP_VARIABLE_DOC_STUBS {
            obarray
                .put_property(name, "variable-documentation", Value::fixnum(0))
                .expect("startup variable-documentation plist should always be valid");
        }
        // Some startup docs are string-valued in GNU Emacs (not integer offsets).
        for &(name, doc) in STARTUP_VARIABLE_DOC_STRING_PROPERTIES {
            obarray
                .put_property(name, "variable-documentation", Value::string(doc))
                .expect("startup variable-documentation plist should always be valid");
        }

        // Bootstrap primitive function cells that GNU `simple.el` references
        // before its own Elisp defs overwrite them. Without these placeholders,
        // loaded GNU bytecode can capture `nil` for forward/runtime calls into
        // Builtin function cells are set by defsubr() during init_builtins().
        for name in ["mark-marker", "region-beginning", "region-end"] {
            obarray.set_symbol_function(name, Value::subr_from_sym_id(intern(name)));
        }

        // `word-at-point` is defined in GNU Emacs Lisp by `thingatpt.el`,
        // not as a startup builtin.
        obarray.clear_function_silent("word-at-point");

        // Mark standard variables as special (dynamically bound)
        for name in &[
            "debug-on-error",
            "debugger",
            // "lexical-binding" — now registered via defvar_per_buffer!
            "load-prefer-newer",
            "load-path",
            "load-history",
            "default-directory",
            "load-file-name",
            "set-auto-coding-for-load",
            "noninteractive",
            "inhibit-quit",
            "inhibit-read-only",
            "inhibit-modification-hooks",
            "internal-make-interpreted-closure-function",
            "print-length",
            "print-level",
            "standard-output",
            "case-fold-search",
            "buffer-read-only",
            "current-prefix-arg",
            "prefix-arg",
            "last-prefix-arg",
            "last-command-event",
            "last-input-event",
            "last-command",
            "real-last-command",
            "this-command",
            "real-this-command",
            "this-command-keys-shift-translated",
            "unread-command-events",
            "unread-input-method-events",
            "unread-post-input-method-events",
            // transient-mark-mode is a C-level variable in GNU (buffer.c),
            // always dynamically scoped. Must be special so (let ((transient-mark-mode t)) ...)
            // creates a dynamic binding visible to called functions like region-active-p.
            "transient-mark-mode",
        ] {
            obarray.make_special(name);
        }

        // Initialize the standard error hierarchy (error, user-error, etc.)
        super::errors::init_standard_errors(&mut obarray);

        // Initialize indentation variables (tab-width, indent-tabs-mode, etc.)
        super::indent::init_indent_vars(&mut obarray);

        let mut custom = CustomManager::new();

        // `case-fold-search` is DEFVAR_LISP + Fmake_variable_buffer_local
        // in GNU `buffer.c:5971-5975`. Install it as a LOCALIZED symbol
        // with `local_if_set = 1` at init time so reads/writes route
        // through the BLV + local_var_alist path instead of the legacy
        // `BufferLocals::lisp_bindings` fallback. Default is `t`.
        {
            let id = crate::emacs_core::intern::intern("case-fold-search");
            obarray.set_symbol_value("case-fold-search", Value::T);
            obarray.make_symbol_localized(id, Value::T);
            obarray.set_blv_local_if_set(id, true);
        }

        // `indent-tabs-mode` is DEFVAR_BOOL + make-variable-buffer-local
        // (bindings.el:1032). GNU's DEFVAR_BOOL installs a C-backed
        // forwarder; NeoMacs stores it as a plain Lisp value and
        // then hoists it to LOCALIZED at init. Default is `t`
        // (matches `init_indent_vars`).
        {
            let id = crate::emacs_core::intern::intern("indent-tabs-mode");
            obarray.make_symbol_localized(id, Value::T);
            obarray.set_blv_local_if_set(id, true);
        }

        super::textprop::init_textprop_vars(&mut obarray, &mut custom);
        super::syntax::init_syntax_vars(&mut obarray, &mut custom);
        // Register all DEFVAR_PER_BUFFER variables from GNU Emacs buffer.c.
        // These are C-level buffer-local variables that must exist before
        // any .el file loads.  Default values match init_buffer_once().
        macro_rules! defvar_per_buffer {
            ($name:expr, $val:expr) => {
                obarray.make_special($name);
                obarray.set_symbol_value($name, $val);
            };
        }
        {
            // Core buffer identity
            defvar_per_buffer!("buffer-file-name", Value::NIL);
            defvar_per_buffer!("buffer-file-truename", Value::NIL);
            // GNU buffer.c:5381 — default-directory defaults to cwd.
            // This sets the GLOBAL default; new buffers inherit it.
            {
                let cwd = std::env::current_dir()
                    .map(|p| {
                        let mut s = p.to_string_lossy().into_owned();
                        if !s.ends_with('/') {
                            s.push('/');
                        }
                        s
                    })
                    .unwrap_or_else(|_| "/".to_string());
                // GNU Emacs uses make_unibyte_string for default-directory
                // because the locale isn't set up yet during dump.  loadup.el
                // checks (multibyte-string-p default-directory) and errors
                // if it's multibyte.
                defvar_per_buffer!("default-directory", Value::unibyte_string(cwd));
            }
            defvar_per_buffer!("buffer-read-only", Value::NIL);
            defvar_per_buffer!("buffer-undo-list", Value::NIL);
            defvar_per_buffer!("buffer-saved-size", Value::fixnum(0));
            defvar_per_buffer!("buffer-backed-up", Value::NIL);
            defvar_per_buffer!("buffer-file-format", Value::NIL);
            defvar_per_buffer!("buffer-auto-save-file-name", Value::NIL);
            defvar_per_buffer!("buffer-auto-save-file-format", Value::T);
            defvar_per_buffer!("buffer-file-coding-system", Value::NIL);
            defvar_per_buffer!("buffer-display-count", Value::fixnum(0));
            defvar_per_buffer!("buffer-display-time", Value::NIL);

            // Modes
            defvar_per_buffer!("major-mode", Value::symbol("fundamental-mode"));
            defvar_per_buffer!("mode-name", Value::NIL);
            defvar_per_buffer!("mode-line-format", Value::string("%-"));
            defvar_per_buffer!("header-line-format", Value::NIL);
            defvar_per_buffer!("tab-line-format", Value::NIL);
            defvar_per_buffer!("local-abbrev-table", Value::NIL);
            defvar_per_buffer!("local-minor-modes", Value::NIL);
            defvar_per_buffer!("abbrev-mode", Value::NIL);
            defvar_per_buffer!("overwrite-mode", Value::NIL);
            defvar_per_buffer!("auto-fill-function", Value::NIL);

            // Lexical binding (GNU buffer.c DEFVAR_PER_BUFFER).
            // Default is nil; each file sets it from -*- cookie.
            defvar_per_buffer!("lexical-binding", Value::NIL);

            // Search (GNU buffer.c DEFVAR_PER_BUFFER)
            defvar_per_buffer!("case-fold-search", Value::T);
            defvar_per_buffer!("indent-tabs-mode", Value::T);

            // Display
            defvar_per_buffer!("tab-width", Value::fixnum(8));
            defvar_per_buffer!("fill-column", Value::fixnum(70));
            defvar_per_buffer!("left-margin", Value::fixnum(0));
            defvar_per_buffer!("truncate-lines", Value::NIL);
            defvar_per_buffer!("word-wrap", Value::NIL);
            defvar_per_buffer!("ctl-arrow", Value::T);
            defvar_per_buffer!("selective-display", Value::NIL);
            defvar_per_buffer!("selective-display-ellipses", Value::T);
            defvar_per_buffer!("enable-multibyte-characters", Value::T);
            defvar_per_buffer!("buffer-display-table", Value::NIL);
            defvar_per_buffer!("buffer-invisibility-spec", Value::NIL);
            defvar_per_buffer!("line-spacing", Value::NIL);
            defvar_per_buffer!("cache-long-scans", Value::T);
            defvar_per_buffer!("point-before-scroll", Value::NIL);

            // Cursor
            defvar_per_buffer!("cursor-type", Value::T);
            defvar_per_buffer!("cursor-in-non-selected-windows", Value::T);

            // Marks
            defvar_per_buffer!("mark-active", Value::NIL);

            // Bidi
            defvar_per_buffer!("bidi-display-reordering", Value::T);
            defvar_per_buffer!("bidi-paragraph-direction", Value::NIL);
            defvar_per_buffer!("bidi-paragraph-start-re", Value::NIL);
            defvar_per_buffer!("bidi-paragraph-separate-re", Value::NIL);

            // Fringes and margins
            defvar_per_buffer!("left-fringe-width", Value::NIL);
            defvar_per_buffer!("right-fringe-width", Value::NIL);
            defvar_per_buffer!("left-margin-width", Value::fixnum(0));
            defvar_per_buffer!("right-margin-width", Value::fixnum(0));
            defvar_per_buffer!("fringes-outside-margins", Value::NIL);
            defvar_per_buffer!("fringe-indicator-alist", Value::NIL);
            defvar_per_buffer!("fringe-cursor-alist", Value::NIL);
            defvar_per_buffer!("indicate-empty-lines", Value::NIL);
            defvar_per_buffer!("indicate-buffer-boundaries", Value::NIL);

            // Scroll bars
            defvar_per_buffer!("scroll-bar-width", Value::NIL);
            defvar_per_buffer!("scroll-bar-height", Value::NIL);
            defvar_per_buffer!("vertical-scroll-bar", Value::T);
            defvar_per_buffer!("horizontal-scroll-bar", Value::T);
            defvar_per_buffer!("scroll-up-aggressively", Value::NIL);
            defvar_per_buffer!("scroll-down-aggressively", Value::NIL);

            // Other
            defvar_per_buffer!("text-conversion-style", Value::NIL);

            // Phase 10B/C: install BUFFER_OBJFWD descriptors for
            // every entry in BUFFER_SLOT_INFO. After this point
            // each of these symbols has redirect=Forwarded with a
            // descriptor that resolves reads/writes to
            // `Buffer::slots[offset]`. The earlier
            // `defvar_per_buffer!` left them as LOCALIZED; we
            // overwrite that with the FORWARDED tag here so the
            // VM lookup/assign hot path takes the slot fast path.
            //
            // Mirrors GNU's `defvar_per_buffer` in `buffer.c`,
            // which always uses BUFFER_OBJFWD for these C-side
            // BVAR slots (`buffer.h:319-329`).
            {
                use crate::buffer::buffer::BUFFER_SLOT_INFO;
                use crate::emacs_core::forward::alloc_buffer_objfwd;
                use crate::emacs_core::intern::intern;

                for info in BUFFER_SLOT_INFO {
                    if !info.install_as_forwarder {
                        // Internal BVAR-only slot (syntax-table /
                        // category-table / case-table). Mirrors GNU's
                        // handling of `syntax_table_` etc. which
                        // occupy BVAR slot positions but are not
                        // DEFVAR_PER_BUFFER'd. Reads/writes happen
                        // exclusively through dedicated builtins.
                        continue;
                    }
                    let id = intern(info.name);
                    let predicate = if info.predicate.is_empty() {
                        intern("null")
                    } else {
                        intern(info.predicate)
                    };
                    let fwd = alloc_buffer_objfwd(
                        info.offset as u16,
                        info.local_flags_idx,
                        predicate,
                        info.default.to_value(),
                    );
                    obarray.install_buffer_objfwd(id, fwd);
                }
            }
        }

        // -----------------------------------------------------------------
        // C-level DEFVAR registrations: mirrors GNU's syms_of_*() functions.
        //
        // GNU Emacs declares hundreds of C-backed Lisp variables via
        // DEFVAR_LISP / DEFVAR_BOOL / DEFVAR_INT in its src/*.c files.
        // Each becomes a globally-visible symbol with a default value.
        // Elisp code reads/writes them freely; many are let-bound in
        // standard .el files during bootstrap and normal operation.
        //
        // If a variable is declared via DEFVAR in GNU's C code, it
        // MUST be registered here. Otherwise any elisp code that
        // reads or let-binds it will get void-variable.
        // -----------------------------------------------------------------

        // --- src/search.c: syms_of_search ---
        // DEFVAR_LISP, default nil. Let-bound extensively in subr.el,
        // custom.el, widget.el, mule.el, etc. to freeze match data
        // during internal string-match calls.
        obarray.set_symbol_value("inhibit-changing-match-data", Value::NIL);
        obarray.make_special("inhibit-changing-match-data");

        // --- src/casefiddle.c: syms_of_casefiddle ---
        // DEFVAR_BOOL + Fmake_variable_buffer_local, default 0 (nil).
        // Checked by case-conversion functions. Buffer-local via
        // make-variable-buffer-local (NOT defvar_per_buffer).
        {
            let id = crate::emacs_core::intern::intern("case-symbols-as-words");
            obarray.set_symbol_value("case-symbols-as-words", Value::NIL);
            obarray.make_symbol_localized(id, Value::NIL);
            obarray.set_blv_local_if_set(id, true);
        }

        // --- src/emacs.c: syms_of_emacs ---
        // DEFVAR_LISP, default nil. Run by kill-emacs.
        obarray.set_symbol_value("kill-emacs-hook", Value::NIL);
        obarray.make_special("kill-emacs-hook");

        // --- src/cmds.c: syms_of_cmds ---
        // DEFVAR_LISP, default nil. `newline' dynamically binds this in
        // simple.el so noninteractive newline insertion runs only its local
        // postprocessor, matching GNU Emacs.
        obarray.set_symbol_value("post-self-insert-hook", Value::NIL);
        obarray.make_special("post-self-insert-hook");

        let mut command_loop = crate::keyboard::CommandLoop::new();
        command_loop
            .keyboard
            .set_terminal_translation_maps(input_decode_map, local_function_key_map);
        let noninteractive = obarray
            .symbol_value_id_or_nil(core_eval_symbols.noninteractive_symbol)
            .is_truthy();
        let symbols_with_pos_enabled = obarray
            .symbol_value_id_or_nil(core_eval_symbols.symbols_with_pos_enabled_symbol)
            .is_truthy();
        let print_symbols_bare = obarray
            .symbol_value_id_or_nil(core_eval_symbols.print_symbols_bare_symbol)
            .is_truthy();
        let quit_flag = obarray.symbol_value_id_or_nil(core_eval_symbols.quit_flag_symbol);
        let inhibit_quit = obarray.symbol_value_id_or_nil(core_eval_symbols.inhibit_quit_symbol);

        let mut ev = Self {
            tagged_heap,
            pdump_image: None,
            obarray,
            specpdl: Vec::new(),
            lexenv: Value::NIL,
            internal_interpreter_environment_symbol: core_eval_symbols
                .internal_interpreter_environment_symbol,
            quit_flag_symbol: core_eval_symbols.quit_flag_symbol,
            inhibit_quit_symbol: core_eval_symbols.inhibit_quit_symbol,
            throw_on_input_symbol: core_eval_symbols.throw_on_input_symbol,
            kill_emacs_symbol: core_eval_symbols.kill_emacs_symbol,
            quit_flag,
            inhibit_quit,
            noninteractive_symbol: core_eval_symbols.noninteractive_symbol,
            noninteractive,
            symbols_with_pos_enabled_symbol: core_eval_symbols.symbols_with_pos_enabled_symbol,
            symbols_with_pos_enabled,
            print_symbols_bare_symbol: core_eval_symbols.print_symbols_bare_symbol,
            print_symbols_bare,
            features: Vec::new(),
            require_stack: Vec::new(),
            loads_in_progress: Vec::new(),
            buffers: BufferManager::new(),
            match_data: None,
            processes: ProcessManager::new(),
            timers: TimerManager::new(),
            watchers: VariableWatcherList::new(),
            standard_syntax_table,
            standard_category_table,
            current_local_map: Value::NIL,
            registers: RegisterManager::new(),
            bookmarks: BookmarkManager::new(),
            abbrevs: AbbrevManager::new(),
            autoloads: AutoloadManager::new(),
            custom,
            rectangle: RectangleState::new(),
            interactive: InteractiveRegistry::new(),
            treesit: super::treesit::TreeSitterManager::new(),
            minibuffers: MinibufferManager::new(),
            interactive_minibuffer_read_count: 0,
            current_message: None,
            minibuffer_selected_window: None,
            active_minibuffer_window: None,
            shutdown_request: None,
            input_mode_interrupt: true,
            quit_char: 7,
            waiting_for_user_input: false,
            frames: FrameManager::new(),
            modes: ModeRegistry::new(),
            threads: ThreadManager::new(),
            kmacro: KmacroManager::new(),
            command_loop,
            input_rx: None,
            #[cfg(unix)]
            wakeup_fd: None,
            quit_requested: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
            redisplay_fn: None,
            display_host: None,
            coding_systems: CodingSystemManager::new(),
            face_table: FaceTable::new(),
            face_change_count: 0,
            redisplay_generation: 0,
            last_redisplay_signature: None,
            depth: 0,
            eval_counter: 0,
            max_depth: 2400, // Matches GNU Emacs default (max-lisp-eval-depth)
            gc_pending: false,
            gc_count: 0,
            gc_inhibit_depth: 0,
            gc_stress: false,
            gc_runtime_settings_cache: GcRuntimeSettingsCache::default(),
            vm_root_frames: Vec::new(),
            bc_buf: Vec::with_capacity(4096),
            bc_frames: Vec::new(),
            condition_stack: Vec::new(),
            next_resume_id: 1,
            pending_safe_funcalls: Vec::new(),
            named_call_cache: HashMap::with_capacity(NAMED_CALL_CACHE_CAPACITY),
            lexenv_assq_cache: RefCell::new(LexenvAssqCache::default()),
            lexenv_special_cache: RefCell::new(LexenvSpecialCache::default()),

            macro_expansion_scope_depth: 0,
            macro_expansion_mutation_epoch: 0,
            macro_cache_hits: 0,
            macro_cache_misses: 0,
            macro_expand_total_us: 0,
            macro_cache_disabled: false,
            runtime_macro_expansion_cache: HashMap::new(),
            macro_perf_enabled: std::env::var_os("NEOVM_TRACE_MACRO_PERF").is_some(),
            macro_perf_stats: MacroPerfStats::default(),
            interpreted_closure_filter_fn: None,
            interpreted_closure_trim_cache: HashMap::new(),
            interpreted_closure_value_cache: HashMap::new(),
        };
        ev.finish_runtime_activation(false);
        ev
    }

    // -----------------------------------------------------------------------
    // pdump reconstruction
    // -----------------------------------------------------------------------

    /// Reconstruct an Context from pdump data.
    ///
    /// Thread-local heap pointers and caches must already be set by the caller
    /// before calling this.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn from_dump(
        tagged_heap: Box<crate::tagged::gc::TaggedHeap>,
        obarray: Obarray,
        lexenv: Value,
        features: Vec<SymId>,
        require_stack: Vec<SymId>,
        loads_in_progress: Vec<crate::heap_types::LispString>,
        buffers: BufferManager,
        autoloads: AutoloadManager,
        custom: CustomManager,
        modes: ModeRegistry,
        coding_systems: CodingSystemManager,
        face_table: FaceTable,
        abbrevs: AbbrevManager,
        interactive: InteractiveRegistry,
        rectangle: RectangleState,
        standard_syntax_table: Value,
        standard_category_table: Value,
        current_local_map: Value,
        kmacro: KmacroManager,
        registers: RegisterManager,
        bookmarks: BookmarkManager,
        watchers: VariableWatcherList,
    ) -> Self {
        let dumped_function_surface = obarray.clone();
        let mut obarray = obarray;
        let core_eval_symbols = install_core_eval_symbols(&mut obarray, false);
        let mut tagged_heap = tagged_heap;
        crate::tagged::gc::set_tagged_heap(&mut tagged_heap);
        let noninteractive = obarray
            .symbol_value_id_or_nil(core_eval_symbols.noninteractive_symbol)
            .is_truthy();
        let symbols_with_pos_enabled = obarray
            .symbol_value_id_or_nil(core_eval_symbols.symbols_with_pos_enabled_symbol)
            .is_truthy();
        let print_symbols_bare = obarray
            .symbol_value_id_or_nil(core_eval_symbols.print_symbols_bare_symbol)
            .is_truthy();
        let quit_flag = obarray.symbol_value_id_or_nil(core_eval_symbols.quit_flag_symbol);
        let inhibit_quit = obarray.symbol_value_id_or_nil(core_eval_symbols.inhibit_quit_symbol);

        let mut ev = Self {
            tagged_heap,
            pdump_image: None,
            obarray,
            specpdl: Vec::new(),
            lexenv,
            internal_interpreter_environment_symbol: core_eval_symbols
                .internal_interpreter_environment_symbol,
            quit_flag_symbol: core_eval_symbols.quit_flag_symbol,
            inhibit_quit_symbol: core_eval_symbols.inhibit_quit_symbol,
            throw_on_input_symbol: core_eval_symbols.throw_on_input_symbol,
            kill_emacs_symbol: core_eval_symbols.kill_emacs_symbol,
            quit_flag,
            inhibit_quit,
            noninteractive_symbol: core_eval_symbols.noninteractive_symbol,
            noninteractive,
            symbols_with_pos_enabled_symbol: core_eval_symbols.symbols_with_pos_enabled_symbol,
            symbols_with_pos_enabled,
            print_symbols_bare_symbol: core_eval_symbols.print_symbols_bare_symbol,
            print_symbols_bare,
            features,
            require_stack,
            loads_in_progress,
            buffers,
            match_data: None,
            processes: ProcessManager::new(),
            timers: TimerManager::new(),
            watchers,
            standard_syntax_table,
            standard_category_table,
            current_local_map,
            registers,
            bookmarks,
            abbrevs,
            autoloads,
            custom,
            rectangle,
            interactive,
            treesit: super::treesit::TreeSitterManager::new(),
            minibuffers: MinibufferManager::new(),
            interactive_minibuffer_read_count: 0,
            current_message: None,
            minibuffer_selected_window: None,
            active_minibuffer_window: None,
            shutdown_request: None,
            input_mode_interrupt: true,
            quit_char: 7,
            waiting_for_user_input: false,
            frames: FrameManager::new(),
            modes,
            threads: ThreadManager::new(),
            kmacro,
            command_loop: crate::keyboard::CommandLoop::new(),
            input_rx: None,
            #[cfg(unix)]
            wakeup_fd: None,
            quit_requested: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
            redisplay_fn: None,
            display_host: None,
            coding_systems,
            face_table,
            face_change_count: 0,
            redisplay_generation: 0,
            last_redisplay_signature: None,
            depth: 0,
            eval_counter: 0,
            max_depth: 2400,
            gc_pending: false,
            gc_count: 0,
            gc_inhibit_depth: 0,
            gc_stress: false,
            gc_runtime_settings_cache: GcRuntimeSettingsCache::default(),
            vm_root_frames: Vec::new(),
            bc_buf: Vec::with_capacity(4096),
            bc_frames: Vec::new(),
            condition_stack: Vec::new(),
            next_resume_id: 1,
            pending_safe_funcalls: Vec::new(),
            named_call_cache: HashMap::with_capacity(NAMED_CALL_CACHE_CAPACITY),
            lexenv_assq_cache: RefCell::new(LexenvAssqCache::default()),
            lexenv_special_cache: RefCell::new(LexenvSpecialCache::default()),

            macro_expansion_scope_depth: 0,
            macro_expansion_mutation_epoch: 0,
            macro_cache_hits: 0,
            macro_cache_misses: 0,
            macro_expand_total_us: 0,
            macro_cache_disabled: false,
            runtime_macro_expansion_cache: HashMap::new(),
            macro_perf_enabled: std::env::var_os("NEOVM_TRACE_MACRO_PERF").is_some(),
            macro_perf_stats: MacroPerfStats::default(),
            interpreted_closure_filter_fn: None,
            interpreted_closure_trim_cache: HashMap::new(),
            interpreted_closure_value_cache: HashMap::new(),
        };
        ev.initialize_gc_stack_bottom();
        ev.setup_thread_locals();

        // Rebuild the builtin subr registry after pdump restore. The dumped
        // obarray already carries the authoritative runtime function-cell
        // surface, so restore that surface immediately afterward.
        builtins::init_builtins(&mut ev);
        for (sym_id, symbol) in dumped_function_surface.iter_symbols() {
            if !symbol.function.is_nil() {
                ev.obarray.set_symbol_function_id(sym_id, symbol.function);
            } else if dumped_function_surface.is_function_unbound_id(sym_id) {
                ev.obarray.fmakunbound_id(sym_id);
            } else {
                ev.obarray.clear_function_silent_id(sym_id);
            }
        }

        ev.finish_runtime_activation(true);

        ev
    }

    pub(crate) fn install_pdump_image(&mut self, image: super::pdump::mmap_image::LoadedMmapImage) {
        self.pdump_image = Some(image);
    }

    #[cfg(test)]
    pub(crate) fn pdump_image_contains_ptr(&self, ptr: *const u8) -> bool {
        self.pdump_image
            .as_ref()
            .is_some_and(|image| image.contains_ptr(ptr))
    }

    // -----------------------------------------------------------------------
    // Garbage collection
    // -----------------------------------------------------------------------

    /// Enumerate every live `Value` reference in the evaluator and all
    /// sub-managers without materializing a single temporary root vector.
    fn trace_roots(&self, visit: &mut dyn FnMut(Value)) {
        for frame in &self.vm_root_frames {
            for root in frame.roots.iter().copied() {
                visit(root);
            }
        }
        for root in self.treesit.roots() {
            visit(root);
        }
        for root in self.bc_buf.iter().copied() {
            visit(root);
        }
        for frame in &self.bc_frames {
            if frame.fun.is_heap_object() {
                visit(frame.fun);
            }
        }
        for frame in &self.condition_stack {
            match frame {
                ConditionFrame::Catch { tag, .. } => visit(*tag),
                ConditionFrame::ConditionCase { conditions, .. } => visit(*conditions),
                ConditionFrame::HandlerBind {
                    conditions,
                    handler,
                    ..
                } => {
                    visit(*conditions);
                    visit(*handler);
                }
                ConditionFrame::SkipConditions { .. } => {}
            }
        }
        for entry in &self.specpdl {
            match entry {
                SpecBinding::Let {
                    old_value: Some(val),
                    ..
                } => visit(*val),
                SpecBinding::LetLocal { old_value, .. } => visit(*old_value),
                SpecBinding::LetDefault {
                    old_value: Some(val),
                    ..
                } => visit(*val),
                SpecBinding::LexicalEnv { old_lexenv } => visit(*old_lexenv),
                SpecBinding::GcRoot { value } => visit(*value),
                SpecBinding::Backtrace { function, args, .. } => {
                    visit(*function);
                    for arg in args.as_slice().iter().copied() {
                        visit(arg);
                    }
                }
                SpecBinding::UnwindProtect { forms, lexenv } => {
                    visit(*forms);
                    visit(*lexenv);
                }
                SpecBinding::SaveRestriction { state } => {
                    let mut roots = Vec::new();
                    state.trace_roots(&mut roots);
                    for root in roots {
                        visit(root);
                    }
                }
                SpecBinding::SaveExcursion { marker, .. } => visit(*marker),
                SpecBinding::SaveCurrentBuffer { .. } | SpecBinding::Nop => {}
                _ => {}
            }
        }
        visit(self.lexenv);
        visit(self.quit_flag);
        visit(self.inhibit_quit);
        for entry in self.runtime_macro_expansion_cache.values() {
            visit(entry.function);
            visit(entry.expanded);
        }
        for bucket in self.interpreted_closure_trim_cache.values() {
            for entry in bucket {
                visit(entry.params_value);
                visit(entry.body_value);
                visit(entry.iform_value);
                visit(entry.trimmed_params_value);
                visit(entry.trimmed_body_value);
            }
        }
        for bucket in self.interpreted_closure_value_cache.values() {
            for entry in bucket {
                visit(entry.source_function);
                visit(entry.trimmed_params_value);
                visit(entry.trimmed_body_value);
            }
        }
        if let Some(filter_fn) = self.interpreted_closure_filter_fn {
            visit(filter_fn);
        }
        for entry in self.named_call_cache.values() {
            if let NamedCallTarget::Obarray(val) = &entry.target {
                visit(*val);
            }
        }
        for funcall in &self.pending_safe_funcalls {
            visit(funcall.function);
            for arg in funcall.args.iter().copied() {
                visit(arg);
            }
        }
        let mut thread_local_roots = Vec::new();
        collect_thread_local_gc_roots(&mut thread_local_roots);
        for root in thread_local_roots {
            visit(root);
        }
        if !self.current_local_map.is_nil() {
            visit(self.current_local_map);
        }
        if self.standard_syntax_table.is_heap_object() {
            visit(self.standard_syntax_table);
        }
        if self.standard_category_table.is_heap_object() {
            visit(self.standard_category_table);
        }
        self.obarray.trace_roots_with(visit);
        self.processes.trace_roots_with(visit);
        self.timers.trace_roots_with(visit);
        self.watchers.trace_roots_with(visit);
        self.registers.trace_roots_with(visit);
        self.custom.trace_roots_with(visit);
        self.autoloads.trace_roots_with(visit);
        self.buffers.trace_roots_with(visit);
        self.face_table.trace_roots_with(visit);
        self.threads.trace_roots_with(visit);
        self.kmacro.trace_roots_with(visit);
        crate::gc_trace::GcTrace::trace_roots_with(&self.command_loop, visit);
        self.modes.trace_roots_with(visit);
        self.frames.trace_roots_with(visit);
        self.coding_systems.trace_roots_with(visit);
        if let Some(ref md) = self.match_data
            && let Some(crate::emacs_core::regex::SearchedString::Heap(val)) = &md.searched_string
        {
            visit(*val);
        }
    }

    /// Get the current GC threshold.
    pub fn gc_threshold(&self) -> usize {
        self.tagged_heap.gc_threshold()
    }

    fn is_gc_runtime_setting_symbol(sym_id: SymId) -> bool {
        sym_id == gc_cons_threshold_symbol()
            || sym_id == gc_cons_percentage_symbol()
            || sym_id == memory_full_symbol()
    }

    pub(crate) fn refresh_gc_runtime_settings_after_change_by_id(&mut self, sym_id: SymId) {
        if Self::is_gc_runtime_setting_symbol(sym_id) {
            self.refresh_gc_runtime_settings_cache();
            self.sync_gc_threshold_from_runtime_settings();
        }
    }

    fn refresh_gc_runtime_settings_cache(&mut self) {
        self.gc_runtime_settings_cache.gc_cons_threshold_bytes = self
            .obarray
            .symbol_value_id(gc_cons_threshold_symbol())
            .copied()
            .and_then(|value| value.as_fixnum())
            .and_then(|n| usize::try_from(n).ok())
            .unwrap_or(GC_DEFAULT_THRESHOLD_BYTES);
        self.gc_runtime_settings_cache.gc_cons_percentage_scaled = self
            .obarray
            .symbol_value_id_or_nil(gc_cons_percentage_symbol())
            .as_number_f64()
            .filter(|float| float.is_finite() && *float > 0.0)
            .map(|float| ((float * GC_PERCENT_SCALE as f64).ceil() as u64).clamp(1, u64::MAX));
        self.gc_runtime_settings_cache.memory_full = !self
            .obarray
            .symbol_value_id_or_nil(memory_full_symbol())
            .is_nil();
    }

    fn effective_gc_threshold_bytes(&mut self) -> usize {
        if self.gc_runtime_settings_cache.memory_full {
            return self.tagged_heap.gc_threshold();
        }

        let mut threshold = self
            .gc_runtime_settings_cache
            .gc_cons_threshold_bytes
            .max(GC_THRESHOLD_FLOOR_BYTES);
        if let Some(percentage_scaled) = self.gc_runtime_settings_cache.gc_cons_percentage_scaled {
            let live_estimate = self
                .tagged_heap
                .live_bytes()
                .saturating_add(self.tagged_heap.bytes_since_gc() / 2);
            let pct_threshold = ((live_estimate as u128)
                .saturating_mul(percentage_scaled as u128)
                .saturating_add((GC_PERCENT_SCALE - 1) as u128)
                / GC_PERCENT_SCALE as u128)
                .min(GC_HI_THRESHOLD_BYTES as u128) as usize;
            threshold = threshold.max(pct_threshold);
        }
        threshold.clamp(1, GC_HI_THRESHOLD_BYTES)
    }

    fn sync_gc_threshold_from_runtime_settings(&mut self) {
        let threshold = self.effective_gc_threshold_bytes();
        if self.tagged_heap.gc_threshold() != threshold {
            self.tagged_heap.set_gc_threshold_from_runtime(threshold);
        }
    }

    fn update_gc_runtime_stats(&mut self, elapsed: std::time::Duration) {
        self.obarray
            .set_symbol_value_id(gcs_done_symbol(), Value::fixnum(self.gc_count as i64));

        let old_elapsed = self
            .obarray
            .symbol_value_id(gc_elapsed_symbol())
            .copied()
            .and_then(|value| value.as_number_f64())
            .unwrap_or(0.0);
        self.obarray.set_symbol_value_id(
            gc_elapsed_symbol(),
            Value::make_float(old_elapsed + elapsed.as_secs_f64()),
        );
    }

    /// Set the GC threshold. Use usize::MAX to effectively disable GC.
    pub fn set_gc_threshold(&mut self, threshold: usize) {
        self.tagged_heap.set_gc_threshold(threshold);
    }

    /// Set the maximum eval recursion depth.
    pub fn set_max_depth(&mut self, depth: usize) {
        self.max_depth = depth;
    }

    /// Set the thread-local heap pointers for the current thread.
    ///
    /// Must be called when using an Context from a thread other than the one
    /// that created it (e.g., in worker thread pools).
    pub fn setup_thread_locals(&mut self) {
        crate::tagged::gc::set_tagged_heap(&mut self.tagged_heap);
        super::syntax::restore_standard_syntax_table_object(self.standard_syntax_table);
        super::category::restore_standard_category_table_object(self.standard_category_table);
        // Install this Context's quit-request flag so leaf functions
        // (regex matcher, other long-running scans) can poll it
        // without `&mut Context` access.
        QUIT_REQUESTED_TLS.with(|cell| {
            *cell.borrow_mut() = Some(std::sync::Arc::clone(&self.quit_requested));
        });
    }

    fn initialize_gc_stack_bottom(&mut self) {
        #[cfg(target_os = "linux")]
        {
            if let Some(stack_end) = crate::tagged::gc::read_stack_end_from_proc() {
                self.tagged_heap.set_stack_bottom(stack_end as *const u8);
            }
        }
    }

    fn finish_runtime_activation(&mut self, sync_keyboard: bool) {
        self.setup_thread_locals();
        self.refresh_gc_runtime_settings_cache();
        self.sync_gc_threshold_from_runtime_settings();
        if sync_keyboard {
            self.sync_keyboard_runtime_from_obarray();
        }
        self.sync_thread_runtime_bindings();
        self.sync_current_thread_buffer_state();
    }

    pub(crate) fn sync_current_thread_buffer_state(&mut self) {
        let current_thread_id = self.threads.current_thread_id();
        let current_buffer_id = self.buffers.current_buffer_id();
        self.threads
            .set_thread_current_buffer(current_thread_id, current_buffer_id);
    }

    fn sync_current_buffer_runtime_state(&mut self) -> Result<(), Flow> {
        self.sync_current_thread_buffer_state();
        super::casetab::sync_current_buffer_case_table_state(self)?;
        super::syntax::sync_current_buffer_syntax_table_state(self)?;
        Ok(())
    }

    pub(crate) fn switch_current_buffer(
        &mut self,
        id: crate::buffer::BufferId,
    ) -> Result<(), Flow> {
        if !self.buffers.switch_current(id) {
            return Err(signal(
                "error",
                vec![Value::string("Selecting deleted buffer")],
            ));
        }
        self.sync_current_buffer_runtime_state()
    }

    pub(crate) fn set_current_buffer_unrecorded(
        &mut self,
        id: crate::buffer::BufferId,
    ) -> Result<(), Flow> {
        if !self.buffers.switch_current_unrecorded(id) {
            return Err(signal(
                "error",
                vec![Value::string("Selecting deleted buffer")],
            ));
        }
        self.sync_current_buffer_runtime_state()
    }

    pub fn restore_current_buffer_if_live(&mut self, id: crate::buffer::BufferId) {
        if self.buffers.get(id).is_none() {
            return;
        }
        let _ = self.buffers.switch_current_unrecorded(id);
        let _ = self.sync_current_buffer_runtime_state();
    }

    /// Connect the input system for interactive mode.
    ///
    /// This mirrors GNU Emacs's `init_keyboard()` — it connects the evaluator
    /// to the render thread's input channel so that `read_char()` can block
    /// waiting for user input instead of returning immediately (batch mode).
    ///
    /// # Arguments
    /// * `input_rx` — Receiver end of the crossbeam channel from the render thread
    /// * `wakeup_fd` — Read end of the wakeup pipe (render thread writes to signal input)
    #[cfg(unix)]
    pub fn init_input_system(
        &mut self,
        input_rx: crossbeam_channel::Receiver<crate::keyboard::InputEvent>,
        wakeup_fd: std::os::unix::io::RawFd,
    ) {
        self.input_rx = Some(input_rx);
        self.wakeup_fd = Some(wakeup_fd);
        self.command_loop.running = true;
    }

    pub fn set_display_host(&mut self, host: Box<dyn DisplayHost>) {
        self.display_host = Some(host);
    }

    // -----------------------------------------------------------------------
    // Command loop (mirrors keyboard.c)
    // -----------------------------------------------------------------------

    /// Enter a recursive edit level.
    ///
    /// Mirrors GNU Emacs `Frecursive_edit()` (keyboard.c:772).
    /// Increments recursive depth, enters the command loop, decrements on exit.
    /// If the command loop exits via `abort-recursive-edit` (throw 'exit t),
    /// signals quit.  If via `exit-recursive-edit` (throw 'exit nil), returns
    /// normally.
    ///
    /// In batch mode (no input_rx), returns nil immediately.
    /// Enter a recursive edit level (public API).
    ///
    /// Returns `Ok(())` on normal exit, `Err(description)` on error.
    #[tracing::instrument(skip_all)]
    pub fn recursive_edit(&mut self) -> Result<(), String> {
        match self.recursive_edit_inner() {
            Ok(_) => Ok(()),
            Err(Flow::Signal(sig)) if sig.symbol == self.kill_emacs_symbol => Ok(()),
            Err(flow) => Err(format!("{:?}", flow)),
        }
    }

    pub(crate) fn request_shutdown(&mut self, exit_code: i32, restart: bool) {
        self.shutdown_request = Some(ShutdownRequest { exit_code, restart });
        self.command_loop.running = false;
    }

    pub fn shutdown_request(&self) -> Option<ShutdownRequest> {
        self.shutdown_request
    }

    #[tracing::instrument(skip_all, fields(depth = self.command_loop.recursive_depth, has_input = self.input_rx.is_some()))]
    pub(crate) fn recursive_edit_inner(&mut self) -> EvalResult {
        self.run_exit_wrapped_command_loop(true)
    }

    #[tracing::instrument(skip_all, fields(depth = self.command_loop.recursive_depth, has_input = self.input_rx.is_some()))]
    pub(crate) fn minibuffer_command_loop_inner(&mut self) -> EvalResult {
        self.run_exit_wrapped_command_loop(false)
    }

    fn run_exit_wrapped_command_loop(&mut self, increment_depth: bool) -> EvalResult {
        // Interactive command loops need an input source. Batch mode is
        // different: GNU still runs `top-level`/`normal-top-level` and lets
        // `read_char` terminate the loop via noninteractive EOF, even when
        // there is no input channel at all.
        if self.input_rx.is_none() && !self.command_loop_noninteractive() {
            tracing::info!("recursive_edit_inner: no input receiver, returning immediately");
            return Ok(Value::NIL);
        }

        // Recursive edits and minibuffer readers enter the command loop even
        // when the outer loop has not been started through init_input_system().
        // GNU's recursive/minibuffer entry points do not consult an external
        // "running" gate before dispatching the first key. Preserve the
        // previous flag so explicit shutdown still unwinds correctly.
        let saved_running = self.command_loop.running;
        if !saved_running {
            self.command_loop.running = true;
        }

        if increment_depth {
            self.command_loop.recursive_depth += 1;
        }

        // Register catch tag for 'exit (mirrors keyboard.c catch handler).
        let exit_tag = Value::symbol("exit");
        self.push_condition_frame(ConditionFrame::Catch {
            tag: exit_tag,
            resume: ResumeTarget::CommandLoopExit,
        });

        let result = self.command_loop_inner();

        self.pop_condition_frame();
        if increment_depth {
            self.command_loop.recursive_depth -= 1;
        }
        if !saved_running {
            self.command_loop.running = false;
        }

        match result {
            Ok(val) => Ok(val),
            // exit-recursive-edit: throw 'exit nil → normal return
            Err(Flow::Throw { ref tag, ref value }) if tag.is_symbol_named("exit") => {
                if value.is_truthy() {
                    // abort-recursive-edit: throw 'exit t → signal quit
                    Err(super::error::signal("quit", vec![]))
                } else {
                    Ok(Value::NIL)
                }
            }
            Err(flow) => Err(flow),
        }
    }

    /// Inner command loop with top-level catch.
    ///
    /// Mirrors GNU Emacs `command_loop()` (keyboard.c:1104).
    /// Wraps command_loop_2 in a catch for 'top-level.
    #[tracing::instrument(skip_all)]
    fn command_loop_inner(&mut self) -> EvalResult {
        let outermost_command_loop =
            self.command_loop.recursive_depth == 1 && self.minibuffers.depth() == 0;
        loop {
            // Catch 'top-level throws (from (top-level) function).
            let top_level_tag = Value::symbol("top-level");
            self.push_condition_frame(ConditionFrame::Catch {
                tag: top_level_tag,
                resume: ResumeTarget::CommandLoopTopLevel,
            });

            // GNU keyboard.c command_loop():
            //   internal_catch (Qtop_level, top_level_1, Qnil);
            //   internal_catch (Qtop_level, command_loop_2, Qerror);
            // Both top_level_1 and command_loop_2 run unconditionally per
            // outer loop iteration. The catch around top_level_1 turns any
            // 'top-level throw into a normal return so the next line — the
            // command_loop_2 catch — still runs. The previous NeoMacs
            // implementation gated command_loop_2 on
            // `self.command_loop.running`, which incorrectly skipped the
            // interactive loop entirely whenever (normal-top-level) raised
            // an error caught inside command_loop_top_level_1: the GUI
            // would create its window, hit the error, return Ok(NIL), and
            // immediately exit before the first redisplay. Match GNU and
            // always run command_loop_2 after top_level_1.
            let result = if outermost_command_loop {
                match self.command_loop_top_level_1() {
                    Ok(_) => self.command_loop_2(),
                    Err(Flow::Throw { ref tag, .. }) if tag.is_symbol_named("top-level") => {
                        // top-level throw inside top_level_1 — fall through
                        // to command_loop_2 just like GNU's two-catch flow.
                        self.command_loop_2()
                    }
                    Err(flow) => Err(flow),
                }
            } else {
                self.command_loop_2()
            };

            self.pop_condition_frame();

            match result {
                // top-level throw → restart the loop
                Err(Flow::Throw { ref tag, .. }) if tag.is_symbol_named("top-level") => {
                    tracing::debug!("command_loop_inner: top-level throw, restarting loop");
                    continue;
                }
                Ok(value) if outermost_command_loop && self.command_loop_noninteractive() => {
                    // GNU keyboard.c:1145 — end of file in batch run
                    tracing::info!("command_loop_inner: noninteractive EOF, calling kill-emacs");
                    match super::builtins::symbols::builtin_kill_emacs(self, vec![Value::T]) {
                        Err(Flow::Signal(sig)) if sig.symbol == self.kill_emacs_symbol => {}
                        Ok(_) => {}
                        Err(flow) => return Err(flow),
                    }
                    return Ok(value);
                }
                // Any other result propagates up
                other => {
                    tracing::debug!(
                        "command_loop_inner: result={:?}, propagating",
                        other.is_ok()
                    );
                    return other;
                }
            }
        }
    }

    fn command_loop_noninteractive(&self) -> bool {
        self.noninteractive
    }

    fn command_loop_top_level_1(&mut self) -> EvalResult {
        let top_level = self
            .obarray
            .symbol_value("top-level")
            .copied()
            .unwrap_or(Value::NIL);

        tracing::debug!("command_loop_top_level_1: top-level={}", top_level);

        if top_level.is_nil() {
            tracing::debug!("command_loop_top_level_1: top-level is nil, skipping");
            self.log_startup_state("top-level-nil");
            return Ok(Value::NIL);
        }

        tracing::debug!("command_loop_top_level_1: evaluating top-level form");
        self.log_startup_state("top-level-before");
        match self.eval_value(&top_level) {
            Ok(_) => {
                tracing::debug!("command_loop_top_level_1: top-level completed OK");
                self.log_startup_state("top-level-after");
                Ok(Value::NIL)
            }
            Err(Flow::Signal(sig)) => {
                if sig.symbol == self.kill_emacs_symbol {
                    return Err(Flow::Signal(sig));
                }
                tracing::warn!(
                    "command_loop_top_level_1: top-level SIGNALED: {} {:?}",
                    sig.symbol_name(),
                    sig.data
                );
                let data_str = sig
                    .data
                    .iter()
                    .map(|value| format!("{value}"))
                    .collect::<Vec<_>>()
                    .join(" ");
                let error_msg = if data_str.is_empty() {
                    sig.symbol_name().to_string()
                } else {
                    format!("{}: {}", sig.symbol_name(), data_str)
                };
                if cfg!(test) {
                    let last_phase = self
                        .obarray
                        .symbol_value("neomacs--startup-last-phase")
                        .copied()
                        .map(|value| crate::emacs_core::print_value_with_eval(self, &value))
                        .unwrap_or_else(|| "nil".to_string());
                    let last_call = self
                        .obarray
                        .symbol_value("neomacs--startup-last-call")
                        .copied()
                        .map(|value| crate::emacs_core::print_value_with_eval(self, &value))
                        .unwrap_or_else(|| "nil".to_string());
                    eprintln!(
                        "top-level startup signal: {} last-phase={} last-call={}",
                        error_msg, last_phase, last_call
                    );
                }
                let _ = super::builtins::dispatch_builtin(
                    self,
                    "message",
                    vec![Value::string(&error_msg)],
                );
                self.log_startup_state("top-level-signal");
                tracing::warn!("Top-level startup error: {}", error_msg);
                Ok(Value::NIL)
            }
            Err(flow) => Err(flow),
        }
    }

    fn trace_startup_state_enabled(&self) -> bool {
        std::env::var("NEOMACS_TRACE_STARTUP_STATE")
            .ok()
            .is_some_and(|value| value == "1")
    }

    fn log_startup_state(&self, phase: &str) {
        if !self.trace_startup_state_enabled() {
            return;
        }

        let current_buffer = self
            .buffers
            .current_buffer()
            .map(|buffer| buffer.name_runtime_string_owned())
            .unwrap_or_else(|| "<none>".to_string());
        let selected_frame = self.frames.selected_frame().map(|frame| {
            let selected_window_buffer = frame
                .selected_window()
                .and_then(|window| window.buffer_id())
                .and_then(|buffer_id| self.buffers.get(buffer_id))
                .map(|buffer| buffer.name_runtime_string_owned())
                .unwrap_or_else(|| "<missing>".to_string());
            format!(
                "id=0x{:x} size={}x{} selected-window=0x{:x} selected-window-buffer={}",
                frame.id.0,
                frame.width,
                frame.height,
                frame.selected_window.0,
                selected_window_buffer
            )
        });
        let frames = self
            .frames
            .frame_list()
            .into_iter()
            .map(|fid| format!("0x{:x}", fid.0))
            .collect::<Vec<_>>();

        tracing::info!(
            "startup-state phase={} command-line-args={} command-line-args-left={} command-line-processed={} window-system={} initial-window-system={} current-buffer={} selected-frame={:?} frames={:?}",
            phase,
            format_startup_value(self.obarray.symbol_value("command-line-args")),
            format_startup_value(self.obarray.symbol_value("command-line-args-left")),
            format_startup_value(self.obarray.symbol_value("command-line-processed")),
            format_startup_value(self.obarray.symbol_value("window-system")),
            format_startup_value(self.obarray.symbol_value("initial-window-system")),
            current_buffer,
            selected_frame,
            frames
        );
    }

    /// Command loop with error recovery.
    ///
    /// Mirrors GNU Emacs `command_loop_2()` (keyboard.c:1146).
    /// Wraps command_loop_1 with condition-case error handling.
    #[tracing::instrument(skip_all)]
    fn command_loop_2(&mut self) -> EvalResult {
        loop {
            match self.command_loop_1() {
                Ok(val) => return Ok(val),
                Err(flow @ Flow::Throw { .. }) => {
                    // Throws propagate (exit, top-level, etc.) without
                    // re-entering the command loop.  Re-running command_loop_1
                    // here traps minibuffer exit throws and blocks waiting for
                    // another key instead of unwinding like GNU Emacs.
                    return Err(flow);
                }
                Err(flow @ Flow::Signal(_))
                    if self
                        .command_loop
                        .keyboard
                        .kboard
                        .executing_kbd_macro
                        .is_some() =>
                {
                    return Err(flow);
                }
                Err(Flow::Signal(sig)) => {
                    // Error in command loop — display and restart.
                    // Mirrors cmd_error() in keyboard.c.
                    let sym_name = sig.symbol_name().to_string();
                    let error_msg = self.display_command_error(&sig);
                    tracing::error!("Command loop error: {}", error_msg);

                    // Clear prefix arg on error (like GNU Emacs)
                    self.assign("prefix-arg", Value::NIL);

                    // Ring the bell for quit signals
                    if sym_name == "quit" {
                        let _ = super::builtins::dispatch_builtin(self, "ding", vec![]);
                    }

                    // Restart the command loop.
                    continue;
                }
            }
        }
    }

    fn display_command_error(&mut self, sig: &SignalData) -> String {
        let error_data = make_signal_binding_value(sig);
        let error_msg =
            crate::emacs_core::errors::builtin_error_message_string(self, vec![error_data])
                .ok()
                .and_then(|value| value.as_runtime_string_owned())
                .unwrap_or_else(|| sig.symbol_name().to_string());
        let _ = super::builtins::dispatch_builtin(self, "message", vec![Value::string(&error_msg)]);
        error_msg
    }

    /// Main command loop — read key sequence, look up binding, execute.
    ///
    /// Mirrors GNU Emacs `command_loop_1()` (keyboard.c:1306).
    /// This is the core interactive loop: read → dispatch → redisplay.
    #[tracing::instrument(skip_all)]
    fn command_loop_1(&mut self) -> EvalResult {
        if !self.command_loop.running {
            return Ok(Value::NIL);
        }

        self.command_loop_1_entry_prologue()?;

        loop {
            if !self.command_loop.running {
                return Ok(Value::NIL);
            }

            self.flush_pending_safe_funcalls();
            self.sync_current_buffer_to_selected_window();

            if self.executing_kbd_macro_iteration_complete_for_command_loop() {
                self.assign("this-command", Value::NIL);
                return Ok(Value::NIL);
            }

            // Save the outgoing `current-prefix-arg` into
            // `last-prefix-arg` before reading the next command.
            //
            // Do NOT also transfer `prefix-arg` here: GNU's Lisp
            // `command-execute` does that itself right before it
            // calls `call-interactively`, and prefix commands such as
            // `universal-argument` rely on `prefix-arg` surviving
            // until that point.
            let outgoing_prefix_arg = self.eval_symbol("current-prefix-arg").unwrap_or(Value::NIL);
            self.assign("last-prefix-arg", outgoing_prefix_arg);

            // Read a complete key sequence (may be multi-key, e.g. C-x C-f).
            let (keys, binding) = self.read_key_sequence()?;
            self.sync_current_buffer_to_selected_window();

            if keys.is_empty() && binding.is_nil() {
                self.assign("this-command", Value::NIL);
                return Ok(Value::NIL);
            }

            if binding.is_nil() {
                // Undefined key sequence — reset prefix arg
                self.assign("prefix-arg", Value::NIL);
                let desc: Vec<String> = keys.iter().map(|v| format!("{:?}", v)).collect();
                tracing::info!("Undefined key sequence: {}", desc.join(" "));
                continue;
            }

            // Set this-command, real-this-command, last-command-event,
            // this-command-keys. Mirrors GNU `keyboard.c:1336-1353`:
            //
            //   Vreal_last_command = KVAR (current_kboard, Vreal_last_command);
            //   Vreal_this_command = cmd;
            //   /* Now do the remap. */
            //   cmd = Fcommand_remapping (cmd, Qnil, Qnil);
            //   ...
            //   Vthis_command = cmd;
            //   if (NILP (Vthis_original_command))
            //     Vthis_original_command = cmd;
            //
            // Keyboard audit Findings 1, 2, 3, 4 in
            // `drafts/keyboard-command-loop-audit.md`.
            tracing::info!("command_loop_1: dispatching binding={}", binding);

            // Snapshot the previous this-command into real-last-command
            // before we overwrite (Finding 3 — GNU
            // `keyboard.c:1336-1339`).
            let previous_this_command = self.eval_symbol("this-command").unwrap_or(Value::NIL);
            self.assign("real-last-command", previous_this_command);

            // The unmapped command (real-this-command) is the binding
            // we read from the keymap, before any remapping is applied.
            self.assign("real-this-command", binding);

            // Apply command remapping per GNU
            // `keyboard.c:1340-1343`. The remapped command becomes
            // this-command for execution. Finding 4.
            let remapped = self.command_remapping_for_loop(binding);
            self.assign("this-command", remapped);

            // Finding 2: this-original-command stays at the original
            // (pre-remap) command for the duration of the iteration
            // unless a pre-command-hook explicitly cleared it.
            if self
                .eval_symbol("this-original-command")
                .unwrap_or(Value::NIL)
                .is_nil()
            {
                self.assign("this-original-command", binding);
            }

            if let Some(last) = keys.last() {
                self.assign("last-command-event", *last);
            }
            tracing::debug!(
                "command_loop_1: binding={} current_buffer={:?} active_minibuffer_window={:?}",
                self.this_command_name_for_log(),
                self.buffers.current_buffer_id(),
                self.active_minibuffer_window
            );

            // Run pre-command-hook via safe-run-hooks so a broken
            // hook function is removed instead of re-firing on every
            // command. Finding 7 — GNU `keyboard.c:1361`
            // (`safe_run_hooks (Qpre_command_hook)`).
            self.safe_run_hook_if_bound("pre-command-hook")?;

            // GNU `keyboard.c:1530-1534` adds undo boundaries here, after
            // `pre-command-hook` and before command execution, so the
            // previous command's edits are grouped before the next command
            // mutates any buffer state.
            if self.obarray.fboundp("undo-auto--add-boundary") {
                let _ = self.apply(Value::symbol("undo-auto--add-boundary"), vec![]);
            }

            // Execute the command. GNU keyboard.c dispatches through
            // `command-execute` from the loop, so we do the same here
            // instead of bypassing the Lisp-side wrapper. That keeps
            // disabled-command handling and related command-execute
            // behavior aligned with GNU for real keyboard invocations.
            self.record_recent_command(remapped);
            let exec_result = self.dispatch_command_in_loop(binding);

            // Keep the selected window's point and current buffer/runtime view
            // aligned before post-command work and redisplay observe state.
            self.sync_current_buffer_to_selected_window();

            if let Err(ref flow) = exec_result {
                match flow {
                    Flow::Throw { .. } => return exec_result,
                    Flow::Signal(_)
                        if self
                            .command_loop
                            .keyboard
                            .kboard
                            .executing_kbd_macro
                            .is_some() =>
                    {
                        return exec_result;
                    }
                    Flow::Signal(sig) => {
                        let error_msg = self.display_command_error(sig);
                        tracing::warn!("Command error: ({}): {}", sig.symbol_name(), error_msg);
                    }
                }
            }

            // Update last-command (GNU `keyboard.c:1473`).
            if let Ok(this_cmd) = self.eval_symbol("this-command") {
                self.assign("last-command", this_cmd);
            }

            // Update last-repeatable-command per GNU
            // `keyboard.c:1467-1470`. Finding 3.
            //
            //   KVAR (current_kboard, Vlast_repeatable_command)
            //     = (EQ (Vreal_this_command, Qself_insert_command)
            //        ? Vreal_last_command
            //        : Vreal_this_command);
            let real_this = self.eval_symbol("real-this-command").unwrap_or(Value::NIL);
            let is_self_insert = real_this
                .as_symbol_name()
                .is_some_and(|n| n == "self-insert-command");
            let last_repeatable = if is_self_insert {
                self.eval_symbol("real-last-command").unwrap_or(Value::NIL)
            } else {
                real_this
            };
            self.assign("last-repeatable-command", last_repeatable);

            // GNU runs deactivate-mark handling BEFORE
            // post-command-hook (`keyboard.c:1471-1484`), so the
            // hook sees the post-deactivate state. Finding 14.
            let _ = self.update_active_region_selection_after_command();

            // Run post-command-hook via safe-run-hooks (Finding 7).
            self.safe_run_hook_if_bound("post-command-hook")?;

            // Reset this-original-command for the next iteration so
            // a fresh command starts the cycle clean (mirroring
            // GNU's clear at the bottom of command_loop_1).
            self.assign("this-original-command", Value::NIL);

            if exec_result.is_ok()
                && self.command_loop.keyboard.kboard.defining_kbd_macro
                && self
                    .eval_symbol("prefix-arg")
                    .unwrap_or(Value::NIL)
                    .is_nil()
            {
                self.finalize_kbd_macro_runtime_chars();
            }

            // Keyboard audit Finding 9: auto-save-interval check.
            // GNU `keyboard.c:1491-1506`:
            //
            //   if (INTEGERP (Vauto_save_interval)
            //       && num_nonmacro_input_events - last_auto_save
            //          > max (XFIXNUM (Vauto_save_interval), 20)
            //       && !detect_input_pending_run_timers (0))
            //     {
            //       Fdo_auto_save (Qnil, Qnil);
            //       last_auto_save = num_nonmacro_input_events;
            //       ...
            //     }
            //
            // The lower floor of 20 prevents saving too often if
            // a user sets `auto-save-interval` to a tiny value.
            // The `detect_input_pending` gate defers the save
            // when the user is typing faster than the check
            // interval — we approximate that with a "no pending
            // events in the unread queue" probe.
            self.command_loop_1_maybe_auto_save();
        }
    }

    /// One-time entry prologue for `command_loop_1`.
    ///
    /// GNU `keyboard.c:1313-1349` runs this before the first
    /// `read_key_sequence` after entering `command_loop_1`, not after the
    /// first command. Doom relies on that ordering: it sets
    /// `inhibit-redisplay` during startup and clears it from an initial
    /// `post-command-hook` before the first input wait/redisplay.
    fn command_loop_1_entry_prologue(&mut self) -> EvalResult {
        self.assign("prefix-arg", Value::NIL);
        self.assign("last-prefix-arg", Value::NIL);
        self.assign("deactivate-mark", Value::NIL);

        if self
            .eval_symbol("memory-full")
            .unwrap_or(Value::NIL)
            .is_nil()
        {
            self.safe_run_hook_if_bound("post-command-hook")?;

            if self
                .eval_symbol("delayed-warnings-list")
                .unwrap_or(Value::NIL)
                .is_truthy()
            {
                self.safe_run_hook_if_bound("delayed-warnings-hook")?;
            }
        }

        let this_command = self.eval_symbol("this-command").unwrap_or(Value::NIL);
        self.assign("last-command", this_command);

        let real_this_command = self.eval_symbol("real-this-command").unwrap_or(Value::NIL);
        self.assign("real-last-command", real_this_command);

        let last_command_event = self.eval_symbol("last-command-event").unwrap_or(Value::NIL);
        if !last_command_event.is_cons() {
            self.assign("last-repeatable-command", real_this_command);
        }

        Ok(Value::NIL)
    }

    /// Per-iteration `auto-save-interval` check, mirroring GNU
    /// `keyboard.c:1491-1506`. Keyboard audit Finding 9.
    fn command_loop_1_maybe_auto_save(&mut self) {
        let interval = match self.eval_symbol("auto-save-interval").ok() {
            Some(v) => match v.as_fixnum() {
                Some(n) if n > 0 => n as u64,
                _ => return,
            },
            None => return,
        };
        let threshold = interval.max(20);
        let current = self.command_loop.num_nonmacro_input_events;
        let last = self.command_loop.last_auto_save_input_events;
        if current.saturating_sub(last) <= threshold {
            return;
        }
        // Defer if input is pending (same spirit as GNU's
        // `detect_input_pending_run_timers (0)` gate). A fast
        // typist should not be interrupted by a save.
        if self.input_pending_for_auto_save() {
            return;
        }
        // Record the attempt *before* calling do-auto-save so a
        // throw/signal from the save doesn't loop the check on
        // every iteration. GNU writes `last_auto_save` after the
        // call but also swallows errors via cmd_error; setting
        // it first is safer in our flow-based error model.
        self.command_loop.last_auto_save_input_events = current;
        if let Err(flow) = self.apply(Value::symbol("do-auto-save"), vec![Value::NIL, Value::NIL]) {
            tracing::warn!("auto-save from command_loop_1 failed: {:?}", flow);
        }
    }

    /// Approximation of GNU `detect_input_pending_run_timers (0)`
    /// used by the command-loop auto-save gate. Returns true when
    /// there is already-queued input that should run before an
    /// expensive auto-save.
    fn input_pending_for_auto_save(&self) -> bool {
        if self.peek_unread_command_event().is_some() {
            return true;
        }
        !self.command_loop.keyboard.pending_input_events.is_empty()
    }

    /// Apply `command-remapping` for the command-loop dispatch
    /// path. Mirrors GNU `keyboard.c:1340-1343` calling
    /// `Fcommand_remapping (cmd, Qnil, Qnil)` and substituting the
    /// result when non-nil. Keyboard audit Finding 4.
    fn command_remapping_for_loop(&mut self, command: Value) -> Value {
        if command.is_nil() {
            return command;
        }
        match self.apply(Value::symbol("command-remapping"), vec![command]) {
            Ok(remapped) if !remapped.is_nil() => remapped,
            _ => command,
        }
    }

    /// Dispatch the current `this-command` via GNU's
    /// `command-execute` command-loop path.
    fn dispatch_command_in_loop(&mut self, command: Value) -> EvalResult {
        // Re-resolve `this-command` from the obarray so a
        // pre-command-hook that mutated the symbol takes effect.
        let cmd = self.eval_symbol("this-command").unwrap_or(command);
        if cmd.is_nil() {
            return Ok(Value::NIL);
        }
        self.apply(Value::symbol("command-execute"), vec![cmd])
    }

    /// Run a hook with `safe-run-hooks` semantics: each hook
    /// function is wrapped in a `condition-case` so a broken
    /// function is removed from the hook instead of re-firing on
    /// every subsequent command. Mirrors GNU
    /// `safe_run_hooks (Qhook_name)` at
    /// `src/keyboard.c:1361,1485` and `src/eval.c:2779-2830`.
    /// Keyboard audit Finding 7.
    fn safe_run_hook_if_bound(&mut self, hook_name: &str) -> EvalResult {
        // GNU `keyboard.c:1970-1978` (`safe_run_hooks`):
        //
        //   void safe_run_hooks (Lisp_Object hook) {
        //     specbind (Qinhibit_quit, Qt);
        //     run_hook_with_args (2, {hook, hook}, safe_run_hook_funcall);
        //     unbind_to (count, Qnil);
        //   }
        //
        // This is a C function — NOT the Lisp `safe-run-hooks` from
        // `subr.el`. It calls `run_hook_with_args` with a custom
        // funcall wrapper (`safe_run_hook_funcall`) that wraps each
        // hook function in `internal_condition_case_n` and removes
        // broken entries on error.
        //
        // neomacs mirrors this by calling
        // `hook_runtime::safe_run_named_hook` directly from Rust,
        // which resolves the hook value (including buffer-local
        // bindings + the `t` global marker), calls each hook
        // function, and swallows Signal errors. This never goes
        // through Lisp — matching GNU's keyboard.c which calls the
        // C function, not the Lisp wrapper.
        let hook_sym = super::intern::intern(hook_name);
        // `safe_run_hook_funcall` only swallows ordinary `error`
        // signals.  Nonlocal exits like `throw`/`quit` still escape
        // the command loop, and `read-char-from-minibuffer` relies on
        // that when its local `post-command-hook` calls
        // `exit-minibuffer`.
        super::hook_runtime::safe_run_named_hook(self, hook_sym, &[])
    }

    fn executing_kbd_macro_iteration_complete_for_command_loop(&self) -> bool {
        matches!(
            self.command_loop.keyboard.kboard.executing_kbd_macro.as_ref(),
            Some(events) if self.command_loop.keyboard.kboard.kbd_macro_index >= events.len()
        ) && self
            .command_loop
            .keyboard
            .kboard
            .unread_selection_event
            .is_none()
            && self.command_loop.keyboard.kboard.unread_events.is_empty()
    }

    pub(crate) fn execute_kbd_macro_iteration_via_command_loop(&mut self) -> EvalResult {
        let saved_running = self.command_loop.running;
        if !saved_running {
            self.command_loop.running = true;
        }
        self.assign("prefix-arg", Value::NIL);
        let result = self.command_loop_2();
        if !saved_running && self.command_loop.running {
            self.command_loop.running = false;
        }
        result
    }

    pub(crate) fn with_executing_kbd_macro_runtime<F>(
        &mut self,
        macro_events: Vec<Value>,
        run: F,
    ) -> EvalResult
    where
        F: FnOnce(&mut Self) -> EvalResult,
    {
        let scope = ExecutingKbdMacroRuntimeScope {
            snapshot: self.snapshot_executing_kbd_macro_runtime(),
            real_this_command: self.eval_symbol("real-this-command").unwrap_or(Value::NIL),
        };
        self.begin_executing_kbd_macro_runtime(macro_events);
        let result = run(self);
        let cleanup = self.finish_executing_kbd_macro_runtime_scope(scope);
        match cleanup {
            Ok(v) if v.is_nil() => result,
            Ok(other) => Ok(other),
            Err(flow) => Err(flow),
        }
    }

    pub(crate) fn reset_executing_kbd_macro_runtime_iteration(&mut self) {
        self.set_executing_kbd_macro_runtime_index(0);
    }

    fn finish_executing_kbd_macro_runtime_scope(
        &mut self,
        scope: ExecutingKbdMacroRuntimeScope,
    ) -> EvalResult {
        self.restore_executing_kbd_macro_runtime(scope.snapshot);
        self.assign("real-this-command", scope.real_this_command);
        self.run_hook_if_bound("kbd-macro-termination-hook")
    }

    fn pending_gnu_timer(timer: Value) -> Option<PendingGnuTimer> {
        if !timer.is_vector() {
            return None;
        };

        let slots = timer.as_vector_data()?.clone();
        if !(9..=10).contains(&slots.len()) {
            return None;
        }

        if !slots[0].is_nil() {
            return None;
        }

        if !slots[7].is_nil() {
            // Idle timers remain on the GNU Lisp path, but NeoVM still does
            // not track GUI/TTY idleness with GNU's fidelity yet. Avoid
            // conflating ordinary timer behavior with partial idle semantics.
            return None;
        }

        Some(PendingGnuTimer {
            timer,
            when: GnuTimerTimestamp {
                high_seconds: slots[1].as_int()?,
                low_seconds: slots[2].as_int()?,
                usecs: slots[3].as_int()?,
                psecs: slots.get(8).and_then(|v| v.as_int()).unwrap_or(0),
            },
        })
    }

    fn pending_gnu_idle_timer(timer: Value) -> Option<PendingGnuTimer> {
        if !timer.is_vector() {
            return None;
        };

        let slots = timer.as_vector_data()?.clone();
        if !(9..=10).contains(&slots.len()) {
            return None;
        }

        if !slots[0].is_nil() {
            return None;
        }

        if slots[7].is_nil() {
            return None;
        }

        Some(PendingGnuTimer {
            timer,
            when: GnuTimerTimestamp {
                high_seconds: slots[1].as_int()?,
                low_seconds: slots[2].as_int()?,
                usecs: slots[3].as_int()?,
                psecs: slots.get(8).and_then(|v| v.as_int()).unwrap_or(0),
            },
        })
    }

    /// Run a named hook if it is bound and non-nil.
    pub(crate) fn run_hook_if_bound(&mut self, hook_name: &str) -> EvalResult {
        match self.eval_symbol(hook_name) {
            Ok(hook_val) if !hook_val.is_nil() => {
                // (run-hooks 'HOOK)
                super::builtins::dispatch_builtin(self, "run-hooks", vec![Value::symbol(hook_name)])
                    .unwrap_or(Ok(Value::NIL))
            }
            _ => Ok(Value::NIL),
        }
    }

    pub(crate) fn queue_pending_safe_funcall(&mut self, function: Value, args: Vec<Value>) {
        self.pending_safe_funcalls.push(PendingSafeFuncall {
            function,
            args: args.into_iter().collect(),
        });
    }

    pub(crate) fn queue_pending_safe_hook(&mut self, hook_name: &str, args: &[Value]) {
        self.queue_pending_safe_funcall(
            Value::symbol("run-hook-with-args"),
            std::iter::once(Value::symbol(hook_name))
                .chain(args.iter().copied())
                .collect(),
        );
    }

    pub(crate) fn flush_pending_safe_funcalls(&mut self) {
        while let Some(funcall) = self.pending_safe_funcalls.pop() {
            let _ = self.apply(funcall.function, funcall.args);
        }
    }

    fn update_active_region_selection_after_command(&mut self) -> EvalResult {
        if self
            .eval_symbol("mark-active")
            .unwrap_or(Value::NIL)
            .is_nil()
        {
            return Ok(Value::NIL);
        }

        let transient_mark_mode = self
            .eval_symbol("transient-mark-mode")
            .unwrap_or(Value::NIL);
        if transient_mark_mode == Value::symbol("identity") {
            self.assign("transient-mark-mode", Value::NIL);
        } else if transient_mark_mode == Value::symbol("only") {
            self.assign("transient-mark-mode", Value::symbol("identity"));
        }

        if !self
            .eval_symbol("deactivate-mark")
            .unwrap_or(Value::NIL)
            .is_nil()
        {
            let _ = self.apply(Value::symbol("deactivate-mark"), vec![])?;
            self.assign("saved-region-selection", Value::NIL);
            return Ok(Value::NIL);
        }

        if self
            .apply(Value::symbol("display-selections-p"), vec![])?
            .is_nil()
        {
            self.assign("saved-region-selection", Value::NIL);
            return Ok(Value::NIL);
        }

        if self
            .eval_symbol("select-active-regions")
            .unwrap_or(Value::NIL)
            .is_nil()
        {
            self.assign("saved-region-selection", Value::NIL);
            return Ok(Value::NIL);
        }

        if self
            .apply(Value::symbol("region-active-p"), vec![])?
            .is_nil()
        {
            self.assign("saved-region-selection", Value::NIL);
            return Ok(Value::NIL);
        }

        let this_command = self.eval_symbol("this-command").unwrap_or(Value::NIL);
        let inhibited_commands = self
            .eval_symbol("selection-inhibit-update-commands")
            .unwrap_or(Value::NIL);
        if self
            .apply(
                Value::symbol("memq"),
                vec![this_command, inhibited_commands],
            )?
            .is_truthy()
        {
            self.assign("saved-region-selection", Value::NIL);
            return Ok(Value::NIL);
        }

        let region_extract = self
            .eval_symbol("region-extract-function")
            .unwrap_or(Value::symbol("buffer-substring"));
        let text = self.apply(region_extract, vec![Value::NIL])?;
        let text_len = match self.apply(Value::symbol("length"), vec![text])?.kind() {
            ValueKind::Fixnum(len) => len,
            _ => 0,
        };
        if text_len > 0 {
            let _ = self.apply(
                Value::symbol("gui-set-selection"),
                vec![Value::symbol("PRIMARY"), text],
            )?;
        }
        let _ = super::builtins::dispatch_builtin(
            self,
            "run-hook-with-args",
            vec![Value::symbol("post-select-region-hook"), text],
        )
        .unwrap_or(Ok(Value::NIL))?;
        self.assign("saved-region-selection", Value::NIL);
        Ok(Value::NIL)
    }

    /// Trigger redisplay — calls the layout engine and sends frame to render thread.
    ///
    /// Mirrors GNU Emacs `redisplay()` (dispnew.c:5259).
    /// In batch mode (no callback), this is a no-op.
    pub(crate) fn redisplay(&mut self) {
        self.redisplay_with_force(false);
    }

    pub(crate) fn redisplay_for_input_wait(&mut self) {
        self.redisplay_with_force(false);
    }

    pub(crate) fn invalidate_redisplay(&mut self) {
        self.redisplay_generation = self.redisplay_generation.wrapping_add(1);
        self.last_redisplay_signature = None;
    }

    pub(crate) fn redisplay_with_force(&mut self, force: bool) {
        // Mirrors GNU `redisplay_internal` (xdisp.c:17242-17245): bail out
        // when `inhibit-redisplay` is non-nil. `run_window_change_functions`
        // (window.c:4116) specbinds this to t so any nested redisplay
        // triggered by a window-change hook is a no-op. Without this check
        // a hook that indirectly calls `redisplay` infinitely recurses.
        let inhibit_redisplay = self.obarray.symbol_value("inhibit-redisplay");
        if !force && inhibit_redisplay.as_ref().is_some_and(|v| v.is_truthy()) {
            tracing::debug!(
                "redisplay inhibited by inhibit-redisplay={}",
                inhibit_redisplay.as_ref().unwrap()
            );
            return;
        }
        self.sync_pending_resize_events();
        // GNU Emacs xdisp.c:20616 — sync selected window's pointm from
        // the buffer's current PT before redisplay.  NeoMacs Window::point
        // is a plain usize, not a marker, so it doesn't auto-update.
        // Only sync when the buffer has been modified (to avoid breaking
        // the initial render where window.point=1 is correct).
        if let Some(buffer) = self.buffers.current_buffer() {
            if buffer.is_modified() {
                let pt = buffer.point_char();
                if let Some(frame) = self.frames.selected_frame_mut() {
                    if let Some(win) = frame.selected_window_mut() {
                        win.set_point(pt);
                    }
                }
            }
        }
        let before_signature = self.redisplay_signature();
        if !force && self.last_redisplay_signature.as_ref() == Some(&before_signature) {
            tracing::debug!("redisplay skipped: visible state unchanged");
            return;
        }
        let has_fn = self.redisplay_fn.is_some();
        tracing::debug!("redisplay called (has_fn={})", has_fn);
        if let Some(mut f) = self.redisplay_fn.take() {
            let saved = self.buffers.reset_outermost_restrictions();
            f(self);
            let _ = super::builtins::run_redisplay_window_change_hooks(self);
            self.buffers.restore_outermost_restrictions(saved);
            self.redisplay_fn = Some(f);
        } else {
            let _ = super::builtins::run_redisplay_window_change_hooks(self);
        }
        self.last_redisplay_signature = Some(self.redisplay_signature());
    }

    fn redisplay_signature(&self) -> RedisplaySignature {
        let selected_frame = self.frames.selected_frame().map(|frame| frame.id.0);
        let selected_window = self
            .frames
            .selected_frame()
            .map(|frame| frame.selected_window.0);
        let frame = self.frames.selected_frame().map(|frame| {
            let mut window_ids = frame.window_list();
            if let Some(minibuffer_window) = frame.minibuffer_window {
                window_ids.push(minibuffer_window);
            }
            let mut windows = Vec::with_capacity(window_ids.len());
            for window_id in window_ids {
                let Some(window) = frame.find_window(window_id) else {
                    continue;
                };
                let Some(state) = window.redisplay_state() else {
                    continue;
                };
                windows.push(RedisplayWindowSignature {
                    id: state.id.0,
                    buffer_id: state.buffer_id.0,
                    bounds: state.bounds,
                    window_start: state.window_start,
                    window_end_pos: state.window_end_pos,
                    window_end_bytepos: state.window_end_bytepos,
                    window_end_vpos: state.window_end_vpos,
                    window_end_valid: state.window_end_valid,
                    point: state.point,
                    old_point: state.old_point,
                    hscroll: state.hscroll,
                    vscroll: state.vscroll,
                    preserve_vscroll_p: state.preserve_vscroll_p,
                    buffer: self.redisplay_buffer_signature(state.buffer_id),
                });
            }
            RedisplayFrameSignature {
                id: frame.id.0,
                width: frame.width,
                height: frame.height,
                char_width: redisplay_f32_bits(frame.char_width),
                char_height: redisplay_f32_bits(frame.char_height),
                font_pixel_size: redisplay_f32_bits(frame.font_pixel_size),
                visible: frame.visible,
                selected_window: frame.selected_window.0,
                window_state_change: frame.window_state_change,
                windows,
            }
        });
        RedisplaySignature {
            selected_frame,
            selected_window,
            current_buffer: self.buffers.current_buffer_id().map(|id| id.0),
            current_message: self.current_message.clone(),
            active_minibuffer_window: self.active_minibuffer_window.map(|id| id.0),
            minibuffer_selected_window: self.minibuffer_selected_window.map(|id| id.0),
            face_change_count: self.face_change_count,
            obarray_function_epoch: self.obarray.function_epoch(),
            redisplay_generation: self.redisplay_generation,
            frame,
        }
    }

    fn redisplay_buffer_signature(
        &self,
        id: crate::buffer::BufferId,
    ) -> Option<RedisplayBufferSignature> {
        let buffer = self.buffers.get(id)?;
        Some(RedisplayBufferSignature {
            id: buffer.id.0,
            modified_tick: buffer.modified_tick(),
            chars_modified_tick: buffer.chars_modified_tick(),
            save_modified_tick: buffer.save_modified_tick(),
            autosave_modified_tick: buffer.autosave_modified_tick,
            point: buffer.point_char(),
            point_byte: buffer.point_byte(),
            begv: buffer.begv,
            begv_byte: buffer.begv_byte,
            zv: buffer.zv,
            zv_byte: buffer.zv_byte,
            total_chars: buffer.total_chars(),
            total_bytes: buffer.total_bytes(),
            last_window_start: buffer.last_window_start,
            last_selected_window: buffer.last_selected_window.map(|id| id.0),
        })
    }

    fn this_command_name_for_log(&self) -> String {
        self.eval_symbol("this-command")
            .map(|value| format!("{}", value))
            .unwrap_or_else(|_| "<unbound>".to_string())
    }

    /// Perform a full mark-and-sweep garbage collection.
    #[tracing::instrument(level = "debug", skip(self))]
    pub fn gc_collect(&mut self) {
        self.gc_collect_exact();
    }

    /// Perform a full mark-and-sweep garbage collection using only explicit roots.
    #[tracing::instrument(level = "debug", skip(self))]
    pub fn gc_collect_exact(&mut self) {
        self.gc_collect_from_current_roots();
    }

    fn gc_collect_from_current_roots(&mut self) {
        let start = std::time::Instant::now();
        *self.lexenv_assq_cache.borrow_mut() = LexenvAssqCache::default();
        *self.lexenv_special_cache.borrow_mut() = LexenvSpecialCache::default();
        let heap_ptr: *mut crate::tagged::gc::TaggedHeap = &mut *self.tagged_heap;
        // Safety: GC is stop-the-world with exclusive `&mut self`. Root
        // enumeration only reads Context state while seeding the collector via
        // the raw heap pointer.
        unsafe {
            (*heap_ptr).begin_collection();
            self.trace_roots(&mut |root| {
                (*heap_ptr).seed_root(root);
            });
            // Install per-buffer marker-chain head slots so
            // `unchain_dead_markers` can splice unmarked markers out of
            // every live chain before sweep. Mirrors GNU
            // `sweep_buffer → unchain_dead_markers` (alloc.c).
            let chain_heads = self.buffers.collect_marker_chain_head_slots();
            (*heap_ptr).set_marker_chain_head_slots(chain_heads);
            (*heap_ptr).complete_collection();
        }
        self.gc_pending = false;
        self.gc_count += 1;
        self.update_gc_runtime_stats(start.elapsed());
        self.sync_gc_threshold_from_runtime_settings();
        self.run_post_gc_hook();
    }

    fn with_gc_inhibited<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
        self.gc_inhibit_depth += 1;
        let result = f(self);
        self.gc_inhibit_depth -= 1;
        result
    }

    fn run_post_gc_hook(&mut self) {
        let hook = crate::emacs_core::hook_runtime::hook_symbol_by_name(self, "post-gc-hook");
        let _ = self.with_gc_inhibited(|eval| {
            crate::emacs_core::hook_runtime::safe_run_named_hook(eval, hook, &[])
        });
    }

    /// GC safe point used at evaluator boundaries.
    pub fn gc_safe_point(&mut self) {
        self.gc_safe_point_exact();
    }

    /// Trigger a safe-point collection using only explicit evaluator roots.
    pub(crate) fn gc_safe_point_exact(&mut self) {
        if self.gc_inhibit_depth > 0 {
            return;
        }
        if self.gc_stress || self.gc_pending {
            self.gc_collect_from_current_roots();
            return;
        }

        if self.tagged_heap.gc_threshold_is_overridden() {
            if self.tagged_heap.should_collect() {
                self.gc_collect_from_current_roots();
            }
            return;
        }

        if !self.tagged_heap.should_collect() {
            return;
        }

        // GNU's maybe_gc hot path only checks consing_until_gc and defers
        // percentage-based threshold recalculation until the countdown crosses
        // zero.  Keep Neomacs' allocation fast path in the same shape.
        let threshold = self.effective_gc_threshold_bytes();
        if self.tagged_heap.gc_threshold() != threshold {
            self.tagged_heap.set_gc_threshold_from_runtime(threshold);
        }
        if self.tagged_heap.should_collect() {
            self.gc_collect_from_current_roots();
        }
    }

    /// GNU-style quit processing used from evaluator boundaries.
    ///
    /// Mirrors `process_quit_flag` in GNU `eval.c`: clear `quit-flag`, then
    /// honor `throw-on-input`, `kill-emacs`, or signal `quit`.
    fn process_quit_flag(&mut self) -> Result<(), Flow> {
        let flag = self.quit_flag;
        self.set_quit_flag_value(Value::NIL);

        let throw_on_input = self
            .obarray
            .symbol_value_id_or_nil(self.throw_on_input_symbol);

        if flag
            .as_symbol_id()
            .map_or(false, |sym| sym == self.kill_emacs_symbol)
        {
            self.request_shutdown(0, false);
            return Err(signal("quit", vec![]));
        }

        if !throw_on_input.is_nil() && equal_value(&flag, &throw_on_input, 0) {
            tracing::debug!(
                target: "neomacs::throw_on_input",
                ?flag,
                ?throw_on_input,
                condition_stack_len = self.condition_stack.len(),
                specpdl_len = self.specpdl.len(),
                has_matching_catch = self.has_active_catch(&throw_on_input),
                "process_quit_flag: throwing for pending input"
            );
            return Err(Flow::Throw {
                tag: throw_on_input,
                value: Value::T,
            });
        }

        Err(signal("quit", vec![]))
    }

    /// GNU `maybe_quit`: do nothing when `quit-flag` is nil or
    /// `inhibit-quit` is non-nil; otherwise process the quit request.
    pub(crate) fn maybe_quit(&mut self) -> Result<(), Flow> {
        // Drain the cross-thread quit-request atomic into `Vquit_flag`.
        // Set by the input-bridge thread when it observes a `quit-char`
        // keystroke while the evaluator is busy (e.g. deep in bytecode
        // and not reading from `input_rx`). See
        // `Context::quit_requested` for the design rationale.
        if self
            .quit_requested
            .load(std::sync::atomic::Ordering::Relaxed)
            && self
                .quit_requested
                .swap(false, std::sync::atomic::Ordering::Relaxed)
        {
            if self.quit_flag.is_nil() {
                self.set_quit_flag_value(Value::T);
            }
        }
        let quit_flag = self.quit_flag;
        if quit_flag.is_nil() {
            return Ok(());
        }

        if self.inhibit_quit.is_truthy() {
            return Ok(());
        }

        self.process_quit_flag()
    }

    #[inline(always)]
    pub(crate) fn quit_flag_value(&self) -> Value {
        self.quit_flag
    }

    #[inline(always)]
    pub(crate) fn set_quit_flag_value(&mut self, value: Value) {
        self.quit_flag = value;
        self.obarray
            .set_symbol_value_id(self.quit_flag_symbol, value);
    }

    pub(crate) fn quit_char(&self) -> i64 {
        self.quit_char
    }

    pub(crate) fn set_quit_char(&mut self, quit: i64) {
        self.quit_char = quit & 0o377;
    }

    pub(crate) fn event_is_quit_char(&self, event: &Value) -> bool {
        event
            .as_fixnum()
            .map_or(false, |code| code == self.quit_char)
    }

    pub(crate) fn request_quit_from_keyboard_input(&mut self) {
        if self.quit_flag_value().is_nil() {
            self.set_quit_flag_value(Value::T);
        }
    }

    pub(crate) fn clear_quit_flag_after_read_key_sequence_event(&mut self, event: &Value) {
        if !self.event_is_quit_char(event) {
            return;
        }

        let quit_flag = self.quit_flag_value();
        if quit_flag.is_nil() {
            return;
        }

        let throw_on_input = self
            .obarray
            .symbol_value_id_or_nil(self.throw_on_input_symbol);
        if equal_value(&quit_flag, &throw_on_input, 0) {
            return;
        }

        self.set_quit_flag_value(Value::NIL);
    }

    pub(crate) fn input_pending_p_filters_events(&self) -> bool {
        self.obarray
            .symbol_value("input-pending-p-filter-events")
            .copied()
            .unwrap_or(Value::T)
            .is_truthy()
    }

    pub(crate) fn track_mouse_enabled(&self) -> bool {
        self.obarray
            .symbol_value("track-mouse")
            .copied()
            .unwrap_or(Value::NIL)
            .is_truthy()
    }

    fn should_ignore_while_no_input_event(&self, event: &crate::keyboard::InputEvent) -> bool {
        let ignore_symbol = match event {
            crate::keyboard::InputEvent::Focus { focused, .. } => {
                Some(if *focused { "focus-in" } else { "focus-out" })
            }
            crate::keyboard::InputEvent::MonitorsChanged { .. } => Some("monitors-changed"),
            crate::keyboard::InputEvent::SelectWindow { .. } => Some("select-window"),
            _ => None,
        };
        let Some(ignore_symbol) = ignore_symbol else {
            return false;
        };

        let ignore_list = self
            .obarray
            .symbol_value("while-no-input-ignore-events")
            .copied()
            .unwrap_or(Value::NIL);
        super::value::list_to_vec(&ignore_list)
            .into_iter()
            .flatten()
            .any(|value| value.is_symbol_named(ignore_symbol))
    }

    pub(crate) fn input_event_counts_as_pending(
        &self,
        event: &crate::keyboard::InputEvent,
        filter_events: bool,
    ) -> bool {
        match event {
            crate::keyboard::InputEvent::Resize { .. } => false,
            crate::keyboard::InputEvent::Focus { .. } if !filter_events => false,
            crate::keyboard::InputEvent::MouseMove { .. } => self.track_mouse_enabled(),
            _ if filter_events && self.should_ignore_while_no_input_event(event) => false,
            _ => true,
        }
    }

    fn poll_pending_input_for_throw_on_input(&mut self) -> Result<(), Flow> {
        // GNU skips the interactive keyboard path only when there is no live
        // input source. Tests and embedded hosts can attach `input_rx` while
        // keeping `noninteractive` true, and `throw-on-input` must still see
        // that host input.
        if self.command_loop_noninteractive() && self.input_rx.is_none() {
            return Ok(());
        }

        let throw_on_input = self
            .obarray
            .symbol_value_id_or_nil(self.throw_on_input_symbol);
        if throw_on_input.is_nil() {
            return Ok(());
        }

        if !self.quit_flag.is_nil() {
            return Ok(());
        }

        while self.stage_next_host_input_event_if_available()? {}

        if self
            .command_loop
            .keyboard
            .pending_input_events
            .iter()
            .any(|event| self.input_event_counts_as_pending(event, true))
        {
            tracing::debug!(
                target: "neomacs::throw_on_input",
                ?throw_on_input,
                condition_stack_len = self.condition_stack.len(),
                specpdl_len = self.specpdl.len(),
                has_matching_catch = self.has_active_catch(&throw_on_input),
                pending_input_events = self.command_loop.keyboard.pending_input_events.len(),
                "poll_pending_input_for_throw_on_input: setting quit-flag"
            );
            self.set_quit_flag_value(throw_on_input);
        }

        Ok(())
    }

    /// Interrupt on input for GNU-style `throw-on-input` users such as
    /// `while-no-input`, while preserving the input event for later reads.
    pub(crate) fn interrupt_for_input_event_if_requested(
        &mut self,
        event: crate::keyboard::InputEvent,
    ) -> Result<bool, Flow> {
        let throw_on_input = self
            .obarray
            .symbol_value_id_or_nil(self.throw_on_input_symbol);
        if throw_on_input.is_nil() {
            return Ok(false);
        }

        if self.inhibit_quit.is_truthy() {
            return Ok(false);
        }

        self.command_loop
            .keyboard
            .pending_input_events
            .push_front(event);
        self.set_quit_flag_value(throw_on_input);
        self.maybe_quit()?;
        Ok(true)
    }

    /// Match GNU `eval_sub` / `funcall_general`: quit check first, then GC.
    ///
    /// The remaining evaluator entry points either root their live Values
    /// explicitly or run before materializing heap-backed Values, so this path
    /// now uses exact roots rather than conservative stack scanning.
    fn maybe_gc_and_quit(&mut self) -> Result<(), Flow> {
        self.poll_pending_input_for_throw_on_input()?;
        self.maybe_quit()?;
        self.gc_safe_point_exact();
        Ok(())
    }
}

impl Context {
    #[inline]
    fn maybe_grow_eval_stack<R>(&mut self, callback: impl FnOnce(&mut Self) -> R) -> R {
        let depth = self.depth;
        if depth < STACK_GROWTH_PROBE_START_DEPTH
            || !depth.is_multiple_of(STACK_GROWTH_PROBE_INTERVAL)
        {
            return callback(self);
        }
        stacker::maybe_grow(EVAL_STACK_RED_ZONE, EVAL_STACK_SEGMENT, || callback(self))
    }

    /// Whether lexical-binding is currently enabled.
    pub fn lexical_binding(&self) -> bool {
        lexenv_is_active(self.lexenv)
    }

    pub(crate) fn current_input_mode_tuple(&self) -> (bool, bool, bool, i64) {
        // Batch oracle compatibility: flow-control and meta are fixed to
        // nil/t respectively; quit-char remains mutable like GNU Emacs.
        (self.input_mode_interrupt, false, true, self.quit_char)
    }

    pub(crate) fn set_input_mode_interrupt(&mut self, interrupt: bool) {
        self.input_mode_interrupt = interrupt;
    }

    #[inline]
    fn sync_cached_runtime_binding_by_id(&mut self, sym_id: SymId, value: Value) {
        if sym_id == self.quit_flag_symbol {
            self.quit_flag = value;
        } else if sym_id == self.inhibit_quit_symbol {
            self.inhibit_quit = value;
        } else if sym_id == self.noninteractive_symbol {
            self.noninteractive = value.is_truthy();
        } else if sym_id == self.symbols_with_pos_enabled_symbol {
            self.symbols_with_pos_enabled = value.is_truthy();
        } else if sym_id == self.print_symbols_bare_symbol {
            self.print_symbols_bare = value.is_truthy();
        }
    }

    fn sync_keyboard_runtime_binding_by_id(&mut self, sym_id: SymId, value: Value) {
        if sym_id == intern("input-decode-map") {
            self.command_loop.keyboard.set_input_decode_map(value);
        } else if sym_id == intern("local-function-key-map") {
            self.command_loop.keyboard.set_local_function_key_map(value);
        }
    }

    pub(crate) fn sync_keyboard_runtime_from_obarray(&mut self) {
        let input_decode_map = self
            .obarray
            .symbol_value("input-decode-map")
            .copied()
            .unwrap_or(Value::NIL);
        let local_function_key_map = self
            .obarray
            .symbol_value("local-function-key-map")
            .copied()
            .unwrap_or(Value::NIL);
        self.command_loop
            .keyboard
            .set_terminal_translation_maps(input_decode_map, local_function_key_map);
    }

    pub(crate) fn waiting_for_user_input(&self) -> bool {
        self.waiting_for_user_input
    }

    pub(crate) fn set_waiting_for_user_input(&mut self, waiting: bool) {
        self.waiting_for_user_input = waiting;
    }

    pub(crate) fn has_input_receiver(&self) -> bool {
        self.input_rx.is_some()
    }

    pub(crate) fn pop_unread_command_event(&mut self) -> Option<Value> {
        let event = self.pop_unread_command_event_unrecorded()?;
        self.record_input_event(event);
        Some(event)
    }

    pub(crate) fn pop_unread_command_event_unrecorded(&mut self) -> Option<Value> {
        let current = match self.eval_symbol("unread-command-events") {
            Ok(value) => value,
            Err(_) => Value::NIL,
        };
        match current.kind() {
            ValueKind::Cons => {
                let mut head = current.cons_car();
                let tail = current.cons_cdr();
                self.assign("unread-command-events", tail);
                if head.is_cons() && head.cons_car() == Value::T {
                    head = head.cons_cdr();
                }
                Some(head)
            }
            _ => None,
        }
    }

    pub(crate) fn peek_unread_command_event(&self) -> Option<Value> {
        let current = match self.eval_symbol("unread-command-events") {
            Ok(value) => value,
            Err(_) => Value::NIL,
        };
        match current.kind() {
            ValueKind::Cons => Some(current.cons_car()),
            _ => None,
        }
    }

    /// Prepend an event to the `unread-command-events` list so that the next
    /// `read_char` / `pop_unread_command_event` will consume it first.
    pub(crate) fn push_unread_command_event(&mut self, event: Value) {
        let current = match self.eval_symbol("unread-command-events") {
            Ok(value) => value,
            Err(_) => Value::NIL,
        };
        let new_list = Value::cons(event, current);
        self.assign("unread-command-events", new_list);
    }

    pub(crate) fn replace_unread_command_event_with_singleton(&mut self, event: Value) {
        self.assign("unread-command-events", Value::list(vec![event]));
    }

    /// Set the file-level `lexical-binding` (per-buffer) and sync the
    /// top-level lexical environment.
    ///
    /// Called at file-loading boundaries (load.rs, lread.rs) and test
    /// setup. Mirrors GNU Emacs where the file loader both sets the
    /// `lexical-binding` buffer-local AND specbinds
    /// `Vinternal_interpreter_environment` to `(t)` or `nil`.
    ///
    /// Uses the runtime assignment path so the visible binding is
    /// updated even when a caller has dynamically let-bound
    /// `lexical-binding`. This matches GNU `Fset`, which mutates the
    /// current binding cell before `readevalloop`.
    ///
    /// Note: `Feval` (begin_eval_with_lexical_arg) does NOT call this.
    /// `Feval` only saves/restores `self.lexenv` without touching the
    /// per-buffer `lexical-binding`, matching GNU where nested eval
    /// calls never clobber the file-level setting.
    pub fn set_lexical_binding(&mut self, enabled: bool) {
        self.set_runtime_binding_by_id(intern("lexical-binding"), Value::bool_val(enabled));
        if enabled {
            if self.lexenv.is_nil() {
                self.lexenv = top_level_lexenv_sentinel();
            }
        } else if is_top_level_lexenv_sentinel(self.lexenv) {
            self.lexenv = Value::NIL;
        }
    }

    /// Reset transient evaluator state at a completed top-level boundary.
    ///
    /// GNU reaches interactive/runtime boundaries by unwinding dynamic state
    /// back to the top level, not by discarding the binding stack.  NeoVM's
    /// source bootstrap can transiently accumulate bindings, lexical
    /// environments, and catch state while loading `loadup.el` and early
    /// startup Lisp, but those structures must be unwound before the
    /// evaluator is reused.
    pub(crate) fn clear_top_level_eval_state(&mut self) {
        self.unbind_to(0);
        self.lexenv = if lexical_binding_in_obarray(&self.obarray) {
            top_level_lexenv_sentinel()
        } else {
            Value::NIL
        };
        self.condition_stack.clear();
        self.depth = 0;
        // Named-call resolution is a runtime memoization layer, not part of
        // GNU's persisted Lisp surface. If it survives bootstrap/pdump
        // boundaries it can disagree with restored function cells while still
        // carrying a matching function epoch.
        self.named_call_cache.clear();
    }

    #[cfg(test)]
    pub(crate) fn top_level_eval_state_is_clean(&self) -> bool {
        let clean_lexenv = self.lexenv.is_nil()
            || (self.lexical_binding() && is_top_level_lexenv_sentinel(self.lexenv));
        self.specpdl.is_empty()
            && clean_lexenv
            && self.vm_root_frames.is_empty()
            && self.condition_stack.is_empty()
            && self.depth == 0
    }

    #[cfg(test)]
    pub(crate) fn condition_stack_depth_for_test(&self) -> usize {
        self.condition_stack.len()
    }

    pub(crate) fn set_interpreted_closure_filter_fn(&mut self, filter_fn: Option<Value>) {
        self.interpreted_closure_filter_fn = filter_fn;
        if filter_fn.is_none() {
            self.interpreted_closure_trim_cache.clear();
            self.interpreted_closure_value_cache.clear();
        }
    }

    /// Load a file, converting EvalError back to Flow for use in special forms.
    pub fn load_file_internal(&mut self, path: &std::path::Path) -> EvalResult {
        self.load_file_internal_with_flags(path, false, false)
    }

    /// Load a file with caller-visible `load` flags, converting EvalError
    /// back to Flow for use in special forms.
    pub fn load_file_internal_with_flags(
        &mut self,
        path: &std::path::Path,
        noerror: bool,
        nomessage: bool,
    ) -> EvalResult {
        super::load::load_file_with_flags(self, path, noerror, nomessage).map_err(|e| match e {
            EvalError::Signal {
                symbol,
                data,
                raw_data,
            } => {
                if let Some(raw) = raw_data {
                    signal_with_data(resolve_sym(symbol), raw)
                } else {
                    signal(resolve_sym(symbol), data)
                }
            }
            EvalError::UncaughtThrow { tag, value } => Flow::Throw { tag, value },
        })
    }

    pub(crate) fn eval_value_with_lexical_arg(
        &mut self,
        form: Value,
        lexical_arg: Option<Value>,
    ) -> EvalResult {
        let state = begin_eval_with_lexical_arg_in_state(
            &mut self.obarray,
            &mut self.lexenv,
            &mut self.specpdl,
            lexical_arg,
        )?;
        let eval_result = self.eval_value(&form);
        let result = self.dispatch_signal_result_if_needed(eval_result);
        finish_eval_with_lexical_arg_in_state(
            &mut self.obarray,
            &mut self.lexenv,
            &mut self.specpdl,
            state,
        );
        result
    }

    pub(crate) fn eval_lambda_body_value(&mut self, body: Value) -> EvalResult {
        self.maybe_grow_eval_stack(|ctx| {
            let mut cursor = body;
            let mut last = Value::NIL;
            while cursor.is_cons() {
                last = ctx.eval_sub(cursor.cons_car())?;
                cursor = cursor.cons_cdr();
            }
            Ok(last)
        })
    }

    pub(crate) fn begin_lambda_call(
        &mut self,
        params: &LambdaParams,
        env: Option<Value>,
        args: &[Value],
    ) -> Result<ActiveLambdaCallState, Flow> {
        begin_lambda_call_in_state(
            &mut self.obarray,
            &mut self.specpdl,
            &mut self.lexenv,
            params,
            env,
            args,
        )
    }

    pub(crate) fn finish_lambda_call(&mut self, state: ActiveLambdaCallState) {
        finish_lambda_call_in_state(
            &mut self.obarray,
            &mut self.specpdl,
            &mut self.lexenv,
            state,
        );
    }

    /// Keep the Lisp-visible `features` variable in sync with the evaluator's
    /// internal feature set.
    pub(crate) fn sync_features_variable(&mut self) {
        sync_features_variable_in_state(&mut self.obarray, &self.features);
    }

    pub(crate) fn refresh_features_from_variable(&mut self) {
        refresh_features_from_variable_in_state(&self.obarray, &mut self.features);
    }

    fn has_feature(&mut self, name: &str) -> bool {
        feature_present_in_state(&self.obarray, &mut self.features, name)
    }

    pub(crate) fn add_feature(&mut self, name: &str) {
        add_feature_in_state(&mut self.obarray, &mut self.features, name);
    }

    pub(crate) fn feature_present(&mut self, name: &str) -> bool {
        self.has_feature(name)
    }

    /// Remove a feature (used to undo temporary provides during bootstrap).
    pub(crate) fn remove_feature(&mut self, name: &str) {
        remove_feature_in_state(&mut self.obarray, &mut self.features, name);
    }

    /// Access the obarray (for builtins that need it).
    pub fn obarray(&self) -> &Obarray {
        &self.obarray
    }

    /// Access the obarray mutably.
    pub fn obarray_mut(&mut self) -> &mut Obarray {
        &mut self.obarray
    }

    /// Public read access to the buffer manager.
    pub fn buffer_manager(&self) -> &BufferManager {
        &self.buffers
    }

    /// Public mutable access to the buffer manager.
    pub fn buffer_manager_mut(&mut self) -> &mut BufferManager {
        &mut self.buffers
    }

    /// Public read access to the frame manager.
    pub fn frame_manager(&self) -> &FrameManager {
        &self.frames
    }

    /// Public mutable access to the frame manager.
    pub fn frame_manager_mut(&mut self) -> &mut FrameManager {
        &mut self.frames
    }

    pub fn current_message_text(&self) -> Option<String> {
        self.current_message
            .as_ref()
            .map(|message| crate::emacs_core::builtins::runtime_string_from_lisp_string(message))
    }

    pub fn current_message_value(&self) -> Option<Value> {
        self.current_message
            .as_ref()
            .map(|message| Value::heap_string(message.clone()))
    }

    pub fn set_current_message(&mut self, message: Option<crate::heap_types::LispString>) {
        if self.current_message != message {
            self.current_message = message;
            self.invalidate_redisplay();
        }
    }

    pub(crate) fn append_current_message_runtime_text(&mut self, text: &str) {
        let multibyte = self
            .current_message
            .as_ref()
            .map(crate::heap_types::LispString::is_multibyte)
            .unwrap_or(true);
        let piece = crate::emacs_core::builtins::runtime_string_to_lisp_string(text, multibyte);
        self.append_current_message_lisp_string(&piece);
    }

    pub(crate) fn append_current_message_lisp_string(
        &mut self,
        text: &crate::heap_types::LispString,
    ) {
        match self.current_message.as_mut() {
            Some(message) => *message = message.concat(text),
            None => self.current_message = Some(text.clone()),
        }
        self.invalidate_redisplay();
    }

    pub fn clear_current_message(&mut self) {
        if self.current_message.is_none() {
            return;
        }
        let hook =
            crate::emacs_core::hook_runtime::hook_symbol_by_name(self, "echo-area-clear-hook");
        let _ = crate::emacs_core::hook_runtime::safe_run_named_hook(self, hook, &[]);
        self.current_message = None;
        self.invalidate_redisplay();
    }

    pub(crate) fn current_message_slot(&mut self) -> &mut Option<crate::heap_types::LispString> {
        &mut self.current_message
    }

    pub(crate) fn sync_keyboard_terminal_owner(&mut self) {
        let terminal_id = self
            .frames
            .selected_frame()
            .map(|frame| frame.terminal_id)
            .unwrap_or(crate::emacs_core::terminal::pure::TERMINAL_ID);
        self.command_loop.keyboard.select_terminal(terminal_id);
    }

    pub(crate) fn sync_keyboard_terminal_owner_for_input_frame(&mut self, emacs_frame_id: u64) {
        let terminal_id = if emacs_frame_id == 0 {
            self.frames
                .selected_frame()
                .map(|frame| frame.terminal_id)
                .unwrap_or(crate::emacs_core::terminal::pure::TERMINAL_ID)
        } else {
            self.frames
                .get(crate::window::FrameId(emacs_frame_id))
                .map(|frame| frame.terminal_id)
                .unwrap_or_else(|| {
                    self.frames
                        .selected_frame()
                        .map(|frame| frame.terminal_id)
                        .unwrap_or(crate::emacs_core::terminal::pure::TERMINAL_ID)
                })
        };
        self.command_loop.keyboard.select_terminal(terminal_id);
    }

    /// Public read access to the face table.
    pub fn face_table(&self) -> &FaceTable {
        &self.face_table
    }

    /// Public mutable access to the face table.
    pub fn face_table_mut(&mut self) -> &mut FaceTable {
        &mut self.face_table
    }

    /// Set a face attribute and bump the change counter.
    /// This is the canonical way to modify face definitions at runtime.
    pub fn set_face_attribute(
        &mut self,
        face_name: &str,
        attr: &str,
        value: crate::face::FaceAttrValue,
    ) -> bool {
        let changed = self.face_table.set_attribute(face_name, attr, value);
        if changed {
            self.face_change_count += 1;
        }
        changed
    }

    // -----------------------------------------------------------------------
    // Public API
    // -----------------------------------------------------------------------

    /// Evaluate a Lisp expression string. Convenience for tests.
    /// Reads via the Value-native reader and evaluates via eval_sub.
    pub fn eval_str(&mut self, source: &str) -> Result<Value, EvalError> {
        crate::tagged::gc::set_tagged_heap(&mut self.tagged_heap);
        let forms = super::value_reader::read_all(source).map_err(|e| EvalError::Signal {
            symbol: crate::emacs_core::intern::intern("error"),
            data: vec![Value::string(format!("Read error: {}", e.message))],
            raw_data: None,
        })?;
        if forms.is_empty() {
            return Ok(Value::NIL);
        }
        // Root every parsed form: each `eval_sub` call may trigger GC, and
        // the un-iterated forms still sitting in the heap-allocated Vec are
        // otherwise invisible to the exact root walk.
        let specpdl_root_scope = self.save_specpdl_roots();
        for form in &forms {
            self.push_specpdl_root(*form);
        }
        let mut result = Value::NIL;
        let mut error = None;
        for form in &forms {
            let eval_result = self.eval_sub(*form);
            match self.finalize_public_eval_result(eval_result) {
                Ok(v) => result = v,
                Err(e) => {
                    error = Some(e);
                    break;
                }
            }
        }
        self.restore_specpdl_roots(specpdl_root_scope);
        match error {
            Some(e) => Err(e),
            None => Ok(result),
        }
    }

    /// Evaluate a single Value form and return a public EvalError on failure.
    /// Evaluate a single Value form, mapping Flow errors to EvalError.
    pub fn eval_form(&mut self, form: Value) -> Result<Value, EvalError> {
        crate::tagged::gc::set_tagged_heap(&mut self.tagged_heap);
        let eval_result = self.eval_sub(form);
        self.finalize_public_eval_result(eval_result)
    }

    fn finalize_public_eval_result(&mut self, result: EvalResult) -> Result<Value, EvalError> {
        match result {
            Ok(value) => Ok(value),
            Err(Flow::Signal(sig)) => match self.dispatch_signal_if_needed(sig) {
                Ok(dispatched) => Err(map_flow(Flow::Signal(dispatched))),
                Err(flow) => Err(map_flow(flow)),
            },
            Err(flow) => Err(map_flow(flow)),
        }
    }

    /// Evaluate a runtime Value form, matching GNU Emacs's `eval_sub` in eval.c.
    ///
    /// Dispatch order (matching GNU eval.c:2552-2766):
    /// 1. Symbol → lexenv lookup or symbol-value
    /// 2. Non-cons → self-evaluating (return as-is)
    /// 3. Cons → special form / macro / function call
    pub fn eval_sub(&mut self, form: Value) -> EvalResult {
        // 1. Symbol → variable lookup (GNU eval.c:2554-2562)
        // Also unwrap symbol-with-pos when symbols-with-pos-enabled is true.
        let form_unwrapped = self.unwrap_symbol(form);
        if let Some(sym_id) = form_unwrapped.as_symbol_id() {
            return self.eval_symbol_by_id(sym_id);
        }

        // 2. Non-cons → self-evaluating (GNU eval.c:2564-2565)
        if !form_unwrapped.is_cons() {
            return Ok(form_unwrapped);
        }

        self.depth += 1;
        if self.depth > self.max_depth {
            if let Some(v) = self.obarray.symbol_value("max-lisp-eval-depth") {
                if let Some(n) = v.as_fixnum() {
                    let new_max = n.max(100) as usize;
                    if new_max != self.max_depth {
                        self.max_depth = new_max;
                    }
                }
            }
        }
        if self.depth > self.max_depth {
            let overflow_depth = self.depth as i64;
            self.depth -= 1;
            return Err(signal(
                "excessive-lisp-nesting",
                vec![Value::fixnum(overflow_depth)],
            ));
        }

        let result = self.maybe_grow_eval_stack(|ctx| {
            let specpdl_root_scope = ctx.save_specpdl_roots();
            ctx.push_specpdl_root(form);
            let result = ctx
                .maybe_gc_and_quit()
                .and_then(|()| ctx.eval_sub_cons(form));
            ctx.restore_specpdl_roots(specpdl_root_scope);
            result
        });
        self.depth -= 1;
        result
    }

    fn eval_sub_cons(&mut self, form: Value) -> EvalResult {
        let original_fun = self.unwrap_symbol(form.cons_car());
        let original_args = form.cons_cdr();

        // GNU eval.c:2583-2585 records an UNEVALLED backtrace frame on
        // every `eval_sub` cons-form evaluation. The frame starts in
        // UNEVALLED shape holding the surface function symbol and the
        // raw argument-form cons list, then transitions to EVALD in
        // place via `set_backtrace_args` once arguments have been
        // evaluated (eval.c:2638, 2660, 3299). Special forms leave
        // the frame UNEVALLED throughout.
        let outer_bt_count = self.specpdl.len();
        self.push_unevalled_backtrace_frame(original_fun, original_args);
        let dispatch_result =
            self.eval_sub_cons_dispatch(original_fun, original_args, outer_bt_count);
        let result = self.dispatch_signal_result_if_needed(dispatch_result);
        self.unbind_to_with_result(outer_bt_count, result)
    }

    fn eval_sub_cons_dispatch(
        &mut self,
        original_fun: Value,
        original_args: Value,
        outer_bt_count: usize,
    ) -> EvalResult {
        // Resolve function (GNU eval.c:2600-2605)
        let sym_id = original_fun.as_symbol_id();

        // Keep only evaluator-internal literal forms on the pre-resolution
        // fast path. GNU decides public special-form dispatch from the
        // function cell's UNEVALLED subr, so user-visible special forms
        // should flow through the resolved subr surface below.
        if let Some(sym_id) = sym_id
            && matches!(
                sym_id,
                id if id == lambda_symbol()
                    || id == byte_code_literal_symbol()
                    || id == byte_code_symbol()
            )
        {
            if let Some(result) = self.try_special_form_value_id(sym_id, original_args) {
                return result;
            }
        }

        // Resolve function value
        let func = if let Some(sym_id) = sym_id {
            if let Some(override_func) =
                compiler_function_override_in_obarray(&self.obarray, sym_id)
            {
                override_func
            } else {
                match self.obarray.symbol_function_id(sym_id) {
                    Some(f) => {
                        let mut f = f;
                        // Follow symbol indirection (GNU eval.c:2604)
                        if let Some(alias_id) = f.as_symbol_id() {
                            if let Some(resolved) = self.obarray.indirect_function_id(alias_id) {
                                f = resolved;
                            }
                        }
                        // Handle autoload
                        if super::autoload::is_autoload_value(&f) {
                            let _ = super::autoload::builtin_autoload_do_load(
                                self,
                                vec![f, Value::from_sym_id(sym_id), Value::NIL],
                            )?;
                            match self.obarray.symbol_function_id(sym_id) {
                                Some(reloaded) => reloaded,
                                _ => {
                                    return Err(signal(
                                        "void-function",
                                        vec![Value::from_sym_id(sym_id)],
                                    ));
                                }
                            }
                        } else {
                            f
                        }
                    }
                    _ => return Err(signal("void-function", vec![Value::from_sym_id(sym_id)])),
                }
            }
        } else if original_fun.is_cons() {
            // Car is a list — could be (lambda ...) form
            // Evaluate it to get the function
            self.eval_sub(original_fun)?
        } else {
            return Err(signal("invalid-function", vec![original_fun]));
        };

        if let Some(surface_sym_id) = sym_id
            && let Some(target_sym_id) = func.as_subr_id()
            && self.subr_is_special_form_id(target_sym_id)
        {
            // The outer eval_sub_cons UNEVALLED frame (pushed by the
            // wrapper) already records the surface function and raw
            // argument forms. Special forms leave the frame UNEVALLED
            // throughout (no `set_backtrace_args_evalled` call),
            // matching GNU eval.c:2618-2619.
            let result = if surface_sym_id == target_sym_id {
                self.try_special_form_value_id(surface_sym_id, original_args)
            } else {
                self.try_aliased_special_form_value_id(surface_sym_id, target_sym_id, original_args)
            };
            if let Some(result) = result {
                return result;
            }
        }

        // Check for macro (GNU eval.c:2730-2755)
        if func.is_macro() {
            let arg_values = value_list_to_values(&original_args);
            let bt_count = self.specpdl.len();
            self.push_backtrace_frame(original_fun, &arg_values);
            let expanded =
                self.with_macro_expansion_scope(|eval| eval.apply_lambda(func, arg_values.into()));
            let expanded = self.unbind_to_with_result(bt_count, expanded);
            let expanded = expanded?;
            let expanded_root_count = self.specpdl.len();
            self.push_specpdl_root(expanded);
            let result = self.eval_sub(expanded);
            return self.unbind_to_with_result(expanded_root_count, result);
        }
        if cons_head_symbol_id(&func) == Some(macro_symbol()) {
            // Cons-cell macro: (macro . fn) — GNU eval.c:2730
            let macro_fn = func.cons_cdr();
            let arg_values = value_list_to_values(&original_args);
            let bt_count = self.specpdl.len();
            self.push_backtrace_frame(original_fun, &arg_values);
            let expanded = self.with_macro_expansion_scope(|eval| eval.apply(macro_fn, arg_values));
            let expanded = self.unbind_to_with_result(bt_count, expanded);
            let expanded = expanded?;
            let expanded_root_count = self.specpdl.len();
            self.push_specpdl_root(expanded);
            let result = self.eval_sub(expanded);
            return self.unbind_to_with_result(expanded_root_count, result);
        }

        // GNU eval.c:2606-2614: for SUBRP `fun`, check arity
        // against the raw `original_args` count BEFORE any arg
        // evaluation, and on mismatch signal
        // `(wrong-number-of-arguments original_fun numargs)` where
        // `original_fun` is the XCAR of the form (the surface
        // symbol, not the resolved subr value). This is how GNU
        // gets `(wrong-number-of-arguments car 0)` for a direct
        // `(car)` call -- the arity check runs inline in eval_sub
        // and never reaches `funcall_subr` which would have emitted
        // `#<subr car>` via `XSETSUBR`.
        //
        // For non-subrs (closures, bytecode, lambdas, cons forms)
        // the dispatch falls through to the normal apply path,
        // which signals with `fun` itself -- also matching GNU
        // funcall_lambda and funcall_subr.
        // GNU keeps the resolved XSUBR in `fun` across argument
        // evaluation and calls it directly. Preserve the SubrEntry we
        // resolved for the direct eval_sub arity check instead of
        // looking it up again after evaluating args.
        let direct_subr_entry = if let Some((sym_id, entry)) = subr_entry_from_value(func) {
            if entry.dispatch_kind != SubrDispatchKind::SpecialForm {
                let numargs = match list_length(&original_args) {
                    Some(n) => n,
                    None => {
                        return Err(signal(
                            "wrong-type-argument",
                            vec![Value::symbol("listp"), original_args],
                        ));
                    }
                };
                let min = entry.min_args as usize;
                let max_ok = match entry.max_args {
                    Some(m) => numargs <= m as usize,
                    None => true, // &rest / MANY
                };
                if numargs < min || !max_ok {
                    return Err(signal(
                        "wrong-number-of-arguments",
                        vec![original_fun, Value::fixnum(numargs as i64)],
                    ));
                }
                Some((sym_id, entry))
            } else {
                None
            }
        } else {
            None
        };

        // GNU eval.c:2716-2726: when `fun` is not a subr, closure,
        // bytecode, or cons-shaped lambda/autoload/macro, signal
        // `(invalid-function original_fun)` with the SURFACE
        // symbol. Verified against emacs 31.0.50:
        //   (fset 'vm-fsetint 1)
        //   (condition-case e (vm-fsetint) (error e))
        //     → (invalid-function vm-fsetint)
        //
        // The check runs inline in eval_sub so the dispatcher
        // `funcall_general` never sees the invalid value and
        // never emits the resolved fncell contents as signal data.
        if !self.function_value_is_callable(&func) {
            if func.is_nil() {
                return Err(signal("void-function", vec![original_fun]));
            }
            return Err(signal("invalid-function", vec![original_fun]));
        }

        // Regular function call: evaluate args, promote the outer
        // UNEVALLED frame to EVALD in place, then dispatch directly.
        // Matches GNU `eval_sub` non-UNEVALLED SUBRP path
        // (eval.c:2631-2640) and CLOSUREP → apply_lambda
        // (eval.c:2715, 3292-3300) which both mutate the outer
        // record_in_backtrace entry via `set_backtrace_args`.
        //
        // `func` and each evaluated arg are rooted on the specpdl via
        // `push_specpdl_root`. GNU relies on conservative stack
        // scanning of `SAFE_ALLOCA_LISP (vals, numargs)` plus the
        // `fun` C local; neomacs uses exact GC, so a local
        // `Vec<Value>` and the Rust-local `func` Value are invisible
        // to the tracer.
        //
        // `func` is rooted BEFORE the arg loop so it survives GC
        // triggered by any arg evaluator, and stays rooted through
        // `funcall_general_untraced` below -- it only gets popped by
        // the outer `eval_sub_cons` `unbind_to(outer_bt_count)`. This
        // is specifically needed when `original_fun` is a cons
        // (lambda-literal head): the resolved Lambda Value lives only
        // on the Rust stack, and the outer UNEVALLED frame records
        // `original_fun`, not `func`.
        //
        // Per-arg roots are popped once `set_backtrace_args_evalled`
        // transfers ownership to the outer frame's args slot.
        // GNU uses SAFE_ALLOCA_LISP for evaluated arguments here. Keep the
        // common arities inline instead of allocating a heap Vec per call.
        let mut args = LispArgVec::new();
        self.push_specpdl_root(func);
        let args_roots_base = self.specpdl.len();
        let mut cursor = original_args;
        while cursor.is_cons() {
            let arg_form = cursor.cons_car();
            let arg_val = self.eval_sub(arg_form)?;
            self.push_specpdl_root(arg_val);
            args.push(arg_val);
            cursor = cursor.cons_cdr();
        }
        if let Some((sym_id, entry)) = direct_subr_entry {
            if Self::subr_entry_uses_fixed_value_call(entry) {
                self.set_backtrace_args_evalled_owned(outer_bt_count, args);
                self.unbind_to(args_roots_base);

                self.maybe_gc_and_quit()?;

                return self.maybe_grow_eval_stack(|ctx| {
                    ctx.dispatch_subr_entry_from_backtrace_unchecked(entry, outer_bt_count)
                        .unwrap_or_else(|| {
                            Err(signal("void-function", vec![Value::from_sym_id(sym_id)]))
                        })
                });
            }
        }

        self.set_backtrace_args_evalled(outer_bt_count, &args);
        self.unbind_to(args_roots_base);

        self.maybe_gc_and_quit()?;

        if let Some((sym_id, entry)) = direct_subr_entry {
            return self.maybe_grow_eval_stack(|ctx| {
                if entry.dispatch_kind == SubrDispatchKind::ContextCallable {
                    return ctx.apply_evaluator_callable_by_id(sym_id, args);
                }
                ctx.dispatch_subr_entry_unchecked(entry, args)
                    .unwrap_or_else(|| {
                        Err(signal("void-function", vec![Value::from_sym_id(sym_id)]))
                    })
            });
        }

        self.maybe_grow_eval_stack(|ctx| ctx.funcall_general_untraced(func, args))
    }

    /// Legacy eval_value: delegates to eval_sub.
    pub fn eval_value(&mut self, value: &Value) -> EvalResult {
        self.eval_sub(*value)
    }

    /// Evaluate all forms in a source string and return per-form results.
    /// Uses the Value-native reader.
    pub fn eval_str_each(&mut self, source: &str) -> Vec<Result<Value, EvalError>> {
        crate::tagged::gc::set_tagged_heap(&mut self.tagged_heap);
        let forms = match super::value_reader::read_all(source) {
            Ok(f) => f,
            Err(e) => {
                return vec![Err(EvalError::Signal {
                    symbol: intern("error"),
                    data: vec![Value::string(format!("Read error: {}", e.message))],
                    raw_data: None,
                })];
            }
        };
        // Root every parsed form upfront. The previous version only rooted
        // successful results; un-iterated parsed forms still sitting in the
        // heap-allocated Vec were otherwise invisible to exact GC.
        let specpdl_root_scope = self.save_specpdl_roots();
        for form in &forms {
            self.push_specpdl_root(*form);
        }
        let mut results = Vec::with_capacity(forms.len());
        for form in &forms {
            let result = self.eval_sub(*form).map_err(map_flow);
            if let Ok(ref val) = result {
                self.push_specpdl_root(*val);
            }
            results.push(result);
        }
        self.restore_specpdl_roots(specpdl_root_scope);
        results
    }

    /// Set a global variable.
    pub fn set_variable(&mut self, name: &str, value: Value) {
        let sym_id = intern(name);
        self.note_macro_expansion_mutation();
        // GNU set_internal (data.c:1762) for SYMBOL_FORWARDED routes
        // the write through `store_symval_forwarding` which for the
        // BUFFER_OBJFWD arm writes to the current buffer's slot.
        // Mirror that here so callers like
        // `obarray.set_symbol_value("default-directory", ...)`
        // (and the test surface that uses set_variable) actually
        // update the visible per-buffer slot rather than just the
        // obarray symbol value (which a FORWARDED symbol no longer
        // consults at read time).
        use super::symbol::SymbolRedirect;
        if let Some(sym) = self.obarray.get_by_id(sym_id)
            && sym.flags.redirect() == SymbolRedirect::Forwarded
            && let Some(buf_id) = self.buffers.current_buffer_id()
        {
            use super::forward::{LispBufferObjFwd, LispFwdType};
            // Safety: install_buffer_objfwd leaks a 'static
            // descriptor; the symbol's redirect tag and val.fwd
            // pointer are immutable once installed.
            let fwd_ptr = unsafe { sym.val.fwd };
            let header = unsafe { &*fwd_ptr };
            if matches!(header.ty, LispFwdType::BufferObj) {
                let buf_fwd = unsafe { &*(fwd_ptr as *const LispBufferObjFwd) };
                let offset = buf_fwd.offset as usize;
                if let Some(buf) = self.buffers.get_mut(buf_id)
                    && offset < buf.slots.len()
                {
                    buf.slots[offset] = value;
                    self.refresh_gc_runtime_settings_after_change_by_id(sym_id);
                    return;
                }
            }
        }
        self.obarray.set_symbol_value(name, value);
        self.sync_cached_runtime_binding_by_id(sym_id, value);
        self.refresh_gc_runtime_settings_after_change_by_id(sym_id);
    }

    #[inline]
    pub(crate) fn noninteractive(&self) -> bool {
        self.noninteractive
    }

    /// If `symbols-with-pos-enabled` and `val` is a symbol-with-pos,
    /// return the bare symbol. Otherwise return `val` unchanged.
    #[inline]
    pub fn unwrap_symbol(&self, val: Value) -> Value {
        if self.symbols_with_pos_enabled && val.is_symbol_with_pos() {
            val.as_symbol_with_pos_sym().unwrap()
        } else {
            val
        }
    }

    pub(crate) fn sync_thread_runtime_bindings(&mut self) {
        if let Some(main_thread) = self.threads.thread_handle(0) {
            self.obarray.set_symbol_value("main-thread", main_thread);
        }
    }

    /// Set a function binding.
    pub fn set_function(&mut self, name: &str, value: Value) {
        self.note_macro_expansion_mutation();
        self.obarray.set_symbol_function(name, value);
    }

    #[inline]
    fn forwarded_buffer_obj_value(
        &self,
        sym: &crate::emacs_core::symbol::LispSymbol,
    ) -> Option<Value> {
        use crate::emacs_core::forward::{LispBufferObjFwd, LispFwdType};

        let fwd = unsafe { &*sym.val.fwd };
        if !matches!(fwd.ty, LispFwdType::BufferObj) {
            return None;
        }

        let buf_fwd = unsafe { &*(fwd as *const _ as *const LispBufferObjFwd) };
        let off = buf_fwd.offset as usize;
        if let Some(buf) = self.buffers.current_buffer() {
            let local = buf_fwd.local_flags_idx < 0 || buf.slot_local_flag(off);
            if local && off < buf.slots.len() {
                return Some(buf.slots[off]);
            }
        }

        if off < self.buffers.buffer_defaults.len() {
            Some(self.buffers.buffer_defaults[off])
        } else {
            Some(buf_fwd.default)
        }
    }

    pub(crate) fn set_buffer_local_binding_by_id(
        &mut self,
        buffer_id: crate::buffer::BufferId,
        sym_id: SymId,
        value: Value,
    ) -> Result<(), Flow> {
        let resolved = builtins::resolve_variable_alias_id_in_obarray(&self.obarray, sym_id)?;
        if crate::buffer::buffer::lookup_buffer_slot_by_sym_id(resolved).is_some()
            || resolved == buffer_undo_list_symbol()
        {
            let _ = self
                .buffers
                .set_buffer_local_property_by_sym_id(buffer_id, resolved, value);
            return Ok(());
        }

        if !self.obarray.get_by_id(resolved).is_some_and(|sym| {
            sym.redirect() == crate::emacs_core::symbol::SymbolRedirect::Localized
        }) {
            let default = self
                .obarray
                .find_symbol_value(resolved)
                .unwrap_or(Value::UNBOUND);
            self.obarray.make_symbol_localized(resolved, default);
        }

        let _ = self
            .buffers
            .set_buffer_local_property_by_sym_id(buffer_id, resolved, value);
        let target_buf = Value::make_buffer(buffer_id);
        let alist = self
            .buffers
            .get(buffer_id)
            .map(|buf| buf.local_var_alist)
            .unwrap_or(Value::NIL);
        let _ = self.obarray.find_symbol_value_in_buffer(
            resolved,
            Some(buffer_id),
            target_buf,
            alist,
            None,
            0,
            None,
        );
        Ok(())
    }

    /// Look up a symbol by its SymId. Uses the SymId directly for lexenv
    /// lookup (preserving uninterned symbol identity, like Emacs's EQ-based
    /// Fassq on Vinternal_interpreter_environment).
    pub(crate) fn eval_symbol_by_id(&self, sym_id: SymId) -> EvalResult {
        // Keywords evaluate to themselves
        if is_keyword_id(sym_id) {
            return Ok(Value::from_kw_id(sym_id));
        }

        // GNU eval.c checks the lexenv for the ORIGINAL symbol BEFORE
        // resolving variable aliases and does not rescan declared-special
        // flags on ordinary reads. Declared-special affects how bindings are
        // created, not whether an existing lexical cell is readable.
        if self.lexical_binding() {
            if let Some(value) = self.lexenv_lookup_cached_in(self.lexenv, sym_id) {
                return Ok(value);
            }
        }

        let resolved = super::builtins::resolve_variable_alias_id(self, sym_id)?;
        let resolved_is_canonical = is_canonical_id(resolved);

        // Also check the lexenv for the resolved alias (rare but possible).
        if resolved != sym_id && self.lexical_binding() {
            if let Some(value) = self.lexenv_lookup_cached_in(self.lexenv, resolved) {
                return Ok(value);
            }
        }

        // Task #36: no t/nil short-circuit here. A lambda-parameter
        // or legitimate specbind can shadow the canonical constants
        // (GNU: `(funcall (lambda (t) t) 7)` → 7 even in dynamic
        // mode, because specbind stores 7 in the t symbol cell).
        // The fall-through to `find_symbol_value` below reads the
        // current cell; the canonical values are restored as a
        // fallback at the very end if no binding is found.
        if is_keyword_id(resolved) {
            return Ok(Value::from_kw_id(resolved));
        }

        use crate::emacs_core::symbol::SymbolRedirect;
        if let Some(sym) = self.obarray.get_by_id(resolved) {
            match sym.redirect() {
                // GNU `find_symbol_value` switches on the symbol
                // redirect tag and only walks `local_var_alist` for
                // `SYMBOL_LOCALIZED`.
                SymbolRedirect::Localized if resolved_is_canonical => {
                    if let Some(buf) = self.buffers.current_buffer() {
                        let target_buf = Value::make_buffer(buf.id);
                        if let Some(value) =
                            self.obarray
                                .read_localized(resolved, target_buf, buf.local_var_alist)
                        {
                            if value.is_unbound() {
                                return Err(signal(
                                    "void-variable",
                                    vec![value_from_symbol_id(sym_id)],
                                ));
                            }
                            return Ok(value);
                        }
                    }
                }
                SymbolRedirect::Forwarded => {
                    if let Some(value) = self.forwarded_buffer_obj_value(sym) {
                        return Ok(value);
                    }
                }
                SymbolRedirect::Plainval | SymbolRedirect::Varalias | SymbolRedirect::Localized => {
                }
            }
        }

        // Neomacs still stores `buffer-undo-list` in SharedUndoState
        // rather than a BUFFER_OBJFWD slot. Keep that special storage
        // out of the generic symbol-read path so ordinary PLAINVAL
        // symbols do not scan `local_var_alist`.
        if resolved_is_canonical
            && resolved == buffer_undo_list_symbol()
            && let Some(buf) = self.buffers.current_buffer()
            && let Some(binding) = buf.get_buffer_local_binding_by_sym_id(resolved)
        {
            return binding
                .as_value()
                .ok_or_else(|| signal("void-variable", vec![value_from_symbol_id(sym_id)]));
        }

        // Obarray value cell. Use `find_symbol_value` (not the
        // legacy `symbol_value_id`) so FORWARDED reads land on the
        // forwarder descriptor's default rather than returning None
        // and signalling void-variable.
        if let Some(value) = self.obarray.find_symbol_value(resolved) {
            return Ok(value);
        }

        // Task #36: canonical constant fallback. When `t` / `nil`
        // aren't explicitly stored in the obarray and aren't
        // specbound, they resolve to their canonical values.
        // Mirrors the vm.rs `lookup_var` fallback path.
        if is_canonical_id(sym_id) && sym_id == nil_symbol() {
            return Ok(Value::NIL);
        }
        if is_canonical_id(sym_id) && sym_id == t_symbol() {
            return Ok(Value::T);
        }
        if resolved_is_canonical && resolved == nil_symbol() {
            return Ok(Value::NIL);
        }
        if resolved_is_canonical && resolved == t_symbol() {
            return Ok(Value::T);
        }

        Err(signal("void-variable", vec![value_from_symbol_id(sym_id)]))
    }

    pub(crate) fn eval_symbol(&self, symbol: &str) -> EvalResult {
        self.eval_symbol_by_id(intern(symbol))
    }

    fn apply_symbol_callable(
        &mut self,
        sym_id: SymId,
        args: LispArgVec,
        rewrite_builtin_wrong_arity: bool,
    ) -> EvalResult {
        if super::builtins::is_canonical_symbol_id(sym_id) {
            let invalid_fn = if self.subr_is_special_form_id(sym_id) {
                Value::subr_from_sym_id(sym_id)
            } else {
                value_from_symbol_id(sym_id)
            };
            return self.apply_named_callable_by_id(
                sym_id,
                args,
                invalid_fn,
                rewrite_builtin_wrong_arity,
            );
        }

        if self.obarray.is_function_unbound_id(sym_id) {
            return Err(signal("void-function", vec![Value::from_sym_id(sym_id)]));
        }

        let Some(function) = self.obarray.symbol_function_id(sym_id) else {
            return Err(signal("void-function", vec![Value::from_sym_id(sym_id)]));
        };

        // Handle autoloads for non-canonical symbols the same as canonical
        // ones: trigger autoload-do-load before calling apply, so the raw
        // autoload cons never reaches apply_inner's Value::Cons path.
        if super::autoload::is_autoload_value(&function) {
            let name = resolve_sym(sym_id);
            return self.apply_named_autoload_callable(
                name,
                function,
                args,
                rewrite_builtin_wrong_arity,
            );
        }

        let function_is_callable = self.function_value_is_callable(&function);
        let result = self.apply_untraced(function, args);
        match &result {
            Err(Flow::Signal(sig))
                if sig.symbol_name() == "invalid-function" && !function_is_callable =>
            {
                Err(signal("invalid-function", vec![Value::from_sym_id(sym_id)]))
            }
            _ => result,
        }
    }

    fn apply_symbol_callable_untraced(
        &mut self,
        sym_id: SymId,
        args: LispArgVec,
        rewrite_builtin_wrong_arity: bool,
    ) -> EvalResult {
        if super::builtins::is_canonical_symbol_id(sym_id) {
            let invalid_fn = if self.subr_is_special_form_id(sym_id) {
                Value::subr_from_sym_id(sym_id)
            } else {
                value_from_symbol_id(sym_id)
            };
            return self.apply_named_callable_by_id_core(
                sym_id,
                args,
                invalid_fn,
                rewrite_builtin_wrong_arity,
            );
        }

        if self.obarray.is_function_unbound_id(sym_id) {
            return Err(signal("void-function", vec![Value::from_sym_id(sym_id)]));
        }

        let Some(function) = self.obarray.symbol_function_id(sym_id) else {
            return Err(signal("void-function", vec![Value::from_sym_id(sym_id)]));
        };

        if super::autoload::is_autoload_value(&function) {
            let name = resolve_sym(sym_id);
            return self.apply_named_autoload_callable(
                name,
                function,
                args,
                rewrite_builtin_wrong_arity,
            );
        }

        let function_is_callable = self.function_value_is_callable(&function);
        let result = self.apply_untraced(function, args);
        match &result {
            Err(Flow::Signal(sig))
                if sig.symbol_name() == "invalid-function" && !function_is_callable =>
            {
                Err(signal("invalid-function", vec![Value::from_sym_id(sym_id)]))
            }
            _ => result,
        }
    }

    pub(crate) fn function_value_is_callable(&self, function: &Value) -> bool {
        match function.kind() {
            ValueKind::Veclike(VecLikeType::Lambda)
            | ValueKind::Veclike(VecLikeType::ByteCode)
            | ValueKind::Veclike(VecLikeType::Macro) => true,
            ValueKind::Subr(_) | ValueKind::Veclike(VecLikeType::Subr) => {
                super::subr_info::subr_is_callable_function_value(function)
            }
            ValueKind::Cons => {
                super::autoload::is_autoload_value(function)
                    || matches!(
                        cons_head_symbol_id(function),
                        Some(id) if is_lambda_like_symbol_id(id) || id == macro_symbol()
                    )
            }
            ValueKind::Symbol(id) => {
                super::builtins::symbols::resolve_indirect_symbol_by_id(self, id)
                    .is_some_and(|(_, resolved)| self.function_value_is_callable(&resolved))
            }
            _ => false,
        }
    }

    fn maybe_writeback_mutating_first_arg(
        &mut self,
        called_name: &str,
        alias_target: Option<&str>,
        call_args: &[Value],
        result: &Value,
    ) {
        let mutates_fillarray =
            called_name == "fillarray" || alias_target.is_some_and(|name| name == "fillarray");
        let mutates_aset = called_name == "aset" || alias_target.is_some_and(|name| name == "aset");
        if !mutates_fillarray && !mutates_aset {
            return;
        }
        let Some(first_arg) = call_args.first() else {
            return;
        };
        if !first_arg.is_string() {
            return;
        }

        let replacement = if mutates_fillarray {
            if !result.is_string() || eq_value(first_arg, result) {
                return;
            }
            *result
        } else {
            if call_args.len() < 3 {
                return;
            }
            let Ok(updated) =
                super::builtins::aset_string_replacement(first_arg, &call_args[1], &call_args[2])
            else {
                return;
            };
            if eq_value(first_arg, &updated) {
                return;
            }
            updated
        };

        if crate::emacs_core::value::equal_value(first_arg, &replacement, 0) {
            return;
        }

        let mut visited = HashSet::new();
        // Walk the lexenv cons alist and replace alias refs in binding values
        {
            let mut lexenv_val = self.lexenv;
            Self::replace_alias_refs_in_value(
                &mut lexenv_val,
                first_arg,
                &replacement,
                &mut visited,
            );
            self.lexenv = lexenv_val;
        }
        // Dynamic bindings are now in the obarray (via specbind), so
        // the obarray iteration below handles them.
        if let Some(current_id) = self.buffers.current_buffer_id()
            && let Some(buf) = self.buffers.get_mut(current_id)
        {
            for value in buf.bound_buffer_local_values_mut() {
                Self::replace_alias_refs_in_value(value, first_arg, &replacement, &mut visited);
            }
        }

        self.obarray.for_each_value_cell_mut(|value| {
            Self::replace_alias_refs_in_value(value, first_arg, &replacement, &mut visited);
        });
    }

    fn replace_alias_refs_in_value(
        value: &mut Value,
        from: &Value,
        to: &Value,
        visited: &mut HashSet<usize>,
    ) {
        if eq_value(value, from) {
            *value = *to;
            return;
        }

        match value.kind() {
            ValueKind::Cons => {
                let key = value.bits() ^ 0x1;
                if !visited.insert(key) {
                    return;
                }
                let mut new_car = value.cons_car();
                let mut new_cdr = value.cons_cdr();
                Self::replace_alias_refs_in_value(&mut new_car, from, to, visited);
                Self::replace_alias_refs_in_value(&mut new_cdr, from, to, visited);
                value.set_car(new_car);
                value.set_cdr(new_cdr);
            }
            ValueKind::Veclike(VecLikeType::Vector) => {
                let key = value.bits() ^ 0x2;
                if !visited.insert(key) {
                    return;
                }
                let mut values = value.as_vector_data().unwrap().clone();
                for item in values.iter_mut() {
                    Self::replace_alias_refs_in_value(item, from, to, visited);
                }
                let _ = value.replace_vector_data(values);
            }
            ValueKind::Veclike(VecLikeType::Record) => {
                let key = value.bits() ^ 0x2;
                if !visited.insert(key) {
                    return;
                }
                let mut values = value.as_record_data().unwrap().clone();
                for item in values.iter_mut() {
                    Self::replace_alias_refs_in_value(item, from, to, visited);
                }
                let _ = value.replace_record_data(values);
            }
            ValueKind::Veclike(VecLikeType::HashTable) => {
                let key = value.bits() ^ 0x4;
                if !visited.insert(key) {
                    return;
                }
                let mut ht = value.as_hash_table().unwrap().clone();
                let old_ptr = if from.is_string() {
                    Some(from.bits())
                } else {
                    None
                };
                let new_ptr = if to.is_string() {
                    Some(to.bits())
                } else {
                    None
                };
                if matches!(ht.test, HashTableTest::Eq | HashTableTest::Eql) {
                    if let (Some(old_ptr), Some(new_ptr)) = (old_ptr, new_ptr) {
                        if let Some(existing) = ht.data.remove(&HashKey::Ptr(old_ptr)) {
                            ht.data.insert(HashKey::Ptr(new_ptr), existing);
                        }
                        if ht.key_snapshots.remove(&HashKey::Ptr(old_ptr)).is_some() {
                            ht.key_snapshots.insert(HashKey::Ptr(new_ptr), *to);
                        }
                        for k in &mut ht.insertion_order {
                            if *k == HashKey::Ptr(old_ptr) {
                                *k = HashKey::Ptr(new_ptr);
                            }
                        }
                    }
                }
                for item in ht.data.values_mut() {
                    Self::replace_alias_refs_in_value(item, from, to, visited);
                }
                let _ = value.replace_hash_table(ht);
            }
            _ => {}
        }
    }

    // -----------------------------------------------------------------------
    // Special forms
    // -----------------------------------------------------------------------

    fn try_special_form_value_id(&mut self, sym_id: SymId, tail: Value) -> Option<EvalResult> {
        let saved_depth = self.depth;
        let result = self.try_special_form_inner_value_id(sym_id, tail);
        self.depth = saved_depth;
        result
    }

    fn try_aliased_special_form_value_id(
        &mut self,
        surface_id: SymId,
        target_id: SymId,
        tail: Value,
    ) -> Option<EvalResult> {
        let saved_depth = self.depth;
        let surface_name = resolve_sym(surface_id);
        let result = Some(match target_id {
            id if id == quote_symbol() => self.sf_quote_value_named(surface_name, tail),
            id if id == function_symbol() => self.sf_function_value_named(surface_name, tail),
            id if id == let_symbol() => self.sf_let_value_named(surface_name, tail),
            id if id == let_star_symbol() => self.sf_let_star_value_named(surface_name, tail),
            id if id == setq_symbol() => self.sf_setq_value_named(surface_name, tail),
            id if id == if_symbol() => self.sf_if_value_named(surface_name, tail),
            id if id == and_symbol() => self.sf_and_value(tail),
            id if id == or_symbol() => self.sf_or_value(tail),
            id if id == cond_symbol() => self.sf_cond_value(tail),
            id if id == while_symbol() => self.sf_while_value_named(surface_name, tail),
            id if id == progn_symbol() => self.sf_progn_value(tail),
            id if id == prog1_symbol() => self.sf_prog1_value_named(surface_name, tail),
            id if id == defvar_symbol() => self.sf_defvar_value_named(surface_name, tail),
            id if id == defconst_symbol() => self.sf_defconst_value_named(surface_name, tail),
            id if id == catch_symbol() => self.sf_catch_value_named(surface_name, tail),
            id if id == unwind_protect_symbol() => {
                self.sf_unwind_protect_value_named(surface_name, tail)
            }
            id if id == condition_case_symbol() => {
                self.sf_condition_case_value_named(surface_name, tail)
            }
            id if id == save_excursion_symbol() => self.sf_save_excursion_value(tail),
            id if id == save_current_buffer_symbol() => self.sf_save_current_buffer_value(tail),
            id if id == save_restriction_symbol() => self.sf_save_restriction_value(tail),
            id if id == interactive_symbol_id() => Ok(Value::NIL),
            _ => return None,
        });
        self.depth = saved_depth;
        result
    }

    fn try_special_form_inner_value_id(
        &mut self,
        sym_id: SymId,
        tail: Value,
    ) -> Option<EvalResult> {
        Some(match sym_id {
            id if id == quote_symbol() => self.sf_quote_value(tail),
            id if id == function_symbol() => self.sf_function_value(tail),
            id if id == let_symbol() => self.sf_let_value(tail),
            id if id == let_star_symbol() => self.sf_let_star_value(tail),
            id if id == setq_symbol() => self.sf_setq_value(tail),
            id if id == if_symbol() => self.sf_if_value(tail),
            id if id == and_symbol() => self.sf_and_value(tail),
            id if id == or_symbol() => self.sf_or_value(tail),
            id if id == cond_symbol() => self.sf_cond_value(tail),
            id if id == while_symbol() => self.sf_while_value(tail),
            id if id == progn_symbol() => self.sf_progn_value(tail),
            id if id == prog1_symbol() => self.sf_prog1_value(tail),
            id if id == defvar_symbol() => self.sf_defvar_value(tail),
            id if id == defconst_symbol() => self.sf_defconst_value(tail),
            id if id == catch_symbol() => self.sf_catch_value(tail),
            id if id == unwind_protect_symbol() => self.sf_unwind_protect_value(tail),
            id if id == condition_case_symbol() => self.sf_condition_case_value(tail),
            id if id == save_excursion_symbol() => self.sf_save_excursion_value(tail),
            id if id == save_current_buffer_symbol() => self.sf_save_current_buffer_value(tail),
            id if id == save_restriction_symbol() => self.sf_save_restriction_value(tail),
            id if id == interactive_symbol_id() => Ok(Value::NIL),
            id if id == lambda_symbol() => self.sf_lambda_value(tail),
            id if id == byte_code_literal_symbol() => self.sf_byte_code_literal_value(tail),
            id if id == byte_code_symbol() => self.sf_byte_code_value(tail),
            _ => return None,
        })
    }

    fn listp_error(&self, value: Value) -> Flow {
        // GNU `CHECK_LIST` walks the cdr chain until it finds the
        // non-cons tail and signals
        // `(wrong-type-argument listp TAIL)` with the offending
        // tail element, not the whole input. Verified against
        // emacs 31.0.50 via:
        //   (condition-case e (length '(1 . 2)) (error e))
        //     -> (wrong-type-argument listp 2)
        //   (condition-case e (let ((x 1) . 2) x) (error e))
        //     -> (wrong-type-argument listp 2)
        let mut tail = value;
        while tail.is_cons() {
            tail = tail.cons_cdr();
        }
        signal("wrong-type-argument", vec![Value::symbol("listp"), tail])
    }

    fn value_list_len_or_error(&self, list: Value) -> Result<usize, Flow> {
        list_length(&list).ok_or_else(|| self.listp_error(list))
    }

    fn one_unevalled_arg(&self, name: &str, tail: Value) -> Result<Value, Flow> {
        let mut cursor = tail;
        if !cursor.is_cons() {
            return if cursor.is_nil() {
                Err(signal(
                    "wrong-number-of-arguments",
                    vec![Value::symbol(name), Value::fixnum(0)],
                ))
            } else {
                Err(self.listp_error(tail))
            };
        }
        let arg = cursor.cons_car();
        cursor = cursor.cons_cdr();
        if !cursor.is_nil() {
            return Err(signal(
                "wrong-number-of-arguments",
                vec![
                    Value::symbol(name),
                    Value::fixnum(self.value_list_len_or_error(tail)? as i64),
                ],
            ));
        }
        Ok(arg)
    }

    fn sf_quote_value(&mut self, tail: Value) -> EvalResult {
        self.sf_quote_value_named("quote", tail)
    }

    fn sf_quote_value_named(&mut self, call_name: &str, tail: Value) -> EvalResult {
        Ok(self.one_unevalled_arg(call_name, tail)?)
    }

    fn sf_function_value(&mut self, tail: Value) -> EvalResult {
        self.sf_function_value_named("function", tail)
    }

    fn sf_function_value_named(&mut self, call_name: &str, tail: Value) -> EvalResult {
        let arg = self.one_unevalled_arg(call_name, tail)?;
        if cons_head_symbol_id(&arg) == Some(lambda_symbol()) {
            return self.instantiate_callable_cons_form(arg);
        }
        Ok(arg)
    }

    fn sf_lambda_value(&mut self, tail: Value) -> EvalResult {
        self.instantiate_callable_cons_form(Value::cons(Value::from_sym_id(lambda_symbol()), tail))
    }

    fn sf_let_value(&mut self, tail: Value) -> EvalResult {
        self.sf_let_value_named("let", tail)
    }

    fn sf_let_value_named(&mut self, call_name: &str, tail: Value) -> EvalResult {
        if tail.is_nil() {
            return Err(signal(
                "wrong-number-of-arguments",
                vec![Value::symbol(call_name), Value::fixnum(0)],
            ));
        }
        if !tail.is_cons() {
            return Err(self.listp_error(tail));
        }

        let varlist = tail.cons_car();
        let body = tail.cons_cdr();
        let mut lexical_bindings = LetBindingVec::new();
        let mut dynamic_sym_ids = LetBindingVec::new();
        let use_lexical = self.lexical_binding();
        let mut constant_binding_error: Option<String> = None;
        let specpdl_root_scope = self.save_specpdl_roots();
        let mut bindings = varlist;

        while bindings.is_cons() {
            let binding = self.unwrap_symbol(bindings.cons_car());
            bindings = bindings.cons_cdr();
            if let Some(id) = binding.as_symbol_id() {
                if let Some(name) = symbol_sets_constant_error(id) {
                    if constant_binding_error.is_none() {
                        constant_binding_error = Some(name.to_owned());
                    }
                    continue;
                }
                if use_lexical
                    && !self.obarray.is_special_id(id)
                    && !self.lexenv_declares_special_cached_in(self.lexenv, id)
                {
                    lexical_bindings.push((id, Value::NIL));
                } else {
                    dynamic_sym_ids.push((id, Value::NIL));
                }
                continue;
            }
            if !binding.is_cons() {
                self.restore_specpdl_roots(specpdl_root_scope);
                return Err(signal("wrong-type-argument", vec![]));
            }
            let head = self.unwrap_symbol(binding.cons_car());
            let Some(id) = head.as_symbol_id() else {
                self.restore_specpdl_roots(specpdl_root_scope);
                return Err(signal(
                    "wrong-type-argument",
                    vec![Value::symbol("symbolp"), head],
                ));
            };
            let mut value_tail = binding.cons_cdr();
            let value = if value_tail.is_nil() {
                Value::NIL
            } else if value_tail.is_cons() {
                let init_form = value_tail.cons_car();
                value_tail = value_tail.cons_cdr();
                if !value_tail.is_nil() {
                    self.restore_specpdl_roots(specpdl_root_scope);
                    return Err(signal(
                        "error",
                        vec![
                            Value::string("`let' bindings can have only one value-form"),
                            binding,
                        ],
                    ));
                }
                match self.eval_sub(init_form) {
                    Ok(value) => value,
                    Err(err) => {
                        self.restore_specpdl_roots(specpdl_root_scope);
                        return Err(err);
                    }
                }
            } else {
                self.restore_specpdl_roots(specpdl_root_scope);
                return Err(self.listp_error(binding));
            };
            self.push_specpdl_root(value);
            if let Some(name) = symbol_sets_constant_error(id) {
                if constant_binding_error.is_none() {
                    constant_binding_error = Some(name.to_owned());
                }
                continue;
            }
            if use_lexical
                && !self.obarray.is_special_id(id)
                && !self.lexenv_declares_special_cached_in(self.lexenv, id)
            {
                lexical_bindings.push((id, value));
            } else {
                dynamic_sym_ids.push((id, value));
            }
        }
        if !bindings.is_nil() {
            self.restore_specpdl_roots(specpdl_root_scope);
            return Err(self.listp_error(varlist));
        }
        if let Some(name) = constant_binding_error {
            self.restore_specpdl_roots(specpdl_root_scope);
            return Err(signal("setting-constant", vec![Value::symbol(name)]));
        }

        // CRITICAL: Restore specpdl roots (drop init-form GcRoot entries) BEFORE
        // pushing LexicalEnv/Let entries. Otherwise `restore_specpdl_roots`
        // drains from `saved_len` and re-extends with non-GcRoot entries,
        // MOVING our LexicalEnv to a lower index. Then `unbind_to(specpdl_count)`
        // becomes a no-op because specpdl.len() already matches, and the stale
        // LexicalEnv leaks below. This caused lexical binding leaks — closures
        // created in the body captured oversized environments.
        self.restore_specpdl_roots(specpdl_root_scope);

        // Save lexenv AFTER init forms run (matches GNU eval.c:1167:
        //   `lexenv = Vinternal_interpreter_environment;`).
        // Capture specpdl_count AFTER restoring so LexicalEnv sits exactly at
        // specpdl[specpdl_count] and unbind_to will pop it.
        let lexenv_at_entry = self.lexenv;
        let specpdl_count = self.specpdl.len();

        // Always save the entry-point lexenv on the specpdl when in lexical
        // mode, so unbind_to restores it regardless of what the body does.
        // Matches GNU's specbind(Qinternal_interpreter_environment).
        if use_lexical {
            self.specpdl.push(SpecBinding::LexicalEnv {
                old_lexenv: lexenv_at_entry,
            });
        }

        // Build new lexenv locally by consing bindings onto the ENTRY-POINT
        // lexenv (not self.lexenv which may have been modified by init forms).
        // Matches GNU eval.c:1167-1186.
        let mut new_lexenv = lexenv_at_entry;
        for (sym_id, val) in &lexical_bindings {
            let binding_pair = Value::make_cons(
                crate::emacs_core::eval::lexenv_binding_symbol_value(*sym_id),
                *val,
            );
            self.specpdl.push(SpecBinding::GcRoot {
                value: binding_pair,
            });
            new_lexenv = Value::make_cons(binding_pair, new_lexenv);
            match self.specpdl.last_mut() {
                Some(SpecBinding::GcRoot { value }) => *value = new_lexenv,
                _ => unreachable!(),
            }
        }
        // Install the new lexenv atomically.
        self.lexenv = new_lexenv;
        for (sym_id, value) in &dynamic_sym_ids {
            self.specbind(*sym_id, *value);
        }

        let result = self.sf_progn_value(body);
        self.unbind_to(specpdl_count);
        result
    }

    fn sf_let_star_value(&mut self, tail: Value) -> EvalResult {
        self.sf_let_star_value_named("let*", tail)
    }

    fn sf_let_star_value_named(&mut self, call_name: &str, tail: Value) -> EvalResult {
        if tail.is_nil() {
            return Err(signal(
                "wrong-number-of-arguments",
                vec![Value::symbol(call_name), Value::fixnum(0)],
            ));
        }
        if !tail.is_cons() {
            return Err(self.listp_error(tail));
        }

        let varlist = tail.cons_car();
        let body = tail.cons_cdr();
        let use_lexical = self.lexical_binding();
        let specpdl_count = self.specpdl.len();
        // Mirrors GNU Flet_star: specbind(Qinternal_interpreter_environment, lexenv)
        // before any per-variable specbinds. unbind_to pops everything.
        if use_lexical {
            self.specpdl.push(SpecBinding::LexicalEnv {
                old_lexenv: self.lexenv,
            });
        }

        let init_result: Result<(), Flow> = (|| {
            let mut bindings = varlist;
            while bindings.is_cons() {
                let binding = self.unwrap_symbol(bindings.cons_car());
                bindings = bindings.cons_cdr();
                let (id, value) = if let Some(id) = binding.as_symbol_id() {
                    (id, Value::NIL)
                } else if binding.is_cons() {
                    let head = self.unwrap_symbol(binding.cons_car());
                    let Some(id) = head.as_symbol_id() else {
                        return Err(signal(
                            "wrong-type-argument",
                            vec![Value::symbol("symbolp"), head],
                        ));
                    };
                    let mut value_tail = binding.cons_cdr();
                    let value = if value_tail.is_nil() {
                        Value::NIL
                    } else if value_tail.is_cons() {
                        let init_form = value_tail.cons_car();
                        value_tail = value_tail.cons_cdr();
                        if !value_tail.is_nil() {
                            return Err(signal(
                                "error",
                                vec![
                                    Value::string("`let' bindings can have only one value-form"),
                                    binding,
                                ],
                            ));
                        }
                        self.eval_sub(init_form)?
                    } else {
                        return Err(self.listp_error(binding));
                    };
                    (id, value)
                } else {
                    return Err(signal("wrong-type-argument", vec![]));
                };

                if let Some(name) = symbol_sets_constant_error(id) {
                    return Err(signal("setting-constant", vec![Value::symbol(name)]));
                }
                if use_lexical
                    && !self.obarray.is_special_id(id)
                    && !self.lexenv_declares_special_cached_in(self.lexenv, id)
                {
                    // Matches GNU Flet_star (eval.c:1113-1120):
                    // Direct cons onto Vinternal_interpreter_environment.
                    // The LexicalEnv entry at specpdl_count saves the pre-let*
                    // state; unbind_to restores it.
                    let binding = Value::make_cons(lexenv_binding_symbol_value(id), value);
                    self.lexenv = Value::make_cons(binding, self.lexenv);
                } else {
                    self.specbind(id, value);
                }
            }
            if !bindings.is_nil() {
                return Err(self.listp_error(varlist));
            }
            Ok(())
        })();
        if let Err(error) = init_result {
            self.unbind_to(specpdl_count);
            return Err(error);
        }

        let result = self.sf_progn_value(body);
        self.unbind_to(specpdl_count);
        result
    }

    fn sf_setq_value(&mut self, tail: Value) -> EvalResult {
        self.sf_setq_value_named("setq", tail)
    }

    fn sf_setq_value_named(&mut self, call_name: &str, tail: Value) -> EvalResult {
        if tail.is_nil() {
            return Ok(Value::NIL);
        }
        let mut cursor = tail;
        let mut last = Value::NIL;
        let mut nargs: usize = 0;
        while cursor.is_cons() {
            let symbol = cursor.cons_car();
            cursor = cursor.cons_cdr();
            nargs += 1;
            if cursor.is_nil() {
                return Err(signal(
                    "wrong-number-of-arguments",
                    vec![Value::symbol(call_name), Value::fixnum(nargs as i64)],
                ));
            }
            if !cursor.is_cons() {
                return Err(self.listp_error(tail));
            }
            let value_form = cursor.cons_car();
            cursor = cursor.cons_cdr();
            nargs += 1;
            let symbol = self.unwrap_symbol(symbol);
            let Some(sym_id) = symbol.as_symbol_id() else {
                return Err(signal(
                    "wrong-type-argument",
                    vec![Value::symbol("symbolp"), symbol],
                ));
            };
            let value = self.eval_sub(value_form)?;
            let resolved_id = super::builtins::resolve_variable_alias_id(self, sym_id)?;
            if self.obarray.is_constant_id(resolved_id)
                && !self.has_local_binding_by_id(sym_id)
                && (resolved_id == sym_id || !self.has_local_binding_by_id(resolved_id))
            {
                if let Some(result) = super::builtins::constant_set_outcome_in_obarray(
                    self.obarray(),
                    resolved_id,
                    value_from_symbol_id(sym_id),
                    value,
                ) {
                    return result;
                }
            }
            // Debug probe for multibyte assignments to default-directory.
            // Kept at debug level so it doesn't pollute normal error
            // output (Doom always fires this with pure-ASCII paths that
            // happen to carry the multibyte flag from string decoding).
            if sym_id == default_directory_symbol()
                && value.is_string()
                && value.string_is_multibyte()
            {
                tracing::debug!(
                    "SETQ default-directory to MULTIBYTE string: {:?}",
                    runtime_string_value(value),
                );
            }
            self.assign_with_watchers_by_id(resolved_id, value, "set")?;
            last = value;
        }
        if !cursor.is_nil() {
            return Err(self.listp_error(tail));
        }
        Ok(last)
    }

    fn sf_if_value(&mut self, tail: Value) -> EvalResult {
        self.sf_if_value_named("if", tail)
    }

    fn sf_if_value_named(&mut self, call_name: &str, tail: Value) -> EvalResult {
        if tail.is_nil() {
            return Err(signal(
                "wrong-number-of-arguments",
                vec![Value::symbol(call_name), Value::fixnum(0)],
            ));
        }
        if !tail.is_cons() {
            return Err(self.listp_error(tail));
        }
        let cond_form = tail.cons_car();
        let mut rest = tail.cons_cdr();
        if rest.is_nil() {
            return Err(signal(
                "wrong-number-of-arguments",
                vec![Value::symbol(call_name), Value::fixnum(1)],
            ));
        }
        if !rest.is_cons() {
            return Err(self.listp_error(tail));
        }
        let then_form = rest.cons_car();
        rest = rest.cons_cdr();
        if self.eval_sub(cond_form)?.is_truthy() {
            self.eval_sub(then_form)
        } else {
            self.sf_progn_value(rest)
        }
    }

    fn sf_and_value(&mut self, tail: Value) -> EvalResult {
        let mut cursor = tail;
        let mut last = Value::T;
        while cursor.is_cons() {
            last = self.eval_sub(cursor.cons_car())?;
            if last.is_nil() {
                return Ok(Value::NIL);
            }
            cursor = cursor.cons_cdr();
        }
        if !cursor.is_nil() {
            return Err(self.listp_error(tail));
        }
        Ok(last)
    }

    fn sf_or_value(&mut self, tail: Value) -> EvalResult {
        let mut cursor = tail;
        while cursor.is_cons() {
            let value = self.eval_sub(cursor.cons_car())?;
            if value.is_truthy() {
                return Ok(value);
            }
            cursor = cursor.cons_cdr();
        }
        if !cursor.is_nil() {
            return Err(self.listp_error(tail));
        }
        Ok(Value::NIL)
    }

    fn sf_cond_value(&mut self, tail: Value) -> EvalResult {
        let mut clauses = tail;
        while clauses.is_cons() {
            let clause = clauses.cons_car();
            clauses = clauses.cons_cdr();
            if clause.is_nil() {
                continue;
            }
            if !clause.is_cons() {
                return Err(signal(
                    "wrong-type-argument",
                    vec![Value::symbol("listp"), clause],
                ));
            }
            let test = clause.cons_car();
            let body = clause.cons_cdr();
            let test_value = self.eval_sub(test)?;
            if test_value.is_truthy() {
                if body.is_nil() {
                    return Ok(test_value);
                }
                return self.sf_progn_value(body);
            }
        }
        if !clauses.is_nil() {
            return Err(self.listp_error(tail));
        }
        Ok(Value::NIL)
    }

    fn sf_while_value(&mut self, tail: Value) -> EvalResult {
        self.sf_while_value_named("while", tail)
    }

    fn sf_while_value_named(&mut self, call_name: &str, tail: Value) -> EvalResult {
        if tail.is_nil() {
            return Err(signal(
                "wrong-number-of-arguments",
                vec![Value::symbol(call_name), Value::fixnum(0)],
            ));
        }
        if !tail.is_cons() {
            return Err(self.listp_error(tail));
        }
        let test_form = tail.cons_car();
        let body = tail.cons_cdr();
        let mut iters: u64 = 0;
        loop {
            if self.eval_sub(test_form)?.is_nil() {
                return Ok(Value::NIL);
            }
            self.sf_progn_value(body)?;
            iters += 1;
            if iters == 1_000_000 {
                let cond_str = super::print::print_value(&test_form);
                tracing::warn!(
                    "while loop exceeded 1M iterations, cond: {}",
                    &cond_str[..cond_str.len().min(300)]
                );
            }
            self.maybe_quit()?;
        }
    }

    fn sf_progn_value(&mut self, forms: Value) -> EvalResult {
        let mut cursor = forms;
        let mut last = Value::NIL;
        while cursor.is_cons() {
            last = self.eval_sub(cursor.cons_car())?;
            cursor = cursor.cons_cdr();
        }
        if !cursor.is_nil() {
            return Err(self.listp_error(forms));
        }
        Ok(last)
    }

    fn sf_prog1_value(&mut self, tail: Value) -> EvalResult {
        self.sf_prog1_value_named("prog1", tail)
    }

    fn sf_prog1_value_named(&mut self, call_name: &str, tail: Value) -> EvalResult {
        if tail.is_nil() {
            return Err(signal(
                "wrong-number-of-arguments",
                vec![Value::symbol(call_name), Value::fixnum(0)],
            ));
        }
        if !tail.is_cons() {
            return Err(self.listp_error(tail));
        }
        let first_form = tail.cons_car();
        let rest = tail.cons_cdr();
        let first = self.eval_sub(first_form)?;
        let specpdl_root_scope = self.save_specpdl_roots();
        self.push_specpdl_root(first);
        let result = self.sf_progn_value(rest);
        self.restore_specpdl_roots(specpdl_root_scope);
        result?;
        Ok(first)
    }

    fn sf_defvar_value(&mut self, tail: Value) -> EvalResult {
        self.sf_defvar_value_named("defvar", tail)
    }

    fn sf_defvar_value_named(&mut self, call_name: &str, tail: Value) -> EvalResult {
        if tail.is_nil() {
            return Err(signal(
                "wrong-number-of-arguments",
                vec![Value::symbol(call_name), Value::fixnum(0)],
            ));
        }
        if !tail.is_cons() {
            return Err(self.listp_error(tail));
        }

        let symbol = self.unwrap_symbol(tail.cons_car());
        let Some(sym_id) = symbol.as_symbol_id() else {
            return Err(signal(
                "wrong-type-argument",
                vec![Value::symbol("symbolp"), symbol],
            ));
        };
        let mut rest = tail.cons_cdr();

        if rest.is_nil() {
            if self.lexical_binding()
                && !self.lexenv.is_nil()
                && !self.obarray.is_special_id(sym_id)
            {
                self.lexenv = Value::cons(Value::from_sym_id(sym_id), self.lexenv);
            }
            return Ok(Value::from_sym_id(sym_id));
        }
        if !rest.is_cons() {
            return Err(self.listp_error(tail));
        }
        let init_form = rest.cons_car();
        rest = rest.cons_cdr();
        let documentation = if rest.is_nil() {
            Value::NIL
        } else if rest.is_cons() {
            let doc = rest.cons_car();
            rest = rest.cons_cdr();
            if !rest.is_nil() {
                return Err(signal("error", vec![Value::string("Too many arguments")]));
            }
            doc
        } else {
            return Err(self.listp_error(tail));
        };

        let mut define_args = vec![symbol];
        if !documentation.is_nil() {
            define_args.push(documentation);
        }
        super::builtins::symbols::builtin_internal_define_uninitialized_variable(
            self,
            define_args,
        )?;

        let was_bound = default_toplevel_value_in_state(
            &self.obarray,
            self.specpdl.as_slice(),
            Some(&self.buffers.buffer_defaults),
            sym_id,
        )
        .is_some()
            || self.obarray.is_constant_id(sym_id);
        if !was_bound {
            let value = self.eval_sub(init_form)?;
            super::builtins::symbols::builtin_set_default_toplevel_value(
                self,
                vec![symbol, value],
            )?;
        }

        Ok(Value::from_sym_id(sym_id))
    }

    fn sf_defconst_value(&mut self, tail: Value) -> EvalResult {
        self.sf_defconst_value_named("defconst", tail)
    }

    fn sf_defconst_value_named(&mut self, call_name: &str, tail: Value) -> EvalResult {
        if tail.is_nil() {
            return Err(signal(
                "wrong-number-of-arguments",
                vec![Value::symbol(call_name), Value::fixnum(0)],
            ));
        }
        if !tail.is_cons() {
            return Err(self.listp_error(tail));
        }
        let symbol = self.unwrap_symbol(tail.cons_car());
        let Some(sym_id) = symbol.as_symbol_id() else {
            return Err(signal(
                "wrong-type-argument",
                vec![Value::symbol("symbolp"), symbol],
            ));
        };
        let mut rest = tail.cons_cdr();
        if rest.is_nil() {
            return Err(signal(
                "wrong-number-of-arguments",
                vec![Value::symbol(call_name), Value::fixnum(1)],
            ));
        }
        if !rest.is_cons() {
            return Err(self.listp_error(tail));
        }
        let init_form = rest.cons_car();
        rest = rest.cons_cdr();
        let documentation = if rest.is_nil() {
            Value::NIL
        } else if rest.is_cons() {
            let doc = rest.cons_car();
            rest = rest.cons_cdr();
            if !rest.is_nil() {
                return Err(signal("error", vec![Value::string("Too many arguments")]));
            }
            doc
        } else {
            return Err(self.listp_error(tail));
        };

        let mut define_args = vec![symbol];
        if !documentation.is_nil() {
            define_args.push(documentation);
        }
        super::builtins::symbols::builtin_internal_define_uninitialized_variable(
            self,
            define_args,
        )?;

        let value = self.eval_sub(init_form)?;
        super::custom::builtin_set_default(self, vec![symbol, value])?;
        self.obarray.make_special_id(sym_id);
        self.obarray
            .put_property_id(sym_id, intern("risky-local-variable"), Value::T)?;
        Ok(Value::from_sym_id(sym_id))
    }

    fn sf_catch_value(&mut self, tail: Value) -> EvalResult {
        self.sf_catch_value_named("catch", tail)
    }

    fn sf_catch_value_named(&mut self, call_name: &str, tail: Value) -> EvalResult {
        if tail.is_nil() {
            return Err(signal(
                "wrong-number-of-arguments",
                vec![Value::symbol(call_name), Value::fixnum(0)],
            ));
        }
        if !tail.is_cons() {
            return Err(self.listp_error(tail));
        }
        let tag = self.eval_sub(tail.cons_car())?;
        self.push_condition_frame(ConditionFrame::Catch {
            tag,
            resume: ResumeTarget::InterpreterCatch,
        });
        let result = match self.sf_progn_value(tail.cons_cdr()) {
            Ok(value) => Ok(value),
            Err(Flow::Signal(sig)) => match self.dispatch_signal_if_needed(sig) {
                Ok(dispatched) => Err(Flow::Signal(dispatched)),
                Err(Flow::Throw {
                    tag: thrown_tag,
                    value,
                }) if eq_value(&tag, &thrown_tag) => Ok(value),
                Err(flow) => Err(flow),
            },
            Err(Flow::Throw {
                tag: thrown_tag,
                value,
            }) if eq_value(&tag, &thrown_tag) => Ok(value),
            Err(flow) => Err(flow),
        };
        self.pop_condition_frame();
        result
    }

    fn sf_unwind_protect_value(&mut self, tail: Value) -> EvalResult {
        self.sf_unwind_protect_value_named("unwind-protect", tail)
    }

    fn sf_unwind_protect_value_named(&mut self, call_name: &str, tail: Value) -> EvalResult {
        // GNU eval.c:1461 declares `unwind-protect` with min_args=1.
        // The generic arity check in GNU `eval_sub` (eval.c:2612) runs
        // for every SUBRP including UNEVALLED. Neomacs skips that check
        // for special forms (dispatch_kind != SpecialForm at
        // eval.rs:6599) so each special form validates itself -- see
        // `sf_condition_case_value_named`.
        let nargs = self.value_list_len_or_error(tail)?;
        if nargs < 1 {
            return Err(signal(
                "wrong-number-of-arguments",
                vec![Value::symbol(call_name), Value::fixnum(nargs as i64)],
            ));
        }
        let body = tail.cons_car();
        let cleanup_forms = tail.cons_cdr();
        // Pre-allocate a `GcRoot` slot BELOW the `UnwindProtect` so
        // the body result is GC-rooted during cleanup. `unbind_to`
        // pops top-down, so when the `UnwindProtect` entry runs
        // cleanup the `GcRoot` slot beneath it is still on the stack
        // and visible to the tracer. GNU relies on conservative stack
        // scanning of a C local `val`; neomacs uses exact GC and
        // needs the value on specpdl.
        let root_slot = self.specpdl.len();
        self.specpdl.push(SpecBinding::GcRoot { value: Value::NIL });
        self.specpdl.push(SpecBinding::UnwindProtect {
            forms: cleanup_forms,
            lexenv: self.lexenv,
        });
        let result = self.eval_sub(body);
        if let Ok(v) = result {
            if let Some(SpecBinding::GcRoot { value }) = self.specpdl.get_mut(root_slot) {
                *value = v;
            }
        }
        self.unbind_to(root_slot);
        result
    }

    fn sf_condition_case_value(&mut self, tail: Value) -> EvalResult {
        self.sf_condition_case_value_named("condition-case", tail)
    }

    fn sf_condition_case_value_named(&mut self, call_name: &str, tail: Value) -> EvalResult {
        let nargs = self.value_list_len_or_error(tail)?;
        if nargs < 3 {
            return Err(signal(
                "wrong-number-of-arguments",
                vec![Value::symbol(call_name), Value::fixnum(nargs as i64)],
            ));
        }
        let var = self.unwrap_symbol(tail.cons_car());
        let Some(var_id) = var.as_symbol_id() else {
            return Err(signal(
                "wrong-type-argument",
                vec![Value::symbol("symbolp"), var],
            ));
        };
        let rest = tail.cons_cdr();
        if !rest.is_cons() {
            return Err(self.listp_error(tail));
        }
        let body = rest.cons_car();
        let handlers = rest.cons_cdr();

        let mut handlers_vec = Vec::new();
        let mut success_handler_idx: Option<usize> = None;
        let mut cursor = handlers;
        while cursor.is_cons() {
            let handler = cursor.cons_car();
            let handler_index = handlers_vec.len();
            handlers_vec.push(handler);
            cursor = cursor.cons_cdr();
            if handler.is_nil() {
                continue;
            }
            if !handler.is_cons() {
                return Err(signal(
                    "error",
                    vec![Value::string(format!(
                        "Invalid condition handler: {}",
                        super::print::print_value(&handler)
                    ))],
                ));
            }
            let head = handler.cons_car();
            if !(head.is_symbol() || head.is_symbol_with_pos() || head.is_cons()) {
                return Err(signal(
                    "error",
                    vec![Value::string(format!(
                        "Invalid condition handler: {}",
                        super::print::print_value(&handler)
                    ))],
                ));
            }
            let head_unwrapped = self.unwrap_symbol(head);
            if head_unwrapped.is_symbol_named(":success") {
                success_handler_idx = Some(handler_index);
            }
        }
        if !cursor.is_nil() {
            return Err(self.listp_error(handlers));
        }

        let condition_stack_base = self.condition_stack_len();
        for (idx, handler) in handlers_vec.iter().enumerate().rev() {
            if success_handler_idx == Some(idx) || handler.is_nil() {
                continue;
            }
            if !handler.is_cons() {
                continue;
            }
            let conditions = handler.cons_car();
            self.push_condition_frame(ConditionFrame::ConditionCase {
                conditions,
                resume: ResumeTarget::InterpreterConditionCase {
                    handler_index: idx,
                    condition_stack_base,
                },
            });
        }

        match self.eval_sub(body) {
            Ok(value) => {
                self.truncate_condition_stack(condition_stack_base);
                if let Some(idx) = success_handler_idx {
                    let handler = handlers_vec[idx];
                    let bind_var = !var.is_nil();
                    let specpdl_count = self.specpdl.len();
                    if bind_var {
                        self.specbind(var_id, value);
                    }
                    let result = self.sf_progn_value(handler.cons_cdr());
                    self.unbind_to(specpdl_count);
                    return result;
                }
                Ok(value)
            }
            Err(Flow::Signal(sig)) => {
                let sig = match self.dispatch_signal_if_needed(sig) {
                    Ok(dispatched) => dispatched,
                    Err(flow) => {
                        self.truncate_condition_stack(condition_stack_base);
                        return Err(flow);
                    }
                };
                self.truncate_condition_stack(condition_stack_base);
                if let Some(ResumeTarget::InterpreterConditionCase {
                    handler_index,
                    condition_stack_base: selected_stack_base,
                }) = sig.selected_resume.clone()
                    && selected_stack_base == condition_stack_base
                {
                    let handler = handlers_vec[handler_index];
                    let bind_var = !var.is_nil();
                    let binding_value = make_signal_binding_value(&sig);
                    let use_lexical_binding = bind_var
                        && self.lexical_binding()
                        && !is_runtime_dynamically_special(&self.obarray, var_id)
                        && !self.lexenv_declares_special_cached_in(self.lexenv, var_id);

                    let specpdl_count = self.specpdl.len();
                    if use_lexical_binding {
                        // Match GNU: specbind the lexenv, then cons the
                        // binding directly.
                        self.specpdl.push(SpecBinding::LexicalEnv {
                            old_lexenv: self.lexenv,
                        });
                        let binding =
                            Value::make_cons(lexenv_binding_symbol_value(var_id), binding_value);
                        self.lexenv = Value::make_cons(binding, self.lexenv);
                    } else if bind_var {
                        self.specbind(var_id, binding_value);
                    }
                    let result = self.sf_progn_value(handler.cons_cdr());
                    self.unbind_to(specpdl_count);
                    return result;
                }
                Err(Flow::Signal(sig))
            }
            Err(flow @ Flow::Throw { .. }) => {
                self.truncate_condition_stack(condition_stack_base);
                Err(flow)
            }
        }
    }

    fn sf_save_excursion_value(&mut self, tail: Value) -> EvalResult {
        let count = self.specpdl.len();
        self.record_save_excursion();
        let result = self.sf_progn_value(tail);
        self.unbind_to(count);
        result
    }

    fn sf_save_current_buffer_value(&mut self, tail: Value) -> EvalResult {
        let saved_buf = self.buffers.current_buffer().map(|b| b.id);
        let result = self.sf_progn_value(tail);
        if let Some(saved_id) = saved_buf {
            self.restore_current_buffer_if_live(saved_id);
        }
        result
    }

    fn sf_save_restriction_value(&mut self, tail: Value) -> EvalResult {
        let count = self.specpdl.len();
        if let Some(state) = self.buffers.save_current_restriction_state() {
            self.specpdl.push(SpecBinding::SaveRestriction { state });
        }
        let result = self.sf_progn_value(tail);
        self.unbind_to(count);
        result
    }

    fn validate_throw(&self, flow: Flow) -> Flow {
        match flow {
            Flow::Throw { ref tag, ref value } => {
                if self.has_active_catch(tag) {
                    flow
                } else {
                    signal("no-catch", vec![*tag, *value])
                }
            }
            other => other,
        }
    }

    /// Recursively walk a `Value`, treating everything as literal data
    /// except `(byte-code-literal ...)` cons cells which are converted to
    /// `Value::ByteCode` via `sf_byte_code_literal_value`.
    fn quote_value_with_bytecode(&mut self, value: Value) -> EvalResult {
        if value.is_cons() && cons_head_symbol_id(&value) == Some(byte_code_literal_symbol()) {
            return self.sf_byte_code_literal_value(value.cons_cdr());
        }

        match value.kind() {
            ValueKind::Veclike(VecLikeType::Vector) => {
                let items = value.as_vector_data().unwrap();
                let mut values = Vec::with_capacity(items.len());
                for item in items {
                    values.push(self.quote_value_with_bytecode(*item)?);
                }
                Ok(Value::vector(values))
            }
            _ => Ok(value),
        }
    }

    fn sf_byte_code_literal_value(&mut self, tail: Value) -> EvalResult {
        let vector = self.one_unevalled_arg("byte-code-literal", tail)?;
        let Some(items) = vector.as_vector_data() else {
            return Err(signal(
                "wrong-type-argument",
                vec![Value::symbol("vectorp"), vector],
            ));
        };

        if items.len() < 4 {
            return Ok(vector);
        }

        let mut values = Vec::with_capacity(items.len());
        for item in items {
            values.push(self.quote_value_with_bytecode(*item)?);
        }

        crate::emacs_core::builtins::make_byte_code_from_slots(&values)
    }

    fn sf_byte_code_value(&mut self, tail: Value) -> EvalResult {
        let args = list_to_vec(&tail).ok_or_else(|| self.listp_error(tail))?;
        if args.len() != 3 {
            return Err(signal(
                "wrong-number-of-arguments",
                vec![Value::symbol("byte-code"), Value::fixnum(args.len() as i64)],
            ));
        }
        let trace_toplevel_bytecode = std::env::var_os("NEOVM_TRACE_TOPLEVEL_BYTECODE").is_some();
        let load_file_name = if trace_toplevel_bytecode {
            self.obarray()
                .symbol_value("load-file-name")
                .and_then(|value| value.as_runtime_string_owned())
                .unwrap_or_else(|| "<unknown>".to_string())
        } else {
            String::new()
        };
        let decode_start = trace_toplevel_bytecode.then(std::time::Instant::now);

        let bytecode_str = args[0];
        let constants_vec = self.quote_value_with_bytecode(args[1])?;
        let maxdepth = args[2];

        use crate::emacs_core::bytecode::ByteCodeFunction;
        use crate::emacs_core::bytecode::decode::{
            decode_gnu_bytecode_with_offset_map, string_value_to_bytes,
        };
        use crate::emacs_core::value::LambdaParams;

        // Bytecode strings are unibyte and may contain non-UTF-8 bytes.
        // Access raw bytes directly, same fix as make_byte_code_from_parts.
        let raw_bytes = if let Some(ls) = bytecode_str.as_lisp_string() {
            ls.as_bytes().to_vec()
        } else {
            Vec::new()
        };

        let mut constants: Vec<Value> = match constants_vec.kind() {
            ValueKind::Veclike(VecLikeType::Vector) => {
                constants_vec.as_vector_data().unwrap().clone()
            }
            _ => Vec::new(),
        };

        for i in 0..constants.len() {
            constants[i] =
                crate::emacs_core::builtins::try_convert_nested_compiled_literal(constants[i]);
        }

        let (ops, gnu_byte_offset_map) =
            decode_gnu_bytecode_with_offset_map(&raw_bytes, &mut constants).map_err(|e| {
                signal(
                    "error",
                    vec![Value::string(format!("bytecode decode error: {}", e))],
                )
            })?;
        if let Some(start) = decode_start {
            tracing::info!(
                "TOPLEVEL-BYTECODE decode file={} bytes={} consts={} ops={} elapsed={:.2?}",
                load_file_name,
                raw_bytes.len(),
                constants.len(),
                ops.len(),
                start.elapsed()
            );
        }

        let max_stack = match maxdepth.kind() {
            ValueKind::Fixnum(n) => n as u16,
            _ => 16,
        };

        let bc = ByteCodeFunction {
            ops,
            constants,
            max_stack,
            params: LambdaParams::simple(vec![]),
            arglist: Value::NIL,
            lexical: false,
            env: None,
            gnu_byte_offset_map: Some(gnu_byte_offset_map),
            gnu_bytecode_bytes: None,
            docstring: None,
            doc_form: None,
            interactive: None,
            closure_slot_count: 4,
            extra_slots: Vec::new(),
        };

        let mut vm = super::bytecode::Vm::from_context(self);
        let exec_start = trace_toplevel_bytecode.then(std::time::Instant::now);
        let result = vm.execute(&bc, vec![]);
        if let Some(start) = exec_start {
            tracing::info!(
                "TOPLEVEL-BYTECODE exec   file={} ops={} elapsed={:.2?}",
                load_file_name,
                bc.ops.len(),
                start.elapsed()
            );
        }
        result
    }

    pub(crate) fn defalias_value(&mut self, sym: Value, def: Value) -> EvalResult {
        let plan = builtins::plan_defalias_in_obarray(self.obarray(), &[sym, def])?;
        let builtins::DefaliasPlan { action, result, .. } = plan;
        self.loadhist_attach(Value::cons(Value::symbol("defun"), result));
        match action {
            builtins::DefaliasAction::SetFunction { symbol, definition } => {
                self.note_macro_expansion_mutation();
                self.obarray.set_symbol_function_id(symbol, definition);
            }
            builtins::DefaliasAction::CallHook {
                hook,
                symbol_value,
                definition,
            } => {
                self.apply(hook, vec![symbol_value, definition])?;
            }
        }
        if let Some(symbol) = result.as_symbol_id() {
            let definition = self
                .obarray
                .symbol_function_id(symbol)
                .unwrap_or(Value::NIL);
            crate::emacs_core::interactive::sync_interactive_registry_for_symbol_definition(
                &mut self.interactive,
                symbol,
                definition,
            );
        }
        Ok(result)
    }

    fn current_load_list_is_file_context(current_load_list: Value) -> bool {
        let mut tail = current_load_list;
        while tail.is_cons() {
            if tail.cons_cdr().is_nil() && tail.cons_car().is_string() {
                return true;
            }
            tail = tail.cons_cdr();
        }
        false
    }

    pub(crate) fn loadhist_attach(&mut self, entry: Value) {
        self.loadhist_attach_inner(entry, false);
    }

    pub(crate) fn loadhist_attach_once(&mut self, entry: Value) {
        self.loadhist_attach_inner(entry, true);
    }

    fn loadhist_attach_inner(&mut self, entry: Value, dedup: bool) {
        let current_load_list = self.visible_variable_value_or_nil("current-load-list");
        if !Self::current_load_list_is_file_context(current_load_list) {
            return;
        }

        if dedup {
            let mut cursor = current_load_list;
            while cursor.is_cons() {
                if equal_value(&cursor.cons_car(), &entry, 0) {
                    return;
                }
                cursor = cursor.cons_cdr();
            }
        }

        let roots = self.save_specpdl_roots();
        self.push_specpdl_root(current_load_list);
        self.push_specpdl_root(entry);
        self.set_variable("current-load-list", Value::cons(entry, current_load_list));
        self.restore_specpdl_roots(roots);
    }

    #[tracing::instrument(level = "info", skip(self, subfeatures))]
    pub(crate) fn provide_value(
        &mut self,
        feature: Value,
        subfeatures: Option<Value>,
    ) -> EvalResult {
        self.note_macro_expansion_mutation();
        provide_value_in_state(&mut self.obarray, &mut self.features, feature, subfeatures)?;
        self.loadhist_attach(Value::cons(Value::symbol("provide"), feature));
        // GNU Emacs Fprovide (fns.c): after adding the feature, run any
        // load-hooks registered in `after-load-alist`.
        //   tem = Fassq(feature, Vafter_load_alist);
        //   if (CONSP(tem))  Fmapc(Qfuncall, XCDR(tem));
        //
        // GNU Emacs Fprovide: (mapc #'funcall (cdr (assq feature after-load-alist)))
        // Does NOT clear load-file-name — the delayed-func from eval-after-load
        // defers to after-load-functions when load-file-name is set, and
        // do-after-load-evaluation fires those hooks after the file finishes loading.
        self.run_after_load_hooks_for_feature(feature)?;
        Ok(feature)
    }

    /// Run `after-load-alist` callbacks for FEATURE, mirroring GNU's
    /// `Fprovide` behavior: `(mapc #'funcall (cdr (assq feature after-load-alist)))`.
    fn run_after_load_hooks_for_feature(&mut self, feature: Value) -> Result<(), Flow> {
        let after_load_alist = self
            .obarray
            .symbol_value("after-load-alist")
            .cloned()
            .unwrap_or(Value::NIL);
        if after_load_alist.is_nil() {
            return Ok(());
        }
        // Walk after-load-alist looking for an entry whose car `eq` FEATURE.
        let entry = {
            let mut cursor = after_load_alist;
            let mut found = Value::NIL;
            while cursor.is_cons() {
                let pair_car = cursor.cons_car();
                let pair_cdr = cursor.cons_cdr();
                if pair_car.is_cons() {
                    let inner_pair_car = pair_car.cons_car();
                    if inner_pair_car == feature {
                        found = pair_car;
                        break;
                    }
                }
                cursor = pair_cdr;
            }
            found
        };
        if entry.is_nil() {
            return Ok(());
        }
        // entry is (FEATURE callback1 callback2 ...).
        // Call funcall on each callback in the cdr.
        let callbacks = entry.cons_cdr();
        let mut cursor = callbacks;
        while cursor.is_cons() {
            let pair_car = cursor.cons_car();
            let pair_cdr = cursor.cons_cdr();
            let callback = pair_car;
            self.apply(callback, vec![])?;
            cursor = pair_cdr;
        }
        Ok(())
    }

    #[tracing::instrument(level = "info", skip(self), err(Debug))]
    pub(crate) fn require_value(
        &mut self,
        feature: Value,
        filename: Option<Value>,
        noerror: Option<Value>,
    ) -> EvalResult {
        let feature_name =
            super::builtins::symbols::symbol_id(&feature).map(|sid| resolve_sym(sid).to_string());
        let filename_str = filename.as_ref().and_then(|v| v.as_runtime_string_owned());
        match plan_require_in_state(
            &self.obarray,
            &mut self.features,
            &self.require_stack,
            feature,
            filename.clone(),
            noerror.clone(),
        ) {
            Err(e) => {
                tracing::error!(
                    feature = ?feature_name,
                    filename = ?filename_str,
                    "require plan failed: {:?}", e
                );
                return Err(e);
            }
            Ok(plan) => {
                self.loadhist_attach_once(Value::cons(Value::symbol("require"), feature));
                match plan {
                    RequirePlan::Return(value) => Ok(value),
                    RequirePlan::Load { sym_id, name, path } => {
                        self.require_stack.push(sym_id);
                        let result = (|| -> EvalResult {
                            self.load_file_internal(&path)?;
                            self.refresh_features_from_variable();
                            finish_require_in_state(&self.features, sym_id, &name)
                        })();
                        let _ = self.require_stack.pop();
                        if let Err(ref e) = result {
                            let noerror_val =
                                noerror.as_ref().map(|v| !v.is_nil()).unwrap_or(false);
                            let path_str = path.display().to_string();
                            tracing::error!(
                                feature_name = ?feature_name,
                                path = %path_str,
                                noerror = noerror_val,
                                "require failed: {:?}", e
                            );
                        }
                        result
                    }
                }
            }
        }
    }

    // -----------------------------------------------------------------------
    // Lambda / Function application
    // -----------------------------------------------------------------------

    fn maybe_use_cached_interpreted_closure_filter(
        &mut self,
        closure_hook: Value,
        params_value: Value,
        body_value: Value,
        env_value: Value,
        docstring_value: Value,
        iform_value: Value,
    ) -> Option<EvalResult> {
        let Some(hook_sym) = closure_hook.as_symbol_id() else {
            return None;
        };
        if hook_sym != cconv_make_interpreted_closure_symbol() {
            return None;
        }
        let Some(expected_fn) = self.interpreted_closure_filter_fn else {
            return None;
        };
        let Some(current_fn) = self
            .obarray
            .symbol_function_id(cconv_make_interpreted_closure_symbol())
        else {
            return None;
        };
        if !eq_value(&current_fn, &expected_fn) {
            return None;
        }

        let env_shape = interpreted_closure_env_entries(env_value);
        let cache_fp =
            interpreted_closure_trim_fingerprint(params_value, body_value, iform_value, &env_shape);
        let entry = self
            .interpreted_closure_trim_cache
            .get(&cache_fp)?
            .iter()
            .find(|entry| entry.matches(params_value, body_value, iform_value, &env_shape))?
            .clone();
        let rebuilt_env =
            rebuild_trimmed_interpreted_closure_env(env_value, &entry.trimmed_env_template);
        Some(builtins::symbols::make_interpreted_closure_from_parts(
            &entry.trimmed_params_value,
            &entry.trimmed_body_value,
            &rebuilt_env,
            Some(&docstring_value),
            Some(&iform_value),
        ))
    }

    fn maybe_cache_interpreted_closure_filter_result(
        &mut self,
        closure_hook: Value,
        params_value: Value,
        body_value: Value,
        env_value: Value,
        iform_value: Value,
        result: &Value,
    ) {
        let Some(hook_sym) = closure_hook.as_symbol_id() else {
            return;
        };
        if hook_sym != cconv_make_interpreted_closure_symbol() {
            return;
        }
        let Some(expected_fn) = self.interpreted_closure_filter_fn else {
            return;
        };
        let Some(current_fn) = self
            .obarray
            .symbol_function_id(cconv_make_interpreted_closure_symbol())
        else {
            return;
        };
        if !eq_value(&current_fn, &expected_fn) {
            return;
        }
        if !result.is_lambda() {
            return;
        };
        let Some(trimmed_params_value) = result.closure_slot(CLOSURE_ARGLIST) else {
            return;
        };
        let Some(trimmed_body_value) = result.closure_body_value() else {
            return;
        };
        let Some(trimmed_env) = result.closure_env().flatten() else {
            return;
        };

        let env_shape = interpreted_closure_env_entries(env_value);
        let cache_fp =
            interpreted_closure_trim_fingerprint(params_value, body_value, iform_value, &env_shape);
        let bucket = self
            .interpreted_closure_trim_cache
            .entry(cache_fp)
            .or_default();
        if bucket
            .iter()
            .any(|entry| entry.matches(params_value, body_value, iform_value, &env_shape))
        {
            return;
        }
        bucket.push(InterpretedClosureTrimCacheEntry {
            params_value,
            body_value,
            iform_value,
            env_shape,
            trimmed_params_value,
            trimmed_body_value,
            trimmed_env_template: interpreted_closure_env_entries(trimmed_env),
        });
    }

    fn maybe_use_cached_value_interpreted_closure_filter(
        &mut self,
        closure_hook: Value,
        source_function: Value,
        env_value: Value,
        docstring_value: Value,
        iform_value: Value,
    ) -> Option<EvalResult> {
        let Some(hook_sym) = closure_hook.as_symbol_id() else {
            return None;
        };
        if hook_sym != cconv_make_interpreted_closure_symbol() {
            return None;
        }
        let Some(expected_fn) = self.interpreted_closure_filter_fn else {
            return None;
        };
        let Some(current_fn) = self
            .obarray
            .symbol_function_id(cconv_make_interpreted_closure_symbol())
        else {
            return None;
        };
        if !eq_value(&current_fn, &expected_fn) {
            return None;
        }

        let env_shape = interpreted_closure_env_entries(env_value);
        let cache_key = (
            runtime_tail_fingerprint(&[source_function]),
            interpreted_closure_env_shape_hash(&env_shape),
        );
        let entry = self
            .interpreted_closure_value_cache
            .get(&cache_key)?
            .iter()
            .find(|entry| entry.matches(source_function, &env_shape))?
            .clone();
        let rebuilt_env =
            rebuild_trimmed_interpreted_closure_env(env_value, &entry.trimmed_env_template);
        Some(builtins::symbols::make_interpreted_closure_from_parts(
            &entry.trimmed_params_value,
            &entry.trimmed_body_value,
            &rebuilt_env,
            Some(&docstring_value),
            Some(&iform_value),
        ))
    }

    fn maybe_cache_value_interpreted_closure_filter_result(
        &mut self,
        closure_hook: Value,
        source_function: Value,
        env_value: Value,
        result: &Value,
    ) {
        let Some(hook_sym) = closure_hook.as_symbol_id() else {
            return;
        };
        if hook_sym != cconv_make_interpreted_closure_symbol() {
            return;
        }
        let Some(expected_fn) = self.interpreted_closure_filter_fn else {
            return;
        };
        let Some(current_fn) = self
            .obarray
            .symbol_function_id(cconv_make_interpreted_closure_symbol())
        else {
            return;
        };
        if !eq_value(&current_fn, &expected_fn) {
            return;
        }
        if !result.is_lambda() {
            return;
        };
        let Some(trimmed_params_value) = result.closure_slot(CLOSURE_ARGLIST) else {
            return;
        };
        let Some(trimmed_body_value) = result.closure_body_value() else {
            return;
        };
        let Some(trimmed_env) = result.closure_env().flatten() else {
            return;
        };

        let env_shape = interpreted_closure_env_entries(env_value);
        let cache_key = (
            runtime_tail_fingerprint(&[source_function]),
            interpreted_closure_env_shape_hash(&env_shape),
        );
        let bucket = self
            .interpreted_closure_value_cache
            .entry(cache_key)
            .or_default();
        if bucket
            .iter()
            .any(|entry| entry.matches(source_function, &env_shape))
        {
            return;
        }
        bucket.push(InterpretedClosureValueCacheEntry {
            source_function,
            env_shape,
            trimmed_params_value,
            trimmed_body_value,
            trimmed_env_template: interpreted_closure_env_entries(trimmed_env),
        });
    }

    fn make_interpreted_closure_with_expr_runtime_hook(
        &mut self,
        params_value: Value,
        body_value: Value,
        env_value: Value,
        docstring_value: Value,
        iform_value: Value,
    ) -> EvalResult {
        if !env_value.is_nil() {
            let closure_hook = self.visible_variable_value_or_nil_by_id(
                internal_make_interpreted_closure_function_symbol(),
            );
            if !closure_hook.is_nil() {
                if let Some(cached) = self.maybe_use_cached_interpreted_closure_filter(
                    closure_hook,
                    params_value,
                    body_value,
                    env_value,
                    docstring_value,
                    iform_value,
                ) {
                    return cached;
                }
                let result = self.apply(
                    closure_hook,
                    vec![
                        params_value,
                        body_value,
                        env_value,
                        docstring_value,
                        iform_value,
                    ],
                );
                if let Ok(value) = &result {
                    self.maybe_cache_interpreted_closure_filter_result(
                        closure_hook,
                        params_value,
                        body_value,
                        env_value,
                        iform_value,
                        value,
                    );
                }
                return result;
            }
        }

        builtins::symbols::make_interpreted_closure_from_parts(
            &params_value,
            &body_value,
            &env_value,
            Some(&docstring_value),
            Some(&iform_value),
        )
    }

    fn make_interpreted_closure_with_value_runtime_hook(
        &mut self,
        source_function: Value,
        params_value: Value,
        body_value: Value,
        env_value: Value,
        docstring_value: Value,
        iform_value: Value,
    ) -> EvalResult {
        if !env_value.is_nil() {
            let closure_hook = self.visible_variable_value_or_nil_by_id(
                internal_make_interpreted_closure_function_symbol(),
            );
            if !closure_hook.is_nil() {
                if let Some(cached) = self.maybe_use_cached_value_interpreted_closure_filter(
                    closure_hook,
                    source_function,
                    env_value,
                    docstring_value,
                    iform_value,
                ) {
                    return cached;
                }
                let result = self.apply(
                    closure_hook,
                    vec![
                        params_value,
                        body_value,
                        env_value,
                        docstring_value,
                        iform_value,
                    ],
                );
                if let Ok(value) = &result {
                    self.maybe_cache_value_interpreted_closure_filter_result(
                        closure_hook,
                        source_function,
                        env_value,
                        value,
                    );
                }
                return result;
            }
        }

        builtins::symbols::make_interpreted_closure_from_parts(
            &params_value,
            &body_value,
            &env_value,
            Some(&docstring_value),
            Some(&iform_value),
        )
    }

    fn eval_dynamic_documentation_value(&mut self, value: Value) -> Result<Option<Value>, Flow> {
        if !value.is_cons() || value.cons_car().as_symbol_name() != Some(":documentation") {
            return Ok(None);
        }

        let tail = value.cons_cdr();
        if tail.is_nil() {
            return Ok(Some(Value::NIL));
        }
        if !tail.is_cons() {
            return Err(signal(
                "wrong-type-argument",
                vec![Value::symbol("listp"), value],
            ));
        }

        self.eval_value(&tail.cons_car()).map(Some)
    }

    pub(crate) fn push_backtrace_frame(&mut self, function: Value, args: &[Value]) {
        self.specpdl.push(SpecBinding::Backtrace {
            function,
            args: BacktraceArgs::Evaluated(args.iter().copied().collect()),
            debug_on_exit: false,
        });
    }

    /// Push a backtrace frame for a special-form call (`nargs == UNEVALLED`
    /// in GNU eval.c:2585). `original_args` is the cons list of un-evaluated
    /// argument forms — XCDR of the original form. The walker emits
    /// `(nil FUNC FORMS FLAGS)` for these frames.
    pub(crate) fn push_unevalled_backtrace_frame(&mut self, function: Value, original_args: Value) {
        self.specpdl.push(SpecBinding::Backtrace {
            function,
            args: BacktraceArgs::Unevalled(original_args),
            debug_on_exit: false,
        });
    }

    /// Promote the UNEVALLED backtrace frame at `specpdl[count]` to the
    /// EVALD shape in place. Mirrors GNU `set_backtrace_args`
    /// (eval.c:144-156) called at eval.c:2638, 2660, 3299 after
    /// argument evaluation completes.
    ///
    /// `count` is the `specpdl.len()` observed *before* the outer
    /// `push_unevalled_backtrace_frame` — the same value a caller
    /// would pass to `unbind_to`.
    ///
    /// Panics if the slot is not an UNEVALLED backtrace frame. Callers
    /// must keep the invariant that every `set_backtrace_args_evalled`
    /// matches exactly one prior `push_unevalled_backtrace_frame`.
    pub(crate) fn set_backtrace_args_evalled(&mut self, count: usize, evaluated: &[Value]) {
        let entry = self
            .specpdl
            .get_mut(count)
            .expect("set_backtrace_args_evalled: specpdl index out of range");
        match entry {
            SpecBinding::Backtrace {
                args: backtrace_args,
                ..
            } if backtrace_args.is_unevalled() => {
                *backtrace_args = BacktraceArgs::Evaluated(evaluated.iter().copied().collect());
            }
            other => panic!(
                "set_backtrace_args_evalled: expected UNEVALLED Backtrace at specpdl[{count}], got {other:?}"
            ),
        }
    }

    pub(crate) fn set_backtrace_args_evalled_owned(&mut self, count: usize, evaluated: LispArgVec) {
        let entry = self
            .specpdl
            .get_mut(count)
            .expect("set_backtrace_args_evalled_owned: specpdl index out of range");
        match entry {
            SpecBinding::Backtrace {
                args: backtrace_args,
                ..
            } if backtrace_args.is_unevalled() => {
                *backtrace_args = BacktraceArgs::Evaluated(evaluated);
            }
            other => panic!(
                "set_backtrace_args_evalled_owned: expected UNEVALLED Backtrace at specpdl[{count}], got {other:?}"
            ),
        }
    }

    pub(crate) fn save_specpdl_roots(&self) -> SpecpdlRootScopeState {
        SpecpdlRootScopeState {
            saved_len: self.specpdl.len(),
        }
    }

    pub(crate) fn push_specpdl_root(&mut self, value: Value) {
        self.specpdl.push(SpecBinding::GcRoot { value });
    }

    pub(crate) fn record_save_excursion(&mut self) -> Option<usize> {
        let (buffer_id, point) = self
            .buffers
            .current_buffer()
            .map(|buffer| (buffer.id, buffer.point_char() as i64 + 1))?;
        let marker = super::marker::make_registered_buffer_marker(
            &mut self.buffers,
            buffer_id,
            point,
            false,
        );
        let marker_id = super::marker::marker_id_value(&marker)
            .expect("registered save-excursion marker should carry an id");
        let count = self.specpdl.len();
        self.specpdl.push(SpecBinding::SaveExcursion {
            buffer_id,
            marker_id,
            marker,
        });
        Some(count)
    }

    pub(crate) fn restore_specpdl_roots(&mut self, scope: SpecpdlRootScopeState) {
        if self.specpdl.len() <= scope.saved_len {
            return;
        }
        if self.specpdl[scope.saved_len..]
            .iter()
            .all(|binding| matches!(binding, SpecBinding::GcRoot { .. }))
        {
            self.specpdl.truncate(scope.saved_len);
            return;
        }

        // GNU's specpdl is unwound in place by moving the stack pointer.
        // Keep Neomacs' extra GC-root entries just as cheap: remove root-only
        // sentinels from the active suffix without allocating a temporary tail.
        let mut index = 0usize;
        self.specpdl.retain(|binding| {
            let keep = index < scope.saved_len || !matches!(binding, SpecBinding::GcRoot { .. });
            index += 1;
            keep
        });
    }
    pub(crate) fn push_vm_root_frame(&mut self) {
        self.vm_root_frames.push(VmRootFrame::new());
    }

    pub(crate) fn pop_vm_root_frame(&mut self) {
        self.vm_root_frames.pop();
    }

    pub(crate) fn push_vm_frame_root(&mut self, value: Value) {
        self.vm_root_frames
            .last_mut()
            .expect("VM root frame missing")
            .roots
            .push(value);
    }

    pub(crate) fn push_eval_result_roots(&mut self, result: &EvalResult) {
        match result {
            Ok(value) => self.push_vm_frame_root(*value),
            Err(Flow::Signal(sig)) => {
                for value in sig.data.iter().copied() {
                    self.push_vm_frame_root(value);
                }
                if let Some(raw_data) = sig.raw_data {
                    self.push_vm_frame_root(raw_data);
                }
            }
            Err(Flow::Throw { tag, value }) => {
                self.push_vm_frame_root(*tag);
                self.push_vm_frame_root(*value);
            }
        }
    }

    pub(crate) fn save_vm_roots(&mut self) -> VmRootScopeState {
        let pushed_vm_root_frame = self.vm_root_frames.is_empty();
        if pushed_vm_root_frame {
            self.push_vm_root_frame();
        }
        VmRootScopeState {
            pushed_vm_root_frame,
            saved_vm_root_frame_len: self.vm_root_frames.last().map(|frame| frame.roots.len()),
        }
    }

    pub(crate) fn save_vm_frame_roots(&self) -> usize {
        self.vm_root_frames
            .last()
            .expect("VM root frame missing")
            .roots
            .len()
    }

    pub(crate) fn restore_vm_frame_roots(&mut self, saved_len: usize) {
        self.vm_root_frames
            .last_mut()
            .expect("VM root frame missing")
            .roots
            .truncate(saved_len);
    }

    pub(crate) fn restore_vm_roots(&mut self, scope: VmRootScopeState) {
        if let Some(saved_len) = scope.saved_vm_root_frame_len {
            self.restore_vm_frame_roots(saved_len);
        }
        if scope.pushed_vm_root_frame {
            self.pop_vm_root_frame();
        }
    }

    pub(crate) fn unbind_to_with_result(&mut self, count: usize, result: EvalResult) -> EvalResult {
        // GNU eval.c `unbind_to(count, value)` carries VALUE through cleanup.
        // In Rust the value is not on the C stack/register root set, so keep
        // all heap payloads rooted while unwind-protect/watchers may allocate.
        let root_scope = self.save_vm_roots();
        self.push_eval_result_roots(&result);
        self.unbind_to(count);
        self.restore_vm_roots(root_scope);
        result
    }

    fn apply_internal(
        &mut self,
        function: Value,
        args: LispArgVec,
        record_backtrace: bool,
    ) -> EvalResult {
        let bt_count = self.specpdl.len();
        if record_backtrace {
            self.push_backtrace_frame(function, &args);
        }
        let result = self.maybe_gc_and_quit().and_then(|_| {
            // GNU does not probe stack space for every funcall. Keep growth
            // checks at the function-application boundary, but only on coarse
            // depth intervals so normal startup is not dominated by TLS lookups
            // in stacker::maybe_grow.
            self.maybe_grow_eval_stack(|ctx| ctx.funcall_general_untraced(function, args))
        });
        let result = self.dispatch_signal_result_if_needed(result);
        self.unbind_to_with_result(bt_count, result)
    }

    /// Apply a function value to evaluated arguments.
    pub(crate) fn apply<A>(&mut self, function: Value, args: A) -> EvalResult
    where
        A: Into<LispArgVec>,
    {
        self.apply_internal(function, args.into(), true)
    }

    #[inline]
    pub(crate) fn apply0(&mut self, function: Value) -> EvalResult {
        self.apply(function, LispArgVec::new())
    }

    #[inline]
    pub(crate) fn apply1(&mut self, function: Value, arg0: Value) -> EvalResult {
        let mut args = LispArgVec::new();
        args.push(arg0);
        self.apply(function, args)
    }

    #[inline]
    pub(crate) fn apply2(&mut self, function: Value, arg0: Value, arg1: Value) -> EvalResult {
        let mut args = LispArgVec::new();
        args.push(arg0);
        args.push(arg1);
        self.apply(function, args)
    }

    pub(crate) fn apply_untraced<A>(&mut self, function: Value, args: A) -> EvalResult
    where
        A: Into<LispArgVec>,
    {
        self.apply_internal(function, args.into(), false)
    }

    /// Apply FUNC to ARGS, but record FRAME_FUNCTION (not FUNC) in the
    /// runtime backtrace frame. Used by `eval_sub_cons` when the form
    /// dispatches through a symbol: the symbol is what GNU stores in
    /// specpdl (and what `backtrace-frame` returns), while the
    /// resolved function cell is what actually runs.
    ///
    /// Mirrors GNU's `eval_sub` SYMBOLP arm at `eval.c:2600-2625`,
    /// where `original_fun` (the symbol) is the value written into the
    /// specpdl entry via `record_in_backtrace (original_fun, args, ...)`.
    pub(crate) fn apply_with_frame_function(
        &mut self,
        frame_function: Value,
        func: Value,
        args: impl Into<LispArgVec>,
    ) -> EvalResult {
        let args = args.into();
        let bt_count = self.specpdl.len();
        self.push_backtrace_frame(frame_function, &args);
        let result = self.maybe_gc_and_quit().and_then(|_| {
            self.maybe_grow_eval_stack(|ctx| ctx.funcall_general_untraced(func, args))
        });
        let result = self.dispatch_signal_result_if_needed(result);
        self.unbind_to_with_result(bt_count, result)
    }

    /// Unified function dispatch — matches GNU Emacs's funcall_general.
    /// Called by both the tree-walking interpreter (via apply) and the
    /// bytecode VM (via Vm::call_function).
    pub(crate) fn funcall_general<A>(&mut self, function: Value, args: A) -> EvalResult
    where
        A: Into<LispArgVec>,
    {
        let args = args.into();
        let bt_count = self.specpdl.len();
        self.push_backtrace_frame(function, &args);
        let result = self.funcall_general_untraced(function, args);
        let result = self.dispatch_signal_result_if_needed(result);
        self.unbind_to_with_result(bt_count, result)
    }

    pub(crate) fn funcall_general_untraced(
        &mut self,
        function: Value,
        args: impl Into<LispArgVec>,
    ) -> EvalResult {
        let args = args.into();
        match function.kind() {
            ValueKind::Veclike(VecLikeType::ByteCode) => {
                // get_bytecode_data returns a reference into the GC-managed
                // ByteCodeObj.  GNU's bytecode interpreter executes from the
                // function struct in place, never copying.  Don't clone here
                // either — bytecode functions can have thousands of ops, and
                // cloning per call dominated debug-build batch-byte-compile
                // runtime.
                let bc_data = function.get_bytecode_data().unwrap();
                let mut vm = super::bytecode::Vm::from_context(self);
                vm.execute_with_func_value(bc_data, args, function)
            }
            ValueKind::Veclike(VecLikeType::Lambda) => self.apply_lambda(function, args),
            ValueKind::Veclike(VecLikeType::Macro) => self.apply_lambda(function, args),
            ValueKind::Subr(_) => self.apply_subr_object(function, args, true),
            ValueKind::Veclike(VecLikeType::Subr) => self.apply_subr_object(function, args, true),
            ValueKind::Symbol(id) => self.apply_symbol_callable_untraced(id, args, true),
            ValueKind::T => self.apply_symbol_callable_untraced(intern("t"), args, true),
            ValueKind::Nil => Err(signal("void-function", vec![Value::symbol("nil")])),
            _ if function.is_symbol_with_pos() => {
                // Transparently unwrap symbol-with-pos → bare symbol for funcall dispatch.
                let bare = function.as_symbol_with_pos_sym().unwrap();
                self.funcall_general_untraced(bare, args)
            }
            ValueKind::Cons => {
                if super::autoload::is_autoload_value(&function) {
                    Err(signal(
                        "wrong-type-argument",
                        vec![Value::symbol("symbolp"), function],
                    ))
                } else if matches!(
                    cons_head_symbol_id(&function),
                    Some(id) if is_lambda_like_symbol_id(id)
                ) {
                    match self.instantiate_callable_cons_form(function) {
                        Ok(callable) => self.apply(callable, args),
                        Err(_) => Err(signal("invalid-function", vec![function])),
                    }
                } else {
                    Err(signal("invalid-function", vec![function]))
                }
            }
            _ => Err(signal("invalid-function", vec![function])),
        }
    }

    /// Convert a `(lambda ...)` or `(closure ...)` cons cell into a
    /// `Value::Lambda`.  This mirrors GNU Emacs's `funcall_lambda` which
    /// handles both forms.  Used by both the interpreter and the bytecode VM.
    pub(crate) fn instantiate_callable_cons_form(&mut self, function: Value) -> EvalResult {
        if !function.is_cons() {
            return Err(signal("invalid-function", vec![function]));
        }
        if list_length(&function).is_none() {
            return Err(signal("invalid-function", vec![function]));
        }

        // Unwrap symbol-with-pos on the car so (lambda ...) / (closure ...)
        // forms with position-wrapped heads are recognized.
        let head_val = self.unwrap_symbol(function.cons_car());
        let Some(head_id) = head_val.as_symbol_id() else {
            return Err(signal("invalid-function", vec![function]));
        };
        let mut tail = function.cons_cdr();

        let (env_value, params_value, is_lambda) = if head_id == lambda_symbol() {
            if !tail.is_cons() {
                return Err(signal("invalid-function", vec![function]));
            }
            let params_value = tail.cons_car();
            tail = tail.cons_cdr();
            // Mirrors GNU eval_sub lambda handling: a lambda gets
            // a lexical closure env only when
            // Vinternal_interpreter_environment is non-nil (i.e.
            // lexical mode is active). We use self.lexenv as the
            // single source of truth, matching GNU.
            let env_value = if !self.lexenv.is_nil() {
                self.lexenv
            } else {
                Value::NIL
            };
            (env_value, params_value, true)
        } else if head_id == closure_symbol() {
            if !tail.is_cons() {
                return Err(signal("invalid-function", vec![function]));
            }
            let env_value = tail.cons_car();
            tail = tail.cons_cdr();
            if !tail.is_cons() {
                return Err(signal("invalid-function", vec![function]));
            }
            let params_value = tail.cons_car();
            tail = tail.cons_cdr();
            (env_value, params_value, false)
        } else {
            return Err(signal("invalid-function", vec![function]));
        };

        let specpdl_root_scope = self.save_specpdl_roots();
        self.push_specpdl_root(function);

        let docstring_value = if tail.is_cons() {
            let value = tail.cons_car();
            let rest = tail.cons_cdr();
            if value.is_string() && !rest.is_nil() {
                tail = rest;
                value
            } else {
                Value::NIL
            }
        } else {
            Value::NIL
        };

        let mut doc_form_value = Value::NIL;
        if tail.is_cons() {
            let item = tail.cons_car();
            if let Some(doc_form) = self.eval_dynamic_documentation_value(item)? {
                doc_form_value = doc_form;
                tail = tail.cons_cdr();
            }
        }

        while tail.is_cons() {
            let item = tail.cons_car();
            if !item.is_cons()
                || item.cons_car().as_symbol_id() != Some(declare_symbol())
                || list_length(&item).is_none()
            {
                break;
            }
            tail = tail.cons_cdr();
        }

        let iform_value = if tail.is_cons() {
            let item = tail.cons_car();
            if item.is_cons() && item.cons_car().as_symbol_id() == Some(interactive_symbol_id()) {
                tail = tail.cons_cdr();
                item
            } else {
                Value::NIL
            }
        } else {
            Value::NIL
        };

        let body_value = if tail.is_nil() {
            Value::list(vec![Value::NIL])
        } else {
            tail
        };
        let closure_doc_value = if !doc_form_value.is_nil() {
            doc_form_value
        } else {
            docstring_value
        };

        self.push_specpdl_root(params_value);
        self.push_specpdl_root(body_value);
        self.push_specpdl_root(env_value);
        self.push_specpdl_root(closure_doc_value);
        self.push_specpdl_root(iform_value);

        let result = if is_lambda {
            self.make_interpreted_closure_with_value_runtime_hook(
                function,
                params_value,
                body_value,
                env_value,
                closure_doc_value,
                iform_value,
            )
        } else {
            builtins::symbols::make_interpreted_closure_from_parts(
                &params_value,
                &body_value,
                &env_value,
                Some(&closure_doc_value),
                Some(&iform_value),
            )
        };
        self.restore_specpdl_roots(specpdl_root_scope);
        result
    }

    /// GNU funcall_subr (eval.c:3266-3280) pre-checks arity and
    /// signals `(wrong-number-of-arguments #<subr NAME> NUMARGS)`
    /// with the SUBR value. Call this before dispatching to a
    /// builtin so the check matches GNU's `funcall_subr` exactly
    /// and we never depend on the builtin's expect_args helper
    /// (which would emit `Value::symbol(name)` instead of the
    /// subr value).
    ///
    /// Returns `Some(Flow::Signal)` on arity mismatch, `None` when
    /// the arity is acceptable or the subr has no explicit arity
    /// registered (opt-out).
    #[inline]
    fn check_funcall_subr_arity_value(&self, function: Value, nargs: usize) -> Option<Flow> {
        let (_, entry) = subr_entry_from_value(function)?;
        let min = entry.min_args as usize;
        let max = entry.max_args.map(|m| m as usize);
        // Opt-out: a subr registered with (0, None) has declared
        // "I do my own arity check". Keep the legacy behaviour for
        // those until each one is migrated explicitly.
        if min == 0 && max.is_none() {
            return None;
        }
        let arity_bad = nargs < min || max.is_some_and(|m| nargs > m);
        if arity_bad {
            Some(signal(
                "wrong-number-of-arguments",
                vec![function, Value::fixnum(nargs as i64)],
            ))
        } else {
            None
        }
    }

    #[inline]
    fn check_funcall_subr_arity(&self, sym_id: SymId, nargs: usize) -> Option<Flow> {
        self.check_funcall_subr_arity_value(Value::subr_from_sym_id(sym_id), nargs)
    }

    fn dispatch_subr_value_internal(
        &mut self,
        function: Value,
        args: LispArgVec,
        wrong_arity_callee: Value,
    ) -> Option<EvalResult> {
        let (_, entry) = subr_entry_from_value(function)?;
        self.dispatch_subr_entry_internal(entry, args, wrong_arity_callee)
    }

    fn dispatch_subr_entry_internal(
        &mut self,
        entry: SubrEntry,
        args: LispArgVec,
        wrong_arity_callee: Value,
    ) -> Option<EvalResult> {
        let func = entry.function?;
        let nargs = args.len();
        if (nargs as u16) < entry.min_args {
            return Some(Err(signal(
                "wrong-number-of-arguments",
                vec![wrong_arity_callee, Value::fixnum(nargs as i64)],
            )));
        }
        if let Some(max) = entry.max_args {
            if nargs as u16 > max {
                return Some(Err(signal(
                    "wrong-number-of-arguments",
                    vec![wrong_arity_callee, Value::fixnum(nargs as i64)],
                )));
            }
        }
        Some(self.dispatch_subr_func_unchecked(func, args))
    }

    #[inline]
    fn dispatch_subr_entry_unchecked(
        &mut self,
        entry: SubrEntry,
        args: LispArgVec,
    ) -> Option<EvalResult> {
        let func = entry.function?;
        Some(self.dispatch_subr_func_unchecked(func, args))
    }

    #[inline]
    fn subr_entry_uses_fixed_value_call(entry: SubrEntry) -> bool {
        entry.dispatch_kind == SubrDispatchKind::Builtin
            && matches!(
                entry.function,
                Some(SubrFn::A0(_) | SubrFn::A1(_) | SubrFn::A2(_) | SubrFn::A3(_))
            )
    }

    #[inline]
    fn backtrace_evaluated_arg_or_nil(&self, count: usize, index: usize) -> Value {
        match self.specpdl.get(count) {
            Some(SpecBinding::Backtrace {
                args: BacktraceArgs::Evaluated(args),
                ..
            }) => args.get(index).copied().unwrap_or(Value::NIL),
            Some(other) => panic!(
                "backtrace_evaluated_arg_or_nil: expected EVALD Backtrace at specpdl[{count}], got {other:?}"
            ),
            None => panic!("backtrace_evaluated_arg_or_nil: specpdl index out of range"),
        }
    }

    #[inline]
    fn dispatch_subr_entry_from_backtrace_unchecked(
        &mut self,
        entry: SubrEntry,
        backtrace_count: usize,
    ) -> Option<EvalResult> {
        match entry.function? {
            SubrFn::A0(func) => Some(func(self)),
            SubrFn::A1(func) => {
                let arg0 = self.backtrace_evaluated_arg_or_nil(backtrace_count, 0);
                Some(func(self, arg0))
            }
            SubrFn::A2(func) => {
                let arg0 = self.backtrace_evaluated_arg_or_nil(backtrace_count, 0);
                let arg1 = self.backtrace_evaluated_arg_or_nil(backtrace_count, 1);
                Some(func(self, arg0, arg1))
            }
            SubrFn::A3(func) => {
                let arg0 = self.backtrace_evaluated_arg_or_nil(backtrace_count, 0);
                let arg1 = self.backtrace_evaluated_arg_or_nil(backtrace_count, 1);
                let arg2 = self.backtrace_evaluated_arg_or_nil(backtrace_count, 2);
                Some(func(self, arg0, arg1, arg2))
            }
            SubrFn::Many(_) | SubrFn::ManySlice(_) => None,
        }
    }

    #[inline]
    fn dispatch_subr_func_unchecked(
        &mut self,
        func: crate::tagged::header::SubrFn,
        args: LispArgVec,
    ) -> EvalResult {
        match func {
            crate::tagged::header::SubrFn::Many(func) => func(self, args.into_vec()),
            crate::tagged::header::SubrFn::ManySlice(func) => func(self, &args),
            crate::tagged::header::SubrFn::A0(func) => func(self),
            crate::tagged::header::SubrFn::A1(func) => {
                func(self, args.first().copied().unwrap_or(Value::NIL))
            }
            crate::tagged::header::SubrFn::A2(func) => func(
                self,
                args.first().copied().unwrap_or(Value::NIL),
                args.get(1).copied().unwrap_or(Value::NIL),
            ),
            crate::tagged::header::SubrFn::A3(func) => func(
                self,
                args.first().copied().unwrap_or(Value::NIL),
                args.get(1).copied().unwrap_or(Value::NIL),
                args.get(2).copied().unwrap_or(Value::NIL),
            ),
        }
    }

    #[inline]
    fn apply_subr_object(
        &mut self,
        function: Value,
        args: LispArgVec,
        _rewrite_builtin_wrong_arity: bool,
    ) -> EvalResult {
        let Some((sym_id, entry)) = subr_entry_from_value(function) else {
            return Err(signal("invalid-function", vec![function]));
        };
        self.apply_subr_object_with_entry(sym_id, function, args, entry)
    }

    #[inline]
    fn apply_subr_object_with_entry(
        &mut self,
        sym_id: SymId,
        function: Value,
        args: LispArgVec,
        entry: SubrEntry,
    ) -> EvalResult {
        if entry.dispatch_kind == SubrDispatchKind::SpecialForm {
            return Err(signal("invalid-function", vec![function]));
        }
        if entry.dispatch_kind == SubrDispatchKind::ContextCallable {
            return self.apply_evaluator_callable_by_id(sym_id, args);
        }
        if let Some(result) = self.dispatch_subr_entry_internal(entry, args, function) {
            result.map_err(|flow| self.validate_throw(flow))
        } else {
            Err(signal("void-function", vec![Value::from_sym_id(sym_id)]))
        }
    }

    #[inline]
    fn resolve_named_call_target_by_id(&mut self, sym_id: SymId) -> NamedCallTarget {
        let compiler_overrides_active =
            compiler_function_overrides_active_in_obarray(&self.obarray);
        let function_epoch = self.obarray.function_epoch();
        if !compiler_overrides_active {
            // Fast path: a HashMap lookup that returns the cached target
            // when the function epoch hasn't moved.  An epoch mismatch
            // signals that some `defalias`/`fset`/autoload installation
            // happened since the cached entry was recorded; in that case
            // fall through and replace the entry below.
            if let Some(entry) = self.named_call_cache.get(&sym_id)
                && entry.function_epoch == function_epoch
            {
                return entry.target.clone();
            }
        }

        let target =
            if let Some(func) = compiler_function_override_in_obarray(&self.obarray, sym_id) {
                NamedCallTarget::Obarray(func)
            } else if let Some(func) = self.obarray.symbol_function_id(sym_id) {
                match func.kind() {
                    ValueKind::Nil => NamedCallTarget::Void,
                    // `(fset 'foo (symbol-function 'foo))` writes `#<subr foo>` into
                    // the function cell. Treat this as the canonical callable
                    // object, not an obarray indirection cycle.
                    ValueKind::Subr(sid) if sid == sym_id => {
                        NamedCallTarget::Subr(Value::subr_from_sym_id(sid))
                    }
                    ValueKind::Veclike(VecLikeType::Subr) if func.as_subr_id() == Some(sym_id) => {
                        NamedCallTarget::Subr(func)
                    }
                    _ => NamedCallTarget::Obarray(func),
                }
            } else if self.obarray.is_function_unbound_id(sym_id) {
                NamedCallTarget::Void
            } else if lookup_global_subr_entry(sym_id).is_some() {
                NamedCallTarget::Subr(Value::subr_from_sym_id(sym_id))
            } else {
                NamedCallTarget::Void
            };

        if !compiler_overrides_active {
            // Cap the cache to avoid unbounded growth on pathologic
            // workloads.  Past the cap we just stop caching new entries
            // — better to take an O(1) miss than to evict a hot entry.
            if self.named_call_cache.len() < NAMED_CALL_CACHE_CAPACITY {
                self.named_call_cache.insert(
                    sym_id,
                    NamedCallCacheEntry {
                        function_epoch,
                        target: target.clone(),
                    },
                );
            }
        }

        target
    }

    #[inline]
    fn resolve_named_call_target(&mut self, name: &str) -> NamedCallTarget {
        self.resolve_named_call_target_by_id(intern(name))
    }

    #[inline]
    fn store_named_call_cache(&mut self, symbol: SymId, target: NamedCallTarget) {
        let function_epoch = self.obarray.function_epoch();
        if self.named_call_cache.len() < NAMED_CALL_CACHE_CAPACITY {
            self.named_call_cache.insert(
                symbol,
                NamedCallCacheEntry {
                    function_epoch,
                    target,
                },
            );
        }
    }

    #[inline]
    fn apply_named_callable_by_id(
        &mut self,
        sym_id: SymId,
        args: LispArgVec,
        invalid_fn: Value,
        rewrite_builtin_wrong_arity: bool,
    ) -> EvalResult {
        let frame_function = Value::from_sym_id(sym_id);
        let bt_count = self.specpdl.len();
        self.push_backtrace_frame(frame_function, &args);
        let result = self.apply_named_callable_by_id_core(
            sym_id,
            args,
            invalid_fn,
            rewrite_builtin_wrong_arity,
        );
        self.unbind_to_with_result(bt_count, result)
    }

    #[inline]
    fn apply_named_callable(
        &mut self,
        name: &str,
        args: LispArgVec,
        invalid_fn: Value,
        rewrite_builtin_wrong_arity: bool,
    ) -> EvalResult {
        let frame_function = Value::symbol(name);
        let bt_count = self.specpdl.len();
        self.push_backtrace_frame(frame_function, &args);
        let result =
            self.apply_named_callable_core(name, args, invalid_fn, rewrite_builtin_wrong_arity);
        self.unbind_to_with_result(bt_count, result)
    }

    fn apply_named_callable_by_id_core(
        &mut self,
        sym_id: SymId,
        args: LispArgVec,
        invalid_fn: Value,
        rewrite_builtin_wrong_arity: bool,
    ) -> EvalResult {
        match self.resolve_named_call_target_by_id(sym_id) {
            NamedCallTarget::Obarray(func) => {
                if super::autoload::is_autoload_value(&func) {
                    return self.apply_named_autoload_callable_by_id(
                        sym_id,
                        func,
                        args,
                        rewrite_builtin_wrong_arity,
                    );
                }
                let function_is_callable = self.function_value_is_callable(&func);
                let result = match self.apply_untraced(func, args) {
                    Err(Flow::Signal(sig))
                        if sig.symbol_name() == "invalid-function" && !function_is_callable =>
                    {
                        Err(signal("invalid-function", vec![Value::from_sym_id(sym_id)]))
                    }
                    other => other,
                };
                result
            }
            NamedCallTarget::Subr(func) => {
                let Some((sym_id, entry)) = subr_entry_from_value(func) else {
                    return Err(signal("invalid-function", vec![invalid_fn]));
                };
                if entry.dispatch_kind == SubrDispatchKind::SpecialForm {
                    return Err(signal("invalid-function", vec![invalid_fn]));
                }
                self.apply_subr_object_with_entry(sym_id, func, args, entry)
            }
            NamedCallTarget::Void => Err(signal("void-function", vec![Value::from_sym_id(sym_id)])),
        }
    }

    fn apply_named_callable_core(
        &mut self,
        name: &str,
        args: LispArgVec,
        invalid_fn: Value,
        rewrite_builtin_wrong_arity: bool,
    ) -> EvalResult {
        match self.resolve_named_call_target(name) {
            NamedCallTarget::Obarray(func) => {
                if super::autoload::is_autoload_value(&func) {
                    return self.apply_named_autoload_callable(
                        name,
                        func,
                        args,
                        rewrite_builtin_wrong_arity,
                    );
                }
                let function_is_callable = self.function_value_is_callable(&func);
                let result = match self.apply(func, args) {
                    Err(Flow::Signal(sig))
                        if sig.symbol_name() == "invalid-function" && !function_is_callable =>
                    {
                        Err(signal("invalid-function", vec![Value::symbol(name)]))
                    }
                    other => other,
                };
                result
            }
            NamedCallTarget::Subr(func) => {
                let sym_id = intern(name);
                let result = self.apply_subr_object(func, args, rewrite_builtin_wrong_arity);
                // Do NOT poison the cache with Void when the subr was found.
                if func
                    .as_subr_id()
                    .and_then(lookup_global_subr_entry)
                    .is_some_and(|e| e.dispatch_kind == SubrDispatchKind::SpecialForm)
                {
                    Err(signal("invalid-function", vec![invalid_fn]))
                } else {
                    result
                }
            }
            NamedCallTarget::Void => Err(signal("void-function", vec![Value::symbol(name)])),
        }
    }

    fn apply_named_autoload_callable(
        &mut self,
        name: &str,
        autoload_form: Value,
        args: LispArgVec,
        rewrite_builtin_wrong_arity: bool,
    ) -> EvalResult {
        self.apply_named_autoload_callable_by_id(
            intern(name),
            autoload_form,
            args,
            rewrite_builtin_wrong_arity,
        )
    }

    fn apply_named_autoload_callable_by_id(
        &mut self,
        sym_id: SymId,
        autoload_form: Value,
        args: LispArgVec,
        rewrite_builtin_wrong_arity: bool,
    ) -> EvalResult {
        // Startup wrappers often expose autoload-shaped function cells for names
        // backed by builtins. Keep the autoload shape while preserving callability.
        if lookup_global_subr_entry(sym_id).is_some() {
            let subr = Value::subr_from_sym_id(sym_id);
            // GNU-faithful pre-check via check_funcall_subr_arity.
            if let Some(flow) = self.check_funcall_subr_arity_value(subr, args.len()) {
                return Err(flow);
            }
            if let Some(result) = self.dispatch_subr_value_internal(
                subr,
                args.clone(),
                Value::subr_from_sym_id(sym_id),
            ) {
                return result;
            }
        }

        let loaded = super::autoload::builtin_autoload_do_load(
            self,
            vec![autoload_form, Value::from_sym_id(sym_id)],
        )?;
        let function_is_callable = self.function_value_is_callable(&loaded);
        match self.apply_untraced(loaded, args) {
            Err(Flow::Signal(sig))
                if sig.symbol_name() == "invalid-function" && !function_is_callable =>
            {
                Err(signal("invalid-function", vec![Value::from_sym_id(sym_id)]))
            }
            other => other,
        }
    }

    fn apply_evaluator_callable(
        &mut self,
        name: &str,
        args: LispArgVec,
        wrong_arity_callee: Value,
    ) -> EvalResult {
        match name {
            "throw" => {
                if args.len() != 2 {
                    return Err(signal(
                        "wrong-number-of-arguments",
                        vec![wrong_arity_callee, Value::fixnum(args.len() as i64)],
                    ));
                }
                let tag = args[0];
                let value = args[1];
                if self.has_active_catch(&tag) {
                    Err(Flow::Throw { tag, value })
                } else {
                    Err(signal("no-catch", vec![tag, value]))
                }
            }
            _ => Err(signal("void-function", vec![Value::symbol(name)])),
        }
    }

    fn apply_evaluator_callable_by_id(&mut self, sym_id: SymId, args: LispArgVec) -> EvalResult {
        if sym_id == throw_symbol() {
            if args.len() != 2 {
                return Err(signal(
                    "wrong-number-of-arguments",
                    vec![
                        Value::subr_from_sym_id(sym_id),
                        Value::fixnum(args.len() as i64),
                    ],
                ));
            }
            let tag = args[0];
            let value = args[1];
            if self.has_active_catch(&tag) {
                Err(Flow::Throw { tag, value })
            } else {
                Err(signal("no-catch", vec![tag, value]))
            }
        } else {
            Err(signal("void-function", vec![Value::from_sym_id(sym_id)]))
        }
    }

    fn apply_lambda(&mut self, func_value: Value, args: LispArgVec) -> EvalResult {
        let Some(params) = func_value.closure_params() else {
            return Err(signal("invalid-function", vec![func_value]));
        };
        let Some(body) = func_value.closure_body_value() else {
            return Err(signal("invalid-function", vec![func_value]));
        };
        let env = func_value.closure_env().unwrap_or(None);

        // Root the function value on the specpdl so GC can trace it
        // (keeping body, env, and params alive through the call).
        let root_count = self.specpdl.len();
        self.specpdl.push(SpecBinding::GcRoot { value: func_value });

        let call_state = match self.begin_lambda_call(params, env, &args) {
            Ok(state) => state,
            Err(err) => {
                self.unbind_to(root_count);
                return Err(err);
            }
        };
        let result = self.eval_lambda_body_value(body);
        self.finish_lambda_call(call_state);
        self.unbind_to(root_count);
        result
    }

    #[inline]
    fn bind_lexical_value_rooted(&mut self, sym: SymId, value: Value) {
        bind_lexical_value_rooted_in_specpdl(&mut self.lexenv, &mut self.specpdl, sym, value);
    }

    // -----------------------------------------------------------------------
    // Macro expansion
    // -----------------------------------------------------------------------

    pub(crate) fn with_macro_expansion_scope<T>(
        &mut self,
        f: impl FnOnce(&mut Self) -> Result<T, Flow>,
    ) -> Result<T, Flow> {
        self.macro_expansion_scope_depth += 1;
        let scope_enter_start = self.macro_perf_enabled.then(std::time::Instant::now);
        let state = begin_macro_expansion_scope_in_state(
            &mut self.obarray,
            &mut self.specpdl,
            &mut self.buffers,
            &self.custom,
            self.lexenv,
        );
        if let Some(start) = scope_enter_start {
            self.macro_perf_stats
                .scope_enter
                .note_duration(start.elapsed());
        }
        let result = f(self);
        let scope_exit_start = self.macro_perf_enabled.then(std::time::Instant::now);
        finish_macro_expansion_scope_in_state(
            &mut self.obarray,
            &mut self.specpdl,
            &mut self.buffers,
            &self.custom,
            state,
        );
        if let Some(start) = scope_exit_start {
            self.macro_perf_stats
                .scope_exit
                .note_duration(start.elapsed());
        }
        self.macro_expansion_scope_depth = self.macro_expansion_scope_depth.saturating_sub(1);
        result
    }

    #[inline]
    pub(crate) fn macro_expansion_mutation_epoch(&self) -> u64 {
        self.macro_expansion_mutation_epoch
    }

    #[inline]
    pub(crate) fn note_macro_expansion_mutation(&mut self) {
        if self.macro_expansion_scope_depth > 0 {
            self.macro_expansion_mutation_epoch =
                self.macro_expansion_mutation_epoch.wrapping_add(1);
        }
    }

    fn macro_expansion_context_key(&self) -> u64 {
        self.macro_expansion_context_key_for_environment(None)
    }

    fn macro_expansion_context_key_for_environment(&self, environment: Option<Value>) -> u64 {
        fn value_identity_key(value: Value) -> u64 {
            match value.kind() {
                ValueKind::Nil => 0,
                ValueKind::T => 1,
                ValueKind::Fixnum(n) => ((n as u64).wrapping_mul(0x9E37_79B1)) ^ 0x10,
                ValueKind::Symbol(sym) => ((sym.0 as u64) << 8) ^ 0x20,
                ValueKind::Subr(sym) => ((sym.0 as u64) << 8) ^ 0x22,
                ValueKind::Veclike(VecLikeType::Subr) => {
                    let sym = value.as_subr_id().unwrap();
                    ((sym.0 as u64) << 8) ^ 0x22
                }
                _ => (value.bits() as u64) ^ 0x30,
            }
        }

        fn semantic_fingerprint(value: Value) -> u64 {
            use std::hash::Hasher;

            let mut hasher = std::collections::hash_map::DefaultHasher::new();
            let mut seen = std::collections::HashSet::new();
            value_fingerprint(value, &mut hasher, 4, &mut seen);
            hasher.finish()
        }

        let current_macroexpand_env = self
            .obarray()
            .symbol_value_id_or_nil(macroexpand_all_environment_symbol());
        let current_dynvars = self
            .obarray()
            .symbol_value_id_or_nil(macroexp_dynvars_symbol());

        let explicit_environment_key = environment.map(semantic_fingerprint).unwrap_or(0);
        let current_macroexpand_env_key = value_identity_key(current_macroexpand_env);
        let current_dynvars_key = value_identity_key(current_dynvars);

        explicit_environment_key.rotate_left(7)
            ^ current_macroexpand_env_key.rotate_left(29)
            ^ current_dynvars_key.rotate_left(43)
    }

    fn runtime_macro_expansion_cache_enabled(&self) -> bool {
        !self.macro_cache_disabled
            && self
                .visible_variable_value_or_nil_by_id(load_in_progress_symbol())
                .is_truthy()
    }

    fn runtime_macro_expansion_cache_key(
        &self,
        function: Value,
        args_fingerprint: u64,
        context_key: u64,
    ) -> (usize, usize, u64) {
        (
            function.bits() ^ 0x9E37_79B1usize,
            args_fingerprint as usize,
            context_key,
        )
    }

    pub(crate) fn lookup_runtime_macro_expansion(
        &mut self,
        function: Value,
        args: &[Value],
        environment: Option<Value>,
    ) -> Option<Value> {
        let perf_start = self.macro_perf_enabled.then(std::time::Instant::now);
        if !self.runtime_macro_expansion_cache_enabled() {
            if let Some(start) = perf_start {
                self.macro_perf_stats
                    .cache_lookup
                    .note_duration(start.elapsed());
            }
            return None;
        }
        let current_fp = runtime_tail_fingerprint(args);
        let context_key = self.macro_expansion_context_key_for_environment(environment);
        let cache_key = self.runtime_macro_expansion_cache_key(function, current_fp, context_key);
        let cached = self
            .runtime_macro_expansion_cache
            .get(&cache_key)
            .cloned()?;
        if cached.fingerprint == current_fp {
            self.macro_cache_hits += 1;
            if let Some(start) = perf_start {
                self.macro_perf_stats
                    .cache_lookup
                    .note_duration(start.elapsed());
            }
            return Some(cached.expanded);
        }
        if let Some(start) = perf_start {
            self.macro_perf_stats
                .cache_lookup
                .note_duration(start.elapsed());
        }
        None
    }

    pub(crate) fn store_runtime_macro_expansion(
        &mut self,
        form: Value,
        function: Value,
        args: &[Value],
        expanded_value: &Value,
        expand_elapsed: std::time::Duration,
        environment: Option<Value>,
    ) {
        let perf_start = self.macro_perf_enabled.then(std::time::Instant::now);
        if !self.runtime_macro_expansion_cache_enabled() {
            if let Some(start) = perf_start {
                self.macro_perf_stats
                    .cache_store
                    .note_duration(start.elapsed());
            }
            return;
        }
        self.macro_cache_misses += 1;
        self.macro_expand_total_us += expand_elapsed.as_micros() as u64;
        let current_fp = runtime_tail_fingerprint(args);
        let context_key = self.macro_expansion_context_key_for_environment(environment);
        let cache_key = self.runtime_macro_expansion_cache_key(function, current_fp, context_key);
        let cache_entry =
            RuntimeMacroExpansionCacheEntry::new(function, *expanded_value, current_fp);
        if self.macro_perf_enabled && expand_elapsed.as_millis() > 50 {
            let macro_head = if form.is_cons() {
                form.cons_car().as_symbol_name().unwrap_or("<non-symbol>")
            } else {
                "<atom>"
            };
            let form_str = crate::emacs_core::print::print_value(&form);
            let form_preview: String = form_str.chars().take(200).collect();
            tracing::warn!(
                "runtime_macro_cache MISS head={macro_head} macro={:#x} fp={:#x} took {expand_elapsed:.2?} form={form_preview}",
                function.bits(),
                current_fp
            );
        }
        self.runtime_macro_expansion_cache
            .insert(cache_key, cache_entry);
        if let Some(start) = perf_start {
            self.macro_perf_stats
                .cache_store
                .note_duration(start.elapsed());
        }
    }

    fn apply_macro_callable_with_dynamic_scope(
        &mut self,
        callable: Value,
        args: Vec<Value>,
    ) -> Result<Value, Flow> {
        let perf_start = self.macro_perf_enabled.then(std::time::Instant::now);
        // GNU macroexpansion runs the expander through the normal apply/call
        // path with live call-frame state holding the argument list. Mirror
        // that here so macroexpander args stay rooted in an active call frame
        // instead of an explicit eval-root adapter vector.
        let result = self.with_macro_expansion_scope(|eval| eval.apply(callable, args));
        if let Some(start) = perf_start {
            self.macro_perf_stats
                .macro_apply
                .note_duration(start.elapsed());
        }
        result
    }

    pub(crate) fn expand_macro_for_macroexpand(
        &mut self,
        form: Value,
        definition: Value,
        args: Vec<Value>,
        environment: Option<Value>,
    ) -> Result<Value, Flow> {
        let perf_start = self.macro_perf_enabled.then(std::time::Instant::now);
        if let Some(cached) = self.lookup_runtime_macro_expansion(definition, &args, environment) {
            if let Some(start) = perf_start {
                self.macro_perf_stats
                    .expand_macro
                    .note_duration(start.elapsed());
            }
            return Ok(cached);
        }
        let args_for_cache = args.clone();
        let expand_start = std::time::Instant::now();
        let specpdl_root_scope = self.save_specpdl_roots();
        self.push_specpdl_root(form);
        self.push_specpdl_root(definition);
        if let Some(environment) = environment {
            self.push_specpdl_root(environment);
        }

        let result = (|| {
            let expanded = if definition.is_macro() {
                self.apply_macro_callable_with_dynamic_scope(definition, args)?
            } else if cons_head_symbol_id(&definition) == Some(macro_symbol()) {
                self.apply_macro_callable_with_dynamic_scope(definition.cons_cdr(), args)?
            } else if self.function_value_is_callable(&definition) {
                // GNU `macroexpand` ENVIRONMENT entries store the macro
                // expander itself, not the full `(macro . fn)` function cell.
                self.apply_macro_callable_with_dynamic_scope(definition, args)?
            } else {
                return Err(signal("invalid-function", vec![definition]));
            };

            let expand_elapsed = expand_start.elapsed();
            self.store_runtime_macro_expansion(
                form,
                definition,
                &args_for_cache,
                &expanded,
                expand_elapsed,
                environment,
            );
            Ok(expanded)
        })();
        self.restore_specpdl_roots(specpdl_root_scope);
        if let Some(start) = perf_start {
            self.macro_perf_stats
                .expand_macro
                .note_duration(start.elapsed());
        }
        result
    }

    pub(crate) fn note_eager_macro_perf_step1(&mut self, duration: std::time::Duration) {
        if self.macro_perf_enabled {
            self.macro_perf_stats.eager_step1.note_duration(duration);
        }
    }

    pub(crate) fn note_eager_macro_perf_step3(&mut self, duration: std::time::Duration) {
        if self.macro_perf_enabled {
            self.macro_perf_stats.eager_step3.note_duration(duration);
        }
    }

    pub(crate) fn note_eager_macro_perf_step4(&mut self, duration: std::time::Duration) {
        if self.macro_perf_enabled {
            self.macro_perf_stats.eager_step4.note_duration(duration);
        }
    }

    pub(crate) fn macro_perf_summary(&self) -> Option<String> {
        if !self.macro_perf_enabled {
            return None;
        }

        let mut parts = vec![format!(
            "cache=hits:{} misses:{} expand-total:{:.2}ms",
            self.macro_cache_hits,
            self.macro_cache_misses,
            self.macro_expand_total_us as f64 / 1000.0
        )];

        for counter in [
            self.macro_perf_stats.scope_enter.summary("scope-enter"),
            self.macro_perf_stats.scope_exit.summary("scope-exit"),
            self.macro_perf_stats.macro_apply.summary("macro-apply"),
            self.macro_perf_stats.cache_lookup.summary("cache-lookup"),
            self.macro_perf_stats.cache_store.summary("cache-store"),
            self.macro_perf_stats.expand_macro.summary("expand-macro"),
            self.macro_perf_stats.eager_step1.summary("eager-step1"),
            self.macro_perf_stats.eager_step3.summary("eager-step3"),
            self.macro_perf_stats.eager_step4.summary("eager-step4"),
        ]
        .into_iter()
        .flatten()
        {
            parts.push(counter);
        }

        Some(parts.join(" | "))
    }

    #[inline]
    pub(crate) fn macro_perf_enabled(&self) -> bool {
        self.macro_perf_enabled
    }

    // -----------------------------------------------------------------------
    // Variable assignment
    // -----------------------------------------------------------------------

    // Shared runtime write path for symbol-cell mutation. This mirrors GNU
    // `set_internal` after lexical handling has already been decided.

    // -----------------------------------------------------------------------
    // specbind / unbind_to — GNU Emacs specpdl-style dynamic variable binding
    // -----------------------------------------------------------------------

    /// Save the current value of a special variable and set a new value.
    /// Matches GNU Emacs's specbind() in eval.c:
    /// - Follows SYMBOL_VARALIAS to the final target
    /// - For buffer-local variables with a local binding: SPECPDL_LET_LOCAL
    /// - For buffer-local variables without local binding: SPECPDL_LET_DEFAULT
    /// - For plain variables: SPECPDL_LET
    pub(crate) fn specbind(&mut self, sym_id: SymId, value: Value) {
        let resolved =
            builtins::resolve_variable_alias_id_in_obarray(&self.obarray, sym_id).unwrap_or(sym_id);
        let name = resolve_sym(resolved);
        // Debug: trace when macroexpand-all-environment gets a non-list value
        if name == "macroexpand-all-environment" && !value.is_nil() && !value.is_cons() {
            tracing::error!(
                "specbind macroexpand-all-environment to non-list: {:?} bits={:#x}",
                value.kind(),
                value.bits()
            );
        }

        // Phase 10D: handle FORWARDED BUFFER_OBJFWD specbind separately
        // from the legacy LOCALIZED path. Mirrors GNU `specbind`
        // SYMBOL_FORWARDED arm at `eval.c:3641-3677`.
        {
            use crate::emacs_core::forward::{LispBufferObjFwd, LispFwdType};
            use crate::emacs_core::symbol::SymbolRedirect;
            let forwarded = self
                .obarray
                .get_by_id(resolved)
                .filter(|s| s.redirect() == SymbolRedirect::Forwarded)
                .map(|s| unsafe { s.val.fwd });
            if let Some(fwd_ptr) = forwarded {
                let fwd = unsafe { &*fwd_ptr };
                if matches!(fwd.ty, LispFwdType::BufferObj) {
                    let buf_fwd = unsafe { &*(fwd as *const _ as *const LispBufferObjFwd) };
                    let off = buf_fwd.offset as usize;
                    let flags_idx = buf_fwd.local_flags_idx;
                    let buf_id_opt = self.buffers.current_buffer_id();
                    let has_local = match buf_id_opt {
                        Some(id) => self
                            .buffers
                            .get(id)
                            .map(|buf| flags_idx < 0 || buf.slot_local_flag(off))
                            .unwrap_or(false),
                        None => false,
                    };
                    if has_local {
                        // SPECPDL_LET_LOCAL — save the current
                        // per-buffer slot value, then overwrite. On
                        // unbind we restore via set_buffer_local
                        // which writes back to the slot.
                        let buf_id = buf_id_opt.expect("has_local implies current buffer");
                        let old_val = self
                            .buffers
                            .get(buf_id)
                            .map(|b| b.slots[off])
                            .unwrap_or(Value::NIL);
                        self.specpdl.push(SpecBinding::LetLocal {
                            sym_id: resolved,
                            old_value: old_val,
                            buffer_id: buf_id,
                        });
                        if self.watchers.has_watchers(resolved) {
                            let _ = self.run_variable_watchers_by_id(
                                resolved,
                                &value,
                                &Value::NIL,
                                "let",
                            );
                        }
                        if let Some(buf) = self.buffers.get_mut(buf_id) {
                            buf.slots[off] = value;
                            // Always-local slots need no flag
                            // change; conditional slots already
                            // have the bit set (has_local check).
                        }
                        return;
                    } else {
                        // SPECPDL_LET_DEFAULT — save old default,
                        // propagate the new value via
                        // set_buffer_default_slot. On unbind we
                        // propagate the saved default back.
                        let old_default = if off < self.buffers.buffer_defaults.len() {
                            Some(self.buffers.buffer_defaults[off])
                        } else {
                            Some(buf_fwd.default)
                        };
                        self.specpdl.push(SpecBinding::LetDefault {
                            sym_id: resolved,
                            old_value: old_default,
                        });
                        if self.watchers.has_watchers(resolved) {
                            let _ = self.run_variable_watchers_by_id(
                                resolved,
                                &value,
                                &Value::NIL,
                                "let",
                            );
                        }
                        let info_ref =
                            crate::buffer::buffer::lookup_buffer_slot_by_sym_id(resolved);
                        if let Some(info) = info_ref {
                            self.buffers.set_buffer_default_slot(info, value);
                        }
                        return;
                    }
                }
            }
        }

        // Phase 10E: SYMBOL_LOCALIZED specbind. Mirrors GNU `specbind`
        // SYMBOL_LOCALIZED arm at `eval.c:3641-3677`:
        //
        //   1. Read the current value (forces BLV swap-in to current
        //      buffer).
        //   2. Tentatively record SPECPDL_LET_LOCAL with the captured
        //      value and buffer.
        //   3. If !blv_found(blv) (the swap-in landed on defcell, not
        //      a per-buffer alist entry), demote to SPECPDL_LET_DEFAULT.
        //   4. Call set_internal_localized(BIND) to write the new
        //      value into wherever the BLV cache currently points.
        if let Some(sym_slot) = self.obarray.get_by_id(resolved)
            && sym_slot.redirect() == crate::emacs_core::symbol::SymbolRedirect::Localized
        {
            if let Some(buf_id) = self.buffers.current_buffer_id() {
                let (cur_val, alist) = match self.buffers.get(buf_id) {
                    Some(buf) => (Value::make_buffer(buf.id), buf.local_var_alist),
                    None => (Value::NIL, Value::NIL),
                };
                // Force a swap so blv.found / blv.valcell match the
                // current buffer state. After this, blv.where_buf =
                // cur_val.
                let old_val = self
                    .obarray
                    .find_symbol_value_in_buffer(
                        resolved,
                        Some(buf_id),
                        cur_val,
                        alist,
                        None,
                        0u64,
                        None,
                    )
                    .unwrap_or(Value::NIL);
                let blv_found = self.obarray.blv(resolved).map(|b| b.found).unwrap_or(false);
                if blv_found {
                    self.specpdl.push(SpecBinding::LetLocal {
                        sym_id: resolved,
                        old_value: old_val,
                        buffer_id: buf_id,
                    });
                } else {
                    self.specpdl.push(SpecBinding::LetDefault {
                        sym_id: resolved,
                        old_value: Some(old_val),
                    });
                }
                if self.watchers.has_watchers(resolved) {
                    let _ = self.run_variable_watchers_by_id(resolved, &value, &Value::NIL, "let");
                }
                // Write the new value via set_internal_localized
                // with bindflag=Bind. Bind never auto-creates a new
                // alist entry, so a let on a non-buffer-local
                // LOCALIZED symbol writes to defcell.cdr (the
                // global default), matching GNU.
                let new_alist = self.obarray.set_internal_localized(
                    resolved,
                    value,
                    cur_val,
                    alist,
                    crate::emacs_core::symbol::SetInternalBind::Bind,
                    false,
                );
                if let Some(buf) = self.buffers.get_mut(buf_id) {
                    buf.local_var_alist = new_alist;
                }
                self.sync_cached_runtime_binding_by_id(resolved, value);
                return;
            }
        }

        // Plain value path (GNU: SYMBOL_PLAINVAL)
        let old_value = self.obarray.symbol_value_id(resolved).copied();
        self.specpdl.push(SpecBinding::Let {
            sym_id: resolved,
            old_value,
        });
        if self.watchers.has_watchers(resolved) {
            let _ = self.run_variable_watchers_by_id(resolved, &value, &Value::NIL, "let");
        }
        self.obarray.set_symbol_value_id(resolved, value);
        self.sync_cached_runtime_binding_by_id(resolved, value);
    }

    /// Check if a `let` is currently shadowing a buffer-local
    /// variable's binding. Matches GNU
    /// `eval.c:3559-3577 (let_shadows_buffer_binding_p)`.
    ///
    /// When true, `setq` inside the let should modify the existing
    /// binding (whichever specpdl record is on top) rather than
    /// auto-creating a brand-new per-buffer binding.
    ///
    /// GNU walks the specpdl looking for either SPECPDL_LET_LOCAL
    /// or SPECPDL_LET_DEFAULT records keyed to the symbol; both
    /// trigger the shadow behavior. neomacs's Phase 7 stub used to
    /// only check `LetDefault`, missing the LetLocal arm. Buffer-
    /// local audit Medium 4 in
    /// `drafts/buffer-local-variables-audit.md`.
    pub(crate) fn let_shadows_buffer_binding_p(&self, sym_id: SymId) -> bool {
        self.specpdl.iter().rev().any(|entry| match entry {
            SpecBinding::LetDefault { sym_id: s, .. } => *s == sym_id,
            SpecBinding::LetLocal { sym_id: s, .. } => *s == sym_id,
            SpecBinding::Let { .. }
            | SpecBinding::LexicalEnv { .. }
            | SpecBinding::GcRoot { .. }
            | SpecBinding::Backtrace { .. }
            | SpecBinding::Nop
            | SpecBinding::UnwindProtect { .. }
            | SpecBinding::SaveExcursion { .. }
            | SpecBinding::SaveCurrentBuffer { .. }
            | SpecBinding::SaveRestriction { .. } => false,
        })
    }

    fn restore_default_binding_by_id(&mut self, sym_id: SymId, old_value: Option<Value>) {
        use crate::emacs_core::forward::{LispBufferObjFwd, LispFwdType};
        use crate::emacs_core::symbol::SymbolRedirect;

        let forwarded_slot = self
            .obarray
            .get_by_id(sym_id)
            .filter(|s| s.redirect() == SymbolRedirect::Forwarded)
            .and_then(|s| {
                let fwd = unsafe { &*s.val.fwd };
                if matches!(fwd.ty, LispFwdType::BufferObj) {
                    let buf_fwd = unsafe { &*(fwd as *const _ as *const LispBufferObjFwd) };
                    crate::buffer::buffer::lookup_buffer_slot_by_sym_id(sym_id)
                        .map(|info| (info, buf_fwd))
                } else {
                    None
                }
            });
        if let Some((info, _buf_fwd)) = forwarded_slot {
            if let Some(val) = old_value {
                self.buffers.set_buffer_default_slot(info, val);
            }
            return;
        }

        match old_value {
            Some(val) => {
                self.obarray.set_symbol_value_id(sym_id, val);
                self.sync_cached_runtime_binding_by_id(sym_id, val);
            }
            None => {
                if self
                    .obarray
                    .get_by_id(sym_id)
                    .is_some_and(|s| s.redirect() == SymbolRedirect::Localized)
                {
                    self.obarray.set_symbol_value_id(sym_id, Value::UNBOUND);
                } else {
                    self.obarray.makunbound_id(sym_id);
                }
                self.sync_cached_runtime_binding_by_id(sym_id, Value::NIL);
            }
        }
    }

    /// Restore all specpdl bindings back to `count`.
    /// Matches GNU Emacs's unbind_to() in eval.c.
    pub(crate) fn unbind_to(&mut self, count: usize) {
        // Mirrors GNU `unbind_to` in `eval.c:3907-3930`: suppress a
        // pending quit during cleanup so `unwind-protect` cleanup forms
        // run to completion, then restore the pending state on exit if
        // no inner form replaced it. Without this an interactive `C-g`
        // arriving during a long-running protected form would abort the
        // CLEANUP clause mid-way, leaving resources in a bad state.
        let quitf = self.quit_flag_value();
        if !quitf.is_nil() {
            self.set_quit_flag_value(Value::NIL);
        }
        while self.specpdl.len() > count {
            let binding = self.specpdl.pop().unwrap();
            match binding {
                SpecBinding::Let { sym_id, old_value } => {
                    if self.watchers.has_watchers(sym_id) {
                        let restore_val = old_value.unwrap_or(Value::NIL);
                        let _ = self.run_variable_watchers_by_id(
                            sym_id,
                            &restore_val,
                            &Value::NIL,
                            "unlet",
                        );
                    }
                    let still_plain = self.obarray.get_by_id(sym_id).is_none_or(|s| {
                        s.redirect() == crate::emacs_core::symbol::SymbolRedirect::Plainval
                    });
                    if still_plain {
                        match old_value {
                            Some(val) => {
                                self.obarray.set_symbol_value_id(sym_id, val);
                                self.sync_cached_runtime_binding_by_id(sym_id, val);
                            }
                            None => {
                                self.obarray.makunbound_id(sym_id);
                                self.sync_cached_runtime_binding_by_id(sym_id, Value::NIL);
                            }
                        }
                    } else {
                        self.restore_default_binding_by_id(sym_id, old_value);
                    }
                }
                SpecBinding::LetLocal {
                    sym_id,
                    old_value,
                    buffer_id,
                } => {
                    if self.watchers.has_watchers(sym_id) {
                        let _ = self.run_variable_watchers_by_id(
                            sym_id,
                            &old_value,
                            &Value::NIL,
                            "unlet",
                        );
                    }
                    // Restore only if the buffer is still live.
                    // Mirrors GNU `do_one_unbind` SPECPDL_LET_LOCAL
                    // arm at `eval.c:3838-3850`:
                    //     if (!NILP (Flocal_variable_p (symbol, where)))
                    //       set_internal (symbol, old_value, where, UNBIND);
                    if self.buffers.get(buffer_id).is_some() {
                        // Phase 10E: for LOCALIZED symbols, restore via
                        // set_internal_localized(UNBIND) targeting the
                        // saved buffer. This walks the buffer's alist
                        // and rewrites the cell's cdr in place,
                        // matching GNU's set_internal LOCALIZED arm
                        // and bypassing the legacy lisp_bindings path.
                        use crate::emacs_core::symbol::{SetInternalBind, SymbolRedirect};
                        let is_localized = self
                            .obarray
                            .get_by_id(sym_id)
                            .map(|s| s.redirect() == SymbolRedirect::Localized)
                            .unwrap_or(false);
                        if is_localized {
                            let buf_val = Value::make_buffer(buffer_id);
                            let alist = self
                                .buffers
                                .get(buffer_id)
                                .map(|b| b.local_var_alist)
                                .unwrap_or(Value::NIL);
                            let new_alist = self.obarray.set_internal_localized(
                                sym_id,
                                old_value,
                                buf_val,
                                alist,
                                SetInternalBind::Unbind,
                                false,
                            );
                            if let Some(buf) = self.buffers.get_mut(buffer_id) {
                                buf.local_var_alist = new_alist;
                            }
                        } else {
                            let _ = self
                                .buffers
                                .set_buffer_local_property_by_sym_id(buffer_id, sym_id, old_value);
                        }
                        self.sync_cached_runtime_binding_by_id(sym_id, old_value);
                    }
                }
                SpecBinding::LetDefault { sym_id, old_value } => {
                    // Restore the default value (GNU: set_default_internal)
                    if self.watchers.has_watchers(sym_id) {
                        let restore_val = old_value.unwrap_or(Value::NIL);
                        let _ = self.run_variable_watchers_by_id(
                            sym_id,
                            &restore_val,
                            &Value::NIL,
                            "unlet",
                        );
                    }
                    self.restore_default_binding_by_id(sym_id, old_value);
                }
                SpecBinding::LexicalEnv { old_lexenv } => {
                    // Mirrors GNU unbind_to for
                    // specbind(Qinternal_interpreter_environment, ...).
                    self.lexenv = old_lexenv;
                }
                SpecBinding::GcRoot { .. } => {}
                SpecBinding::Backtrace { .. } => {
                    // No-op, matches GNU SPECPDL_BACKTRACE
                }
                SpecBinding::Nop => {
                    // No-op, matches GNU SPECPDL_NOP
                }
                SpecBinding::UnwindProtect {
                    forms: cleanup,
                    lexenv,
                } => {
                    // Entry already popped — re-entrant errors won't re-unwind.
                    let saved_lexenv = self.lexenv;
                    self.lexenv = lexenv;
                    if cleanup.is_cons() || cleanup.is_nil() {
                        // Interpreter path: list of forms
                        let _ = self.sf_progn_value(cleanup);
                    } else {
                        // VM path: callable (bytecode function)
                        let _ = self.apply(cleanup, vec![]);
                    }
                    self.lexenv = saved_lexenv;
                }
                SpecBinding::SaveExcursion {
                    buffer_id,
                    marker_id,
                    marker: _,
                } => {
                    self.restore_current_buffer_if_live(buffer_id);
                    if let Some(saved_pt) = self.buffers.marker_position(buffer_id, marker_id) {
                        let _ = self.buffers.goto_buffer_byte(buffer_id, saved_pt);
                    }
                    self.buffers.remove_marker(marker_id);
                }
                SpecBinding::SaveCurrentBuffer { buffer_id } => {
                    self.restore_current_buffer_if_live(buffer_id);
                }
                SpecBinding::SaveRestriction { state } => {
                    self.buffers.restore_saved_restriction_state(state);
                }
            }
        }
        // If cleanup forms didn't set their own quit, reinstate the
        // pending state. Matches `eval.c:3927-3928`.
        if !quitf.is_nil() && self.quit_flag_value().is_nil() {
            self.set_quit_flag_value(quitf);
        }
    }
}

/// Save the current value of a special variable and set a new value (standalone version).
/// Used by bytecode VM and other split-state paths.
/// Follows variable aliases like GNU's specbind().
pub(crate) fn specbind_in_state(
    obarray: &mut Obarray,
    specpdl: &mut Vec<SpecBinding>,
    sym_id: SymId,
    value: Value,
) {
    let resolved =
        super::builtins::resolve_variable_alias_id_in_obarray(obarray, sym_id).unwrap_or(sym_id);
    let old_value = obarray.symbol_value_id(resolved).copied();
    specpdl.push(SpecBinding::Let {
        sym_id: resolved,
        old_value,
    });
    obarray.set_symbol_value_id(resolved, value);
}

/// Restore all specpdl bindings back to `count` (standalone version).
/// Used by bytecode VM and other split-state paths.
/// Note: LetLocal bindings require a buffer manager; the standalone version
/// only handles Let bindings. LetLocal in the VM is not expected since
/// the VM's VarBind opcode doesn't produce buffer-local bindings.
pub(crate) fn unbind_to_in_state(
    obarray: &mut Obarray,
    specpdl: &mut Vec<SpecBinding>,
    count: usize,
) {
    while specpdl.len() > count {
        let binding = specpdl.pop().unwrap();
        match binding {
            SpecBinding::Let { sym_id, old_value } => match old_value {
                Some(val) => obarray.set_symbol_value_id(sym_id, val),
                None => obarray.makunbound_id(sym_id),
            },
            SpecBinding::LetLocal {
                sym_id, old_value, ..
            } => {
                // Standalone path doesn't have buffer manager access.
                // Fall back to setting the obarray default value.
                tracing::warn!(
                    "unbind_to_in_state: LetLocal for {} without buffer manager",
                    resolve_sym(sym_id)
                );
                obarray.set_symbol_value_id(sym_id, old_value);
            }
            SpecBinding::LetDefault { sym_id, old_value } => match old_value {
                Some(val) => obarray.set_symbol_value_id(sym_id, val),
                None => obarray.makunbound_id(sym_id),
            },
            SpecBinding::LexicalEnv { .. } => {
                // Standalone path doesn't have self.lexenv access.
                // This variant should not appear on the standalone
                // specpdl (used by bytecode VM which has its own
                // LexicalEnv / specbind mechanism).
                tracing::warn!("unbind_to_in_state: LexicalEnv without Context");
            }
            SpecBinding::GcRoot { .. } => {}
            SpecBinding::Backtrace { .. }
            | SpecBinding::Nop
            | SpecBinding::UnwindProtect { .. }
            | SpecBinding::SaveExcursion { .. }
            | SpecBinding::SaveCurrentBuffer { .. }
            | SpecBinding::SaveRestriction { .. } => {
                // These should not appear in standalone unbind_to_in_state.
                // Once the VM is fully migrated, this function may be removed.
            }
        }
    }
}

fn default_toplevel_binding(specpdl: &[SpecBinding], sym_id: SymId) -> Option<&SpecBinding> {
    specpdl.iter().find(|binding| match binding {
        SpecBinding::Let {
            sym_id: binding_sym,
            ..
        }
        | SpecBinding::LetDefault {
            sym_id: binding_sym,
            ..
        } => *binding_sym == sym_id,
        SpecBinding::LetLocal { .. }
        | SpecBinding::LexicalEnv { .. }
        | SpecBinding::GcRoot { .. }
        | SpecBinding::Backtrace { .. }
        | SpecBinding::Nop
        | SpecBinding::UnwindProtect { .. }
        | SpecBinding::SaveExcursion { .. }
        | SpecBinding::SaveCurrentBuffer { .. }
        | SpecBinding::SaveRestriction { .. } => false,
    })
}

pub(crate) fn default_toplevel_value_in_state(
    obarray: &Obarray,
    specpdl: &[SpecBinding],
    buffer_defaults: Option<&[Value]>,
    sym_id: SymId,
) -> Option<Value> {
    match default_toplevel_binding(specpdl, sym_id) {
        Some(SpecBinding::Let { old_value, .. })
        | Some(SpecBinding::LetDefault { old_value, .. }) => *old_value,
        Some(SpecBinding::LetLocal { .. })
        | Some(SpecBinding::LexicalEnv { .. })
        | Some(SpecBinding::GcRoot { .. })
        | Some(SpecBinding::Backtrace { .. })
        | Some(SpecBinding::Nop)
        | Some(SpecBinding::UnwindProtect { .. })
        | Some(SpecBinding::SaveExcursion { .. })
        | Some(SpecBinding::SaveCurrentBuffer { .. })
        | Some(SpecBinding::SaveRestriction { .. }) => {
            unreachable!("non-variable bindings are excluded above")
        }
        None => {
            use crate::emacs_core::forward::{LispBufferObjFwd, LispFwdType};
            use crate::emacs_core::symbol::SymbolRedirect;

            if let Some(sym) = obarray.get_by_id(sym_id)
                && sym.redirect() == SymbolRedirect::Forwarded
            {
                let fwd = unsafe { &*sym.val.fwd };
                if matches!(fwd.ty, LispFwdType::BufferObj) {
                    let buf_fwd = unsafe { &*(fwd as *const _ as *const LispBufferObjFwd) };
                    let off = buf_fwd.offset as usize;
                    if let Some(defaults) = buffer_defaults
                        && off < defaults.len()
                    {
                        return Some(defaults[off]);
                    }
                    return Some(buf_fwd.default);
                }
            }

            obarray.default_value_id(sym_id).copied()
        }
    }
}

pub(crate) fn set_default_toplevel_value_in_state(
    specpdl: &mut [SpecBinding],
    sym_id: SymId,
    value: Value,
) -> bool {
    for binding in specpdl.iter_mut() {
        match binding {
            SpecBinding::Let {
                sym_id: binding_sym,
                old_value,
            }
            | SpecBinding::LetDefault {
                sym_id: binding_sym,
                old_value,
            } if *binding_sym == sym_id => {
                *old_value = Some(value);
                return true;
            }
            SpecBinding::Let { .. }
            | SpecBinding::LetDefault { .. }
            | SpecBinding::LetLocal { .. }
            | SpecBinding::LexicalEnv { .. }
            | SpecBinding::GcRoot { .. }
            | SpecBinding::Backtrace { .. }
            | SpecBinding::Nop
            | SpecBinding::UnwindProtect { .. }
            | SpecBinding::SaveExcursion { .. }
            | SpecBinding::SaveCurrentBuffer { .. }
            | SpecBinding::SaveRestriction { .. } => {}
        }
    }
    false
}

pub(crate) fn set_runtime_binding_in_state(
    ctx: &mut Context,
    sym_id: SymId,
    value: Value,
) -> Option<crate::buffer::BufferId> {
    set_runtime_binding(
        &mut ctx.obarray,
        &mut ctx.buffers,
        &ctx.custom,
        ctx.specpdl.as_slice(),
        sym_id,
        value,
    )
}

pub(crate) fn set_runtime_binding(
    obarray: &mut Obarray,
    buffers: &mut BufferManager,
    _custom: &CustomManager,
    specpdl: &[SpecBinding],
    sym_id: SymId,
    value: Value,
) -> Option<crate::buffer::BufferId> {
    use crate::emacs_core::symbol::{SetInternalBind, SymbolRedirect};

    let symbol_is_canonical = super::builtins::is_canonical_symbol_id(sym_id);

    // Phase 10E: route writes for LOCALIZED symbols through the BLV
    // machinery. Mirrors GNU `set_internal` SYMBOL_LOCALIZED arm
    // (`data.c:1687-1762`) and the vm.rs assign_var_id LOCALIZED
    // path — keeps the eval.rs and vm.rs hot paths semantically
    // identical so a buffer-local visible from the bytecode VM is
    // also visible from the tree-walk interpreter and the `set`
    // builtin.
    let redirect = obarray.get_by_id(sym_id).map(|s| s.redirect());
    if symbol_is_canonical
        && matches!(redirect, Some(SymbolRedirect::Localized))
        && let Some(buf_id) = buffers.current_buffer_id()
    {
        let (cur_val, alist) = match buffers.get(buf_id) {
            Some(buf) => (Value::make_buffer(buf.id), buf.local_var_alist),
            None => (Value::NIL, Value::NIL),
        };
        let let_shadows = specpdl.iter().rev().any(
            |entry| matches!(entry, SpecBinding::LetDefault { sym_id: s, .. } if *s == sym_id),
        );
        let new_alist = obarray.set_internal_localized(
            sym_id,
            value,
            cur_val,
            alist,
            SetInternalBind::Set,
            let_shadows,
        );
        if let Some(buf) = buffers.get_mut(buf_id) {
            buf.local_var_alist = new_alist;
        }
        return Some(buf_id);
    }

    // Phase 10D: ordinary `setq` on a FORWARDED BUFFER_OBJFWD symbol
    // mirrors GNU `set_internal` (`data.c:1774-1784`):
    //
    //   - always-local slots write the current buffer slot directly
    //   - conditional slots with an existing local flag write the
    //     current buffer slot directly
    //   - conditional slots without a local flag auto-create a local
    //     binding, unless a surrounding `let` is shadowing the buffer
    //     binding, in which case the write targets the default path
    //     (`set_default_internal`)
    if symbol_is_canonical
        && matches!(redirect, Some(SymbolRedirect::Forwarded))
        && let Some(current_id) = buffers.current_buffer_id()
        && let Some(info) = crate::buffer::buffer::lookup_buffer_slot_by_sym_id(sym_id)
    {
        let has_local = buffers
            .get(current_id)
            .map(|buf| info.local_flags_idx < 0 || buf.slot_local_flag(info.offset))
            .unwrap_or(false);
        if has_local {
            let _ = buffers.set_buffer_local_property_by_sym_id(current_id, sym_id, value);
            return Some(current_id);
        }

        let let_shadows = specpdl.iter().rev().any(|entry| {
            matches!(
                entry,
                SpecBinding::LetDefault { sym_id: s, .. } | SpecBinding::LetLocal { sym_id: s, .. }
                    if *s == sym_id
            )
        });
        if let_shadows {
            buffers.set_buffer_default_slot(info, value);
            return None;
        }

        let _ = buffers.set_buffer_local_property_by_sym_id(current_id, sym_id, value);
        return Some(current_id);
    }

    // Non-forwarded per-buffer variables like `buffer-undo-list`
    // still live behind the generic buffer-local storage helpers.
    // Preserve the pre-Phase-10 behavior for those names: if the
    // current buffer already reports the variable as local, write the
    // current buffer binding instead of the obarray cell.
    if symbol_is_canonical
        && let Some(current_id) = buffers.current_buffer_id()
        && let Some(buf) = buffers.get(current_id)
        && buf.has_buffer_local_by_sym_id(sym_id)
    {
        let _ = buffers.set_buffer_local_property_by_sym_id(current_id, sym_id, value);
        return Some(current_id);
    }

    obarray.set_symbol_value_id(sym_id, value);
    None
}

pub(crate) fn makunbound_runtime_binding_in_state(
    obarray: &mut Obarray,
    buffers: &mut BufferManager,
    _custom: &CustomManager,
    _specpdl: &[SpecBinding],
    sym_id: SymId,
) {
    let symbol_is_canonical = super::builtins::is_canonical_symbol_id(sym_id);

    // specbind writes directly to obarray, so no dynamic frame lookup needed.

    if symbol_is_canonical
        && let Some(current_id) = buffers.current_buffer_id()
        && let Some(buf) = buffers.get(current_id)
        && buf.has_buffer_local_by_sym_id(sym_id)
    {
        let _ = buffers.set_buffer_local_void_property_by_sym_id(current_id, sym_id);
        return;
    }

    // Mirrors GNU `set_internal` SYMBOL_LOCALIZED arm with
    // `unbinding_p = true` (`src/data.c:1687-1762`). The BLV's
    // `local_if_set` flag determines whether to create a per-buffer
    // void binding; LOCALIZED symbols carry a BLV so this fires only
    // for them.
    let local_if_set = obarray
        .blv(sym_id)
        .map(|blv| blv.local_if_set)
        .unwrap_or(false);
    if symbol_is_canonical && local_if_set {
        if let Some(current_id) = buffers.current_buffer_id() {
            let _ = buffers.set_buffer_local_void_property_by_sym_id(current_id, sym_id);
            return;
        }
    }

    obarray.makunbound_id(sym_id);
}

impl Context {
    pub(crate) fn materialize_public_evaluator_function_cells(&mut self) {
        // GNU `defsubr` installs public special forms and evaluator callables
        // directly into the symbol's function cell. Keep those cells
        // authoritative instead of synthesizing them later from name tables.
        for name in super::subr_info::public_evaluator_subr_names() {
            let sym_id = intern(name);
            let name_id = symbol_name_id(sym_id);
            let (min_args, max_args, dispatch_kind) =
                super::subr_info::lookup_compat_subr_metadata(name, 0, None);
            // Register in global static table so lookups by sym_id work
            register_global_subr_entry(
                sym_id,
                SubrEntry {
                    function: None, // evaluator-handled, no SubrFn
                    min_args,
                    max_args,
                    dispatch_kind,
                    name_id,
                },
            );
            self.obarray.intern(name);
            self.obarray
                .set_symbol_function_id(sym_id, Value::subr_from_sym_id(sym_id));
        }
    }

    // -----------------------------------------------------------------------
    // defsubr — builtin function registration (matches GNU Emacs's defsubr)
    // -----------------------------------------------------------------------

    /// Register a builtin function by name, storing a function pointer in the
    /// registry. At call time, the function pointer is invoked directly — no
    /// string-matching dispatch needed.
    pub fn defsubr(
        &mut self,
        name: &str,
        func: fn(&mut Context, Vec<Value>) -> EvalResult,
        min_args: u16,
        max_args: Option<u16>,
    ) {
        self.defsubr_with_entry(
            name,
            crate::tagged::header::SubrFn::Many(func),
            min_args,
            max_args,
        );
    }

    pub fn defsubr_slice(
        &mut self,
        name: &str,
        func: fn(&mut Context, &[Value]) -> EvalResult,
        min_args: u16,
        max_args: Option<u16>,
    ) {
        self.defsubr_with_entry(
            name,
            crate::tagged::header::SubrFn::ManySlice(func),
            min_args,
            max_args,
        );
    }

    pub fn defsubr_0(&mut self, name: &str, func: fn(&mut Context) -> EvalResult) {
        self.defsubr_with_entry(name, crate::tagged::header::SubrFn::A0(func), 0, Some(0));
    }

    pub fn defsubr_1(
        &mut self,
        name: &str,
        func: fn(&mut Context, Value) -> EvalResult,
        min_args: u16,
    ) {
        self.defsubr_with_entry(
            name,
            crate::tagged::header::SubrFn::A1(func),
            min_args,
            Some(1),
        );
    }

    pub fn defsubr_2(
        &mut self,
        name: &str,
        func: fn(&mut Context, Value, Value) -> EvalResult,
        min_args: u16,
    ) {
        self.defsubr_with_entry(
            name,
            crate::tagged::header::SubrFn::A2(func),
            min_args,
            Some(2),
        );
    }

    pub fn defsubr_3(
        &mut self,
        name: &str,
        func: fn(&mut Context, Value, Value, Value) -> EvalResult,
        min_args: u16,
    ) {
        self.defsubr_with_entry(
            name,
            crate::tagged::header::SubrFn::A3(func),
            min_args,
            Some(3),
        );
    }

    fn defsubr_with_entry(
        &mut self,
        name: &str,
        func: crate::tagged::header::SubrFn,
        min_args: u16,
        max_args: Option<u16>,
    ) {
        let (min_args, max_args, dispatch_kind) =
            super::subr_info::lookup_compat_subr_metadata(name, min_args, max_args);
        let sym_id = intern(name);
        let name_id = symbol_name_id(sym_id);

        // Register in global static table
        register_global_subr_entry(
            sym_id,
            SubrEntry {
                function: Some(func),
                min_args,
                max_args,
                dispatch_kind,
                name_id,
            },
        );

        self.obarray.intern(name);
        // `init_builtins` runs both on a fresh evaluator and again after
        // restoring a pdump image. On the pdump path, GNU-loaded Lisp
        // definitions may already shadow a primitive with the same name
        // (e.g. `global-set-key`, `local-set-key`, `transient-mark-mode`).
        // Refresh stale subr cells, but do not clobber an existing non-subr
        // function cell that the dumped runtime already established.
        let should_install_public_subr =
            self.obarray
                .symbol_function_id(sym_id)
                .is_none_or(|existing| {
                    matches!(
                        existing.kind(),
                        ValueKind::Subr(_) | ValueKind::Veclike(VecLikeType::Subr)
                    )
                });
        if should_install_public_subr {
            self.obarray
                .set_symbol_function(name, Value::subr_from_sym_id(sym_id));
        }
    }

    /// Call a registered subr value directly. Returns None if VALUE is not a
    /// fully registered subr.
    pub fn dispatch_subr_value(&mut self, function: Value, args: Vec<Value>) -> Option<EvalResult> {
        let sym_id = function.as_subr_id()?;
        let wrong_arity_callee = Value::symbol(resolve_sym(sym_id));
        self.dispatch_subr_value_internal(function, args.into(), wrong_arity_callee)
    }

    /// Resolve a symbol identity to its canonical subr object and call it.
    /// Returns None if the symbol's canonical name has no registered subr.
    /// Supports uninterned symbols: falls back to canonical SymId via NameId lookup.
    pub fn dispatch_subr_id(&mut self, sym_id: SymId, args: Vec<Value>) -> Option<EvalResult> {
        // Try the sym_id directly first
        let resolved = if lookup_global_subr_entry(sym_id).is_some() {
            sym_id
        } else {
            // Fall back to canonical symbol for this name (handles uninterned SymIds)
            let name_id = symbol_name_id(sym_id);
            let canonical = crate::emacs_core::intern::canonical_symbol_for_name(name_id)?;
            lookup_global_subr_entry(canonical)?;
            canonical
        };
        let function = Value::subr_from_sym_id(resolved);
        self.dispatch_subr_value(function, args)
    }

    pub fn dispatch_subr(&mut self, name: &str, args: Vec<Value>) -> Option<EvalResult> {
        self.dispatch_subr_id(intern(name), args)
    }

    // -----------------------------------------------------------------------
    // Methods previously on VmSharedState, now on Context directly
    // -----------------------------------------------------------------------

    pub(crate) fn begin_eval_with_lexical_arg(
        &mut self,
        lexical_arg: Option<Value>,
    ) -> Result<ActiveEvalLexicalArgState, Flow> {
        begin_eval_with_lexical_arg_in_state(
            &mut self.obarray,
            &mut self.lexenv,
            &mut self.specpdl,
            lexical_arg,
        )
    }

    pub(crate) fn finish_eval_with_lexical_arg(&mut self, state: ActiveEvalLexicalArgState) {
        finish_eval_with_lexical_arg_in_state(
            &mut self.obarray,
            &mut self.lexenv,
            &mut self.specpdl,
            state,
        );
    }

    pub(crate) fn begin_macro_expansion_scope(&mut self) -> ActiveMacroExpansionScopeState {
        self.macro_expansion_scope_depth += 1;
        begin_macro_expansion_scope_in_state(
            &mut self.obarray,
            &mut self.specpdl,
            &mut self.buffers,
            &self.custom,
            self.lexenv,
        )
    }

    pub(crate) fn finish_macro_expansion_scope(&mut self, state: ActiveMacroExpansionScopeState) {
        finish_macro_expansion_scope_in_state(
            &mut self.obarray,
            &mut self.specpdl,
            &mut self.buffers,
            &self.custom,
            state,
        );
        self.macro_expansion_scope_depth = self.macro_expansion_scope_depth.saturating_sub(1);
    }

    pub(crate) fn kmacro_mut(&mut self) -> &mut KmacroManager {
        &mut self.kmacro
    }

    pub(crate) fn gui_frame_creation_state(
        &mut self,
    ) -> (
        &mut FrameManager,
        &mut BufferManager,
        &mut Option<Box<dyn DisplayHost>>,
    ) {
        (&mut self.frames, &mut self.buffers, &mut self.display_host)
    }

    pub(crate) fn recursive_command_loop_depth(&self) -> usize {
        // GNU's `command_loop_level` starts at -1 before entering the
        // top-level recursive edit, so ordinary interactive execution happens
        // at level 0. Neomacs stores the raw active-loop count instead
        // (0 outside the loop, 1 at top level), so translate here to the
        // GNU-visible level used by mode-line and minibuffer semantics.
        self.command_loop.recursive_depth.saturating_sub(1)
    }

    pub(crate) fn interactive_minibuffer_read_count(&self) -> u64 {
        self.interactive_minibuffer_read_count
    }

    pub(crate) fn note_interactive_minibuffer_read(&mut self) {
        self.interactive_minibuffer_read_count =
            self.interactive_minibuffer_read_count.saturating_add(1);
    }

    fn sync_current_buffer_to_selected_window(&mut self) {
        let Some(frame_id) = self.frames.selected_frame().map(|frame| frame.id) else {
            return;
        };
        super::window_cmds::remember_selected_window_point_in_state(
            &mut self.frames,
            &self.buffers,
            frame_id,
        );
        super::window_cmds::sync_selected_window_buffer_in_state(
            &self.frames,
            &mut self.buffers,
            frame_id,
        );
        let _ = self.sync_current_buffer_runtime_state();
    }

    // -----------------------------------------------------------------------

    pub(crate) fn lexenv_assq_cached_in(&self, lexenv: Value, sym_id: SymId) -> Option<Value> {
        let lexenv_bits = lexenv.bits();
        let mut cache = self.lexenv_assq_cache.borrow_mut();
        if let Some(cell) = cache.find(lexenv_bits, sym_id) {
            return Some(cell);
        }

        let cell = lexenv_assq(lexenv, sym_id)?;
        cache.push(LexenvAssqCacheEntry {
            lexenv_bits,
            symbol: sym_id,
            cell,
        });
        Some(cell)
    }

    pub(crate) fn lexenv_lookup_cached_in(&self, lexenv: Value, sym_id: SymId) -> Option<Value> {
        self.lexenv_assq_cached_in(lexenv, sym_id)
            .map(|cell| cell.cons_cdr())
    }

    pub(crate) fn lexenv_declares_special_cached_in(&self, lexenv: Value, sym_id: SymId) -> bool {
        let lexenv_bits = lexenv.bits();
        let mut cache = self.lexenv_special_cache.borrow_mut();
        if let Some(declared_special) = cache.find(lexenv_bits, sym_id) {
            return declared_special;
        }

        let declared_special = lexenv_declares_special(lexenv, sym_id);
        cache.push(LexenvSpecialCacheEntry {
            lexenv_bits,
            symbol: sym_id,
            declared_special,
        });
        declared_special
    }

    /// Assign a value to a variable identified by SymId.
    /// Uses the SymId directly for lexenv/dynamic lookup, preserving
    /// uninterned symbol identity (like Emacs's EQ-based setq).
    pub(crate) fn assign_by_id(&mut self, sym_id: SymId, value: Value) {
        let _ = self.assign_by_id_with_locus(sym_id, value);
    }

    pub(crate) fn assign_by_id_with_locus(
        &mut self,
        sym_id: SymId,
        value: Value,
    ) -> Option<crate::buffer::BufferId> {
        // GNU `setq` follows the same rule as `eval_sub`: if a lexical binding
        // cell exists, mutate it directly. Declared-special affects whether
        // that cell was created, not whether assignment should reuse it.
        if self.lexical_binding() {
            if let Some(cell_id) = self.lexenv_assq_cached_in(self.lexenv, sym_id) {
                lexenv_set(cell_id, value);
                return None;
            }
        }

        let locus = set_runtime_binding(
            &mut self.obarray,
            &mut self.buffers,
            &self.custom,
            &self.specpdl,
            sym_id,
            value,
        );
        self.sync_cached_runtime_binding_by_id(sym_id, value);
        self.sync_keyboard_runtime_binding_by_id(sym_id, value);
        self.refresh_gc_runtime_settings_after_change_by_id(sym_id);
        locus
    }

    pub(crate) fn assign(&mut self, name: &str, value: Value) {
        self.assign_by_id(intern(name), value);
    }

    pub(crate) fn set_runtime_binding_by_id(
        &mut self,
        sym_id: SymId,
        value: Value,
    ) -> Option<crate::buffer::BufferId> {
        let locus = set_runtime_binding(
            &mut self.obarray,
            &mut self.buffers,
            &self.custom,
            &self.specpdl,
            sym_id,
            value,
        );
        self.sync_cached_runtime_binding_by_id(sym_id, value);
        self.sync_keyboard_runtime_binding_by_id(sym_id, value);
        self.refresh_gc_runtime_settings_after_change_by_id(sym_id);
        locus
    }

    pub(crate) fn makunbound_runtime_binding_by_id(&mut self, sym_id: SymId) {
        makunbound_runtime_binding_in_state(
            &mut self.obarray,
            &mut self.buffers,
            &self.custom,
            &[],
            sym_id,
        );
        self.sync_cached_runtime_binding_by_id(sym_id, Value::NIL);
        self.sync_keyboard_runtime_binding_by_id(sym_id, Value::NIL);
        self.refresh_gc_runtime_settings_after_change_by_id(sym_id);
    }

    fn has_local_binding_by_id(&self, sym_id: SymId) -> bool {
        self.lexenv_assq_cached_in(self.lexenv, sym_id).is_some()
            || self
                .specpdl
                .iter()
                .rev()
                .any(|entry| matches!(entry, SpecBinding::Let { sym_id: s, .. } if *s == sym_id))
    }

    pub(crate) fn visible_variable_value_or_nil(&self, name: &str) -> Value {
        self.visible_variable_value_or_nil_by_id(intern(name))
    }

    pub(crate) fn visible_variable_value_or_nil_by_id(&self, sym_id: SymId) -> Value {
        if let Some(value) = self.lexenv_lookup_cached_in(self.lexenv, sym_id) {
            return value;
        }
        if let Ok(Some(value)) = self.visible_runtime_variable_value_by_id(sym_id) {
            return value;
        }
        Value::NIL
    }

    pub(crate) fn visible_runtime_variable_value_by_id(
        &self,
        sym_id: SymId,
    ) -> Result<Option<Value>, Flow> {
        let resolved = builtins::resolve_variable_alias_id_in_obarray(&self.obarray, sym_id)?;
        Ok(self.visible_runtime_variable_value_by_id_resolved(resolved))
    }

    pub(crate) fn visible_runtime_variable_value_by_id_resolved(
        &self,
        resolved: SymId,
    ) -> Option<Value> {
        let resolved_is_canonical = is_canonical_id(resolved);

        use crate::emacs_core::symbol::SymbolRedirect;
        if let Some(sym) = self.obarray.get_by_id(resolved) {
            match sym.redirect() {
                SymbolRedirect::Localized if resolved_is_canonical => {
                    if let Some(buf) = self.buffers.current_buffer() {
                        let target_buf = Value::make_buffer(buf.id);
                        if let Some(value) =
                            self.obarray
                                .read_localized(resolved, target_buf, buf.local_var_alist)
                        {
                            if value.is_unbound() {
                                return None;
                            }
                            return Some(value);
                        }
                    }
                }
                SymbolRedirect::Forwarded => {
                    if let Some(value) = self.forwarded_buffer_obj_value(sym) {
                        return Some(value);
                    }
                }
                SymbolRedirect::Plainval | SymbolRedirect::Varalias | SymbolRedirect::Localized => {
                }
            }
        }

        if resolved_is_canonical
            && resolved == buffer_undo_list_symbol()
            && let Some(buf) = self.buffers.current_buffer()
            && let Some(binding) = buf.get_buffer_local_binding_by_sym_id(resolved)
        {
            return binding.as_value();
        }

        if let Some(value) = self.obarray.symbol_value_id(resolved).copied() {
            return Some(value);
        }

        if resolved_is_canonical && resolved == nil_symbol() {
            return Some(Value::NIL);
        }
        if resolved_is_canonical && resolved == t_symbol() {
            return Some(Value::T);
        }
        if is_keyword_id(resolved) {
            return Some(Value::from_kw_id(resolved));
        }

        None
    }

    fn run_unlet_watchers(&mut self, bindings: &[(String, Value, Value)]) -> Result<(), Flow> {
        for (name, _, restored_value) in bindings.iter().rev() {
            self.run_variable_watchers(name, restored_value, &Value::NIL, "unlet")?;
        }
        Ok(())
    }

    pub(crate) fn run_variable_watchers_by_id(
        &mut self,
        sym_id: SymId,
        new_value: &Value,
        old_value: &Value,
        operation: &str,
    ) -> Result<(), Flow> {
        self.run_variable_watchers_by_id_with_where(
            sym_id,
            new_value,
            old_value,
            operation,
            &Value::NIL,
        )
    }

    pub(crate) fn run_variable_watchers_by_id_with_where(
        &mut self,
        sym_id: SymId,
        new_value: &Value,
        old_value: &Value,
        operation: &str,
        where_value: &Value,
    ) -> Result<(), Flow> {
        if !self.watchers.has_watchers(sym_id) {
            return Ok(());
        }
        let calls =
            self.watchers
                .notify_watchers(sym_id, new_value, old_value, operation, where_value);
        for (callback, args) in calls {
            let _ = self.apply(callback, args)?;
        }
        Ok(())
    }

    pub(crate) fn run_variable_watchers(
        &mut self,
        name: &str,
        new_value: &Value,
        old_value: &Value,
        operation: &str,
    ) -> Result<(), Flow> {
        self.run_variable_watchers_by_id(intern(name), new_value, old_value, operation)
    }

    pub(crate) fn run_variable_watchers_with_where(
        &mut self,
        name: &str,
        new_value: &Value,
        old_value: &Value,
        operation: &str,
        where_value: &Value,
    ) -> Result<(), Flow> {
        self.run_variable_watchers_by_id_with_where(
            intern(name),
            new_value,
            old_value,
            operation,
            where_value,
        )
    }

    pub(crate) fn assign_with_watchers(
        &mut self,
        name: &str,
        value: Value,
        operation: &str,
    ) -> EvalResult {
        self.assign_with_watchers_by_id(intern(name), value, operation)
    }

    pub(crate) fn assign_with_watchers_by_id(
        &mut self,
        sym_id: SymId,
        value: Value,
        operation: &str,
    ) -> EvalResult {
        let where_value = self
            .assign_by_id_with_locus(sym_id, value)
            .map(Value::make_buffer)
            .unwrap_or(Value::NIL);
        self.run_variable_watchers_by_id_with_where(
            sym_id,
            &value,
            &Value::NIL,
            operation,
            &where_value,
        )?;
        Ok(value)
    }
}

fn format_startup_value(value: Option<&Value>) -> String {
    value
        .map(super::print::print_value)
        .unwrap_or_else(|| "<unbound>".to_string())
}

/// Convert a Value cons list to the evaluator's inline argument buffer.
fn value_list_to_values(list: &Value) -> LispArgVec {
    let mut result = LispArgVec::new();
    let mut cursor = *list;
    while cursor.is_cons() {
        result.push(cursor.cons_car());
        cursor = cursor.cons_cdr();
    }
    result
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
#[path = "eval_test.rs"]
mod tests;
fn runtime_string_value(value: Value) -> String {
    value
        .as_runtime_string_owned()
        .expect("ValueKind::String must carry LispString payload")
}