logicaffeine-compile 0.10.1

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

use std::collections::{HashMap, HashSet};
use std::fs;
use std::io::Write;
use std::path::Path;
use std::process::Command;

// Runtime crates paths (relative to workspace root)
const CRATES_DATA_PATH: &str = "crates/logicaffeine_data";
const CRATES_SYSTEM_PATH: &str = "crates/logicaffeine_system";

use std::fmt::Write as FmtWrite;

use crate::analysis::{DiscoveryPass, EscapeChecker, OwnershipChecker, PolicyRegistry};
use crate::arena::Arena;
use crate::arena_ctx::AstContext;
use crate::ast::{Expr, MatchArm, Stmt, TypeExpr};
use crate::ast::stmt::{BinaryOpKind, ClosureBody, Literal, Pattern, ReadSource, SelectBranch, StringPart};
use crate::codegen::{codegen_program, generate_c_header, generate_python_bindings, generate_typescript_bindings};
use crate::diagnostic::{parse_rustc_json, translate_diagnostics, LogosError};
use crate::drs::WorldState;
use crate::error::ParseError;
use crate::intern::Interner;
use crate::lexer::Lexer;
use crate::parser::Parser;
use crate::sourcemap::SourceMap;

/// A declared external crate dependency from a `## Requires` block.
#[derive(Debug, Clone)]
pub struct CrateDependency {
    pub name: String,
    pub version: String,
    pub features: Vec<String>,
}

/// Full compilation output including generated Rust code and extracted dependencies.
#[derive(Debug)]
pub struct CompileOutput {
    pub rust_code: String,
    pub dependencies: Vec<CrateDependency>,
    /// Generated C header content (populated when C exports exist).
    pub c_header: Option<String>,
    /// Generated Python ctypes bindings (populated when C exports exist).
    pub python_bindings: Option<String>,
    /// Generated TypeScript type declarations (.d.ts content, populated when C exports exist).
    pub typescript_types: Option<String>,
    /// Generated TypeScript FFI bindings (.js content, populated when C exports exist).
    pub typescript_bindings: Option<String>,
}

/// Interpret LOGOS source and return output as a string.
///
/// Runs the full pipeline (lex → discovery → parse → interpret) without
/// generating Rust code. Useful for sub-second feedback during development.
///
/// # Arguments
///
/// * `source` - LOGOS source code as a string
///
/// # Returns
///
/// The collected output from `Show` statements, joined by newlines.
///
/// # Errors
///
/// Returns [`ParseError`] if parsing fails or the interpreter encounters
/// a runtime error.
pub fn interpret_program(source: &str) -> Result<String, ParseError> {
    let result = crate::ui_bridge::interpret_for_ui_sync(source);
    if let Some(err) = result.error {
        Err(ParseError {
            kind: crate::error::ParseErrorKind::Custom(err),
            span: crate::token::Span::default(),
        })
    } else {
        Ok(result.lines.join("\n"))
    }
}

/// Parse LOGOS source and execute it on the register bytecode VM, returning the
/// captured output. Uses the SAME front-end as the tree-walker
/// ([`crate::ui_bridge::with_parsed_program`]: lex → MWE → discovery → parse),
/// so differential tests compare two engines on one program, never two
/// programs. Returns `Err` for programs outside the VM's supported subset (the
/// compiler reports `vm: unsupported …`).
pub fn vm_run_source(source: &str) -> Result<String, String> {
    crate::ui_bridge::with_parsed_program(source, |parsed, interner| match parsed {
        Ok((stmts, types, policies)) => {
            let (output, error) =
                crate::vm::run_to_outcome(stmts, interner, Some(types), Some(&policies));
            match error {
                None => Ok(output),
                Some(e) => Err(e),
            }
        }
        Err(advice) => Err(advice),
    })
}

/// What a program run produced: every output line emitted before completion or
/// failure, plus the error if it failed. The differential contract is
/// `vm_outcome(src) == tw_outcome(src)` — output AND error.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RunOutcome {
    pub output: String,
    pub error: Option<String>,
}

/// Run `source` on the TREE-WALKER (the oracle), capturing partial output and
/// the error, if any. This entry point always uses the tree-walker — the
/// dispatching `interpret_for_ui_sync` now runs the VM for the sync path, and
/// the differential suites need the oracle by itself.
pub fn tw_outcome(source: &str) -> RunOutcome {
    // Deterministic oracle: no relay transport, so `Connect` runs as a single-node local no-op (the
    // networking analogue of the fixed clock). Only affects a `Connect` program; inert otherwise.
    crate::concurrency::net_inbox::set_net_offline(true);
    crate::ui_bridge::with_parsed_program(source, |parsed, interner| match parsed {
        Ok((stmts, types, policies)) => {
            let force_async = crate::interpreter::needs_async(stmts);
            let result = crate::ui_bridge::run_treewalker(
                stmts, types, policies, interner, force_async, &[],
            );
            RunOutcome { output: result.lines.join("\n"), error: result.error }
        }
        Err(advice) => RunOutcome { output: String::new(), error: Some(advice) },
    })
}

/// Run `source` on the bytecode VM, capturing partial output and the error,
/// if any. Same front-end as [`tw_outcome`].
pub fn vm_outcome(source: &str) -> RunOutcome {
    crate::ui_bridge::with_parsed_program(source, |parsed, interner| match parsed {
        Ok((stmts, types, policies)) => {
            let (output, error) =
                crate::vm::run_to_outcome(stmts, interner, Some(types), Some(&policies));
            RunOutcome { output, error }
        }
        Err(advice) => RunOutcome { output: String::new(), error: Some(advice) },
    })
}

/// The VM outcome for a CONCURRENT program — drives the bytecode VM on the cooperative scheduler
/// (`VmTask` on `run_with_seed`, seed 0) exactly as the browser/playground does, so a `Pipe`/task/
/// `Select` program runs on the VM byte-identical to the tree-walker's async path. The plain
/// [`vm_outcome`] errors on any concurrency op (`requires the scheduler driver`); this is the oracle
/// the AOT concurrency lock compares against so tw == VM == AOT is verifiable for the concurrent set.
#[cfg(not(target_arch = "wasm32"))]
pub fn vm_outcome_concurrent(source: &str) -> RunOutcome {
    let r = crate::ui_bridge::run_vm_concurrent(source);
    RunOutcome { output: r.lines.join("\n"), error: r.error }
}

/// The VM outcome for a peer-NETWORKING program — drives the resumable bytecode VM and services each
/// `VmBlock::Net*` through the shared LOCAL `NetInbox` (the same inbox the tree-walker's offline
/// mode uses), so `Listen`/`Send`/`Sync`/`PeerAgent` run on the VM byte-identical to the tree-walker.
/// The AOT networking lock compares against this so tw == VM == AOT holds for the local-mode net set.
#[cfg(not(target_arch = "wasm32"))]
pub fn vm_outcome_net(source: &str) -> RunOutcome {
    // Deterministic oracle: offline single node, so `Connect` is a local no-op (matches `tw_outcome`).
    crate::concurrency::net_inbox::set_net_offline(true);
    let r = futures::executor::block_on(crate::ui_bridge::run_vm_net_async(source));
    RunOutcome { output: r.lines.join("\n"), error: r.error }
}

/// [`tw_outcome`] with the program argument vector for the `args()` system
/// native (full argv; index 0 is the program name) — the seam the benchmark
/// corpus differential uses to run `main.lg` programs that read their size
/// from argv.
pub fn tw_outcome_with_args(source: &str, program_args: &[String]) -> RunOutcome {
    crate::ui_bridge::with_parsed_program(source, |parsed, interner| match parsed {
        Ok((stmts, types, policies)) => {
            let force_async = crate::interpreter::needs_async(stmts);
            let result = crate::ui_bridge::run_treewalker(
                stmts, types, policies, interner, force_async, program_args,
            );
            RunOutcome { output: result.lines.join("\n"), error: result.error }
        }
        Err(advice) => RunOutcome { output: String::new(), error: Some(advice) },
    })
}

/// [`vm_outcome`] with the program argument vector and an optional private
/// native tier (so a differential test can observe THAT program's JIT compile
/// counters in isolation — the process-wide tier's counters are shared by
/// every test in the binary).
pub fn vm_outcome_with_args(
    source: &str,
    program_args: &[String],
    tier: Option<&dyn crate::vm::NativeTier>,
) -> RunOutcome {
    crate::ui_bridge::with_parsed_program(source, |parsed, interner| match parsed {
        Ok((stmts, types, policies)) => {
            let (output, error) = crate::vm::run_to_outcome_with_args(
                stmts,
                interner,
                Some(types),
                Some(&policies),
                program_args,
                tier,
            );
            RunOutcome { output, error }
        }
        Err(advice) => RunOutcome { output: String::new(), error: Some(advice) },
    })
}

/// [`vm_outcome_with_args`], but the statements pass through the run-path optimizer
/// at an explicit hotness `tier` (HOTSWAP §4) before reaching the VM — the seam the
/// `tier_invariance` gate drives at every tier T0..T3 to assert byte-identical
/// output. `tier = Tier::T3` reproduces today's optimized run path.
pub fn vm_outcome_tiered(
    source: &str,
    program_args: &[String],
    tier: crate::optimization::Tier,
    native_tier: Option<&dyn crate::vm::NativeTier>,
) -> RunOutcome {
    crate::ui_bridge::with_optimized_program_tiered(source, tier, |parsed, interner| match parsed {
        Ok((stmts, types, policies)) => {
            let (output, error) = crate::vm::run_to_outcome_with_args(
                stmts,
                interner,
                Some(types),
                Some(&policies),
                program_args,
                native_tier,
            );
            RunOutcome { output, error }
        }
        Err(advice) => RunOutcome { output: String::new(), error: Some(advice) },
    })
}

/// [`vm_outcome_with_args`] driven through the BACKGROUND native compiler (HOTSWAP §6):
/// hot functions compile on a worker thread off the interpreter's path. Requires a
/// process-installed tier (the P8 gate installs one first). The compiled chain is
/// identical to the synchronous one — only WHEN it is produced differs — so output
/// must match the synchronous/tree-walker engines exactly.
#[cfg(not(target_arch = "wasm32"))]
pub fn vm_outcome_bg(source: &str, program_args: &[String]) -> RunOutcome {
    crate::ui_bridge::with_parsed_program(source, |parsed, interner| match parsed {
        Ok((stmts, types, policies)) => {
            let (output, error) = crate::vm::run_to_outcome_bg(
                stmts,
                interner,
                Some(types),
                Some(&policies),
                program_args,
            );
            RunOutcome { output, error }
        }
        Err(advice) => RunOutcome { output: String::new(), error: Some(advice) },
    })
}

/// Compile LOGOS source to Rust source code.
///
/// This is the basic compilation function that runs lexing, parsing, and
/// escape analysis before generating Rust code.
///
/// # Arguments
///
/// * `source` - LOGOS source code as a string
///
/// # Returns
///
/// Generated Rust source code on success.
///
/// # Errors
///
/// Returns [`ParseError`] if:
/// - Lexical analysis fails (invalid tokens)
/// - Parsing fails (syntax errors)
/// - Escape analysis fails (zone-local values escaping)
///
/// # Example
///
/// ```
/// # use logicaffeine_compile::compile::compile_to_rust;
/// # use logicaffeine_compile::ParseError;
/// # fn main() -> Result<(), ParseError> {
/// let source = "## Main\nLet x be 5.\nShow x.";
/// let rust_code = compile_to_rust(source)?;
/// assert!(rust_code.contains("let x = 5;"));
/// # Ok(())
/// # }
/// ```
pub fn compile_to_rust(source: &str) -> Result<String, ParseError> {
    compile_program_full(source).map(|o| o.rust_code)
}

/// Compile in **Mode B (deterministic replay)**: identical to [`compile_to_rust`]
/// except a `Select` lowers to the *seeded* winner-pick that shares the
/// interpreter's choice function, so a binary run under `LOGOS_SEED=…` reproduces
/// the interpreter's selection. Used by `largo build --deterministic` and the
/// seeded differential harness. Non-`Select` emission is unchanged.
pub fn compile_to_rust_deterministic(source: &str) -> Result<String, ParseError> {
    crate::codegen::with_seeded_select(|| compile_to_rust(source))
}

/// Compile imperative LOGOS to Rust with an extracted math/logic module bundled in.
/// `proven` is a main-less Rust module body (the Forge's extraction); it is emitted
/// as `pub mod proven { … } use proven::*;` so the imperative program can call its
/// functions / `check_*` predicates by name. See [`compile_program_full_with_proven`].
pub fn compile_to_rust_with_proven(source: &str, proven: &str) -> Result<String, ParseError> {
    compile_program_full_with_proven(source, Some(proven)).map(|o| o.rust_code)
}

/// Which optimizations actually FIRE for `source`: an optimization is "used" when
/// disabling it (via a file-level `## No <X>` decorator) changes the generated
/// Rust. Lets the benchmarks UI show, per program, which optimizations it USES vs
/// the full set it CAN use. O(number of optimizations) compiles — intended for
/// per-benchmark, not hot-path, use. Returns the decorator keywords of the firing
/// optimizations (in registry order).
pub fn optimizations_used(source: &str) -> Vec<&'static str> {
    let base = match compile_to_rust(source) {
        Ok(r) => r,
        Err(_) => return Vec::new(),
    };
    crate::optimization::REGISTRY
        .iter()
        .filter(|m| {
            let decorated = crate::optimization::decorate_source(source, &[m.keyword]);
            compile_to_rust(&decorated).map(|r| r != base).unwrap_or(false)
        })
        .map(|m| m.keyword)
        .collect()
}

/// Compile `source` while recording which optimizations actually FIRED — the
/// honest, single-compile alternative to [`optimizations_used`]'s O(N) diff. An
/// optimization is "fired" when it actually changed the program or emitted its
/// optimized form for this compile, under the effective (normalized) config.
/// Reusable: any caller can compile a program and learn what fired, for tracing
/// and tooling.
pub fn compile_program_traced(
    source: &str,
) -> Result<(CompileOutput, crate::optimization::FiredOptimizations), ParseError> {
    crate::optimize::begin_fired_trace();
    let result = compile_program_full(source);
    // Always end the trace (even on a parse error) so the thread-local never
    // leaks into a later compile on this thread.
    let fired = crate::optimize::end_fired_trace().unwrap_or_default();
    result.map(|o| (o, fired))
}

/// The decorator keywords of the optimizations that fired for `source` (registry
/// order), under the default/effective config. One compile, exact.
pub fn optimizations_fired(source: &str) -> Vec<&'static str> {
    compile_program_traced(source)
        .map(|(_, fired)| fired.keywords())
        .unwrap_or_default()
}

/// The optimizations that fired for `source` under an explicit config — re-traces
/// an arbitrary toggle state (turning some off can make others fire). Realised by
/// disabling that config's off-keywords on the source, then tracing.
pub fn optimizations_fired_with(
    source: &str,
    cfg: &crate::optimization::OptimizationConfig,
) -> Vec<&'static str> {
    let disabled: Vec<&'static str> = cfg.disabled_keywords().collect();
    let decorated = crate::optimization::decorate_source(source, &disabled);
    optimizations_fired(&decorated)
}

/// One compile returning the generated Rust, the fired-optimization keywords, AND
/// the `(winner, loser)` precedence decisions made — what an interactive viewer
/// calls per toggle state to show the firing opts and the conflicts that occurred.
pub fn compile_to_rust_traced(
    source: &str,
) -> Result<(String, Vec<&'static str>, Vec<(&'static str, &'static str)>), ParseError> {
    crate::optimize::begin_fired_trace();
    let result = compile_program_full(source);
    let fired = crate::optimize::end_fired_trace().unwrap_or_default().keywords();
    let preempted = preempted_keywords();
    result.map(|o| (o.rust_code, fired, preempted))
}

/// The `(winner, loser)` precedence decisions the compiler made for `source` — the
/// conflicts traced at their source (`mark_preempted`), under the effective config.
pub fn optimization_preemptions(source: &str) -> Vec<(&'static str, &'static str)> {
    crate::optimize::begin_fired_trace();
    let _ = compile_program_full(source);
    let _ = crate::optimize::end_fired_trace();
    preempted_keywords()
}

/// Convert the trace's `(Opt, Opt)` preemption edges to `(keyword, keyword)`.
fn preempted_keywords() -> Vec<(&'static str, &'static str)> {
    crate::optimize::end_preempted_trace()
        .into_iter()
        .map(|(w, l)| (w.meta().keyword, l.meta().keyword))
        .collect()
}

/// The per-program DEPENDENCY edges for `source`, discovered by evaluating with
/// all optimizations on and probing: disabling a fired optimization `dep` that
/// makes another fired optimization `dependent` STOP firing means `dependent`
/// depended on `dep` for this program. Stops already explained by a declared
/// `requires`-cascade (`normalize` would disable the dependent anyway) are
/// excluded — those are captured by the static registry graph. What remains are
/// the EMERGENT, program-specific dependencies (e.g. dead-code elimination only
/// had work because scalarization produced the dead code): returned as
/// `(dependent, dep)` keyword pairs, sorted and deduped (deterministic).
///
/// This is offline analysis (one compile per fired optimization) — it is baked
/// into the benchmark data, never run in the hot path.
pub fn optimization_dependencies(source: &str) -> Vec<(&'static str, &'static str)> {
    use crate::optimization::{by_keyword, decorate_source, OptimizationConfig};
    use std::collections::BTreeSet;

    let base: Vec<&'static str> = optimizations_fired(source);
    let base_set: BTreeSet<&'static str> = base.iter().copied().collect();
    let mut out: Vec<(&'static str, &'static str)> = Vec::new();
    for &dep in &base {
        let dep_opt = match by_keyword(dep) {
            Some(o) => o,
            None => continue,
        };
        // What the declared `requires`-cascade disables when `dep` is off.
        let mut cfg = OptimizationConfig::all_on();
        cfg.set(dep_opt, false);
        cfg.normalize();
        let off: BTreeSet<&'static str> =
            optimizations_fired(&decorate_source(source, &[dep])).into_iter().collect();
        for &dependent in &base_set {
            if dependent == dep || off.contains(dependent) {
                continue;
            }
            let dependent_opt = match by_keyword(dependent) {
                Some(o) => o,
                None => continue,
            };
            // Skip stops the static graph already explains (normalize disabled it).
            if cfg.is_on(dependent_opt) {
                out.push((dependent, dep));
            }
        }
    }
    out.sort();
    out.dedup();
    out
}

/// The complete per-program optimization graph from one all-on evaluation: the
/// optimizations that `fired`, the `blockers` (`(winner, loser)` preemptions that
/// occurred), and the emergent `dependencies` (`(dependent, dep)` — see
/// [`optimization_dependencies`]). Everything the menu-tree needs, baked once per
/// benchmark so the UI never probes in the hot path. All on the AOT codegen path
/// (the one that produces the shown Rust), so the three views agree.
pub fn optimization_graph(
    source: &str,
) -> (
    Vec<&'static str>,
    Vec<(&'static str, &'static str)>,
    Vec<(&'static str, &'static str)>,
) {
    (
        optimizations_fired(source),
        optimization_preemptions(source),
        optimization_dependencies(source),
    )
}

/// The optimizations that fired on the RUN path — the VM/interpreter optimizer
/// (`optimize_for_run`) — for `source`. The run-path analogue of
/// [`optimizations_fired`] (which traces the AOT codegen path); it surfaces the
/// run-path-only passes — inlining, loop-carried CSE, float strength reduction —
/// the AOT trace cannot see. Respects file-level `## No <opt>` decorators.
pub fn optimizations_fired_run(source: &str) -> Vec<&'static str> {
    crate::optimize::begin_fired_trace();
    crate::ui_bridge::with_optimized_program(source, |_parsed, _interner| {});
    crate::optimize::end_fired_trace()
        .map(|fired| fired.keywords())
        .unwrap_or_default()
}

/// The optimizations that fired while compiling `source` to VM bytecode — the
/// third path, after AOT codegen and the run-path optimizer. Surfaces the
/// VM-compile-time opts (constant-divisor magic division, VM `i32` narrowing)
/// the other two traces cannot see. Compiles only (no execution), so it is fast
/// and needs no program arguments.
pub fn optimizations_fired_vm(source: &str) -> Vec<&'static str> {
    crate::optimize::begin_fired_trace();
    crate::ui_bridge::with_optimized_program(source, |parsed, interner| {
        if let Ok((stmts, types, _policies)) = parsed {
            let oracle = crate::optimize::oracle_analyze_with(stmts, interner);
            let _ = crate::vm::Compiler::compile_with_oracle(stmts, interner, Some(types), Some(oracle));
        }
    });
    crate::optimize::end_fired_trace()
        .map(|fired| fired.keywords())
        .unwrap_or_default()
}

/// Compile LOGOS source to C code (benchmark-only subset).
///
/// Produces a self-contained C file with embedded runtime that can be
/// compiled with `gcc -O2 -o program output.c`.
pub fn compile_to_c(source: &str) -> Result<String, ParseError> {
    let mut interner = Interner::new();
    let mut lexer = Lexer::new(source, &mut interner);
    let tokens = lexer.tokenize();

    let (type_registry, _policy_registry) = {
        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
        let result = discovery.run_full();
        (result.types, result.policies)
    };
    let codegen_registry = type_registry.clone();

    let mut world_state = WorldState::new();
    let expr_arena = Arena::new();
    let term_arena = Arena::new();
    let np_arena = Arena::new();
    let sym_arena = Arena::new();
    let role_arena = Arena::new();
    let pp_arena = Arena::new();
    let stmt_arena: Arena<Stmt> = Arena::new();
    let imperative_expr_arena: Arena<Expr> = Arena::new();
    let type_expr_arena: Arena<TypeExpr> = Arena::new();

    let ast_ctx = AstContext::with_types(
        &expr_arena, &term_arena, &np_arena, &sym_arena,
        &role_arena, &pp_arena, &stmt_arena, &imperative_expr_arena,
        &type_expr_arena,
    );

    let mut parser = Parser::new(tokens, &mut world_state, &mut interner, ast_ctx, type_registry);
    let stmts = parser.parse_program()?;
    let stmts = crate::optimize::optimize_program(stmts, &imperative_expr_arena, &stmt_arena, &mut interner, &crate::optimization::OptimizationConfig::from_env());

    Ok(crate::codegen_c::codegen_program_c(&stmts, &codegen_registry, &interner))
}

/// Compile LOGOS source DIRECTLY to a self-contained WebAssembly module — no rustc, no cargo,
/// no wasm-bindgen, no toolchain. Uses the SAME front-end as [`vm_outcome`]
/// ([`crate::ui_bridge::with_parsed_program`] → [`crate::vm::Compiler::compile_with_types`]),
/// so the emitted module runs the IDENTICAL bytecode the VM does; the AOT WebAssembly backend
/// then lowers the whole program to `.wasm`.
///
/// Returns the bytes of a `.wasm` file. A program outside the backend's supported fragment
/// yields a [`ParseError`] carrying the backend's `unsupported …` reason — the corpus lock
/// turns that into a tracked, shrinking gap rather than a silent skip.
pub fn compile_to_wasm(source: &str) -> Result<Vec<u8>, ParseError> {
    fn custom(msg: String) -> ParseError {
        ParseError { kind: crate::error::ParseErrorKind::Custom(msg), span: crate::token::Span::default() }
    }
    crate::ui_bridge::with_parsed_program(source, |parsed, interner| {
        let (stmts, types, policies) = parsed.map_err(custom)?;
        // Compile with the SAME Oracle the VM/native tier use (`run_to_outcome`), so the AOT receives
        // the optimized bytecode — DivPow2 / MagicDivU (magic-reciprocal division) and the Oracle-proven
        // bounds-check-elimination forms (IndexUnchecked / SetIndexUnchecked / RegionBoundsGuard). The
        // AOT lowers each (division bit-exact to the VM's `magic_eval`; the unchecked forms keep the
        // bounds check, a safe superset), so WASM == VM stays exact while the two share one bytecode.
        let oracle = crate::optimize::oracle_analyze_with(stmts, interner);
        let program = crate::vm::Compiler::compile_with_oracle(stmts, interner, Some(types), Some(oracle))
            .map_err(custom)?;
        crate::vm::wasm::assemble_program(&program, &policies, interner).map_err(|e| custom(e.to_string()))
    })
}

/// Compile LOGOS source to a LINKED WebAssembly module that uses the real `logicaffeine_base::BigInt`
/// runtime for arbitrary-precision integer arithmetic: an overflowing integer expression
/// (`Show 99999999999 * 99999999999`, `Show 2 to the power of 200`) computes the EXACT big number —
/// matching the VM's promote-on-overflow — instead of trapping, and `Show` prints its decimal.
///
/// Unlike [`compile_to_wasm`] (fully self-contained, no toolchain), this is TOOLCHAIN-DEPENDENT: the
/// BigInt-aware emitter ([`crate::vm::wasm::assemble_program_linked`]) produces a RELOCATABLE object that
/// is linked against `logicaffeine_base` (compiled once to `wasm32-unknown-unknown`) with the Rust
/// toolchain's `rust-lld`. The runtime object is cached per process, so the amortized cost is one link.
/// Returns the bytes of a `.wasm` file, or a [`ParseError`] carrying the reason the backend or linker
/// declined (an unsupported program shape, or an unavailable toolchain / base wasm32 build).
#[cfg(all(feature = "wasm-jit", not(target_arch = "wasm32")))]
pub fn compile_to_wasm_linked(source: &str) -> Result<Vec<u8>, ParseError> {
    fn custom(msg: String) -> ParseError {
        ParseError { kind: crate::error::ParseErrorKind::Custom(msg), span: crate::token::Span::default() }
    }
    let relocatable = crate::ui_bridge::with_parsed_program(source, |parsed, interner| -> Result<Vec<u8>, ParseError> {
        let (stmts, types, policies) = parsed.map_err(custom)?;
        let oracle = crate::optimize::oracle_analyze_with(stmts, interner);
        let program = crate::vm::Compiler::compile_with_oracle(stmts, interner, Some(types), Some(oracle)).map_err(custom)?;
        let module = crate::vm::wasm::assemble_program_linked(&program, &policies, interner).map_err(|e| custom(e.to_string()))?;
        crate::vm::wasm::module_to_relocatable(&module).map_err(|e| custom(e.to_string()))
    })?;
    crate::vm::wasm::link_relocatable_bigint(&relocatable).map_err(|e| custom(e.to_string()))
}

/// Format an `f64` exactly as a `Show` of a `Float` would — i.e. byte-identical to the
/// tree-walker / VM (`RuntimeValue::to_display_string`). The direct-WASM host's `print_f64`
/// sink uses this so a `Show` of a float matches every other engine. Delegating to the real
/// formatter (rather than re-deriving it) makes drift impossible.
pub fn display_float_like_logos(f: f64) -> String {
    crate::interpreter::RuntimeValue::Float(f).to_display_string()
}

/// Phase 0 (work/FINISH_INTERPRETER.md): classify the determinacy of a LOGOS program.
///
/// Parses `source` and runs the determinacy classifier over the parsed program.
/// Pure analysis — no optimization, no codegen. Returns whether the program is
/// in the determinate (Kahn-deterministic) or nondeterminate fragment, with the
/// nondeterminism witnesses.
pub fn classify_source(source: &str) -> Result<crate::concurrency::Determinacy, ParseError> {
    let mut interner = Interner::new();
    let mut lexer = Lexer::new(source, &mut interner);
    let tokens = lexer.tokenize();

    let (type_registry, _policy_registry) = {
        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
        let result = discovery.run_full();
        (result.types, result.policies)
    };

    let mut world_state = WorldState::new();
    let expr_arena = Arena::new();
    let term_arena = Arena::new();
    let np_arena = Arena::new();
    let sym_arena = Arena::new();
    let role_arena = Arena::new();
    let pp_arena = Arena::new();
    let stmt_arena: Arena<Stmt> = Arena::new();
    let imperative_expr_arena: Arena<Expr> = Arena::new();
    let type_expr_arena: Arena<TypeExpr> = Arena::new();

    let ast_ctx = AstContext::with_types(
        &expr_arena, &term_arena, &np_arena, &sym_arena,
        &role_arena, &pp_arena, &stmt_arena, &imperative_expr_arena,
        &type_expr_arena,
    );

    let mut parser = Parser::new(tokens, &mut world_state, &mut interner, ast_ctx, type_registry);
    let stmts = parser.parse_program()?;
    Ok(crate::concurrency::classify_program(&stmts))
}

/// Phase 0 test seam: is the first `Simultaneously:` / `Attempt all of the
/// following:` block in `source` made of data-independent branches?
/// `None` if the program contains no such block.
pub fn first_parallel_block_independent(source: &str) -> Result<Option<bool>, ParseError> {
    let mut interner = Interner::new();
    let mut lexer = Lexer::new(source, &mut interner);
    let tokens = lexer.tokenize();

    let (type_registry, _policy_registry) = {
        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
        let result = discovery.run_full();
        (result.types, result.policies)
    };

    let mut world_state = WorldState::new();
    let expr_arena = Arena::new();
    let term_arena = Arena::new();
    let np_arena = Arena::new();
    let sym_arena = Arena::new();
    let role_arena = Arena::new();
    let pp_arena = Arena::new();
    let stmt_arena: Arena<Stmt> = Arena::new();
    let imperative_expr_arena: Arena<Expr> = Arena::new();
    let type_expr_arena: Arena<TypeExpr> = Arena::new();

    let ast_ctx = AstContext::with_types(
        &expr_arena, &term_arena, &np_arena, &sym_arena,
        &role_arena, &pp_arena, &stmt_arena, &imperative_expr_arena,
        &type_expr_arena,
    );

    let mut parser = Parser::new(tokens, &mut world_state, &mut interner, ast_ctx, type_registry);
    let stmts = parser.parse_program()?;
    Ok(find_first_parallel_independence(&stmts))
}

fn find_first_parallel_independence(stmts: &[Stmt]) -> Option<bool> {
    for s in stmts {
        match s {
            Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => {
                return Some(crate::concurrency::branches_independent(tasks));
            }
            Stmt::FunctionDef { body, .. }
            | Stmt::While { body, .. }
            | Stmt::Repeat { body, .. }
            | Stmt::Zone { body, .. } => {
                if let Some(r) = find_first_parallel_independence(body) {
                    return Some(r);
                }
            }
            Stmt::If { then_block, else_block, .. } => {
                if let Some(r) = find_first_parallel_independence(then_block) {
                    return Some(r);
                }
                if let Some(eb) = else_block {
                    if let Some(r) = find_first_parallel_independence(eb) {
                        return Some(r);
                    }
                }
            }
            _ => {}
        }
    }
    None
}

/// Phase 4 (work/FINISH_INTERPRETER.md): run the Send/escape analysis over a program.
///
/// Parses `source` and returns the Send/escape diagnostics (empty = the program
/// respects the message-passing + CRDT discipline). Pure analysis — no codegen.
pub fn send_check_source(source: &str) -> Result<Vec<crate::concurrency::SendDiagnostic>, ParseError> {
    let mut interner = Interner::new();
    let mut lexer = Lexer::new(source, &mut interner);
    let tokens = lexer.tokenize();

    let (type_registry, _policy_registry) = {
        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
        let result = discovery.run_full();
        (result.types, result.policies)
    };

    let mut world_state = WorldState::new();
    let expr_arena = Arena::new();
    let term_arena = Arena::new();
    let np_arena = Arena::new();
    let sym_arena = Arena::new();
    let role_arena = Arena::new();
    let pp_arena = Arena::new();
    let stmt_arena: Arena<Stmt> = Arena::new();
    let imperative_expr_arena: Arena<Expr> = Arena::new();
    let type_expr_arena: Arena<TypeExpr> = Arena::new();

    let ast_ctx = AstContext::with_types(
        &expr_arena, &term_arena, &np_arena, &sym_arena,
        &role_arena, &pp_arena, &stmt_arena, &imperative_expr_arena,
        &type_expr_arena,
    );

    let mut parser = Parser::new(tokens, &mut world_state, &mut interner, ast_ctx, type_registry);
    let stmts = parser.parse_program()?;
    Ok(crate::concurrency::check_send_escape(&stmts))
}

/// Compile LOGOS source and return full output including dependency metadata.
///
/// This is the primary compilation entry point that returns both the generated
/// Rust code and any crate dependencies declared in `## Requires` blocks.
/// [`compile_program_full`] in **Mode B (deterministic replay)** — the full
/// output (rust + dependencies) with the seeded `Select` lowering. The seeded
/// differential harness uses this so it gets the same dependency set as Mode A.
pub fn compile_program_full_deterministic(source: &str) -> Result<CompileOutput, ParseError> {
    crate::codegen::with_seeded_select(|| compile_program_full(source))
}

pub fn compile_program_full(source: &str) -> Result<CompileOutput, ParseError> {
    // Mixed-document aware: a source interleaving imperative code with Coq-style math
    // (`Definition`/`## Theorem:`/…) routes the math to the Forge and bundles it as
    // `mod proven`. Pure imperative programs partition to `(source, None)` — a no-op.
    let (imperative_src, math_src) = crate::ui_bridge::partition_mixed(source);
    let proven = math_src.as_deref().and_then(crate::ui_bridge::mixed_proven_module);
    compile_program_full_with_proven(&imperative_src, proven.as_deref())
}

/// Like [`compile_program_full`], but every emitted (non-generic) `enum` also gets
/// `WireEncode`/`WireDecode` impls over the shared `logicaffeine_data::wire` codec — byte-identical
/// to the peer codec's `encode_value_raw`. This lets a compile-once native partial evaluator
/// receive a program AST as data over the same fast codec the interpreter uses. Ordinary compiles
/// (the default) are byte-unchanged.
pub fn compile_program_full_with_wire(source: &str) -> Result<CompileOutput, ParseError> {
    crate::codegen::types::with_wire_impls(true, || compile_program_full(source))
}

/// Like [`compile_program_full`], but bundles an extracted math/logic module
/// (`proven`) into the generated Rust — the imperative half of a mixed document.
/// The module is emitted as `pub mod proven { … } use proven::*;` so the imperative
/// program can call its functions / `check_*` predicates by name. `None` (or a
/// blank module) yields output byte-identical to [`compile_program_full`].
pub fn compile_program_full_with_proven(source: &str, proven: Option<&str>) -> Result<CompileOutput, ParseError> {
    // Phase 10: auto-prepend the stdlib modules the program references (no-op when
    // it uses no stdlib vocabulary, so the benchmark corpus stays byte-identical).
    let prelude_src = crate::loader::apply_prelude(source);
    let source = prelude_src.as_ref();

    let mut interner = Interner::new();
    let mut lexer = Lexer::new(source, &mut interner);
    let tokens = lexer.tokenize();

    // Pass 1: Discovery - scan for type definitions and policies
    let (type_registry, policy_registry) = {
        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
        let result = discovery.run_full();
        (result.types, result.policies)
    };
    // Clone for codegen (parser takes ownership)
    let codegen_registry = type_registry.clone();
    let codegen_policies = policy_registry.clone();

    let mut world_state = WorldState::new();
    let expr_arena = Arena::new();
    let term_arena = Arena::new();
    let np_arena = Arena::new();
    let sym_arena = Arena::new();
    let role_arena = Arena::new();
    let pp_arena = Arena::new();
    let stmt_arena: Arena<Stmt> = Arena::new();
    let imperative_expr_arena: Arena<Expr> = Arena::new();
    let type_expr_arena: Arena<TypeExpr> = Arena::new();

    let ast_ctx = AstContext::with_types(
        &expr_arena,
        &term_arena,
        &np_arena,
        &sym_arena,
        &role_arena,
        &pp_arena,
        &stmt_arena,
        &imperative_expr_arena,
        &type_expr_arena,
    );

    // Pass 2: Parse with type context
    let mut parser = Parser::new(tokens, &mut world_state, &mut interner, ast_ctx, type_registry);
    // Note: Don't call process_block_headers() - parse_program handles blocks itself

    let stmts = parser.parse_program()?;
    // The ONE optimization config for this compile: env baseline merged with the
    // file-level `## No <X>` decorators (program-wide), normalized. Threaded to
    // BOTH the optimizer and codegen so they never disagree. Captured here (the
    // last use of `parser`) so its `&mut interner` borrow ends before reuse.
    let opt_config = {
        let mut c = crate::optimization::OptimizationConfig::from_env()
            .merged(&parser.program_opt_flags());
        c.normalize();
        c
    };

    // Type-directed division: rewrite `Divide → ExactDivide` in every Rational context
    // (the integer default stays floor), so a `Let x: Rational be 7 / 2` compiles exact
    // (`7/2`) instead of flooring to `3` — matching the tree-walker and VM. The optimizer
    // treats `ExactDivide` as opaque (never floor-folds it), so this is purely additive.
    let resolved = crate::resolve_division::resolve_divisions(
        &stmts,
        &stmt_arena,
        &imperative_expr_arena,
        &interner,
        opt_config.is_on(crate::optimization::Opt::Comptime),
    );
    let stmts: Vec<Stmt> = match resolved {
        Some(rw) => rw.to_vec(),
        None => stmts,
    };

    // Pass 2.5: Optimization - constant folding and dead code elimination
    let stmts = crate::optimize::optimize_program(stmts, &imperative_expr_arena, &stmt_arena, &mut interner, &opt_config);

    // Extract dependencies before escape analysis
    let mut dependencies = extract_dependencies(&stmts, &interner)?;

    // FFI: Auto-inject wasm-bindgen dependency if any function is exported for WASM
    let needs_wasm_bindgen = stmts.iter().any(|stmt| {
        if let Stmt::FunctionDef { is_exported: true, export_target: Some(target), .. } = stmt {
            interner.resolve(*target).eq_ignore_ascii_case("wasm")
        } else {
            false
        }
    });
    if needs_wasm_bindgen && !dependencies.iter().any(|d| d.name == "wasm-bindgen") {
        dependencies.push(CrateDependency {
            name: "wasm-bindgen".to_string(),
            version: "0.2".to_string(),
            features: vec![],
        });
    }

    // Pass 3: Escape analysis - check for zone escape violations
    // This catches obvious cases like returning zone-local variables
    let mut escape_checker = EscapeChecker::new(&interner);
    escape_checker.check_program(&stmts).map_err(|e| {
        // Convert EscapeError to ParseError for now
        // The error message is already Socratic from EscapeChecker
        ParseError {
            kind: crate::error::ParseErrorKind::Custom(e.to_string()),
            span: e.span,
        }
    })?;

    // Note: Static verification is available when the `verification` feature is enabled,
    // but must be explicitly invoked via compile_to_rust_verified().

    let type_env = crate::analysis::check_program(&stmts, &interner, &codegen_registry)
        .map_err(|e| ParseError {
            kind: e.to_parse_error_kind(&interner),
            span: crate::token::Span::default(),
        })?;
    let rust_code = crate::codegen::codegen_program_with_proven(&stmts, &codegen_registry, &codegen_policies, &interner, &type_env, &opt_config, "proven", proven);

    // Universal ABI: Generate C header + bindings if any C exports exist
    let has_c = stmts.iter().any(|stmt| {
        if let Stmt::FunctionDef { is_exported: true, export_target, .. } = stmt {
            match export_target {
                None => true,
                Some(t) => interner.resolve(*t).eq_ignore_ascii_case("c"),
            }
        } else {
            false
        }
    });

    let c_header = if has_c {
        Some(generate_c_header(&stmts, "module", &interner, &codegen_registry))
    } else {
        None
    };

    // Auto-inject serde_json dependency when C exports exist (needed for collection to_json and portable struct JSON accessors)
    if has_c && !dependencies.iter().any(|d| d.name == "serde_json") {
        dependencies.push(CrateDependency {
            name: "serde_json".to_string(),
            version: "1".to_string(),
            features: vec![],
        });
    }

    let python_bindings = if has_c {
        Some(generate_python_bindings(&stmts, "module", &interner, &codegen_registry))
    } else {
        None
    };

    let (typescript_bindings, typescript_types) = if has_c {
        let (js, dts) = generate_typescript_bindings(&stmts, "module", &interner, &codegen_registry);
        (Some(js), Some(dts))
    } else {
        (None, None)
    };

    Ok(CompileOutput { rust_code, dependencies, c_header, python_bindings, typescript_types, typescript_bindings })
}

/// Generate the Rust SOURCE for an AOT-native cdylib of ONE function (HOTSWAP §Axis-3
/// / P14b): the `target` function plus its transitive callees ([`crate::codegen::function_slice`]),
/// emitted through the normal ARCHITECT codegen, with the
/// [`crate::codegen::codegen_native_tier_export`] shim appended so the loader can
/// resolve the `logos_native_<target>` symbol. Mirrors [`compile_program_full`]'s
/// front-end, then slices before codegen.
///
/// Returns `Ok(None)` when `target` is absent or outside the sound scalar ABI subset —
/// the caller then keeps that function on VM+JIT (no AOT-native, no gap at the seam).
/// `Err` only on a genuine parse/type error in the source.
pub fn compile_function_to_native_rust(
    source: &str,
    target: &str,
) -> Result<Option<AotModule>, ParseError> {
    let mut interner = Interner::new();
    let mut lexer = Lexer::new(source, &mut interner);
    let tokens = lexer.tokenize();

    let (type_registry, policy_registry) = {
        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
        let result = discovery.run_full();
        (result.types, result.policies)
    };
    let codegen_registry = type_registry.clone();
    let codegen_policies = policy_registry.clone();

    let mut world_state = WorldState::new();
    let expr_arena = Arena::new();
    let term_arena = Arena::new();
    let np_arena = Arena::new();
    let sym_arena = Arena::new();
    let role_arena = Arena::new();
    let pp_arena = Arena::new();
    let stmt_arena: Arena<Stmt> = Arena::new();
    let imperative_expr_arena: Arena<Expr> = Arena::new();
    let type_expr_arena: Arena<TypeExpr> = Arena::new();
    let ast_ctx = AstContext::with_types(
        &expr_arena,
        &term_arena,
        &np_arena,
        &sym_arena,
        &role_arena,
        &pp_arena,
        &stmt_arena,
        &imperative_expr_arena,
        &type_expr_arena,
    );

    let mut parser = Parser::new(tokens, &mut world_state, &mut interner, ast_ctx, type_registry);
    let stmts = parser.parse_program()?;
    let opt_config = {
        let mut c = crate::optimization::OptimizationConfig::from_env()
            .merged(&parser.program_opt_flags());
        c.normalize();
        c
    };
    // Optimize the whole program (ARCHITECT), THEN slice: the slice picks the optimized
    // target + its (optimized) transitive callees.
    let stmts = crate::optimize::optimize_program(
        stmts,
        &imperative_expr_arena,
        &stmt_arena,
        &mut interner,
        &opt_config,
    );

    // Resolve the target's symbol + signature for the shim; absent ⇒ no AOT-native fn.
    let target_sig = stmts.iter().find_map(|s| match s {
        Stmt::FunctionDef { name, params, return_type, .. }
            if interner.resolve(*name) == target =>
        {
            let ps: Vec<(crate::intern::Symbol, &TypeExpr)> =
                params.iter().map(|(s, t)| (*s, *t)).collect();
            Some((*name, ps, *return_type))
        }
        _ => None,
    });
    let Some((target_sym, params, return_type)) = target_sig else {
        return Ok(None);
    };
    // The shim only exists for the sound scalar subset; otherwise no AOT-native fn.
    let Some(shim) =
        crate::codegen::codegen_native_tier_export(target_sym, &params, return_type, &interner)
    else {
        return Ok(None);
    };

    let slice = crate::codegen::function_slice(&stmts, target_sym, &interner);
    let type_env = crate::analysis::check_program(&slice, &interner, &codegen_registry).map_err(|e| {
        ParseError {
            kind: e.to_parse_error_kind(&interner),
            span: crate::token::Span::default(),
        }
    })?;
    let module = crate::codegen::codegen_program(
        &slice,
        &codegen_registry,
        &codegen_policies,
        &interner,
        &type_env,
        &opt_config,
    );
    let symbol = format!(
        "logos_native_{}",
        crate::analysis::types::RustNames::new(&interner).raw(target_sym)
    );
    Ok(Some(AotModule {
        rust: format!("{module}\n{shim}"),
        symbol,
        arity: params.len(),
    }))
}

/// A compiled AOT-native module (HOTSWAP §Axis-3): the cdylib Rust SOURCE plus the
/// exact exported `symbol` to resolve and its `arity` — everything the loader needs.
#[derive(Debug, Clone)]
pub struct AotModule {
    pub rust: String,
    pub symbol: String,
    pub arity: usize,
}

/// Build a function's AOT module to a browser-loadable `wasm32-unknown-unknown` cdylib
/// (HOTSWAP §Axis-3 / P17 — the browser analog of [`build_native_cdylib`]). The module
/// is the same scalar-ABI shim; the wasm crate keeps `logicaffeine-data` +
/// `logicaffeine-system` (both wasm-ready) but drops the desktop-only `tokio`, the
/// `logicaffeine-system` `full` feature, and `target-cpu=native`. Returns the `.wasm` path;
/// the browser then `WebAssembly.instantiate`s it and the entry calls into it through
/// the warm-bytecode indirection. Requires the `wasm32-unknown-unknown` target.
#[cfg(not(target_arch = "wasm32"))]
pub fn build_native_wasm(
    rust_source: &str,
    crate_name: &str,
    work_dir: &std::path::Path,
) -> Result<std::path::PathBuf, String> {
    use std::process::Command;
    let proj = work_dir.join(crate_name);
    let _ = fs::remove_dir_all(&proj);
    fs::create_dir_all(proj.join("src")).map_err(|e| e.to_string())?;
    fs::write(proj.join("src").join("lib.rs"), rust_source).map_err(|e| e.to_string())?;

    let cargo_toml = format!(
        "[package]\nname = \"{crate_name}\"\nversion = \"0.0.0\"\nedition = \"2021\"\n\n\
         [lib]\ncrate-type = [\"cdylib\"]\n\n\
         [dependencies]\n\
         logicaffeine-data = {{ path = \"./crates/logicaffeine_data\" }}\n\
         logicaffeine-system = {{ path = \"./crates/logicaffeine_system\" }}\n\n\
         [profile.release]\nlto = true\nopt-level = 3\ncodegen-units = 1\nstrip = true\n"
    );
    fs::write(proj.join("Cargo.toml"), &cargo_toml).map_err(|e| e.to_string())?;

    copy_runtime_crates(&proj).map_err(|e| e.to_string())?;

    let out = Command::new("cargo")
        .args(["build", "--release", "--lib", "--target", "wasm32-unknown-unknown"])
        .current_dir(&proj)
        .output()
        .map_err(|e| format!("failed to run cargo: {e}"))?;
    if !out.status.success() {
        return Err(format!(
            "wasm bundle build failed:\n{}",
            String::from_utf8_lossy(&out.stderr)
        ));
    }

    let wasm = proj
        .join("target")
        .join("wasm32-unknown-unknown")
        .join("release")
        .join(format!("{crate_name}.wasm"));
    if !wasm.exists() {
        return Err(format!("wasm module not found at {}", wasm.display()));
    }
    Ok(wasm)
}

/// Build AOT-native cdylib Rust source (from [`compile_function_to_native_rust`]) into
/// a loadable `cdylib` (HOTSWAP §Axis-3 / P16). Generates a minimal crate under
/// `work_dir/<crate_name>`, copies the shared runtime crates (so the `.so` and the
/// interpreter share the SAME `logicaffeine_data` ABI), and runs `cargo build
/// --release`. Returns the path to the produced dynamic library. `panic = "unwind"`
/// (the default) — NOT `abort` — so a panic in a loaded function can be contained
/// rather than killing the host process.
#[cfg(not(target_arch = "wasm32"))]
pub fn build_native_cdylib(
    rust_source: &str,
    crate_name: &str,
    work_dir: &std::path::Path,
) -> Result<std::path::PathBuf, String> {
    use std::process::Command;
    let proj = work_dir.join(crate_name);
    let _ = fs::remove_dir_all(&proj);
    fs::create_dir_all(proj.join("src")).map_err(|e| e.to_string())?;
    fs::write(proj.join("src").join("lib.rs"), rust_source).map_err(|e| e.to_string())?;

    let cargo_toml = format!(
        "[package]\nname = \"{crate_name}\"\nversion = \"0.0.0\"\nedition = \"2021\"\n\n\
         [lib]\ncrate-type = [\"cdylib\"]\n\n\
         [dependencies]\n\
         logicaffeine-data = {{ path = \"./crates/logicaffeine_data\" }}\n\
         logicaffeine-system = {{ path = \"./crates/logicaffeine_system\", features = [\"full\"] }}\n\
         tokio = {{ version = \"1\", features = [\"rt-multi-thread\", \"macros\"] }}\n\n\
         [profile.release]\nlto = true\nopt-level = 3\ncodegen-units = 1\nstrip = true\n"
    );
    fs::write(proj.join("Cargo.toml"), &cargo_toml).map_err(|e| e.to_string())?;

    let cargo_cfg = proj.join(".cargo");
    fs::create_dir_all(&cargo_cfg).map_err(|e| e.to_string())?;
    fs::write(
        cargo_cfg.join("config.toml"),
        "[build]\nrustflags = [\"-C\", \"target-cpu=native\"]\n",
    )
    .map_err(|e| e.to_string())?;

    copy_runtime_crates(&proj).map_err(|e| e.to_string())?;

    let out = Command::new("cargo")
        .args(["build", "--release", "--lib"])
        .current_dir(&proj)
        .output()
        .map_err(|e| format!("failed to run cargo: {e}"))?;
    if !out.status.success() {
        return Err(format!(
            "AOT cdylib build failed:\n{}",
            String::from_utf8_lossy(&out.stderr)
        ));
    }

    let so = proj.join("target").join("release").join(format!(
        "{}{}{}",
        std::env::consts::DLL_PREFIX,
        crate_name,
        std::env::consts::DLL_SUFFIX
    ));
    if !so.exists() {
        return Err(format!("AOT cdylib not found at {}", so.display()));
    }
    Ok(so)
}

/// The cache key for an AOT-native artifact (HOTSWAP §Axis-3 / P16): a deterministic
/// FNV-1a hash of the rustc toolchain version AND the optimized Rust source. The
/// toolchain is in the key because Rust has no stable cross-version ABI — a different
/// `rustc`/runtime yields a different key, so a stale, ABI-mismatched `.so` is NEVER
/// reused (soundness over convenience). The source captures the function, its callees,
/// and the optimization config (it IS the codegen output).
#[cfg(not(target_arch = "wasm32"))]
pub fn aot_cache_key(rust_source: &str) -> String {
    let toolchain = std::process::Command::new("rustc")
        .arg("--version")
        .output()
        .ok()
        .map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
        .unwrap_or_default();
    let mut h: u64 = 0xcbf29ce4_84222325;
    for b in toolchain.bytes().chain(rust_source.bytes()) {
        h ^= b as u64;
        h = h.wrapping_mul(0x0000_0100_0000_01b3);
    }
    format!("{h:016x}")
}

/// [`build_native_cdylib`] with a persistent cache (HOTSWAP §Axis-3 / P16). The artifact
/// lives at `cache_dir/aot_<fn>_<key>/…` keyed by [`aot_cache_key`]; an identical
/// function reuses its `.so` across runs (no rebuild), and a toolchain change yields a
/// new key so the stale library is never loaded.
#[cfg(not(target_arch = "wasm32"))]
pub fn build_native_cdylib_cached(
    rust_source: &str,
    fn_name: &str,
    cache_dir: &std::path::Path,
) -> Result<std::path::PathBuf, String> {
    let key = aot_cache_key(rust_source);
    let crate_name = format!("aot_{fn_name}_{key}");
    let so = cache_dir.join(&crate_name).join("target").join("release").join(format!(
        "{}{}{}",
        std::env::consts::DLL_PREFIX,
        crate_name,
        std::env::consts::DLL_SUFFIX
    ));
    if so.exists() {
        return Ok(so); // cache hit — reuse, skip the rustc build
    }
    fs::create_dir_all(cache_dir).map_err(|e| e.to_string())?;
    build_native_cdylib(rust_source, &crate_name, cache_dir)
}

/// On-demand AOT-native build + load (HOTSWAP §Axis-3): compile `fn_name` (and its
/// callees) to an optimized cdylib (cached), `dlopen` it, and return the loaded
/// [`crate::vm::NativeFn`] ready to install via `Vm::install_aot_native`. `None` if the
/// function is absent / outside the scalar subset / the build or load failed — the
/// caller keeps it on VM+JIT. Blocking (runs `rustc`); the background worker
/// (`BgAotCompiler`) calls this off the interpreter thread.
#[cfg(not(target_arch = "wasm32"))]
pub fn aot_build_function(
    source: &str,
    fn_name: &str,
    cache_dir: &std::path::Path,
) -> Option<Box<dyn crate::vm::NativeFn>> {
    let module = compile_function_to_native_rust(source, fn_name).ok().flatten()?;
    let so = build_native_cdylib_cached(&module.rust, fn_name, cache_dir).ok()?;
    let (nf, _calls) = crate::vm::aot_tier::load_aot_native(&so, &module.symbol, module.arity)?;
    Some(nf)
}

/// The names of functions annotated for the AOT-native tier — `## To <fn> … is
/// exported for native:` (HOTSWAP §Axis-3 selectivity). These are the functions
/// `largo build --native-functions` pre-bundles; everything else stays on VM+JIT.
pub fn native_export_function_names(source: &str) -> Vec<String> {
    crate::ui_bridge::with_parsed_program(source, |parsed, interner| match parsed {
        Ok((stmts, _types, _policies)) => stmts
            .iter()
            .filter_map(|s| match s {
                Stmt::FunctionDef { name, is_exported: true, export_target: Some(t), .. }
                    if interner.resolve(*t).eq_ignore_ascii_case("native") =>
                {
                    Some(interner.resolve(*name).to_string())
                }
                _ => None,
            })
            .collect(),
        Err(_) => Vec::new(),
    })
}

/// Load every `native`-annotated function in `source` as a compiled-native
/// [`crate::vm::NativeFn`] (HOTSWAP §Axis-3): the run path installs these via
/// `Vm::install_aot_native`, so an annotated function dispatches to `rustc -O3` machine
/// code from its first call. Uses the persistent cache, so a bundle pre-built by
/// `largo build --native-functions` is a cache hit — no `rustc` on the run path. A
/// function outside the scalar subset / failing to build is skipped (stays on VM+JIT).
#[cfg(not(target_arch = "wasm32"))]
pub fn aot_load_bundle(
    source: &str,
    cache_dir: &std::path::Path,
) -> Vec<(String, Box<dyn crate::vm::NativeFn>)> {
    native_export_function_names(source)
        .into_iter()
        .filter_map(|name| aot_build_function(source, &name, cache_dir).map(|nf| (name, nf)))
        .collect()
}

/// Pre-build every `native`-annotated function in `source` into the AOT bundle under
/// `bundle_dir` (HOTSWAP §Axis-3 / P16 — the "tools to bundle them"). Returns the
/// `(function_name, cdylib_path)` manifest. Functions outside the sound scalar subset
/// are silently skipped — they keep running on VM+JIT, no gap at the seam. `Err` only
/// on a genuine parse/type error.
#[cfg(not(target_arch = "wasm32"))]
pub fn build_native_bundle(
    source: &str,
    bundle_dir: &std::path::Path,
) -> Result<Vec<(String, std::path::PathBuf)>, ParseError> {
    let mut manifest = Vec::new();
    for name in native_export_function_names(source) {
        let Some(module) = compile_function_to_native_rust(source, &name)? else {
            continue; // not in the scalar subset — stays on VM+JIT
        };
        if let Ok(so) = build_native_cdylib_cached(&module.rust, &name, bundle_dir) {
            manifest.push((name, so));
        }
    }
    Ok(manifest)
}

/// Extract crate dependencies from `Stmt::Require` nodes.
///
/// Deduplicates by crate name: same name + same version keeps one copy.
/// Same name + different version returns a `ParseError`.
/// Preserves declaration order (first occurrence wins).
fn extract_dependencies(stmts: &[Stmt], interner: &Interner) -> Result<Vec<CrateDependency>, ParseError> {
    use std::collections::HashMap;

    let mut seen: HashMap<String, String> = HashMap::new(); // name → version
    let mut deps: Vec<CrateDependency> = Vec::new();

    for stmt in stmts {
        if let Stmt::Require { crate_name, version, features, span } = stmt {
            let name = interner.resolve(*crate_name).to_string();
            let ver = interner.resolve(*version).to_string();

            if let Some(existing_ver) = seen.get(&name) {
                if *existing_ver != ver {
                    return Err(ParseError {
                        kind: crate::error::ParseErrorKind::Custom(format!(
                            "Conflicting versions for crate \"{}\": \"{}\" and \"{}\".",
                            name, existing_ver, ver
                        )),
                        span: *span,
                    });
                }
                // Same name + same version: skip duplicate
            } else {
                seen.insert(name.clone(), ver.clone());
                deps.push(CrateDependency {
                    name,
                    version: ver,
                    features: features.iter().map(|f| interner.resolve(*f).to_string()).collect(),
                });
            }
        }
    }

    Ok(deps)
}

/// Compile LOGOS source to Rust with ownership checking enabled.
///
/// This runs the lightweight ownership analysis pass that catches use-after-move
/// errors with control flow awareness. The analysis is fast enough to run on
/// every keystroke in an IDE.
///
/// # Arguments
///
/// * `source` - LOGOS source code as a string
///
/// # Returns
///
/// Generated Rust source code on success.
///
/// # Errors
///
/// Returns [`ParseError`] if:
/// - Any error from [`compile_to_rust`] occurs
/// - Ownership analysis detects use-after-move
/// - Ownership analysis detects use-after-borrow violations
///
/// # Example
///
/// ```
/// # use logicaffeine_compile::compile::compile_to_rust_checked;
/// // This will fail ownership checking
/// let source = "## Main\nLet x be 5.\nGive x to y.\nShow x.";
/// let result = compile_to_rust_checked(source);
/// assert!(result.is_err()); // "x has already been given away"
/// ```
///
/// # Use Case
///
/// Use this function with the `--check` CLI flag for instant feedback on
/// ownership errors before running the full Rust compilation.
pub fn compile_to_rust_checked(source: &str) -> Result<String, ParseError> {
    // Mixed document: ownership-check only the imperative stream (math blocks are
    // blanked, preserving line numbers). The math half is checked by the kernel.
    let (imperative_src, _) = crate::ui_bridge::partition_mixed(source);
    let source = imperative_src.as_str();
    let mut interner = Interner::new();
    let mut lexer = Lexer::new(source, &mut interner);
    let tokens = lexer.tokenize();

    // Pass 1: Discovery - scan for type definitions and policies
    let (type_registry, policy_registry) = {
        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
        let result = discovery.run_full();
        (result.types, result.policies)
    };
    // Clone for codegen (parser takes ownership)
    let codegen_registry = type_registry.clone();
    let codegen_policies = policy_registry.clone();

    let mut world_state = WorldState::new();
    let expr_arena = Arena::new();
    let term_arena = Arena::new();
    let np_arena = Arena::new();
    let sym_arena = Arena::new();
    let role_arena = Arena::new();
    let pp_arena = Arena::new();
    let stmt_arena: Arena<Stmt> = Arena::new();
    let imperative_expr_arena: Arena<Expr> = Arena::new();
    let type_expr_arena: Arena<TypeExpr> = Arena::new();

    let ast_ctx = AstContext::with_types(
        &expr_arena,
        &term_arena,
        &np_arena,
        &sym_arena,
        &role_arena,
        &pp_arena,
        &stmt_arena,
        &imperative_expr_arena,
        &type_expr_arena,
    );

    // Pass 2: Parse with type context
    let mut parser = Parser::new(tokens, &mut world_state, &mut interner, ast_ctx, type_registry);
    let stmts = parser.parse_program()?;

    // Pass 2.5: Optimization - constant folding, propagation, and dead code elimination
    let stmts = crate::optimize::optimize_program(stmts, &imperative_expr_arena, &stmt_arena, &mut interner, &crate::optimization::OptimizationConfig::from_env());

    // Pass 3: Escape analysis
    let mut escape_checker = EscapeChecker::new(&interner);
    escape_checker.check_program(&stmts).map_err(|e| {
        ParseError {
            kind: crate::error::ParseErrorKind::Custom(e.to_string()),
            span: e.span,
        }
    })?;

    // Pass 4: Ownership analysis
    // Catches use-after-move errors with control flow awareness
    let mut ownership_checker = OwnershipChecker::new(&interner);
    ownership_checker.check_program(&stmts).map_err(|e| {
        ParseError {
            kind: crate::error::ParseErrorKind::Custom(e.to_string()),
            span: e.span,
        }
    })?;

    let type_env = crate::analysis::check_program(&stmts, &interner, &codegen_registry)
        .map_err(|e| ParseError {
            kind: e.to_parse_error_kind(&interner),
            span: crate::token::Span::default(),
        })?;
    let rust_code = codegen_program(&stmts, &codegen_registry, &codegen_policies, &interner, &type_env, &crate::optimization::OptimizationConfig::from_env());

    Ok(rust_code)
}

/// Compile LOGOS source to Rust with full Z3 static verification.
///
/// This runs the Z3-based verifier on Assert statements before code generation,
/// proving that assertions hold for all possible inputs. This is the most
/// thorough compilation mode, suitable for high-assurance code.
///
/// # Arguments
///
/// * `source` - LOGOS source code as a string
///
/// # Returns
///
/// Generated Rust source code on success.
///
/// # Errors
///
/// Returns [`ParseError`] if:
/// - Any error from [`compile_to_rust`] occurs
/// - Z3 cannot prove an Assert statement
/// - Refinement type constraints cannot be satisfied
/// - Termination cannot be proven for loops with `decreasing`
///
/// # Example
///
/// ```no_run
/// # use logicaffeine_compile::compile::compile_to_rust_verified;
/// # use logicaffeine_compile::ParseError;
/// # fn main() -> Result<(), ParseError> {
/// let source = r#"
/// ## Main
/// Let x: { it: Int | it > 0 } be 5.
/// Assert that x > 0.
/// "#;
/// let rust_code = compile_to_rust_verified(source)?;
/// # Ok(())
/// # }
/// ```
///
/// # Feature Flag
///
/// This function requires the `verification` feature to be enabled:
///
/// ```toml
/// [dependencies]
/// logicaffeine_compile = { version = "...", features = ["verification"] }
/// ```
#[cfg(feature = "verification")]
pub fn compile_to_rust_verified(source: &str) -> Result<String, ParseError> {
    use crate::verification::VerificationPass;

    let mut interner = Interner::new();
    let mut lexer = Lexer::new(source, &mut interner);
    let tokens = lexer.tokenize();

    // Pass 1: Discovery - scan for type definitions and policies
    let (type_registry, policy_registry) = {
        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
        let result = discovery.run_full();
        (result.types, result.policies)
    };
    // Clone for codegen (parser takes ownership)
    let codegen_registry = type_registry.clone();
    let codegen_policies = policy_registry.clone();

    let mut world_state = WorldState::new();
    let expr_arena = Arena::new();
    let term_arena = Arena::new();
    let np_arena = Arena::new();
    let sym_arena = Arena::new();
    let role_arena = Arena::new();
    let pp_arena = Arena::new();
    let stmt_arena: Arena<Stmt> = Arena::new();
    let imperative_expr_arena: Arena<Expr> = Arena::new();
    let type_expr_arena: Arena<TypeExpr> = Arena::new();

    let ast_ctx = AstContext::with_types(
        &expr_arena,
        &term_arena,
        &np_arena,
        &sym_arena,
        &role_arena,
        &pp_arena,
        &stmt_arena,
        &imperative_expr_arena,
        &type_expr_arena,
    );

    // Pass 2: Parse with type context
    let mut parser = Parser::new(tokens, &mut world_state, &mut interner, ast_ctx, type_registry);
    let stmts = parser.parse_program()?;

    // Pass 3: Escape analysis
    let mut escape_checker = EscapeChecker::new(&interner);
    escape_checker.check_program(&stmts).map_err(|e| {
        ParseError {
            kind: crate::error::ParseErrorKind::Custom(e.to_string()),
            span: e.span,
        }
    })?;

    // Pass 4: Static verification
    let mut verifier = VerificationPass::new(&interner);
    verifier.verify_program(&stmts).map_err(|e| {
        ParseError {
            kind: crate::error::ParseErrorKind::Custom(format!(
                "Verification Failed:\n\n{}",
                e
            )),
            span: crate::token::Span::default(),
        }
    })?;

    let type_env = crate::analysis::check_program(&stmts, &interner, &codegen_registry)
        .map_err(|e| ParseError {
            kind: e.to_parse_error_kind(&interner),
            span: crate::token::Span::default(),
        })?;
    let rust_code = codegen_program(&stmts, &codegen_registry, &codegen_policies, &interner, &type_env, &crate::optimization::OptimizationConfig::from_env());

    Ok(rust_code)
}

/// Compile LOGOS source and write output to a directory as a Cargo project.
///
/// Creates a complete Cargo project structure with:
/// - `src/main.rs` containing the generated Rust code
/// - `Cargo.toml` with runtime dependencies
/// - `crates/` directory with runtime crate copies
///
/// # Arguments
///
/// * `source` - LOGOS source code as a string
/// * `output_dir` - Directory to create the Cargo project in
///
/// # Errors
///
/// Returns [`CompileError`] if:
/// - Compilation fails (wrapped as `CompileError::Parse`)
/// - File system operations fail (wrapped as `CompileError::Io`)
///
/// # Example
///
/// ```no_run
/// # use logicaffeine_compile::compile::{compile_to_dir, CompileError};
/// # use std::path::Path;
/// # fn main() -> Result<(), CompileError> {
/// let source = "## Main\nShow \"Hello\".";
/// compile_to_dir(source, Path::new("/tmp/my_project"))?;
/// // Now /tmp/my_project is a buildable Cargo project
/// # Ok(())
/// # }
/// ```
/// Everything [`rustc_check`] needs short of running cargo: generated Rust,
/// dependencies, the POPULATED rustc→LOGOS source map, and the interner the
/// program was compiled with — the substrate the diagnostic bridge translates
/// through.
pub struct CheckArtifacts {
    pub rust_code: String,
    pub dependencies: Vec<CrateDependency>,
    pub source_map: crate::sourcemap::SourceMap,
    pub interner: Interner,
}

/// Compile for CHECKING: the same front as [`compile_program_full`] but with
/// the optimizer off and mapped codegen, so every generated line ties back to
/// its statement span and the map stays 1:1 (the optimizer may fuse or drop
/// statements; a check build has no use for its output anyway).
///
/// Deliberately does NOT bail on typecheck/escape/ownership findings — the
/// interactive pipeline already reports those; this path exists to surface
/// what only rustc can see, and a borrow error in the generated code comes
/// back TRANSLATED rather than pre-empted.
pub fn rustc_check_artifacts(source: &str) -> Result<CheckArtifacts, ParseError> {
    let user_source = source;

    // The stdlib prelude is PREPENDED when referenced; spans from the parse
    // are offsets into the expanded text and shift back by the prelude length.
    let prelude_src = crate::loader::apply_prelude(user_source);
    let expanded: &str = prelude_src.as_ref();
    debug_assert!(
        expanded.ends_with(user_source),
        "apply_prelude must PREPEND; span translation depends on it"
    );
    let prelude_offset = expanded.len() - user_source.len();

    let mut interner = Interner::new();
    let mut lexer = Lexer::new(expanded, &mut interner);
    let tokens = lexer.tokenize();

    let (type_registry, policy_registry) = {
        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
        let result = discovery.run_full();
        (result.types, result.policies)
    };
    let codegen_registry = type_registry.clone();
    let codegen_policies = policy_registry.clone();

    let mut world_state = WorldState::new();
    let expr_arena = Arena::new();
    let term_arena = Arena::new();
    let np_arena = Arena::new();
    let sym_arena = Arena::new();
    let role_arena = Arena::new();
    let pp_arena = Arena::new();
    let stmt_arena: Arena<Stmt> = Arena::new();
    let imperative_expr_arena: Arena<Expr> = Arena::new();
    let type_expr_arena: Arena<TypeExpr> = Arena::new();

    let ast_ctx = AstContext::with_types(
        &expr_arena,
        &term_arena,
        &np_arena,
        &sym_arena,
        &role_arena,
        &pp_arena,
        &stmt_arena,
        &imperative_expr_arena,
        &type_expr_arena,
    );

    let mut parser = Parser::new(tokens, &mut world_state, &mut interner, ast_ctx, type_registry);
    let stmts = parser.parse_program()?;

    // Translate spans back into the USER buffer; prelude statements become
    // zero-width sentinels that mapped codegen skips.
    let stmt_spans: Vec<crate::token::Span> = parser
        .stmt_spans()
        .iter()
        .map(|span| {
            if span.start >= prelude_offset {
                crate::token::Span::new(span.start - prelude_offset, span.end - prelude_offset)
            } else {
                crate::token::Span::default()
            }
        })
        .collect();

    // Exact division still resolves (type semantics, statement-count
    // preserving); the optimizer stays OFF so spans align 1:1.
    let resolved = crate::resolve_division::resolve_divisions(
        &stmts,
        &stmt_arena,
        &imperative_expr_arena,
        &interner,
        false,
    );
    let stmts: Vec<Stmt> = match resolved {
        Some(rw) => rw.to_vec(),
        None => stmts,
    };

    // Best-effort env: findings are the interactive pipeline's job here.
    let (type_env, _findings) =
        crate::analysis::check_program_collect(&stmts, &interner, &codegen_registry);

    let dependencies = extract_dependencies(&stmts, &interner)?;

    let (rust_code, source_map) = crate::codegen::codegen_program_mapped(
        &stmts,
        &codegen_registry,
        &codegen_policies,
        &interner,
        &type_env,
        &crate::optimization::OptimizationConfig::all_off(),
        &stmt_spans,
        user_source,
    );

    Ok(CheckArtifacts {
        rust_code,
        dependencies,
        source_map,
        interner,
    })
}

/// Run rustc's analysis over a LOGOS program and translate every finding
/// back to English with real user-source spans — the flycheck engine.
///
/// `cache_dir` is a persistent per-workspace directory: the first run stages
/// the runtime crates and compiles them; later runs are incremental. Uses
/// `cargo check` (no codegen, no linking).
///
/// Fail-loud contract: `Ok(vec![])` means cargo ran AND found nothing. A
/// cargo failure that translates to no LOGOS finding is a `Build` error, not
/// a silent all-clear.
pub fn rustc_check(source: &str, cache_dir: &Path) -> Result<Vec<LogosError>, CompileError> {
    let artifacts = rustc_check_artifacts(source).map_err(CompileError::Parse)?;
    write_cargo_project(&artifacts.rust_code, &artifacts.dependencies, cache_dir)?;

    let check_output = Command::new("cargo")
        .arg("check")
        .arg("--message-format=json")
        .current_dir(cache_dir)
        .output()
        .map_err(|e| CompileError::Io(e.to_string()))?;

    let stdout = String::from_utf8_lossy(&check_output.stdout);
    let diagnostics = parse_rustc_json(&stdout);
    let findings =
        crate::diagnostic::translate_diagnostics_all(&diagnostics, &artifacts.source_map, &artifacts.interner);

    if !check_output.status.success() && findings.is_empty() {
        let stderr = String::from_utf8_lossy(&check_output.stderr);
        return Err(CompileError::Build(stderr.to_string()));
    }

    Ok(findings)
}

pub fn compile_to_dir(source: &str, output_dir: &Path) -> Result<(), CompileError> {
    let output = compile_program_full(source).map_err(CompileError::Parse)?;
    write_cargo_project(&output.rust_code, &output.dependencies, output_dir)
}

/// Write a generated program as a runnable cargo project: `src/main.rs`,
/// `Cargo.toml` (runtime path-deps + user `## Requires`), `.cargo/config.toml`,
/// and the staged runtime crates. Shared by [`compile_to_dir`] and
/// [`rustc_check`].
pub fn write_cargo_project(
    rust_code: &str,
    dependencies: &[CrateDependency],
    output_dir: &Path,
) -> Result<(), CompileError> {
    // Create output directory structure
    let src_dir = output_dir.join("src");
    fs::create_dir_all(&src_dir).map_err(|e| CompileError::Io(e.to_string()))?;

    // Write main.rs (codegen already includes the use statements)
    let main_path = src_dir.join("main.rs");
    let mut file = fs::File::create(&main_path).map_err(|e| CompileError::Io(e.to_string()))?;
    file.write_all(rust_code.as_bytes()).map_err(|e| CompileError::Io(e.to_string()))?;

    // Write Cargo.toml with runtime crate dependencies
    let mut cargo_toml = String::from(r#"[package]
name = "logos_output"
version = "0.1.0"
edition = "2021"

[dependencies]
logicaffeine-data = { path = "./crates/logicaffeine_data" }
logicaffeine-system = { path = "./crates/logicaffeine_system", features = ["full"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }
"#);

    // Append user-declared dependencies from ## Requires blocks — inside
    // [dependencies], before any later section header (a dep written after
    // a [target.*] or [profile.*] header would silently change meaning).
    for dep in dependencies {
        if dep.features.is_empty() {
            let _ = writeln!(cargo_toml, "{} = \"{}\"", dep.name, dep.version);
        } else {
            let feats = dep.features.iter()
                .map(|f| format!("\"{}\"", f))
                .collect::<Vec<_>>()
                .join(", ");
            let _ = writeln!(
                cargo_toml,
                "{} = {{ version = \"{}\", features = [{}] }}",
                dep.name, dep.version, feats
            );
        }
    }

    cargo_toml.push_str(r#"
[target.'cfg(target_os = "linux")'.dependencies]
logicaffeine-system = { path = "./crates/logicaffeine_system", features = ["full", "io-uring"] }
"#);

    cargo_toml.push_str("\n[profile.release]\nlto = true\nopt-level = 3\ncodegen-units = 1\npanic = \"abort\"\nstrip = true\n");

    let cargo_path = output_dir.join("Cargo.toml");
    let mut file = fs::File::create(&cargo_path).map_err(|e| CompileError::Io(e.to_string()))?;
    file.write_all(cargo_toml.as_bytes()).map_err(|e| CompileError::Io(e.to_string()))?;

    // Write .cargo/config.toml with target-cpu=native for optimal codegen.
    // Enables SIMD auto-vectorization and CPU-specific instruction selection.
    let cargo_config_dir = output_dir.join(".cargo");
    fs::create_dir_all(&cargo_config_dir).map_err(|e| CompileError::Io(e.to_string()))?;
    let config_content = "[build]\nrustflags = [\"-C\", \"target-cpu=native\"]\n";
    let config_path = cargo_config_dir.join("config.toml");
    fs::write(&config_path, config_content).map_err(|e| CompileError::Io(e.to_string()))?;

    // Copy runtime crates to output directory
    copy_runtime_crates(output_dir)?;

    Ok(())
}

/// Copy the runtime crates to the output directory.
/// Copies logicaffeine_data and logicaffeine_system.
pub fn copy_runtime_crates(output_dir: &Path) -> Result<(), CompileError> {
    let crates_dir = output_dir.join("crates");
    fs::create_dir_all(&crates_dir).map_err(|e| CompileError::Io(e.to_string()))?;

    // Find workspace root
    let workspace_root = find_workspace_root()?;

    // Copy logicaffeine_data
    let data_src = workspace_root.join(CRATES_DATA_PATH);
    let data_dest = crates_dir.join("logicaffeine_data");
    copy_dir_recursive(&data_src, &data_dest)?;
    deworkspace_cargo_toml(&data_dest.join("Cargo.toml"))?;

    // Copy logicaffeine_system
    let system_src = workspace_root.join(CRATES_SYSTEM_PATH);
    let system_dest = crates_dir.join("logicaffeine_system");
    copy_dir_recursive(&system_src, &system_dest)?;
    deworkspace_cargo_toml(&system_dest.join("Cargo.toml"))?;

    // Also need to copy logicaffeine_base since both crates depend on it
    let base_src = workspace_root.join("crates/logicaffeine_base");
    let base_dest = crates_dir.join("logicaffeine_base");
    copy_dir_recursive(&base_src, &base_dest)?;
    deworkspace_cargo_toml(&base_dest.join("Cargo.toml"))?;

    Ok(())
}

/// Resolve workspace-inherited fields in a copied crate's Cargo.toml.
///
/// When runtime crates are copied to a standalone project, any fields using
/// `*.workspace = true` won't resolve because there's no parent workspace.
/// This rewrites them with concrete values (matching the workspace's settings).
fn deworkspace_cargo_toml(cargo_toml_path: &Path) -> Result<(), CompileError> {
    let content = fs::read_to_string(cargo_toml_path)
        .map_err(|e| CompileError::Io(e.to_string()))?;

    let mut result = String::with_capacity(content.len());
    for line in content.lines() {
        let trimmed = line.trim();
        if trimmed == "edition.workspace = true" {
            result.push_str("edition = \"2021\"");
        } else if trimmed == "rust-version.workspace = true" {
            result.push_str("rust-version = \"1.75\"");
        } else if trimmed == "authors.workspace = true"
            || trimmed == "repository.workspace = true"
            || trimmed == "homepage.workspace = true"
            || trimmed == "documentation.workspace = true"
            || trimmed == "keywords.workspace = true"
            || trimmed == "categories.workspace = true"
            || trimmed == "license.workspace = true"
        {
            // Drop these lines — they're metadata not needed for compilation
            continue;
        } else if trimmed.contains(".workspace = true") {
            // Catch-all: drop any other workspace-inherited fields
            continue;
        } else if let Some(rewritten) = deworkspace_dep_line(trimmed)? {
            // A dependency-TABLE inheritance (`name = { workspace = true, … }`):
            // internal crates are staged side-by-side under `crates/`, so the
            // inherited entry rewrites to a sibling path (extra keys kept).
            result.push_str(&rewritten);
        } else {
            result.push_str(line);
        }
        result.push('\n');
    }

    fs::write(cargo_toml_path, result)
        .map_err(|e| CompileError::Io(e.to_string()))?;

    Ok(())
}

/// Rewrite a `name = { workspace = true, … }` DEPENDENCY line for a staged
/// crate. Internal `logicaffeine-*` deps become sibling-path deps (the staged
/// layout puts every runtime crate under one `crates/` directory); any other
/// key on the line (`features`, `optional`, …) is preserved. A THIRD-PARTY
/// workspace-inherited dep fails LOUDLY here — at staging time, with the dep
/// named — instead of as an opaque cargo resolution error deep in a build log.
/// Returns `Ok(None)` for lines that are not workspace-dep tables.
fn deworkspace_dep_line(trimmed: &str) -> Result<Option<String>, CompileError> {
    let Some((name_part, rest)) = trimmed.split_once('=') else {
        return Ok(None);
    };
    let rest = rest.trim();
    if !rest.starts_with('{') || !rest.ends_with('}') || !rest.contains("workspace = true") {
        return Ok(None);
    }
    let name = name_part.trim();
    if !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
        return Ok(None);
    }
    let extra_keys: Vec<&str> = rest[1..rest.len() - 1]
        .split(',')
        .map(str::trim)
        .filter(|k| !k.is_empty() && *k != "workspace = true")
        .collect();
    if !name.starts_with("logicaffeine-") {
        return Err(CompileError::Io(format!(
            "staged crate inherits third-party dependency `{}` from the workspace — \
             declare a concrete version in the crate's Cargo.toml (the staged copy \
             has no workspace root to inherit from)",
            name
        )));
    }
    let dir = name.replace('-', "_");
    let mut entry = format!("{} = {{ path = \"../{}\"", name, dir);
    for key in extra_keys {
        entry.push_str(", ");
        entry.push_str(key);
    }
    entry.push_str(" }");
    Ok(Some(entry))
}

/// Find the workspace root directory.
fn find_workspace_root() -> Result<std::path::PathBuf, CompileError> {
    // 1. Explicit override via LOGOS_WORKSPACE env var
    if let Ok(workspace) = std::env::var("LOGOS_WORKSPACE") {
        let path = Path::new(&workspace);
        if path.join("Cargo.toml").exists() && path.join("crates").exists() {
            return Ok(path.to_path_buf());
        }
    }

    // 2. Try CARGO_MANIFEST_DIR (works during cargo build of largo itself)
    if let Ok(manifest_dir) = std::env::var("CARGO_MANIFEST_DIR") {
        let path = Path::new(&manifest_dir);
        if let Some(parent) = path.parent().and_then(|p| p.parent()) {
            if parent.join("Cargo.toml").exists() {
                return Ok(parent.to_path_buf());
            }
        }
    }

    // 3. Infer from the largo binary's own location
    //    e.g. /workspace/target/release/largo → /workspace
    if let Ok(exe) = std::env::current_exe() {
        if let Some(dir) = exe.parent() {
            // Walk up from the binary's directory
            let mut candidate = dir.to_path_buf();
            for _ in 0..5 {
                if candidate.join("Cargo.toml").exists() && candidate.join("crates").exists() {
                    return Ok(candidate);
                }
                if !candidate.pop() {
                    break;
                }
            }
        }
    }

    // 4. Fallback to current directory traversal
    let mut current = std::env::current_dir()
        .map_err(|e| CompileError::Io(e.to_string()))?;

    loop {
        if current.join("Cargo.toml").exists() && current.join("crates").exists() {
            return Ok(current);
        }
        if !current.pop() {
            return Err(CompileError::Io(
                "Could not find workspace root. Set LOGOS_WORKSPACE env var or run from within the workspace.".to_string()
            ));
        }
    }
}

/// Recursively copy a directory.
/// Skips files that disappear during copy (race condition with parallel builds).
fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<(), CompileError> {
    fs::create_dir_all(dst).map_err(|e| CompileError::Io(e.to_string()))?;

    for entry in fs::read_dir(src).map_err(|e| CompileError::Io(e.to_string()))? {
        let entry = entry.map_err(|e| CompileError::Io(e.to_string()))?;
        let src_path = entry.path();
        let file_name = entry.file_name();
        let dst_path = dst.join(&file_name);

        // Skip target directory, build artifacts, and lock files
        if file_name == "target"
            || file_name == ".git"
            || file_name == "Cargo.lock"
            || file_name == ".DS_Store"
        {
            continue;
        }

        // Skip files that start with a dot (hidden files)
        if file_name.to_string_lossy().starts_with('.') {
            continue;
        }

        // Check if path still exists (race condition protection)
        if !src_path.exists() {
            continue;
        }

        if src_path.is_dir() {
            copy_dir_recursive(&src_path, &dst_path)?;
        } else if file_name == "Cargo.toml" {
            // Special handling for Cargo.toml: remove [workspace] line
            // which can interfere with nested crate dependencies
            match fs::read_to_string(&src_path) {
                Ok(content) => {
                    let filtered: String = content
                        .lines()
                        .filter(|line| !line.trim().starts_with("[workspace]"))
                        .collect::<Vec<_>>()
                        .join("\n");
                    fs::write(&dst_path, filtered)
                        .map_err(|e| CompileError::Io(e.to_string()))?;
                }
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
                Err(e) => return Err(CompileError::Io(e.to_string())),
            }
        } else {
            match fs::copy(&src_path, &dst_path) {
                Ok(_) => {}
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
                Err(e) => return Err(CompileError::Io(e.to_string())),
            }
        }
    }

    Ok(())
}

/// Compile and run a LOGOS program end-to-end.
///
/// This function performs the full compilation workflow:
/// 1. Compile LOGOS to Rust via [`compile_to_dir`]
/// 2. Run `cargo build` with JSON diagnostics
/// 3. Translate any rustc errors to LOGOS-friendly messages
/// 4. Run the compiled program via `cargo run`
///
/// # Arguments
///
/// * `source` - LOGOS source code as a string
/// * `output_dir` - Directory to create the temporary Cargo project in
///
/// # Returns
///
/// The stdout output of the executed program.
///
/// # Errors
///
/// Returns [`CompileError`] if:
/// - Compilation fails (see [`compile_to_dir`])
/// - Rust compilation fails (`CompileError::Build` or `CompileError::Ownership`)
/// - The program crashes at runtime (`CompileError::Runtime`)
///
/// # Diagnostic Translation
///
/// When rustc reports errors (e.g., E0382 for use-after-move), this function
/// uses the [`diagnostic`](crate::diagnostic) module to translate them into
/// LOGOS-friendly Socratic error messages.
///
/// # Example
///
/// ```no_run
/// # use logicaffeine_compile::compile::{compile_and_run, CompileError};
/// # use std::path::Path;
/// # fn main() -> Result<(), CompileError> {
/// let source = "## Main\nShow \"Hello, World!\".";
/// let output = compile_and_run(source, Path::new("/tmp/run"))?;
/// assert_eq!(output.trim(), "Hello, World!");
/// # Ok(())
/// # }
/// ```
pub fn compile_and_run(source: &str, output_dir: &Path) -> Result<String, CompileError> {
    // Pre-check: catch ownership errors (use-after-move) with friendly messages
    // before codegen runs (codegen defensively clones, masking these errors)
    compile_to_rust_checked(source).map_err(CompileError::Parse)?;

    compile_to_dir(source, output_dir)?;

    // Run cargo build with JSON message format for structured error parsing
    let build_output = Command::new("cargo")
        .arg("build")
        .arg("--message-format=json")
        .current_dir(output_dir)
        .output()
        .map_err(|e| CompileError::Io(e.to_string()))?;

    if !build_output.status.success() {
        let stderr = String::from_utf8_lossy(&build_output.stderr);
        let stdout = String::from_utf8_lossy(&build_output.stdout);

        // Try to parse JSON diagnostics and translate them
        let diagnostics = parse_rustc_json(&stdout);

        if !diagnostics.is_empty() {
            // Create a basic source map with the LOGOS source
            let source_map = SourceMap::new(source.to_string());
            let interner = Interner::new();

            if let Some(logos_error) = translate_diagnostics(&diagnostics, &source_map, &interner) {
                return Err(CompileError::Ownership(logos_error));
            }
        }

        // Fallback to raw error if translation fails
        return Err(CompileError::Build(stderr.to_string()));
    }

    // Run the compiled program
    let run_output = Command::new("cargo")
        .arg("run")
        .arg("--quiet")
        .current_dir(output_dir)
        .output()
        .map_err(|e| CompileError::Io(e.to_string()))?;

    if !run_output.status.success() {
        let stderr = String::from_utf8_lossy(&run_output.stderr);
        return Err(CompileError::Runtime(stderr.to_string()));
    }

    let stdout = String::from_utf8_lossy(&run_output.stdout);
    Ok(stdout.to_string())
}

/// Compile a LOGOS source file.
/// For single-file compilation without dependencies.
pub fn compile_file(path: &Path) -> Result<String, CompileError> {
    let source = fs::read_to_string(path).map_err(|e| CompileError::Io(e.to_string()))?;
    compile_to_rust(&source).map_err(CompileError::Parse)
}

/// Compile a multi-file LOGOS project with dependency resolution.
///
/// This function:
/// 1. Reads the entry file
/// 2. Scans for dependencies in the abstract (Markdown links)
/// 3. Recursively loads and discovers types from dependencies
/// 4. Compiles with the combined type registry
///
/// # Arguments
/// * `entry_file` - The main entry file to compile (root is derived from parent directory)
///
/// # Example
/// ```no_run
/// # use logicaffeine_compile::compile::compile_project;
/// # use std::path::Path;
/// let result = compile_project(Path::new("/project/main.md"));
/// ```
pub fn compile_project(entry_file: &Path) -> Result<CompileOutput, CompileError> {
    use crate::loader::Loader;
    use crate::analysis::discover_with_imports;

    let root_path = entry_file.parent().unwrap_or(Path::new(".")).to_path_buf();
    let mut loader = Loader::new(root_path);
    let mut interner = Interner::new();

    // Read the entry file
    let raw_source = fs::read_to_string(entry_file)
        .map_err(|e| CompileError::Io(format!("Failed to read entry file: {}", e)))?;

    // Auto-import the demand-driven stdlib prelude (uuid.lg, io/net/crdt/time/…) — the SAME seam the
    // string-compile and interpreter paths use (see `apply_prelude`), so `largo build` resolves stdlib
    // functions like `md5`/`sha1`/`uuidV3`/`uuidParse`/`flush`. Demand-driven + idempotent: a program
    // that references no stdlib name compiles byte-identically to before.
    let source = crate::loader::apply_prelude(&raw_source).into_owned();

    // Discover types from entry file and all imports
    let type_registry = discover_with_imports(entry_file, &source, &mut loader, &mut interner)
        .map_err(|e| CompileError::Io(e))?;

    // Now compile with the discovered types
    compile_to_rust_with_registry_full(&source, type_registry, &mut interner)
        .map_err(CompileError::Parse)
}

/// Compile LOGOS source with a pre-populated type registry, returning full output.
/// Returns both generated Rust code and extracted dependencies.
fn compile_to_rust_with_registry_full(
    source: &str,
    type_registry: crate::analysis::TypeRegistry,
    interner: &mut Interner,
) -> Result<CompileOutput, ParseError> {
    let mut lexer = Lexer::new(source, interner);
    let tokens = lexer.tokenize();

    // Discovery pass for policies (types already discovered)
    let policy_registry = {
        let mut discovery = DiscoveryPass::new(&tokens, interner);
        discovery.run_full().policies
    };

    let codegen_registry = type_registry.clone();
    let codegen_policies = policy_registry.clone();

    let mut world_state = WorldState::new();
    let expr_arena = Arena::new();
    let term_arena = Arena::new();
    let np_arena = Arena::new();
    let sym_arena = Arena::new();
    let role_arena = Arena::new();
    let pp_arena = Arena::new();
    let stmt_arena: Arena<Stmt> = Arena::new();
    let imperative_expr_arena: Arena<Expr> = Arena::new();
    let type_expr_arena: Arena<TypeExpr> = Arena::new();

    let ast_ctx = AstContext::with_types(
        &expr_arena,
        &term_arena,
        &np_arena,
        &sym_arena,
        &role_arena,
        &pp_arena,
        &stmt_arena,
        &imperative_expr_arena,
        &type_expr_arena,
    );

    let mut parser = Parser::new(tokens, &mut world_state, interner, ast_ctx, type_registry);
    let stmts = parser.parse_program()?;

    // Run the AST optimizer in the production (largo) compile path so
    // compiled binaries get the same optimizations the test path
    // (compile_program_full) already validates: closed-form / modulus
    // deferral, partial evaluation, constant folding, GVN, LICM,
    // deforestation, CTFE, supercompilation. Previously skipped here, which
    // left the whole optimize layer off for compiled programs. Confirmed a
    // clean win (geomean 1.388x -> 1.735x C-speed, all benchmarks verify
    // correct, no regressions).
    let stmts = crate::optimize::optimize_program(stmts, &imperative_expr_arena, &stmt_arena, interner, &crate::optimization::OptimizationConfig::from_env());

    // Extract dependencies before escape analysis
    let mut dependencies = extract_dependencies(&stmts, interner)?;

    // FFI: Auto-inject wasm-bindgen dependency if any function is exported for WASM
    let needs_wasm_bindgen = stmts.iter().any(|stmt| {
        if let Stmt::FunctionDef { is_exported: true, export_target: Some(target), .. } = stmt {
            interner.resolve(*target).eq_ignore_ascii_case("wasm")
        } else {
            false
        }
    });
    if needs_wasm_bindgen && !dependencies.iter().any(|d| d.name == "wasm-bindgen") {
        dependencies.push(CrateDependency {
            name: "wasm-bindgen".to_string(),
            version: "0.2".to_string(),
            features: vec![],
        });
    }

    let mut escape_checker = EscapeChecker::new(interner);
    escape_checker.check_program(&stmts).map_err(|e| {
        ParseError {
            kind: crate::error::ParseErrorKind::Custom(e.to_string()),
            span: e.span,
        }
    })?;

    let type_env = crate::analysis::check_program(&stmts, interner, &codegen_registry)
        .map_err(|e| ParseError {
            kind: e.to_parse_error_kind(interner),
            span: crate::token::Span::default(),
        })?;
    let rust_code = codegen_program(&stmts, &codegen_registry, &codegen_policies, interner, &type_env, &crate::optimization::OptimizationConfig::from_env());

    // Universal ABI: Generate C header + bindings if any C exports exist
    let has_c = stmts.iter().any(|stmt| {
        if let Stmt::FunctionDef { is_exported: true, export_target, .. } = stmt {
            match export_target {
                None => true,
                Some(t) => interner.resolve(*t).eq_ignore_ascii_case("c"),
            }
        } else {
            false
        }
    });

    let c_header = if has_c {
        Some(generate_c_header(&stmts, "module", interner, &codegen_registry))
    } else {
        None
    };

    if has_c && !dependencies.iter().any(|d| d.name == "serde_json") {
        dependencies.push(CrateDependency {
            name: "serde_json".to_string(),
            version: "1".to_string(),
            features: vec![],
        });
    }

    let python_bindings = if has_c {
        Some(generate_python_bindings(&stmts, "module", interner, &codegen_registry))
    } else {
        None
    };

    let (typescript_bindings, typescript_types) = if has_c {
        let (js, dts) = generate_typescript_bindings(&stmts, "module", interner, &codegen_registry);
        (Some(js), Some(dts))
    } else {
        (None, None)
    };

    Ok(CompileOutput { rust_code, dependencies, c_header, python_bindings, typescript_types, typescript_bindings })
}

/// Errors that can occur during the LOGOS compilation pipeline.
///
/// This enum represents the different stages where compilation can fail,
/// from parsing through to runtime execution.
///
/// # Error Hierarchy
///
/// ```text
/// CompileError
/// ├── Parse      ← Lexing, parsing, or static analysis
/// ├── Io         ← File system operations
/// ├── Build      ← Rust compilation (cargo build)
/// ├── Ownership  ← Translated borrow checker errors
/// └── Runtime    ← Program execution failure
/// ```
///
/// # Error Translation
///
/// The `Ownership` variant contains LOGOS-friendly error messages translated
/// from rustc's borrow checker errors (E0382, E0505, E0597) using the
/// [`diagnostic`](crate::diagnostic) module.
#[derive(Debug)]
pub enum CompileError {
    /// Parsing or static analysis failed.
    ///
    /// This includes lexer errors, syntax errors, escape analysis failures,
    /// ownership analysis failures, and Z3 verification failures.
    Parse(ParseError),

    /// File system operation failed.
    ///
    /// Typically occurs when reading source files or writing output.
    Io(String),

    /// Rust compilation failed (`cargo build`).
    ///
    /// Contains the raw stderr output from rustc when diagnostic translation
    /// was not possible.
    Build(String),

    /// Runtime execution failed.
    ///
    /// Contains stderr output from the executed program.
    Runtime(String),

    /// Translated ownership/borrow checker error with LOGOS-friendly message.
    ///
    /// This variant is used when rustc reports errors like E0382 (use after move)
    /// and we can translate them into natural language error messages that
    /// reference the original LOGOS source.
    Ownership(LogosError),
}

impl std::fmt::Display for CompileError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CompileError::Parse(e) => write!(f, "Parse error: {:?}", e),
            CompileError::Io(e) => write!(f, "IO error: {}", e),
            CompileError::Build(e) => write!(f, "Build error: {}", e),
            CompileError::Runtime(e) => write!(f, "Runtime error: {}", e),
            CompileError::Ownership(e) => write!(f, "{}", e),
        }
    }
}

impl std::error::Error for CompileError {}

// ============================================================
// Futamura Projection Support — encode_program + verify_no_overhead
// ============================================================

/// Encode a LogicAffeine program (given as source) into CProgram construction source.
///
/// Takes LogicAffeine source code (with or without `## Main` header) and returns
/// LogicAffeine source code that constructs the equivalent CProgram data structure.
/// The result defines a variable `prog` of type CProgram.
pub fn encode_program_source(source: &str) -> Result<String, ParseError> {
    let full_source = if source.contains("## Main") || source.contains("## To ") {
        source.to_string()
    } else {
        format!("## Main\n{}", source)
    };

    let mut interner = Interner::new();
    let mut lexer = Lexer::new(&full_source, &mut interner);
    let tokens = lexer.tokenize();

    let type_registry = {
        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
        let result = discovery.run_full();
        result.types
    };

    // Collect variant constructors before the parser takes ownership of type_registry
    let mut variant_constructors: HashMap<String, Vec<String>> = HashMap::new();
    for (_type_name, type_def) in type_registry.iter_types() {
        if let crate::analysis::TypeDef::Enum { variants, .. } = type_def {
            for variant in variants {
                let vname = interner.resolve(variant.name).to_string();
                let field_names: Vec<String> = variant.fields.iter()
                    .map(|f| interner.resolve(f.name).to_string())
                    .collect();
                variant_constructors.insert(vname, field_names);
            }
        }
    }

    let mut world_state = WorldState::new();
    let expr_arena = Arena::new();
    let term_arena = Arena::new();
    let np_arena = Arena::new();
    let sym_arena = Arena::new();
    let role_arena = Arena::new();
    let pp_arena = Arena::new();
    let stmt_arena: Arena<Stmt> = Arena::new();
    let imperative_expr_arena: Arena<Expr> = Arena::new();
    let type_expr_arena: Arena<TypeExpr> = Arena::new();

    let ast_ctx = AstContext::with_types(
        &expr_arena, &term_arena, &np_arena, &sym_arena,
        &role_arena, &pp_arena, &stmt_arena, &imperative_expr_arena,
        &type_expr_arena,
    );

    let mut parser = crate::parser::Parser::new(
        tokens, &mut world_state, &mut interner, ast_ctx, type_registry,
    );
    let stmts = parser.parse_program()?;

    let mut functions: Vec<(String, Vec<String>, Vec<String>, String, Vec<&Stmt>)> = Vec::new();
    let mut main_stmts: Vec<&Stmt> = Vec::new();

    for stmt in &stmts {
        if let Stmt::FunctionDef { name, params, body, return_type, is_native, .. } = stmt {
            if *is_native {
                continue; // Skip native function declarations — they have no encodable body
            }
            let fn_name = interner.resolve(*name).to_string();
            let param_names: Vec<String> = params
                .iter()
                .map(|(name, _)| interner.resolve(*name).to_string())
                .collect();
            let param_types: Vec<String> = params
                .iter()
                .map(|(_, ty)| decompile_type_expr(ty, &interner))
                .collect();
            let ret_type = return_type
                .map(|rt| decompile_type_expr(rt, &interner))
                .unwrap_or_else(|| "Nothing".to_string());
            let body_stmts: Vec<&Stmt> = body.iter().collect();
            functions.push((fn_name, param_names, param_types, ret_type, body_stmts));
        } else {
            main_stmts.push(stmt);
        }
    }

    let mut counter = 0usize;
    let mut output = String::new();
    reset_inspect_otherwise_idx(); // deterministic `__inspectMatched_N` numbering, shared with the native builder

    // Build the funcMap directly (Map of Text to CFunc) with fixed name, plus a parallel
    // `encodedFuncSeq` (Seq of CFunc, declaration order) — the map has no meaning-preserving
    // iteration order, so the wire serializer (which ships a `CProg with funcs …`) needs the seq.
    output.push_str("Let encodedFuncMap be a new Map of Text to CFunc.\n");
    output.push_str("Let encodedFuncSeq be a new Seq of CFunc.\n");

    for (fn_name, params, param_types, ret_type, body) in &functions {
        let body_var = encode_stmt_list_src(body, &mut counter, &mut output, &interner, &variant_constructors);

        let params_var = format!("params_{}", counter);
        counter += 1;
        output.push_str(&format!("Let {} be a new Seq of Text.\n", params_var));
        for p in params {
            output.push_str(&format!("Push \"{}\" to {}.\n", p, params_var));
        }

        let param_types_var = format!("paramTypes_{}", counter);
        counter += 1;
        output.push_str(&format!("Let {} be a new Seq of Text.\n", param_types_var));
        for pt in param_types {
            output.push_str(&format!("Push \"{}\" to {}.\n", pt, param_types_var));
        }

        let func_var = format!("func_{}", counter);
        counter += 1;
        output.push_str(&format!(
            "Let {} be a new CFuncDef with name \"{}\" and params {} and paramTypes {} and returnType \"{}\" and body {}.\n",
            func_var, fn_name, params_var, param_types_var, ret_type, body_var
        ));
        // `copy of` + emitted BEFORE the map `Set` (which MOVES func_var in AOT codegen): the seq
        // gets an identical clone, the map keeps the original — no use-after-move (E0382) when the
        // encoded program is compiled to Rust. The interpreter clones anyway, so this is a pure
        // codegen-soundness fix, behaviourally identical on every tier.
        output.push_str(&format!("Push copy of {} to encodedFuncSeq.\n", func_var));
        output.push_str(&format!(
            "Set item \"{}\" of encodedFuncMap to {}.\n",
            fn_name, func_var
        ));
    }

    // Build main statement list with fixed name
    let main_var = encode_stmt_list_src(&main_stmts, &mut counter, &mut output, &interner, &variant_constructors);
    output.push_str(&format!("Let encodedMain be {}.\n", main_var));

    Ok(output)
}

/// Compact encoding: inlines simple expressions (literals, variables) to reduce
/// encoding size by ~3x. Same semantics as encode_program_source but produces
/// fewer Let statements.
pub fn encode_program_source_compact(source: &str) -> Result<String, ParseError> {
    let full_source = if source.contains("## Main") || source.contains("## To ") {
        source.to_string()
    } else {
        format!("## Main\n{}", source)
    };

    let mut interner = Interner::new();
    let mut lexer = Lexer::new(&full_source, &mut interner);
    let tokens = lexer.tokenize();

    let type_registry = {
        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
        let result = discovery.run_full();
        result.types
    };

    let mut variant_constructors: HashMap<String, Vec<String>> = HashMap::new();
    for (_type_name, type_def) in type_registry.iter_types() {
        if let crate::analysis::TypeDef::Enum { variants, .. } = type_def {
            for variant in variants {
                let vname = interner.resolve(variant.name).to_string();
                let field_names: Vec<String> = variant.fields.iter()
                    .map(|f| interner.resolve(f.name).to_string())
                    .collect();
                variant_constructors.insert(vname, field_names);
            }
        }
    }

    let mut world_state = WorldState::new();
    let expr_arena = Arena::new();
    let term_arena = Arena::new();
    let np_arena = Arena::new();
    let sym_arena = Arena::new();
    let role_arena = Arena::new();
    let pp_arena = Arena::new();
    let stmt_arena: Arena<Stmt> = Arena::new();
    let imperative_expr_arena: Arena<Expr> = Arena::new();
    let type_expr_arena: Arena<TypeExpr> = Arena::new();

    let ast_ctx = AstContext::with_types(
        &expr_arena, &term_arena, &np_arena, &sym_arena,
        &role_arena, &pp_arena, &stmt_arena, &imperative_expr_arena,
        &type_expr_arena,
    );

    let mut parser = crate::parser::Parser::new(
        tokens, &mut world_state, &mut interner, ast_ctx, type_registry,
    );
    let stmts = parser.parse_program()?;

    let mut functions: Vec<(String, Vec<String>, Vec<String>, String, Vec<&Stmt>)> = Vec::new();
    let mut main_stmts: Vec<&Stmt> = Vec::new();

    for stmt in &stmts {
        if let Stmt::FunctionDef { name, params, body, return_type, is_native, .. } = stmt {
            if *is_native { continue; }
            let fn_name = interner.resolve(*name).to_string();
            let param_names: Vec<String> = params
                .iter()
                .map(|(name, _)| interner.resolve(*name).to_string())
                .collect();
            let param_types: Vec<String> = params
                .iter()
                .map(|(_, ty)| decompile_type_expr(ty, &interner))
                .collect();
            let ret_type = return_type
                .map(|rt| decompile_type_expr(rt, &interner))
                .unwrap_or_else(|| "Nothing".to_string());
            let body_stmts: Vec<&Stmt> = body.iter().collect();
            functions.push((fn_name, param_names, param_types, ret_type, body_stmts));
        } else {
            main_stmts.push(stmt);
        }
    }

    let mut counter = 0usize;
    let mut output = String::new();

    output.push_str("Let encodedFuncMap be a new Map of Text to CFunc.\n");

    for (fn_name, params, param_types, ret_type, body) in &functions {
        let body_var = encode_stmt_list_compact(body, &mut counter, &mut output, &interner, &variant_constructors);

        let params_var = format!("params_{}", counter);
        counter += 1;
        output.push_str(&format!("Let {} be a new Seq of Text.\n", params_var));
        for p in params {
            output.push_str(&format!("Push \"{}\" to {}.\n", p, params_var));
        }

        let param_types_var = format!("paramTypes_{}", counter);
        counter += 1;
        output.push_str(&format!("Let {} be a new Seq of Text.\n", param_types_var));
        for pt in param_types {
            output.push_str(&format!("Push \"{}\" to {}.\n", pt, param_types_var));
        }

        let func_var = format!("func_{}", counter);
        counter += 1;
        output.push_str(&format!(
            "Let {} be a new CFuncDef with name \"{}\" and params {} and paramTypes {} and returnType \"{}\" and body {}.\n",
            func_var, fn_name, params_var, param_types_var, ret_type, body_var
        ));
        output.push_str(&format!(
            "Set item \"{}\" of encodedFuncMap to {}.\n",
            fn_name, func_var
        ));
    }

    let main_var = encode_stmt_list_compact(&main_stmts, &mut counter, &mut output, &interner, &variant_constructors);
    output.push_str(&format!("Let encodedMain be {}.\n", main_var));

    Ok(output)
}

/// Returns an inline expression string for simple expressions (no Let variable needed).
/// Returns None for complex expressions that require a Let variable.
fn try_inline_expr(expr: &Expr, interner: &Interner) -> Option<String> {
    match expr {
        Expr::Literal(lit) => match lit {
            Literal::Number(n) => Some(format!("(a new CInt with value {})", n)),
            Literal::Boolean(b) => Some(format!("(a new CBool with value {})", b)),
            Literal::Text(s) => {
                let text = interner.resolve(*s);
                Some(format!("(a new CText with value \"{}\")", text))
            }
            Literal::Float(f) => {
                let fs = format!("{}", f);
                let fs = if fs.contains('.') { fs } else { format!("{}.0", fs) };
                Some(format!("(a new CFloat with value {})", fs))
            }
            Literal::Nothing => Some("(a new CText with value \"nothing\")".to_string()),
            _ => None,
        },
        Expr::Identifier(sym) => {
            let name = interner.resolve(*sym);
            Some(format!("(a new CVar with name \"{}\")", name))
        }
        Expr::Not { operand } => {
            if let Some(inner) = try_inline_expr(operand, interner) {
                Some(format!("(a new CNot with inner {})", inner))
            } else {
                None
            }
        }
        Expr::OptionNone => Some("(a new COptionNone)".to_string()),
        _ => None,
    }
}

fn encode_expr_compact(expr: &Expr, counter: &mut usize, output: &mut String, interner: &Interner, variants: &HashMap<String, Vec<String>>) -> String {
    // Try inline first
    if let Some(inline) = try_inline_expr(expr, interner) {
        return inline;
    }

    // Fall back to Let variable (reuse encode_expr_src logic but with compact children)
    let var = format!("e_{}", *counter);
    *counter += 1;

    match expr {
        Expr::BinaryOp { op, left, right } => {
            let left_var = encode_expr_compact(left, counter, output, interner, variants);
            let right_var = encode_expr_compact(right, counter, output, interner, variants);
            let op_str = match op {
                BinaryOpKind::Add => "+",
                BinaryOpKind::Subtract => "-",
                BinaryOpKind::Multiply => "*",
                BinaryOpKind::Divide | BinaryOpKind::ExactDivide => "/",
                BinaryOpKind::FloorDivide => "//",
                BinaryOpKind::Modulo => "%",
                BinaryOpKind::Eq => "==",
                BinaryOpKind::NotEq => "!=",
                BinaryOpKind::Lt => "<",
                BinaryOpKind::Gt => ">",
                BinaryOpKind::LtEq => "<=",
                BinaryOpKind::GtEq => ">=",
                BinaryOpKind::And => "&&",
                BinaryOpKind::Or => "||",
                BinaryOpKind::Concat => "+",
                BinaryOpKind::SeqConcat => "followed by",
                BinaryOpKind::ApproxEq => "is approximately",
                BinaryOpKind::Pow => "**",
                BinaryOpKind::BitXor => "^",
                BinaryOpKind::BitAnd => "&",
                BinaryOpKind::BitOr => "|",
                BinaryOpKind::Shl => "<<",
                BinaryOpKind::Shr => ">>",
            };
            output.push_str(&format!(
                "Let {} be a new CBinOp with op \"{}\" and left {} and right {}.\n",
                var, op_str, left_var, right_var
            ));
        }
        Expr::Call { function, args } => {
            let fn_name = interner.resolve(*function);
            if let Some(field_names) = variants.get(fn_name) {
                let names_var = format!("nvNames_{}", *counter);
                *counter += 1;
                output.push_str(&format!("Let {} be a new Seq of Text.\n", names_var));
                let vals_var = format!("nvVals_{}", *counter);
                *counter += 1;
                output.push_str(&format!("Let {} be a new Seq of CExpr.\n", vals_var));
                for (i, arg) in args.iter().enumerate() {
                    let fname = field_names.get(i).map(|s| s.as_str()).unwrap_or("value");
                    output.push_str(&format!("Push \"{}\" to {}.\n", fname, names_var));
                    let arg_var = encode_expr_compact(arg, counter, output, interner, variants);
                    output.push_str(&format!("Push {} to {}.\n", arg_var, vals_var));
                }
                output.push_str(&format!(
                    "Let {} be a new CNewVariant with tag \"{}\" and fnames {} and fvals {}.\n",
                    var, fn_name, names_var, vals_var
                ));
            } else {
                let args_var = format!("callArgs_{}", *counter);
                *counter += 1;
                output.push_str(&format!("Let {} be a new Seq of CExpr.\n", args_var));
                for arg in args {
                    let arg_var = encode_expr_compact(arg, counter, output, interner, variants);
                    output.push_str(&format!("Push {} to {}.\n", arg_var, args_var));
                }
                output.push_str(&format!(
                    "Let {} be a new CCall with name \"{}\" and args {}.\n",
                    var, fn_name, args_var
                ));
            }
        }
        Expr::Index { collection, index } => {
            let coll_var = encode_expr_compact(collection, counter, output, interner, variants);
            let idx_var = encode_expr_compact(index, counter, output, interner, variants);
            output.push_str(&format!(
                "Let {} be a new CIndex with coll {} and idx {}.\n",
                var, coll_var, idx_var
            ));
        }
        Expr::Length { collection } => {
            let coll_var = encode_expr_compact(collection, counter, output, interner, variants);
            output.push_str(&format!("Let {} be a new CLen with target {}.\n", var, coll_var));
        }
        Expr::FieldAccess { object, field } => {
            let obj_var = encode_expr_compact(object, counter, output, interner, variants);
            let field_name = interner.resolve(*field);
            output.push_str(&format!(
                "Let {} be a new CMapGet with target {} and key (a new CText with value \"{}\").\n",
                var, obj_var, field_name
            ));
        }
        Expr::NewVariant { variant, fields, .. } => {
            let variant_name = interner.resolve(*variant);
            let names_var = format!("nvNames_{}", *counter);
            *counter += 1;
            output.push_str(&format!("Let {} be a new Seq of Text.\n", names_var));
            let vals_var = format!("nvVals_{}", *counter);
            *counter += 1;
            output.push_str(&format!("Let {} be a new Seq of CExpr.\n", vals_var));
            for (field_name, field_expr) in fields {
                let fname = interner.resolve(*field_name);
                output.push_str(&format!("Push \"{}\" to {}.\n", fname, names_var));
                let field_var = encode_expr_compact(field_expr, counter, output, interner, variants);
                output.push_str(&format!("Push {} to {}.\n", field_var, vals_var));
            }
            output.push_str(&format!(
                "Let {} be a new CNewVariant with tag \"{}\" and fnames {} and fvals {}.\n",
                var, variant_name, names_var, vals_var
            ));
        }
        Expr::New { type_name, init_fields, .. } => {
            let tn = interner.resolve(*type_name);
            if tn == "Seq" || tn == "List" {
                output.push_str(&format!("Let {} be a new CNewSeq.\n", var));
            } else if tn == "Set" {
                output.push_str(&format!("Let {} be a new CNewSet.\n", var));
            } else {
                let names_var = format!("nvNames_{}", *counter);
                *counter += 1;
                output.push_str(&format!("Let {} be a new Seq of Text.\n", names_var));
                let vals_var = format!("nvVals_{}", *counter);
                *counter += 1;
                output.push_str(&format!("Let {} be a new Seq of CExpr.\n", vals_var));
                for (field_name, field_expr) in init_fields {
                    let fname = interner.resolve(*field_name);
                    output.push_str(&format!("Push \"{}\" to {}.\n", fname, names_var));
                    let field_var = encode_expr_compact(field_expr, counter, output, interner, variants);
                    output.push_str(&format!("Push {} to {}.\n", field_var, vals_var));
                }
                output.push_str(&format!(
                    "Let {} be a new CNewVariant with tag \"{}\" and fnames {} and fvals {}.\n",
                    var, tn, names_var, vals_var
                ));
            }
        }
        Expr::InterpolatedString(parts) => {
            if parts.is_empty() {
                output.push_str(&format!("Let {} be (a new CText with value \"\").\n", var));
            } else {
                // Preserve as a first-class CInterpolatedString rather than desugaring to a
                // lossy `+` chain (see encode_expr_src for the rationale).
                let parts_var = format!("isparts_{}", *counter);
                *counter += 1;
                output.push_str(&format!("Let {} be a new Seq of CStringPart.\n", parts_var));
                for part in parts {
                    match part {
                        StringPart::Literal(sym) => {
                            let text = interner.resolve(*sym);
                            output.push_str(&format!(
                                "Push a new CLiteralPart with value \"{}\" to {}.\n", text, parts_var
                            ));
                        }
                        StringPart::Expr { value, .. } => {
                            let pv = encode_expr_compact(value, counter, output, interner, variants);
                            output.push_str(&format!(
                                "Push a new CExprPart with expr {} to {}.\n", pv, parts_var
                            ));
                        }
                    }
                }
                output.push_str(&format!(
                    "Let {} be a new CInterpolatedString with parts {}.\n", var, parts_var
                ));
            }
        }
        Expr::Range { start, end } => {
            let start_var = encode_expr_compact(start, counter, output, interner, variants);
            let end_var = encode_expr_compact(end, counter, output, interner, variants);
            output.push_str(&format!(
                "Let {} be a new CRange with start {} and end {}.\n",
                var, start_var, end_var
            ));
        }
        Expr::Copy { expr } => {
            let inner_var = encode_expr_compact(expr, counter, output, interner, variants);
            output.push_str(&format!("Let {} be a new CCopy with target {}.\n", var, inner_var));
        }
        Expr::Contains { collection, value } => {
            let coll_var = encode_expr_compact(collection, counter, output, interner, variants);
            let val_var = encode_expr_compact(value, counter, output, interner, variants);
            output.push_str(&format!(
                "Let {} be a new CContains with coll {} and elem {}.\n",
                var, coll_var, val_var
            ));
        }
        Expr::OptionSome { value } => {
            let inner_var = encode_expr_compact(value, counter, output, interner, variants);
            output.push_str(&format!(
                "Let {} be a new COptionSome with inner {}.\n", var, inner_var
            ));
        }
        Expr::Tuple(elems) => {
            let items_var = format!("tupItems_{}", *counter);
            *counter += 1;
            output.push_str(&format!("Let {} be a new Seq of CExpr.\n", items_var));
            for elem in elems {
                let elem_var = encode_expr_compact(elem, counter, output, interner, variants);
                output.push_str(&format!("Push {} to {}.\n", elem_var, items_var));
            }
            output.push_str(&format!(
                "Let {} be a new CTuple with items {}.\n", var, items_var
            ));
        }
        Expr::Closure { params, body, .. } => {
            let params_var = format!("clp_{}", *counter);
            *counter += 1;
            output.push_str(&format!("Let {} be a new Seq of Text.\n", params_var));
            let mut param_names = HashSet::new();
            for (sym, _) in params {
                let name = interner.resolve(*sym);
                param_names.insert(name.to_string());
                output.push_str(&format!("Push \"{}\" to {}.\n", name, params_var));
            }
            let body_var = format!("clb_{}", *counter);
            *counter += 1;
            output.push_str(&format!("Let {} be a new Seq of CStmt.\n", body_var));
            match body {
                ClosureBody::Expression(e) => {
                    let ret_expr = encode_expr_compact(e, counter, output, interner, variants);
                    let ret_var = format!("s_{}", *counter);
                    *counter += 1;
                    output.push_str(&format!("Let {} be a new CReturn with expr {}.\n", ret_var, ret_expr));
                    output.push_str(&format!("Push {} to {}.\n", ret_var, body_var));
                }
                ClosureBody::Block(stmts) => {
                    for s in stmts.iter() {
                        let sv = encode_stmt_compact(s, counter, output, interner, variants);
                        output.push_str(&format!("Push {} to {}.\n", sv, body_var));
                    }
                }
            }
            let bound: HashSet<String> = param_names;
            // Sort the captured free variables for a DETERMINISTIC encoding — a `HashSet`'s random
            // iteration order would make the wire bytes vary run-to-run (breaking content-addressing
            // AND the fast native-builder byte-identity). The capture set is order-independent
            // semantically, so sorting is a pure improvement.
            let mut free: Vec<String> = collect_free_vars_expr(expr, interner, &bound).into_iter().collect();
            free.sort();
            let cap_var = format!("clc_{}", *counter);
            *counter += 1;
            output.push_str(&format!("Let {} be a new Seq of Text.\n", cap_var));
            for fv in &free {
                output.push_str(&format!("Push \"{}\" to {}.\n", fv, cap_var));
            }
            output.push_str(&format!(
                "Let {} be a new CClosure with params {} and body {} and captured {}.\n",
                var, params_var, body_var, cap_var
            ));
        }
        Expr::CallExpr { callee, args } => {
            let callee_var = encode_expr_compact(callee, counter, output, interner, variants);
            let args_var = format!("cea_{}", *counter);
            *counter += 1;
            output.push_str(&format!("Let {} be a new Seq of CExpr.\n", args_var));
            for a in args {
                let av = encode_expr_compact(a, counter, output, interner, variants);
                output.push_str(&format!("Push {} to {}.\n", av, args_var));
            }
            output.push_str(&format!(
                "Let {} be a new CCallExpr with target {} and args {}.\n",
                var, callee_var, args_var
            ));
        }
        Expr::Slice { collection, start, end } => {
            let coll_var = encode_expr_compact(collection, counter, output, interner, variants);
            let start_var = encode_expr_compact(start, counter, output, interner, variants);
            let end_var = encode_expr_compact(end, counter, output, interner, variants);
            output.push_str(&format!(
                "Let {} be a new CSlice with coll {} and startIdx {} and endIdx {}.\n",
                var, coll_var, start_var, end_var
            ));
        }
        Expr::Union { left, right } => {
            let left_var = encode_expr_compact(left, counter, output, interner, variants);
            let right_var = encode_expr_compact(right, counter, output, interner, variants);
            output.push_str(&format!(
                "Let {} be a new CUnion with left {} and right {}.\n",
                var, left_var, right_var
            ));
        }
        Expr::Intersection { left, right } => {
            let left_var = encode_expr_compact(left, counter, output, interner, variants);
            let right_var = encode_expr_compact(right, counter, output, interner, variants);
            output.push_str(&format!(
                "Let {} be a new CIntersection with left {} and right {}.\n",
                var, left_var, right_var
            ));
        }
        Expr::Give { value } => {
            let inner_var = encode_expr_compact(value, counter, output, interner, variants);
            output.push_str(&format!("Let {} be {}.\n", var, inner_var));
        }
        Expr::Escape { code, .. } => {
            let code_str = interner.resolve(*code);
            output.push_str(&format!(
                "Let {} be a new CEscExpr with code \"{}\".\n",
                var, code_str.replace('\"', "\\\"")
            ));
        }
        _ => {
            // For unsupported expressions, use the non-compact version
            output.push_str(&format!("Let {} be (a new CText with value \"unsupported\").\n", var));
        }
    }

    var
}

fn encode_stmt_compact(stmt: &Stmt, counter: &mut usize, output: &mut String, interner: &Interner, variants: &HashMap<String, Vec<String>>) -> String {
    let var = format!("s_{}", *counter);
    *counter += 1;

    match stmt {
        Stmt::Let { var: name, value, .. } => {
            let name_str = interner.resolve(*name);
            let expr_var = encode_expr_compact(value, counter, output, interner, variants);
            output.push_str(&format!(
                "Let {} be a new CLet with name \"{}\" and expr {}.\n",
                var, name_str, expr_var
            ));
        }
        Stmt::Set { target, value } => {
            let name_str = interner.resolve(*target);
            let expr_var = encode_expr_compact(value, counter, output, interner, variants);
            output.push_str(&format!(
                "Let {} be a new CSet with name \"{}\" and expr {}.\n",
                var, name_str, expr_var
            ));
        }
        Stmt::If { cond, then_block, else_block } => {
            let cond_var = encode_expr_compact(cond, counter, output, interner, variants);
            let then_stmts: Vec<&Stmt> = then_block.iter().collect();
            let then_var = encode_stmt_list_compact(&then_stmts, counter, output, interner, variants);
            let else_var = if let Some(els) = else_block {
                let else_stmts: Vec<&Stmt> = els.iter().collect();
                encode_stmt_list_compact(&else_stmts, counter, output, interner, variants)
            } else {
                let empty_var = format!("emptyBlock_{}", *counter);
                *counter += 1;
                output.push_str(&format!("Let {} be a new Seq of CStmt.\n", empty_var));
                empty_var
            };
            output.push_str(&format!(
                "Let {} be a new CIf with cond {} and thenBlock {} and elseBlock {}.\n",
                var, cond_var, then_var, else_var
            ));
        }
        Stmt::While { cond, body, .. } => {
            let cond_var = encode_expr_compact(cond, counter, output, interner, variants);
            let body_stmts: Vec<&Stmt> = body.iter().collect();
            let body_var = encode_stmt_list_compact(&body_stmts, counter, output, interner, variants);
            output.push_str(&format!(
                "Let {} be a new CWhile with cond {} and body {}.\n",
                var, cond_var, body_var
            ));
        }
        Stmt::Return { value } => {
            if let Some(val) = value {
                let expr_var = encode_expr_compact(val, counter, output, interner, variants);
                output.push_str(&format!("Let {} be a new CReturn with expr {}.\n", var, expr_var));
            } else {
                output.push_str(&format!("Let {} be a new CReturn with expr (a new CText with value \"nothing\").\n", var));
            }
        }
        Stmt::Show { object, .. } => {
            let expr_var = encode_expr_compact(object, counter, output, interner, variants);
            output.push_str(&format!("Let {} be a new CShow with expr {}.\n", var, expr_var));
        }
        Stmt::Repeat { pattern, iterable, body } => {
            let var_str = match pattern {
                Pattern::Identifier(sym) => interner.resolve(*sym).to_string(),
                Pattern::Tuple(syms) => {
                    if let Some(s) = syms.first() {
                        interner.resolve(*s).to_string()
                    } else {
                        "item".to_string()
                    }
                }
            };
            let coll_var = encode_expr_compact(iterable, counter, output, interner, variants);
            let body_stmts: Vec<&Stmt> = body.iter().collect();
            let body_var = encode_stmt_list_compact(&body_stmts, counter, output, interner, variants);
            output.push_str(&format!(
                "Let {} be a new CRepeat with var \"{}\" and coll {} and body {}.\n",
                var, var_str, coll_var, body_var
            ));
        }
        Stmt::Push { value, collection } => {
            let coll_name = extract_ident_name(collection, interner);
            let expr_var = encode_expr_compact(value, counter, output, interner, variants);
            output.push_str(&format!(
                "Let {} be a new CPush with expr {} and target \"{}\".\n",
                var, expr_var, coll_name
            ));
        }
        Stmt::SetIndex { collection, index, value } => {
            let target_str = extract_ident_name(collection, interner);
            let idx_var = encode_expr_compact(index, counter, output, interner, variants);
            let val_var = encode_expr_compact(value, counter, output, interner, variants);
            output.push_str(&format!(
                "Let {} be a new CSetIdx with target \"{}\" and idx {} and val {}.\n",
                var, target_str, idx_var, val_var
            ));
        }
        Stmt::SetField { object, field, value } => {
            let target_str = extract_ident_name(object, interner);
            let field_str = interner.resolve(*field);
            let val_var = encode_expr_compact(value, counter, output, interner, variants);
            output.push_str(&format!(
                "Let {} be a new CSetField with target \"{}\" and field \"{}\" and val {}.\n",
                var, target_str, field_str, val_var
            ));
        }
        Stmt::Break => {
            output.push_str(&format!("Let {} be a new CBreak.\n", var));
        }
        Stmt::Inspect { target, arms, .. } => {
            let target_var = encode_expr_compact(target, counter, output, interner, variants);
            let arms_var = format!("arms_{}", *counter);
            *counter += 1;
            output.push_str(&format!("Let {} be a new Seq of CMatchArm.\n", arms_var));
            for arm in arms {
                if let Some(variant_sym) = arm.variant {
                    let vname = interner.resolve(variant_sym);
                    let bindings_var = format!("bindings_{}", *counter);
                    *counter += 1;
                    output.push_str(&format!("Let {} be a new Seq of Text.\n", bindings_var));
                    for (_, binding_name) in &arm.bindings {
                        let bn = interner.resolve(*binding_name);
                        output.push_str(&format!("Push \"{}\" to {}.\n", bn, bindings_var));
                    }
                    let body_stmts: Vec<&Stmt> = arm.body.iter().collect();
                    let body_var = encode_stmt_list_compact(&body_stmts, counter, output, interner, variants);
                    let arm_var = format!("arm_{}", *counter);
                    *counter += 1;
                    output.push_str(&format!(
                        "Let {} be a new CWhen with variantName \"{}\" and bindings {} and body {}.\n",
                        arm_var, vname, bindings_var, body_var
                    ));
                    output.push_str(&format!("Push {} to {}.\n", arm_var, arms_var));
                } else {
                    let body_stmts: Vec<&Stmt> = arm.body.iter().collect();
                    let body_var = encode_stmt_list_compact(&body_stmts, counter, output, interner, variants);
                    let arm_var = format!("arm_{}", *counter);
                    *counter += 1;
                    output.push_str(&format!(
                        "Let {} be a new COtherwise with body {}.\n",
                        arm_var, body_var
                    ));
                    output.push_str(&format!("Push {} to {}.\n", arm_var, arms_var));
                }
            }
            output.push_str(&format!(
                "Let {} be a new CInspect with target {} and arms {}.\n",
                var, target_var, arms_var
            ));
        }
        _ => {
            // Delegate to non-compact encoder for unsupported statements
            return encode_stmt_src(stmt, counter, output, interner, variants);
        }
    }

    var
}

fn encode_stmt_list_compact(stmts: &[&Stmt], counter: &mut usize, output: &mut String, interner: &Interner, variants: &HashMap<String, Vec<String>>) -> String {
    let list_var = format!("stmts_{}", *counter);
    *counter += 1;
    output.push_str(&format!("Let {} be a new Seq of CStmt.\n", list_var));
    for s in stmts {
        let sv = encode_stmt_compact(s, counter, output, interner, variants);
        output.push_str(&format!("Push {} to {}.\n", sv, list_var));
    }
    list_var
}

fn collect_free_vars_expr<'a>(expr: &'a Expr, interner: &Interner, bound: &HashSet<String>) -> HashSet<String> {
    let mut free = HashSet::new();
    match expr {
        Expr::Identifier(sym) => {
            let name = interner.resolve(*sym).to_string();
            if !bound.contains(&name) {
                free.insert(name);
            }
        }
        Expr::BinaryOp { left, right, .. } => {
            free.extend(collect_free_vars_expr(left, interner, bound));
            free.extend(collect_free_vars_expr(right, interner, bound));
        }
        Expr::Not { operand } => {
            free.extend(collect_free_vars_expr(operand, interner, bound));
        }
        Expr::Copy { expr: inner } => {
            free.extend(collect_free_vars_expr(inner, interner, bound));
        }
        Expr::CallExpr { callee, args } => {
            free.extend(collect_free_vars_expr(callee, interner, bound));
            for a in args {
                free.extend(collect_free_vars_expr(a, interner, bound));
            }
        }
        Expr::Index { collection, index } => {
            free.extend(collect_free_vars_expr(collection, interner, bound));
            free.extend(collect_free_vars_expr(index, interner, bound));
        }
        Expr::InterpolatedString(parts) => {
            for part in parts {
                if let StringPart::Expr { value, .. } = part {
                    free.extend(collect_free_vars_expr(value, interner, bound));
                }
            }
        }
        Expr::Closure { params, body, .. } => {
            let mut inner_bound = bound.clone();
            for (sym, _) in params {
                inner_bound.insert(interner.resolve(*sym).to_string());
            }
            match body {
                ClosureBody::Expression(e) => {
                    free.extend(collect_free_vars_expr(e, interner, &inner_bound));
                }
                ClosureBody::Block(stmts) => {
                    for s in stmts.iter() {
                        free.extend(collect_free_vars_stmt(s, interner, &inner_bound));
                    }
                }
            }
        }
        _ => {}
    }
    free
}

fn collect_free_vars_stmt<'a>(stmt: &'a Stmt, interner: &Interner, bound: &HashSet<String>) -> HashSet<String> {
    let mut free = HashSet::new();
    match stmt {
        Stmt::Let { var, value, .. } => {
            free.extend(collect_free_vars_expr(value, interner, bound));
        }
        Stmt::Set { target, value, .. } => {
            let n = interner.resolve(*target).to_string();
            if !bound.contains(&n) {
                free.insert(n);
            }
            free.extend(collect_free_vars_expr(value, interner, bound));
        }
        Stmt::Show { object, .. } => {
            free.extend(collect_free_vars_expr(object, interner, bound));
        }
        Stmt::Return { value } => {
            if let Some(v) = value {
                free.extend(collect_free_vars_expr(v, interner, bound));
            }
        }
        _ => {}
    }
    free
}

fn encode_expr_src(expr: &Expr, counter: &mut usize, output: &mut String, interner: &Interner, variants: &HashMap<String, Vec<String>>) -> String {
    let var = format!("e_{}", *counter);
    *counter += 1;

    match expr {
        Expr::Literal(lit) => match lit {
            Literal::Number(n) => {
                output.push_str(&format!("Let {} be a new CInt with value {}.\n", var, n));
            }
            Literal::Boolean(b) => {
                output.push_str(&format!("Let {} be a new CBool with value {}.\n", var, b));
            }
            Literal::Text(s) => {
                let text = interner.resolve(*s);
                output.push_str(&format!("Let {} be a new CText with value \"{}\".\n", var, text));
            }
            Literal::Float(f) => {
                // Format faithfully: Rust's `{}` prints integer-valued floats without a
                // decimal point (9.0 -> "9"), which would re-parse as an Int and silently
                // turn float ops into integer ops. Guarantee a decimal point.
                let fs = format!("{}", f);
                let fs = if fs.contains('.') || fs.contains('e') || fs.contains('E') {
                    fs
                } else {
                    format!("{}.0", fs)
                };
                output.push_str(&format!("Let {} be a new CFloat with value {}.\n", var, fs));
            }
            Literal::Duration(nanos) => {
                let millis = nanos / 1_000_000;
                let amount_var = format!("e_{}", *counter);
                *counter += 1;
                output.push_str(&format!("Let {} be a new CInt with value {}.\n", amount_var, millis));
                output.push_str(&format!("Let {} be a new CDuration with amount {} and unit \"milliseconds\".\n", var, amount_var));
            }
            Literal::Nothing => {
                output.push_str(&format!("Let {} be a new CText with value \"nothing\".\n", var));
            }
            _ => {
                output.push_str(&format!("Let {} be a new CText with value \"unsupported\".\n", var));
            }
        },
        Expr::Identifier(sym) => {
            let name = interner.resolve(*sym);
            output.push_str(&format!("Let {} be a new CVar with name \"{}\".\n", var, name));
        }
        Expr::BinaryOp { op, left, right } => {
            let left_var = encode_expr_src(left, counter, output, interner, variants);
            let right_var = encode_expr_src(right, counter, output, interner, variants);
            let op_str = match op {
                BinaryOpKind::Add => "+",
                BinaryOpKind::Subtract => "-",
                BinaryOpKind::Multiply => "*",
                BinaryOpKind::Divide | BinaryOpKind::ExactDivide => "/",
                BinaryOpKind::FloorDivide => "//",
                BinaryOpKind::Modulo => "%",
                BinaryOpKind::Eq => "==",
                BinaryOpKind::NotEq => "!=",
                BinaryOpKind::Lt => "<",
                BinaryOpKind::Gt => ">",
                BinaryOpKind::LtEq => "<=",
                BinaryOpKind::GtEq => ">=",
                BinaryOpKind::And => "&&",
                BinaryOpKind::Or => "||",
                BinaryOpKind::Concat => "+",
                BinaryOpKind::SeqConcat => "followed by",
                BinaryOpKind::ApproxEq => "is approximately",
                BinaryOpKind::Pow => "**",
                BinaryOpKind::BitXor => "^",
                BinaryOpKind::BitAnd => "&",
                BinaryOpKind::BitOr => "|",
                BinaryOpKind::Shl => "<<",
                BinaryOpKind::Shr => ">>",
            };
            output.push_str(&format!(
                "Let {} be a new CBinOp with op \"{}\" and left {} and right {}.\n",
                var, op_str, left_var, right_var
            ));
        }
        Expr::Not { operand } => {
            let inner_var = encode_expr_src(operand, counter, output, interner, variants);
            output.push_str(&format!("Let {} be a new CNot with inner {}.\n", var, inner_var));
        }
        Expr::Call { function, args } => {
            let fn_name = interner.resolve(*function);
            if let Some(field_names) = variants.get(fn_name) {
                // Variant constructor call — encode as CNewVariant
                let names_var = format!("nvNames_{}", *counter);
                *counter += 1;
                output.push_str(&format!("Let {} be a new Seq of Text.\n", names_var));
                let vals_var = format!("nvVals_{}", *counter);
                *counter += 1;
                output.push_str(&format!("Let {} be a new Seq of CExpr.\n", vals_var));
                for (i, arg) in args.iter().enumerate() {
                    let fname = field_names.get(i).map(|s| s.as_str()).unwrap_or("value");
                    output.push_str(&format!("Push \"{}\" to {}.\n", fname, names_var));
                    let arg_var = encode_expr_src(arg, counter, output, interner, variants);
                    output.push_str(&format!("Push {} to {}.\n", arg_var, vals_var));
                }
                output.push_str(&format!(
                    "Let {} be a new CNewVariant with tag \"{}\" and fnames {} and fvals {}.\n",
                    var, fn_name, names_var, vals_var
                ));
            } else {
                let args_var = format!("callArgs_{}", *counter);
                *counter += 1;
                output.push_str(&format!("Let {} be a new Seq of CExpr.\n", args_var));
                for arg in args {
                    let arg_var = encode_expr_src(arg, counter, output, interner, variants);
                    output.push_str(&format!("Push {} to {}.\n", arg_var, args_var));
                }
                output.push_str(&format!(
                    "Let {} be a new CCall with name \"{}\" and args {}.\n",
                    var, fn_name, args_var
                ));
            }
        }
        Expr::Index { collection, index } => {
            let coll_var = encode_expr_src(collection, counter, output, interner, variants);
            let idx_var = encode_expr_src(index, counter, output, interner, variants);
            output.push_str(&format!(
                "Let {} be a new CIndex with coll {} and idx {}.\n",
                var, coll_var, idx_var
            ));
        }
        Expr::Length { collection } => {
            let coll_var = encode_expr_src(collection, counter, output, interner, variants);
            output.push_str(&format!("Let {} be a new CLen with target {}.\n", var, coll_var));
        }
        Expr::FieldAccess { object, field } => {
            let obj_var = encode_expr_src(object, counter, output, interner, variants);
            let field_name = interner.resolve(*field);
            let key_var = format!("e_{}", *counter);
            *counter += 1;
            output.push_str(&format!("Let {} be a new CText with value \"{}\".\n", key_var, field_name));
            output.push_str(&format!(
                "Let {} be a new CMapGet with target {} and key {}.\n",
                var, obj_var, key_var
            ));
        }
        Expr::NewVariant { variant, fields, .. } => {
            let variant_name = interner.resolve(*variant);
            let names_var = format!("nvNames_{}", *counter);
            *counter += 1;
            output.push_str(&format!("Let {} be a new Seq of Text.\n", names_var));
            let vals_var = format!("nvVals_{}", *counter);
            *counter += 1;
            output.push_str(&format!("Let {} be a new Seq of CExpr.\n", vals_var));
            for (field_name, field_expr) in fields {
                let fname = interner.resolve(*field_name);
                output.push_str(&format!("Push \"{}\" to {}.\n", fname, names_var));
                let field_var = encode_expr_src(field_expr, counter, output, interner, variants);
                output.push_str(&format!("Push {} to {}.\n", field_var, vals_var));
            }
            output.push_str(&format!(
                "Let {} be a new CNewVariant with tag \"{}\" and fnames {} and fvals {}.\n",
                var, variant_name, names_var, vals_var
            ));
        }
        Expr::New { type_name, init_fields, .. } => {
            let tn = interner.resolve(*type_name);
            if tn == "Seq" || tn == "List" {
                output.push_str(&format!("Let {} be a new CNewSeq.\n", var));
            } else if tn == "Set" {
                output.push_str(&format!("Let {} be a new CNewSet.\n", var));
            } else if tn == "Map" || tn.starts_with("Map ") {
                // Empty map creation — encode as CNew with "Map" type
                let names_var = format!("nvNames_{}", *counter);
                *counter += 1;
                output.push_str(&format!("Let {} be a new Seq of Text.\n", names_var));
                let vals_var = format!("nvVals_{}", *counter);
                *counter += 1;
                output.push_str(&format!("Let {} be a new Seq of CExpr.\n", vals_var));
                output.push_str(&format!(
                    "Let {} be a new CNew with typeName \"Map\" and fieldNames {} and fields {}.\n",
                    var, names_var, vals_var
                ));
            } else if init_fields.is_empty() {
                let names_var = format!("nvNames_{}", *counter);
                *counter += 1;
                output.push_str(&format!("Let {} be a new Seq of Text.\n", names_var));
                let vals_var = format!("nvVals_{}", *counter);
                *counter += 1;
                output.push_str(&format!("Let {} be a new Seq of CExpr.\n", vals_var));
                output.push_str(&format!(
                    "Let {} be a new CNewVariant with tag \"{}\" and fnames {} and fvals {}.\n",
                    var, tn, names_var, vals_var
                ));
            } else {
                let names_var = format!("nvNames_{}", *counter);
                *counter += 1;
                output.push_str(&format!("Let {} be a new Seq of Text.\n", names_var));
                let vals_var = format!("nvVals_{}", *counter);
                *counter += 1;
                output.push_str(&format!("Let {} be a new Seq of CExpr.\n", vals_var));
                for (field_name, field_expr) in init_fields {
                    let fname = interner.resolve(*field_name);
                    output.push_str(&format!("Push \"{}\" to {}.\n", fname, names_var));
                    let field_var = encode_expr_src(field_expr, counter, output, interner, variants);
                    output.push_str(&format!("Push {} to {}.\n", field_var, vals_var));
                }
                output.push_str(&format!(
                    "Let {} be a new CNewVariant with tag \"{}\" and fnames {} and fvals {}.\n",
                    var, tn, names_var, vals_var
                ));
            }
        }
        Expr::InterpolatedString(parts) => {
            if parts.is_empty() {
                output.push_str(&format!("Let {} be a new CText with value \"\".\n", var));
            } else {
                // Preserve the interpolation as a first-class CInterpolatedString — the IR,
                // PE (peExpr), decompiler, and self-interpreter (coreEval) all handle it and
                // coerce each part via valToText. Desugaring to a `+` chain was lossy: a
                // non-Text leading part produced `Int + Text`, which evalBinOp/applyBinOp do
                // not fold (→ VNothing → __unresolvable in the residual).
                let parts_var = format!("isparts_{}", *counter);
                *counter += 1;
                output.push_str(&format!("Let {} be a new Seq of CStringPart.\n", parts_var));
                for part in parts {
                    match part {
                        StringPart::Literal(sym) => {
                            let text = interner.resolve(*sym);
                            output.push_str(&format!(
                                "Push a new CLiteralPart with value \"{}\" to {}.\n", text, parts_var
                            ));
                        }
                        StringPart::Expr { value, .. } => {
                            let pv = encode_expr_src(value, counter, output, interner, variants);
                            output.push_str(&format!(
                                "Push a new CExprPart with expr {} to {}.\n", pv, parts_var
                            ));
                        }
                    }
                }
                output.push_str(&format!(
                    "Let {} be a new CInterpolatedString with parts {}.\n", var, parts_var
                ));
            }
        }
        Expr::Range { start, end } => {
            let start_var = encode_expr_src(start, counter, output, interner, variants);
            let end_var = encode_expr_src(end, counter, output, interner, variants);
            output.push_str(&format!(
                "Let {} be a new CRange with start {} and end {}.\n",
                var, start_var, end_var
            ));
        }
        Expr::Slice { collection, start, end } => {
            let coll_var = encode_expr_src(collection, counter, output, interner, variants);
            let start_var = encode_expr_src(start, counter, output, interner, variants);
            let end_var = encode_expr_src(end, counter, output, interner, variants);
            output.push_str(&format!(
                "Let {} be a new CSlice with coll {} and startIdx {} and endIdx {}.\n",
                var, coll_var, start_var, end_var
            ));
        }
        Expr::Copy { expr } => {
            let inner_var = encode_expr_src(expr, counter, output, interner, variants);
            output.push_str(&format!("Let {} be a new CCopy with target {}.\n", var, inner_var));
        }
        Expr::Contains { collection, value } => {
            let coll_var = encode_expr_src(collection, counter, output, interner, variants);
            let val_var = encode_expr_src(value, counter, output, interner, variants);
            output.push_str(&format!(
                "Let {} be a new CContains with coll {} and elem {}.\n",
                var, coll_var, val_var
            ));
        }
        Expr::Union { left, right } => {
            let left_var = encode_expr_src(left, counter, output, interner, variants);
            let right_var = encode_expr_src(right, counter, output, interner, variants);
            output.push_str(&format!(
                "Let {} be a new CUnion with left {} and right {}.\n",
                var, left_var, right_var
            ));
        }
        Expr::Intersection { left, right } => {
            let left_var = encode_expr_src(left, counter, output, interner, variants);
            let right_var = encode_expr_src(right, counter, output, interner, variants);
            output.push_str(&format!(
                "Let {} be a new CIntersection with left {} and right {}.\n",
                var, left_var, right_var
            ));
        }
        Expr::OptionSome { value } => {
            let inner_var = encode_expr_src(value, counter, output, interner, variants);
            output.push_str(&format!(
                "Let {} be a new COptionSome with inner {}.\n",
                var, inner_var
            ));
        }
        Expr::OptionNone => {
            output.push_str(&format!("Let {} be a new COptionNone.\n", var));
        }
        Expr::Tuple(elems) => {
            let items_var = format!("tupItems_{}", *counter);
            *counter += 1;
            output.push_str(&format!("Let {} be a new Seq of CExpr.\n", items_var));
            for elem in elems {
                let elem_var = encode_expr_src(elem, counter, output, interner, variants);
                output.push_str(&format!("Push {} to {}.\n", elem_var, items_var));
            }
            output.push_str(&format!(
                "Let {} be a new CTuple with items {}.\n",
                var, items_var
            ));
        }
        Expr::Closure { params, body, .. } => {
            let params_var = format!("clp_{}", *counter);
            *counter += 1;
            output.push_str(&format!("Let {} be a new Seq of Text.\n", params_var));
            let mut param_names = HashSet::new();
            for (sym, _) in params {
                let name = interner.resolve(*sym);
                param_names.insert(name.to_string());
                output.push_str(&format!("Push \"{}\" to {}.\n", name, params_var));
            }
            let body_var = format!("clb_{}", *counter);
            *counter += 1;
            output.push_str(&format!("Let {} be a new Seq of CStmt.\n", body_var));
            match body {
                ClosureBody::Expression(e) => {
                    let ret_expr = encode_expr_src(e, counter, output, interner, variants);
                    let ret_var = format!("s_{}", *counter);
                    *counter += 1;
                    output.push_str(&format!("Let {} be a new CReturn with expr {}.\n", ret_var, ret_expr));
                    output.push_str(&format!("Push {} to {}.\n", ret_var, body_var));
                }
                ClosureBody::Block(stmts) => {
                    for s in stmts.iter() {
                        let sv = encode_stmt_src(s, counter, output, interner, variants);
                        output.push_str(&format!("Push {} to {}.\n", sv, body_var));
                    }
                }
            }
            let bound: HashSet<String> = param_names;
            // Sort the captured free variables for a DETERMINISTIC encoding — a `HashSet`'s random
            // iteration order would make the wire bytes vary run-to-run (breaking content-addressing
            // AND the fast native-builder byte-identity). The capture set is order-independent
            // semantically, so sorting is a pure improvement.
            let mut free: Vec<String> = collect_free_vars_expr(expr, interner, &bound).into_iter().collect();
            free.sort();
            let cap_var = format!("clc_{}", *counter);
            *counter += 1;
            output.push_str(&format!("Let {} be a new Seq of Text.\n", cap_var));
            for fv in &free {
                output.push_str(&format!("Push \"{}\" to {}.\n", fv, cap_var));
            }
            output.push_str(&format!(
                "Let {} be a new CClosure with params {} and body {} and captured {}.\n",
                var, params_var, body_var, cap_var
            ));
        }
        Expr::CallExpr { callee, args } => {
            let callee_var = encode_expr_src(callee, counter, output, interner, variants);
            let args_var = format!("cea_{}", *counter);
            *counter += 1;
            output.push_str(&format!("Let {} be a new Seq of CExpr.\n", args_var));
            for a in args {
                let av = encode_expr_src(a, counter, output, interner, variants);
                output.push_str(&format!("Push {} to {}.\n", av, args_var));
            }
            output.push_str(&format!(
                "Let {} be a new CCallExpr with target {} and args {}.\n",
                var, callee_var, args_var
            ));
        }
        Expr::Give { value } => {
            let inner_var = encode_expr_src(value, counter, output, interner, variants);
            output.push_str(&format!("Let {} be {}.\n", var, inner_var));
        }
        Expr::Escape { code, .. } => {
            let code_str = interner.resolve(*code);
            output.push_str(&format!(
                "Let {} be a new CEscExpr with code \"{}\".\n",
                var, code_str.replace('\"', "\\\"")
            ));
        }
        Expr::List(elems) => {
            let items_var = format!("litems_{}", *counter);
            *counter += 1;
            output.push_str(&format!("Let {} be a new Seq of CExpr.\n", items_var));
            for elem in elems {
                let elem_var = encode_expr_src(elem, counter, output, interner, variants);
                output.push_str(&format!("Push {} to {}.\n", elem_var, items_var));
            }
            output.push_str(&format!(
                "Let {} be a new CList with items {}.\n",
                var, items_var
            ));
        }
        Expr::ManifestOf { zone } => {
            let zone_var = encode_expr_src(zone, counter, output, interner, variants);
            output.push_str(&format!(
                "Let {} be a new CManifestOf with zn {}.\n",
                var, zone_var
            ));
        }
        Expr::ChunkAt { index, zone } => {
            let idx_var = encode_expr_src(index, counter, output, interner, variants);
            let zone_var = encode_expr_src(zone, counter, output, interner, variants);
            output.push_str(&format!(
                "Let {} be a new CChunkAt with idx {} and zn {}.\n",
                var, idx_var, zone_var
            ));
        }
        Expr::WithCapacity { value, .. } => {
            // Capacity is an allocation hint with no runtime semantics (the interpreter ignores
            // it). Encode the inner value directly so the residual carries the value, not the
            // erased hint — no Core-IR node needed.
            return encode_expr_src(value, counter, output, interner, variants);
        }
        _ => {
            output.push_str(&format!("Let {} be a new CText with value \"unsupported\".\n", var));
        }
    }

    var
}

fn encode_stmt_src(stmt: &Stmt, counter: &mut usize, output: &mut String, interner: &Interner, variants: &HashMap<String, Vec<String>>) -> String {
    let var = format!("s_{}", *counter);
    *counter += 1;

    match stmt {
        Stmt::Let { var: name, value, .. } => {
            let name_str = interner.resolve(*name);
            let expr_var = encode_expr_src(value, counter, output, interner, variants);
            output.push_str(&format!(
                "Let {} be a new CLet with name \"{}\" and expr {}.\n",
                var, name_str, expr_var
            ));
        }
        Stmt::Set { target, value } => {
            let name_str = interner.resolve(*target);
            let expr_var = encode_expr_src(value, counter, output, interner, variants);
            output.push_str(&format!(
                "Let {} be a new CSet with name \"{}\" and expr {}.\n",
                var, name_str, expr_var
            ));
        }
        Stmt::If { cond, then_block, else_block } => {
            let cond_var = encode_expr_src(cond, counter, output, interner, variants);
            let then_stmts: Vec<&Stmt> = then_block.iter().collect();
            let then_var = encode_stmt_list_src(&then_stmts, counter, output, interner, variants);
            let else_var = if let Some(els) = else_block {
                let else_stmts: Vec<&Stmt> = els.iter().collect();
                encode_stmt_list_src(&else_stmts, counter, output, interner, variants)
            } else {
                let empty_var = format!("emptyBlock_{}", *counter);
                *counter += 1;
                output.push_str(&format!("Let {} be a new Seq of CStmt.\n", empty_var));
                empty_var
            };
            output.push_str(&format!(
                "Let {} be a new CIf with cond {} and thenBlock {} and elseBlock {}.\n",
                var, cond_var, then_var, else_var
            ));
        }
        Stmt::While { cond, body, .. } => {
            let cond_var = encode_expr_src(cond, counter, output, interner, variants);
            let body_stmts: Vec<&Stmt> = body.iter().collect();
            let body_var = encode_stmt_list_src(&body_stmts, counter, output, interner, variants);
            output.push_str(&format!(
                "Let {} be a new CWhile with cond {} and body {}.\n",
                var, cond_var, body_var
            ));
        }
        Stmt::Splice { body } => {
            // A Splice encodes as an always-taken CIf: observationally
            // equivalent, because every desugar temporary is both defined and
            // consumed inside the body — no new pe_source node needed.
            let cond_var = format!("splice_cond_{}", *counter);
            *counter += 1;
            output.push_str(&format!("Let {} be a new CBool with value true.\n", cond_var));
            let body_stmts: Vec<&Stmt> = body.iter().collect();
            let body_var = encode_stmt_list_src(&body_stmts, counter, output, interner, variants);
            let empty_var = format!("emptyBlock_{}", *counter);
            *counter += 1;
            output.push_str(&format!("Let {} be a new Seq of CStmt.\n", empty_var));
            output.push_str(&format!(
                "Let {} be a new CIf with cond {} and thenBlock {} and elseBlock {}.\n",
                var, cond_var, body_var, empty_var
            ));
        }
        Stmt::Return { value } => {
            if let Some(expr) = value {
                let expr_var = encode_expr_src(expr, counter, output, interner, variants);
                output.push_str(&format!("Let {} be a new CReturn with expr {}.\n", var, expr_var));
            } else {
                let nothing_var = format!("e_{}", *counter);
                *counter += 1;
                output.push_str(&format!("Let {} be a new CInt with value 0.\n", nothing_var));
                output.push_str(&format!("Let {} be a new CReturn with expr {}.\n", var, nothing_var));
            }
        }
        Stmt::Show { object, .. } => {
            let expr_var = encode_expr_src(object, counter, output, interner, variants);
            output.push_str(&format!("Let {} be a new CShow with expr {}.\n", var, expr_var));
        }
        Stmt::Call { function, args } => {
            let fn_name = interner.resolve(*function);
            let args_var = format!("callSArgs_{}", *counter);
            *counter += 1;
            output.push_str(&format!("Let {} be a new Seq of CExpr.\n", args_var));
            for arg in args {
                let arg_var = encode_expr_src(arg, counter, output, interner, variants);
                output.push_str(&format!("Push {} to {}.\n", arg_var, args_var));
            }
            output.push_str(&format!(
                "Let {} be a new CCallS with name \"{}\" and args {}.\n",
                var, fn_name, args_var
            ));
        }
        Stmt::Push { value, collection } => {
            let val_var = encode_expr_src(value, counter, output, interner, variants);
            let coll_name = extract_ident_name(collection, interner);
            output.push_str(&format!(
                "Let {} be a new CPush with expr {} and target \"{}\".\n",
                var, val_var, coll_name
            ));
        }
        Stmt::SetIndex { collection, index, value } => {
            let coll_name = extract_ident_name(collection, interner);
            let idx_var = encode_expr_src(index, counter, output, interner, variants);
            let val_var = encode_expr_src(value, counter, output, interner, variants);
            output.push_str(&format!(
                "Let {} be a new CSetIdx with target \"{}\" and idx {} and val {}.\n",
                var, coll_name, idx_var, val_var
            ));
        }
        Stmt::SetField { object, field, value } => {
            let map_name = extract_ident_name(object, interner);
            let field_name = interner.resolve(*field);
            let key_var = format!("e_{}", *counter);
            *counter += 1;
            output.push_str(&format!("Let {} be a new CText with value \"{}\".\n", key_var, field_name));
            let val_var = encode_expr_src(value, counter, output, interner, variants);
            output.push_str(&format!(
                "Let {} be a new CMapSet with target \"{}\" and key {} and val {}.\n",
                var, map_name, key_var, val_var
            ));
        }
        Stmt::Pop { collection, .. } => {
            let coll_name = extract_ident_name(collection, interner);
            output.push_str(&format!(
                "Let {} be a new CPop with target \"{}\".\n",
                var, coll_name
            ));
        }
        Stmt::Add { value, collection } => {
            let val_var = encode_expr_src(value, counter, output, interner, variants);
            let coll_name = extract_ident_name(collection, interner);
            output.push_str(&format!(
                "Let {} be a new CAdd with elem {} and target \"{}\".\n",
                var, val_var, coll_name
            ));
        }
        Stmt::Remove { value, collection } => {
            let val_var = encode_expr_src(value, counter, output, interner, variants);
            let coll_name = extract_ident_name(collection, interner);
            output.push_str(&format!(
                "Let {} be a new CRemove with elem {} and target \"{}\".\n",
                var, val_var, coll_name
            ));
        }
        Stmt::Inspect { .. } => {
            return String::new(); // Handled by encode_stmts_src
        }
        Stmt::Repeat { .. } => {
            return String::new(); // Handled by encode_stmts_src
        }
        Stmt::Break => {
            output.push_str(&format!("Let {} be a new CBreak.\n", var));
        }
        Stmt::RuntimeAssert { condition, hard } => {
            let cond_var = encode_expr_src(condition, counter, output, interner, variants);
            let msg_var = format!("e_{}", *counter);
            *counter += 1;
            output.push_str(&format!("Let {} be a new CText with value \"assertion failed\".\n", msg_var));
            // `Require that` (hard) encodes as a distinct CStmt variant `CHardAssert`
            // (NOT `CRequire`, which is the `## Requires` dependency directive) so the
            // self-encoding round-trip preserves the enforced/dev distinction.
            let variant = if *hard { "CHardAssert" } else { "CRuntimeAssert" };
            output.push_str(&format!(
                "Let {} be a new {} with cond {} and msg {}.\n",
                var, variant, cond_var, msg_var
            ));
        }
        Stmt::Give { object, recipient } => {
            let expr_var = encode_expr_src(object, counter, output, interner, variants);
            let target_name = extract_ident_name(recipient, interner);
            output.push_str(&format!(
                "Let {} be a new CGive with expr {} and target \"{}\".\n",
                var, expr_var, target_name
            ));
        }
        Stmt::Escape { code, .. } => {
            let code_str = interner.resolve(*code);
            output.push_str(&format!(
                "Let {} be a new CEscStmt with code \"{}\".\n",
                var, code_str.replace('\"', "\\\"")
            ));
        }
        Stmt::Sleep { milliseconds } => {
            let dur_var = encode_expr_src(milliseconds, counter, output, interner, variants);
            output.push_str(&format!(
                "Let {} be a new CSleep with duration {}.\n",
                var, dur_var
            ));
        }
        Stmt::ReadFrom { var: read_var, source } => {
            let var_name = interner.resolve(*read_var);
            match source {
                ReadSource::Console => {
                    output.push_str(&format!(
                        "Let {} be a new CReadConsole with target \"{}\".\n",
                        var, var_name
                    ));
                }
                ReadSource::File(path_expr) => {
                    let path_var = encode_expr_src(path_expr, counter, output, interner, variants);
                    output.push_str(&format!(
                        "Let {} be a new CReadFile with path {} and target \"{}\".\n",
                        var, path_var, var_name
                    ));
                }
            }
        }
        Stmt::WriteFile { content, path } => {
            let path_var = encode_expr_src(path, counter, output, interner, variants);
            let content_var = encode_expr_src(content, counter, output, interner, variants);
            output.push_str(&format!(
                "Let {} be a new CWriteFile with path {} and content {}.\n",
                var, path_var, content_var
            ));
        }
        Stmt::Check { source_text, .. } => {
            let pred_var = format!("e_{}", *counter);
            *counter += 1;
            output.push_str(&format!("Let {} be a new CBool with value true.\n", pred_var));
            let msg_var = format!("e_{}", *counter);
            *counter += 1;
            output.push_str(&format!("Let {} be a new CText with value \"{}\".\n", msg_var, source_text.replace('\"', "\\\"")));
            output.push_str(&format!(
                "Let {} be a new CCheck with predicate {} and msg {}.\n",
                var, pred_var, msg_var
            ));
        }
        Stmt::Assert { .. } => {
            let prop_var = format!("e_{}", *counter);
            *counter += 1;
            output.push_str(&format!("Let {} be a new CBool with value true.\n", prop_var));
            output.push_str(&format!(
                "Let {} be a new CAssert with proposition {}.\n",
                var, prop_var
            ));
        }
        Stmt::Trust { justification, .. } => {
            let prop_var = format!("e_{}", *counter);
            *counter += 1;
            output.push_str(&format!("Let {} be a new CBool with value true.\n", prop_var));
            let just_str = interner.resolve(*justification);
            output.push_str(&format!(
                "Let {} be a new CTrust with proposition {} and justification \"{}\".\n",
                var, prop_var, just_str
            ));
        }
        Stmt::Require { crate_name, .. } => {
            let dep_name = interner.resolve(*crate_name);
            output.push_str(&format!(
                "Let {} be a new CRequire with dependency \"{}\".\n",
                var, dep_name
            ));
        }
        Stmt::MergeCrdt { source, target } => {
            let source_var = encode_expr_src(source, counter, output, interner, variants);
            // The target may be a struct (`a`) or a struct field (`local's active`); both
            // round-trip as surface syntax.
            let target_name = extract_ident_name(target, interner);
            output.push_str(&format!(
                "Let {} be a new CMerge with target \"{}\" and other {}.\n",
                var, target_name, source_var
            ));
        }
        Stmt::IncreaseCrdt { object, field, amount } => {
            let amount_var = encode_expr_src(amount, counter, output, interner, variants);
            // `Increase c's points` — the target is the FIELD, so carry both the object and
            // the field name (the residual must say `Increase c's points`, not `Increase c`).
            let target_name =
                format!("{}'s {}", extract_ident_name(object, interner), interner.resolve(*field));
            output.push_str(&format!(
                "Let {} be a new CIncrease with target \"{}\" and amount {}.\n",
                var, target_name, amount_var
            ));
        }
        Stmt::DecreaseCrdt { object, field, amount } => {
            let amount_var = encode_expr_src(amount, counter, output, interner, variants);
            let target_name =
                format!("{}'s {}", extract_ident_name(object, interner), interner.resolve(*field));
            output.push_str(&format!(
                "Let {} be a new CDecrease with target \"{}\" and amount {}.\n",
                var, target_name, amount_var
            ));
        }
        Stmt::AppendToSequence { sequence, value } => {
            let value_var = encode_expr_src(value, counter, output, interner, variants);
            let target_name = extract_ident_name(sequence, interner);
            output.push_str(&format!(
                "Let {} be a new CAppendToSeq with target \"{}\" and value {}.\n",
                var, target_name, value_var
            ));
        }
        Stmt::ResolveConflict { object, field, .. } => {
            let target_name =
                format!("{}'s {}", extract_ident_name(object, interner), interner.resolve(*field));
            output.push_str(&format!(
                "Let {} be a new CResolve with target \"{}\".\n",
                var, target_name
            ));
        }
        Stmt::Sync { var: sync_var, topic } => {
            let topic_var = encode_expr_src(topic, counter, output, interner, variants);
            let var_name = interner.resolve(*sync_var);
            output.push_str(&format!(
                "Let {} be a new CSync with target \"{}\" and channel {}.\n",
                var, var_name, topic_var
            ));
        }
        Stmt::Mount { var: mount_var, path } => {
            let path_var = encode_expr_src(path, counter, output, interner, variants);
            let var_name = interner.resolve(*mount_var);
            output.push_str(&format!(
                "Let {} be a new CMount with target \"{}\" and path {}.\n",
                var, var_name, path_var
            ));
        }
        Stmt::Concurrent { tasks } => {
            let branches_var = format!("e_{}", *counter);
            *counter += 1;
            output.push_str(&format!("Let {} be a new Seq of Seq of CStmt.\n", branches_var));
            // One inner branch per task — collapsing them loses the per-task
            // branch structure the executor / PE handlers iterate over.
            for stmt in tasks.iter() {
                let branch_var = format!("e_{}", *counter);
                *counter += 1;
                output.push_str(&format!("Let {} be a new Seq of CStmt.\n", branch_var));
                let sv = encode_stmt_src(stmt, counter, output, interner, variants);
                if !sv.is_empty() {
                    output.push_str(&format!("Push {} to {}.\n", sv, branch_var));
                }
                output.push_str(&format!("Push {} to {}.\n", branch_var, branches_var));
            }
            output.push_str(&format!(
                "Let {} be a new CConcurrent with branches {}.\n",
                var, branches_var
            ));
        }
        Stmt::Parallel { tasks } => {
            let branches_var = format!("e_{}", *counter);
            *counter += 1;
            output.push_str(&format!("Let {} be a new Seq of Seq of CStmt.\n", branches_var));
            // One inner branch per task (see Concurrent above).
            for stmt in tasks.iter() {
                let branch_var = format!("e_{}", *counter);
                *counter += 1;
                output.push_str(&format!("Let {} be a new Seq of CStmt.\n", branch_var));
                let sv = encode_stmt_src(stmt, counter, output, interner, variants);
                if !sv.is_empty() {
                    output.push_str(&format!("Push {} to {}.\n", sv, branch_var));
                }
                output.push_str(&format!("Push {} to {}.\n", branch_var, branches_var));
            }
            output.push_str(&format!(
                "Let {} be a new CParallel with branches {}.\n",
                var, branches_var
            ));
        }
        Stmt::LaunchTask { function, args } | Stmt::LaunchTaskWithHandle { function, args, .. } => {
            let func_name = interner.resolve(*function);
            let args_var = format!("e_{}", *counter);
            *counter += 1;
            output.push_str(&format!("Let {} be a new Seq of CExpr.\n", args_var));
            for arg in args {
                let av = encode_expr_src(arg, counter, output, interner, variants);
                output.push_str(&format!("Push {} to {}.\n", av, args_var));
            }
            let body_var = format!("e_{}", *counter);
            *counter += 1;
            output.push_str(&format!("Let {} be a new Seq of CStmt.\n", body_var));
            let call_var = format!("e_{}", *counter);
            *counter += 1;
            output.push_str(&format!(
                "Let {} be a new CCallS with name \"{}\" and args {}.\n",
                call_var, func_name, args_var
            ));
            output.push_str(&format!("Push {} to {}.\n", call_var, body_var));
            let handle_name = if let Stmt::LaunchTaskWithHandle { handle, .. } = stmt {
                interner.resolve(*handle).to_string()
            } else {
                "_task".to_string()
            };
            output.push_str(&format!(
                "Let {} be a new CLaunchTask with body {} and handle \"{}\".\n",
                var, body_var, handle_name
            ));
        }
        Stmt::StopTask { handle } => {
            let handle_var = encode_expr_src(handle, counter, output, interner, variants);
            output.push_str(&format!(
                "Let {} be a new CStopTask with handle {}.\n",
                var, handle_var
            ));
        }
        Stmt::CreatePipe { var: pipe_var, capacity, .. } => {
            let cap = capacity.unwrap_or(32);
            let cap_var = format!("e_{}", *counter);
            *counter += 1;
            output.push_str(&format!("Let {} be a new CInt with value {}.\n", cap_var, cap));
            let pipe_name = interner.resolve(*pipe_var);
            output.push_str(&format!(
                "Let {} be a new CCreatePipe with name \"{}\" and capacity {}.\n",
                var, pipe_name, cap_var
            ));
        }
        Stmt::SendPipe { value, pipe } => {
            let val_var = encode_expr_src(value, counter, output, interner, variants);
            let pipe_name = match pipe {
                Expr::Identifier(sym) => interner.resolve(*sym).to_string(),
                _ => "pipe".to_string(),
            };
            output.push_str(&format!(
                "Let {} be a new CSendPipe with chan \"{}\" and value {}.\n",
                var, pipe_name, val_var
            ));
        }
        Stmt::ReceivePipe { var: recv_var, pipe } => {
            let recv_name = interner.resolve(*recv_var);
            let pipe_name = match pipe {
                Expr::Identifier(sym) => interner.resolve(*sym).to_string(),
                _ => "pipe".to_string(),
            };
            output.push_str(&format!(
                "Let {} be a new CReceivePipe with chan \"{}\" and target \"{}\".\n",
                var, pipe_name, recv_name
            ));
        }
        Stmt::TrySendPipe { value, pipe, .. } => {
            let val_var = encode_expr_src(value, counter, output, interner, variants);
            let pipe_name = match pipe {
                Expr::Identifier(sym) => interner.resolve(*sym).to_string(),
                _ => "pipe".to_string(),
            };
            output.push_str(&format!(
                "Let {} be a new CTrySendPipe with chan \"{}\" and value {}.\n",
                var, pipe_name, val_var
            ));
        }
        Stmt::TryReceivePipe { var: recv_var, pipe } => {
            let recv_name = interner.resolve(*recv_var);
            let pipe_name = match pipe {
                Expr::Identifier(sym) => interner.resolve(*sym).to_string(),
                _ => "pipe".to_string(),
            };
            output.push_str(&format!(
                "Let {} be a new CTryReceivePipe with chan \"{}\" and target \"{}\".\n",
                var, pipe_name, recv_name
            ));
        }
        Stmt::Select { branches } => {
            let branches_var = format!("e_{}", *counter);
            *counter += 1;
            output.push_str(&format!("Let {} be a new Seq of CSelectBranch.\n", branches_var));
            for branch in branches {
                match branch {
                    SelectBranch::Receive { var: recv_var, pipe, body } => {
                        let recv_name = interner.resolve(*recv_var);
                        let pipe_name = match pipe {
                            Expr::Identifier(sym) => interner.resolve(*sym).to_string(),
                            _ => "pipe".to_string(),
                        };
                        let body_var = format!("e_{}", *counter);
                        *counter += 1;
                        output.push_str(&format!("Let {} be a new Seq of CStmt.\n", body_var));
                        for stmt in body.iter() {
                            let sv = encode_stmt_src(stmt, counter, output, interner, variants);
                            if !sv.is_empty() {
                                output.push_str(&format!("Push {} to {}.\n", sv, body_var));
                            }
                        }
                        let branch_var = format!("e_{}", *counter);
                        *counter += 1;
                        output.push_str(&format!(
                            "Let {} be a new CSelectRecv with chan \"{}\" and var \"{}\" and body {}.\n",
                            branch_var, pipe_name, recv_name, body_var
                        ));
                        output.push_str(&format!("Push {} to {}.\n", branch_var, branches_var));
                    }
                    SelectBranch::Timeout { milliseconds, body } => {
                        let dur_var = encode_expr_src(milliseconds, counter, output, interner, variants);
                        let body_var = format!("e_{}", *counter);
                        *counter += 1;
                        output.push_str(&format!("Let {} be a new Seq of CStmt.\n", body_var));
                        for stmt in body.iter() {
                            let sv = encode_stmt_src(stmt, counter, output, interner, variants);
                            if !sv.is_empty() {
                                output.push_str(&format!("Push {} to {}.\n", sv, body_var));
                            }
                        }
                        let branch_var = format!("e_{}", *counter);
                        *counter += 1;
                        output.push_str(&format!(
                            "Let {} be a new CSelectTimeout with duration {} and body {}.\n",
                            branch_var, dur_var, body_var
                        ));
                        output.push_str(&format!("Push {} to {}.\n", branch_var, branches_var));
                    }
                }
            }
            output.push_str(&format!(
                "Let {} be a new CSelect with branches {}.\n",
                var, branches_var
            ));
        }
        Stmt::Spawn { agent_type, name } => {
            let agent_name = interner.resolve(*agent_type);
            let target_name = interner.resolve(*name);
            output.push_str(&format!(
                "Let {} be a new CSpawn with agentType \"{}\" and target \"{}\".\n",
                var, agent_name, target_name
            ));
        }
        Stmt::SendMessage { message, destination, .. } => {
            let target_var = encode_expr_src(destination, counter, output, interner, variants);
            let msg_var = encode_expr_src(message, counter, output, interner, variants);
            output.push_str(&format!(
                "Let {} be a new CSendMessage with target {} and msg {}.\n",
                var, target_var, msg_var
            ));
        }
        // A batch stream send is encoded for the projection-1 self-interpreter exactly like a send,
        // so it is NEVER dropped from the residual (the catch-all would silently drop it). The PE
        // dialects pass it through unchanged — networking is opaque to specialization.
        Stmt::StreamMessage { values, destination } => {
            let target_var = encode_expr_src(destination, counter, output, interner, variants);
            let vals_var = encode_expr_src(values, counter, output, interner, variants);
            output.push_str(&format!(
                "Let {} be a new CStreamMessage with target {} and values {}.\n",
                var, target_var, vals_var
            ));
        }
        Stmt::AwaitMessage { into, .. } => {
            let await_name = interner.resolve(*into);
            output.push_str(&format!(
                "Let {} be a new CAwaitMessage with target \"{}\".\n",
                var, await_name
            ));
        }
        // The PNP `secure` binding is not modeled by the partial-evaluation self-interpreter (a
        // PNP program is a live-networking program, not a PE target); the address encoding is unchanged.
        Stmt::Listen { address, secure: _ } => {
            let addr_var = encode_expr_src(address, counter, output, interner, variants);
            output.push_str(&format!(
                "Let {} be a new CListen with addr {} and handler \"default\".\n",
                var, addr_var
            ));
        }
        Stmt::ConnectTo { address, secure: _ } => {
            let addr_var = encode_expr_src(address, counter, output, interner, variants);
            output.push_str(&format!(
                "Let {} be a new CConnectTo with addr {} and target \"conn\".\n",
                var, addr_var
            ));
        }
        Stmt::Zone { name, body, .. } => {
            let zone_name = interner.resolve(*name);
            let body_var = format!("e_{}", *counter);
            *counter += 1;
            output.push_str(&format!("Let {} be a new Seq of CStmt.\n", body_var));
            for stmt in body.iter() {
                let sv = encode_stmt_src(stmt, counter, output, interner, variants);
                if !sv.is_empty() {
                    output.push_str(&format!("Push {} to {}.\n", sv, body_var));
                }
            }
            output.push_str(&format!(
                "Let {} be a new CZone with name \"{}\" and kind \"heap\" and body {}.\n",
                var, zone_name, body_var
            ));
        }
        Stmt::LetPeerAgent { var: pa_var, address } => {
            let addr_var = encode_expr_src(address, counter, output, interner, variants);
            let pa_name = interner.resolve(*pa_var);
            output.push_str(&format!(
                "Let {} be a new CConnectTo with addr {} and target \"{}\".\n",
                var, addr_var, pa_name
            ));
        }
        // ── DECLARATIONS — no projection-1 BODY encoding (intentionally empty) ──
        // These are handled at the PROGRAM level, not as body statements: functions are encoded into
        // `encodedFuncMap` as `CFuncDef`; struct/type declarations live in the type catalog; theorems
        // and definitions are proof-layer only, with no runtime effect to specialize. They contribute
        // nothing to a statement body.
        //
        // ⚠️  THIS MATCH IS EXHAUSTIVE ON PURPOSE — there is NO `_` wildcard. ⚠️  Every one of the 52
        // EXECUTABLE statements above has a real encoding arm, and these 4 declarations are the only
        // ones that encode to nothing. Adding a new statement to `Stmt` will FAIL TO COMPILE here
        // until it is given an explicit arm — so a statement can NEVER be silently dropped from the
        // Futamura projection again (this is exactly how the CStreamMessage drop hid). Do not "fix" a
        // build break here by re-adding a `_ =>` wildcard; add the statement's real encoding instead.
        Stmt::FunctionDef { .. }
        | Stmt::StructDef { .. }
        | Stmt::Theorem(_)
        | Stmt::Definition(_)
        | Stmt::Axiom(_)
        | Stmt::Theory(_) => {
            return String::new();
        }
    }

    var
}

fn encode_stmts_src(stmt: &Stmt, counter: &mut usize, output: &mut String, interner: &Interner, variants: &HashMap<String, Vec<String>>) -> Vec<String> {
    match stmt {
        Stmt::Inspect { target, arms, .. } => {
            let mut otherwise_stmts: Vec<&Stmt> = Vec::new();
            let mut variant_arms: Vec<(&MatchArm, Vec<&Stmt>)> = Vec::new();

            for arm in arms {
                if arm.variant.is_none() {
                    otherwise_stmts = arm.body.iter().collect();
                } else {
                    let body_refs: Vec<&Stmt> = arm.body.iter().collect();
                    variant_arms.push((arm, body_refs));
                }
            }

            if variant_arms.is_empty() {
                let mut result = Vec::new();
                for s in &otherwise_stmts {
                    for v in encode_stmts_src(s, counter, output, interner, variants) {
                        result.push(v);
                    }
                }
                return result;
            }

            // Flat CIf encoding: each arm becomes an independent CIf with empty else.
            // Since Inspect arms are mutually exclusive (exactly one tag matches),
            // flat CIf is semantically equivalent to nested CIf chains but avoids
            // deep nesting that the interpreter's inline CIf handler can't navigate.
            let has_otherwise = !otherwise_stmts.is_empty();
            let mut result = Vec::new();

            // If there's an Otherwise block, track whether any arm matched
            let matched_var_name = if has_otherwise {
                // The flag name uses the DETERMINISTIC per-program Inspect-Otherwise index (shared with
                // the native builder), NOT the global intermediate counter — so the fast builder can
                // reproduce this desugaring byte-for-byte. The `counter` bump is kept so every OTHER
                // (source-only, non-wire) intermediate name downstream is unchanged.
                let name = format!("__inspectMatched_{}", next_inspect_otherwise_idx());
                *counter += 1;
                let false_expr = format!("e_{}", *counter);
                *counter += 1;
                output.push_str(&format!("Let {} be a new CBool with value false.\n", false_expr));
                let let_stmt = format!("s_{}", *counter);
                *counter += 1;
                output.push_str(&format!(
                    "Let {} be a new CLet with name \"{}\" and expr {}.\n",
                    let_stmt, name, false_expr
                ));
                result.push(let_stmt);
                Some(name)
            } else {
                None
            };

            // Each variant arm becomes: CIf(tag == "Variant", [bindings + body], [])
            for (arm, body_stmts) in &variant_arms {
                let variant_name = interner.resolve(arm.variant.unwrap());

                // Condition: tag == "VariantName"
                let tag_target = encode_expr_src(target, counter, output, interner, variants);
                let tag_key = format!("e_{}", *counter);
                *counter += 1;
                output.push_str(&format!("Let {} be a new CText with value \"__tag\".\n", tag_key));
                let tag_get = format!("e_{}", *counter);
                *counter += 1;
                output.push_str(&format!(
                    "Let {} be a new CMapGet with target {} and key {}.\n",
                    tag_get, tag_target, tag_key
                ));
                let variant_text = format!("e_{}", *counter);
                *counter += 1;
                output.push_str(&format!("Let {} be a new CText with value \"{}\".\n", variant_text, variant_name));
                let cond_var = format!("e_{}", *counter);
                *counter += 1;
                output.push_str(&format!(
                    "Let {} be a new CBinOp with op \"==\" and left {} and right {}.\n",
                    cond_var, tag_get, variant_text
                ));

                // Then-block: [optionally set matched flag, bindings, body]
                let then_list = format!("stmtList_{}", *counter);
                *counter += 1;
                output.push_str(&format!("Let {} be a new Seq of CStmt.\n", then_list));

                // Set matched flag if needed
                if let Some(ref mname) = matched_var_name {
                    let true_expr = format!("e_{}", *counter);
                    *counter += 1;
                    output.push_str(&format!("Let {} be a new CBool with value true.\n", true_expr));
                    let set_stmt = format!("s_{}", *counter);
                    *counter += 1;
                    output.push_str(&format!(
                        "Let {} be a new CSet with name \"{}\" and expr {}.\n",
                        set_stmt, mname, true_expr
                    ));
                    output.push_str(&format!("Push {} to {}.\n", set_stmt, then_list));
                }

                // Bindings
                for (field_name, binding_name) in &arm.bindings {
                    let field_str = interner.resolve(*field_name);
                    let bind_str = interner.resolve(*binding_name);
                    let bind_target = encode_expr_src(target, counter, output, interner, variants);
                    let fkey = format!("e_{}", *counter);
                    *counter += 1;
                    output.push_str(&format!("Let {} be a new CText with value \"{}\".\n", fkey, field_str));
                    let fget = format!("e_{}", *counter);
                    *counter += 1;
                    output.push_str(&format!(
                        "Let {} be a new CMapGet with target {} and key {}.\n",
                        fget, bind_target, fkey
                    ));
                    let bind_let = format!("s_{}", *counter);
                    *counter += 1;
                    output.push_str(&format!(
                        "Let {} be a new CLet with name \"{}\" and expr {}.\n",
                        bind_let, bind_str, fget
                    ));
                    output.push_str(&format!("Push {} to {}.\n", bind_let, then_list));
                }

                // Body statements (use encode_stmts_src for Inspect/Repeat)
                for body_stmt in body_stmts {
                    match body_stmt {
                        Stmt::Inspect { .. } | Stmt::Repeat { .. } => {
                            let vars = encode_stmts_src(body_stmt, counter, output, interner, variants);
                            for v in vars {
                                output.push_str(&format!("Push {} to {}.\n", v, then_list));
                            }
                        }
                        _ => {
                            let bvar = encode_stmt_src(body_stmt, counter, output, interner, variants);
                            if !bvar.is_empty() {
                                output.push_str(&format!("Push {} to {}.\n", bvar, then_list));
                            }
                        }
                    }
                }

                // Empty else block
                let empty_else = format!("stmtList_{}", *counter);
                *counter += 1;
                output.push_str(&format!("Let {} be a new Seq of CStmt.\n", empty_else));

                // CIf node
                let if_var = format!("s_{}", *counter);
                *counter += 1;
                output.push_str(&format!(
                    "Let {} be a new CIf with cond {} and thenBlock {} and elseBlock {}.\n",
                    if_var, cond_var, then_list, empty_else
                ));

                result.push(if_var);
            }

            // Otherwise: CIf(CNot(__inspectMatched), otherwise_body, [])
            if let Some(ref mname) = matched_var_name {
                let matched_ref = format!("e_{}", *counter);
                *counter += 1;
                output.push_str(&format!("Let {} be a new CVar with name \"{}\".\n", matched_ref, mname));
                let not_matched = format!("e_{}", *counter);
                *counter += 1;
                output.push_str(&format!("Let {} be a new CNot with inner {}.\n", not_matched, matched_ref));

                let otherwise_block = encode_stmt_list_src(&otherwise_stmts, counter, output, interner, variants);
                let empty_else = format!("stmtList_{}", *counter);
                *counter += 1;
                output.push_str(&format!("Let {} be a new Seq of CStmt.\n", empty_else));

                let otherwise_if = format!("s_{}", *counter);
                *counter += 1;
                output.push_str(&format!(
                    "Let {} be a new CIf with cond {} and thenBlock {} and elseBlock {}.\n",
                    otherwise_if, not_matched, otherwise_block, empty_else
                ));
                result.push(otherwise_if);
            }

            result
        }
        Stmt::Repeat { pattern, iterable, body, .. } => {
            let loop_var_name = match pattern {
                Pattern::Identifier(sym) => interner.resolve(*sym).to_string(),
                Pattern::Tuple(syms) => {
                    if let Some(s) = syms.first() {
                        interner.resolve(*s).to_string()
                    } else {
                        "item".to_string()
                    }
                }
            };

            // Range-based repeat: encode as CRepeatRange
            if let Expr::Range { start, end } = iterable {
                let start_var = encode_expr_src(start, counter, output, interner, variants);
                let end_var = encode_expr_src(end, counter, output, interner, variants);
                let body_stmts: Vec<&Stmt> = body.iter().collect();
                let body_var = encode_stmt_list_src(&body_stmts, counter, output, interner, variants);
                let rr = format!("s_{}", *counter);
                *counter += 1;
                output.push_str(&format!(
                    "Let {} be a new CRepeatRange with var \"{}\" and start {} and end {} and body {}.\n",
                    rr, loop_var_name, start_var, end_var, body_var
                ));
                return vec![rr];
            }

            // Collection-based repeat: encode as CRepeat
            let coll_var = encode_expr_src(iterable, counter, output, interner, variants);
            let body_stmts: Vec<&Stmt> = body.iter().collect();
            let body_var = encode_stmt_list_src(&body_stmts, counter, output, interner, variants);
            let rep = format!("s_{}", *counter);
            *counter += 1;
            output.push_str(&format!(
                "Let {} be a new CRepeat with var \"{}\" and coll {} and body {}.\n",
                rep, loop_var_name, coll_var, body_var
            ));
            vec![rep]
        }
        // A CRDT op through a struct field (`Add x to p's guests`, `Append x to d's lines`)
        // — force the base struct dynamic FIRST, so the PE doesn't statically fold a struct
        // it then mutates, then emit the op itself.
        Stmt::Add { collection, .. }
        | Stmt::Remove { collection, .. }
        | Stmt::AppendToSequence { sequence: collection, .. } => {
            let mut result = Vec::new();
            if let Some(fd) = emit_force_dynamic(collection, counter, output, interner) {
                result.push(fd);
            }
            let v = encode_stmt_src(stmt, counter, output, interner, variants);
            if !v.is_empty() {
                result.push(v);
            }
            result
        }
        // A CRDT op that mutates the WHOLE struct (`Increase c's score`, `Merge b into a`) —
        // force the struct's root variable dynamic first, so the PE doesn't fold a counter /
        // register it then mutates.
        Stmt::IncreaseCrdt { object, .. }
        | Stmt::DecreaseCrdt { object, .. }
        | Stmt::ResolveConflict { object, .. }
        | Stmt::MergeCrdt { target: object, .. } => {
            let mut result = Vec::new();
            if let Some(fd) = emit_force_dynamic_struct(object, counter, output, interner) {
                result.push(fd);
            }
            let v = encode_stmt_src(stmt, counter, output, interner, variants);
            if !v.is_empty() {
                result.push(v);
            }
            result
        }
        _ => {
            let v = encode_stmt_src(stmt, counter, output, interner, variants);
            if v.is_empty() {
                vec![]
            } else {
                vec![v]
            }
        }
    }
}

fn encode_stmt_list_src(stmts: &[&Stmt], counter: &mut usize, output: &mut String, interner: &Interner, variants: &HashMap<String, Vec<String>>) -> String {
    let list_var = format!("stmtList_{}", *counter);
    *counter += 1;
    output.push_str(&format!("Let {} be a new Seq of CStmt.\n", list_var));

    for stmt in stmts {
        for stmt_var in encode_stmts_src(stmt, counter, output, interner, variants) {
            output.push_str(&format!("Push {} to {}.\n", stmt_var, list_var));
        }
    }

    list_var
}

fn extract_ident_name(expr: &Expr, interner: &Interner) -> String {
    match expr {
        Expr::Identifier(sym) => interner.resolve(*sym).to_string(),
        // A struct-field target (`p's guests`) round-trips as its LOGOS surface syntax, so
        // the PE residual decompiles back to a valid field access the tree-walker re-parses
        // — `Add x to p's guests`, `Append x to d's lines`. Without this the target collapsed
        // to "unknown" and the residual referenced an undefined variable.
        Expr::FieldAccess { object, field } => {
            format!("{}'s {}", extract_ident_name(object, interner), interner.resolve(*field))
        }
        _ => "unknown".to_string(),
    }
}

/// The ROOT variable a CRDT target mutates: `p's guests` → `p`, a bare `s` → `s`. The PE
/// can't fold a struct it later mutates through a field, so when this differs from the
/// surface target (i.e. the target IS a struct field) the encoder emits a [`CForceDynamic`]
/// marker that forces `p` dynamic. Computed in Rust so the self-interpreter — which must
/// compile to statically-typed Rust for self-application — never parses the field path.
fn crdt_base_var(expr: &Expr, interner: &Interner) -> Option<String> {
    match expr {
        Expr::FieldAccess { object, .. } => Some(crdt_base_var_root(object, interner)),
        _ => None,
    }
}

fn crdt_base_var_root(expr: &Expr, interner: &Interner) -> String {
    match expr {
        Expr::Identifier(sym) => interner.resolve(*sym).to_string(),
        Expr::FieldAccess { object, .. } => crdt_base_var_root(object, interner),
        _ => "unknown".to_string(),
    }
}

/// Emit a `CForceDynamic` node binding `base` and return its node var. Prepended before a
/// CRDT op so the PE invalidates the (struct) binding before it can fold it.
fn emit_force_dynamic_named(base: &str, counter: &mut usize, output: &mut String) -> String {
    let v = format!("s_{}", *counter);
    *counter += 1;
    output.push_str(&format!(
        "Let {} be a new CForceDynamic with name \"{}\".\n",
        v, base
    ));
    v
}

/// `CForceDynamic` for a COLLECTION op (`Add`/`Remove`/`Append`): only a struct-field target
/// needs it (a bare-variable collection is one the PE already tracks). `None` for bare vars.
fn emit_force_dynamic(
    collection: &Expr,
    counter: &mut usize,
    output: &mut String,
    interner: &Interner,
) -> Option<String> {
    let base = crdt_base_var(collection, interner)?;
    Some(emit_force_dynamic_named(&base, counter, output))
}

/// `CForceDynamic` for a struct-MUTATING CRDT op (`Increase`/`Decrease`/`Resolve`/`Merge`):
/// the whole struct is mutated, so its root variable is ALWAYS forced dynamic.
fn emit_force_dynamic_struct(
    object: &Expr,
    counter: &mut usize,
    output: &mut String,
    interner: &Interner,
) -> Option<String> {
    match object {
        Expr::Identifier(_) | Expr::FieldAccess { .. } => {
            Some(emit_force_dynamic_named(&crdt_base_var_root(object, interner), counter, output))
        }
        _ => None,
    }
}


/// First Futamura Projection: PE(interpreter, program) = compiled_program
///
/// Specializes the interpreter with respect to a fixed program, producing
/// a compiled version with no interpretive overhead. For a self-interpreter
/// (where source and target language are the same), this produces the
/// program itself, with static optimizations applied.
///
/// The pipeline:
/// 1. Parse the program source
/// 2. Run the optimizer (fold, propagate, PE, DCE)
/// 3. Decompile the optimized AST back to source
/// 4. Verify no interpretive overhead remains
pub fn projection1_source(_core_types: &str, _interpreter: &str, program: &str) -> Result<String, String> {
    let full_source = if program.contains("## Main") || program.contains("## To ") {
        program.to_string()
    } else {
        format!("## Main\n{}", program)
    };

    let mut interner = Interner::new();
    let mut lexer = Lexer::new(&full_source, &mut interner);
    let tokens = lexer.tokenize();

    let type_registry = {
        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
        let result = discovery.run_full();
        result.types
    };

    let mut world_state = WorldState::new();
    let expr_arena = Arena::new();
    let term_arena = Arena::new();
    let np_arena = Arena::new();
    let sym_arena = Arena::new();
    let role_arena = Arena::new();
    let pp_arena = Arena::new();
    let stmt_arena: Arena<Stmt> = Arena::new();
    let imperative_expr_arena: Arena<Expr> = Arena::new();
    let type_expr_arena: Arena<TypeExpr> = Arena::new();

    let ast_ctx = AstContext::with_types(
        &expr_arena, &term_arena, &np_arena, &sym_arena,
        &role_arena, &pp_arena, &stmt_arena, &imperative_expr_arena,
        &type_expr_arena,
    );

    let mut parser = crate::parser::Parser::new(
        tokens, &mut world_state, &mut interner, ast_ctx, type_registry,
    );
    let stmts = parser.parse_program().map_err(|e| format!("Parse error: {:?}", e))?;

    // First Futamura Projection: PE(interpreter, program) = compiled_program.
    // Use the projection-safe optimizer: fold + propagate + PE + CTFE.
    // This preserves control-flow structure (If/While) while still folding
    // constants, propagating values, and specializing function calls.
    let optimized = crate::optimize::optimize_for_projection(
        stmts, &imperative_expr_arena, &stmt_arena, &mut interner,
        &crate::optimization::OptimizationConfig::from_env(),
    );

    let mut output = String::new();

    for stmt in &optimized {
        if matches!(stmt, Stmt::FunctionDef { .. }) {
            decompile_stmt(stmt, &interner, &mut output, 0);
            output.push('\n');
        }
    }

    output.push_str("## Main\n");
    for stmt in &optimized {
        if !matches!(stmt, Stmt::FunctionDef { .. }) {
            decompile_stmt(stmt, &interner, &mut output, 0);
        }
    }

    // Re-attach the program's type / struct definitions so a `new <Shared struct>`
    // in the residual can default-fill its CRDT fields (matches the genuine PE's
    // `projection1_source_real_fast`). Without this the residual reads an unset
    // field → "Field 'guests' not found".
    Ok(prepend_type_definitions(&full_source, output))
}

fn decompile_stmt(stmt: &Stmt, interner: &Interner, out: &mut String, indent: usize) {
    let pad = "    ".repeat(indent);
    match stmt {
        Stmt::FunctionDef { name, params, body, return_type, .. } => {
            let fn_name = interner.resolve(*name);
            let param_strs: Vec<String> = params
                .iter()
                .map(|(name, ty)| {
                    let pname = interner.resolve(*name);
                    format!("{}: {}", pname, decompile_type_expr(ty, interner))
                })
                .collect();
            let ret_str = if let Some(rt) = return_type {
                format!(" -> {}", decompile_type_expr(rt, interner))
            } else {
                String::new()
            };
            out.push_str(&format!("{}## To {} ({}){}:\n", pad, fn_name, param_strs.join(", "), ret_str));
            for s in body.iter() {
                decompile_stmt(s, interner, out, indent + 1);
            }
        }
        Stmt::Let { var, value, mutable, .. } => {
            let name = interner.resolve(*var);
            let expr_str = decompile_expr(value, interner);
            if *mutable {
                out.push_str(&format!("{}Let mutable {} be {}.\n", pad, name, expr_str));
            } else {
                out.push_str(&format!("{}Let {} be {}.\n", pad, name, expr_str));
            }
        }
        Stmt::Set { target, value } => {
            let name = interner.resolve(*target);
            let expr_str = decompile_expr(value, interner);
            out.push_str(&format!("{}Set {} to {}.\n", pad, name, expr_str));
        }
        Stmt::Show { object, .. } => {
            let expr_str = decompile_expr(object, interner);
            out.push_str(&format!("{}Show {}.\n", pad, expr_str));
        }
        Stmt::Return { value } => {
            if let Some(expr) = value {
                let expr_str = decompile_expr(expr, interner);
                out.push_str(&format!("{}Return {}.\n", pad, expr_str));
            } else {
                out.push_str(&format!("{}Return.\n", pad));
            }
        }
        Stmt::If { cond, then_block, else_block } => {
            let cond_str = decompile_expr(cond, interner);
            out.push_str(&format!("{}If {}:\n", pad, cond_str));
            for s in then_block.iter() {
                decompile_stmt(s, interner, out, indent + 1);
            }
            if let Some(els) = else_block {
                out.push_str(&format!("{}Otherwise:\n", pad));
                for s in els.iter() {
                    decompile_stmt(s, interner, out, indent + 1);
                }
            }
        }
        Stmt::While { cond, body, .. } => {
            let cond_str = decompile_expr(cond, interner);
            out.push_str(&format!("{}While {}:\n", pad, cond_str));
            for s in body.iter() {
                decompile_stmt(s, interner, out, indent + 1);
            }
        }
        Stmt::Call { function, args } => {
            let fn_name = interner.resolve(*function);
            let arg_strs: Vec<String> = args.iter().map(|a| decompile_expr(a, interner)).collect();
            if arg_strs.is_empty() {
                out.push_str(&format!("{}{}().\n", pad, fn_name));
            } else {
                out.push_str(&format!("{}{}({}).\n", pad, fn_name, arg_strs.join(", ")));
            }
        }
        Stmt::Push { value, collection } => {
            let val_str = decompile_expr(value, interner);
            let coll_str = decompile_expr(collection, interner);
            out.push_str(&format!("{}Push {} to {}.\n", pad, val_str, coll_str));
        }
        Stmt::SetIndex { collection, index, value } => {
            let coll_str = decompile_expr(collection, interner);
            let idx_str = decompile_expr(index, interner);
            let val_str = decompile_expr(value, interner);
            out.push_str(&format!("{}Set item {} of {} to {}.\n", pad, idx_str, coll_str, val_str));
        }
        Stmt::SetField { object, field, value } => {
            let obj_str = decompile_expr(object, interner);
            let field_name = interner.resolve(*field);
            let val_str = decompile_expr(value, interner);
            out.push_str(&format!("{}Set {} of {} to {}.\n", pad, field_name, obj_str, val_str));
        }
        Stmt::Repeat { pattern, iterable, body, .. } => {
            let var_name = match pattern {
                Pattern::Identifier(sym) => interner.resolve(*sym).to_string(),
                Pattern::Tuple(syms) => {
                    syms.iter().map(|s| interner.resolve(*s).to_string()).collect::<Vec<_>>().join(", ")
                }
            };
            let iter_str = decompile_expr(iterable, interner);
            out.push_str(&format!("{}Repeat for {} in {}:\n", pad, var_name, iter_str));
            for s in body.iter() {
                decompile_stmt(s, interner, out, indent + 1);
            }
        }
        Stmt::Inspect { target, arms, .. } => {
            let target_str = decompile_expr(target, interner);
            out.push_str(&format!("{}Inspect {}:\n", pad, target_str));
            for arm in arms {
                if let Some(variant) = arm.variant {
                    let variant_name = interner.resolve(variant);
                    let bindings: Vec<String> = arm.bindings.iter()
                        .map(|(_, b)| interner.resolve(*b).to_string())
                        .collect();
                    if bindings.is_empty() {
                        out.push_str(&format!("{}    When {}:\n", pad, variant_name));
                    } else {
                        out.push_str(&format!("{}    When {}({}):\n", pad, variant_name, bindings.join(", ")));
                    }
                } else {
                    out.push_str(&format!("{}    Otherwise:\n", pad));
                }
                for s in arm.body.iter() {
                    decompile_stmt(s, interner, out, indent + 2);
                }
            }
        }
        Stmt::Pop { collection, into } => {
            let coll_str = decompile_expr(collection, interner);
            if let Some(target) = into {
                let target_name = interner.resolve(*target);
                out.push_str(&format!("{}Pop from {} into {}.\n", pad, coll_str, target_name));
            } else {
                out.push_str(&format!("{}Pop from {}.\n", pad, coll_str));
            }
        }
        Stmt::Break => {
            out.push_str(&format!("{}Break.\n", pad));
        }
        Stmt::RuntimeAssert { condition, hard } => {
            let cond_str = decompile_expr(condition, interner);
            // Preserve the enforced/dev distinction: `Require that` (hard) survives the
            // round-trip rather than silently becoming the dev-only `Assert that`.
            let kw = if *hard { "Require that" } else { "Assert that" };
            out.push_str(&format!("{}{} {}.\n", pad, kw, cond_str));
        }
        Stmt::Add { value, collection } => {
            let val_str = decompile_expr(value, interner);
            let coll_str = decompile_expr(collection, interner);
            out.push_str(&format!("{}Add {} to {}.\n", pad, val_str, coll_str));
        }
        Stmt::Remove { value, collection } => {
            let val_str = decompile_expr(value, interner);
            let coll_str = decompile_expr(collection, interner);
            out.push_str(&format!("{}Remove {} from {}.\n", pad, val_str, coll_str));
        }
        Stmt::Zone { name, body, .. } => {
            let zone_name = interner.resolve(*name);
            out.push_str(&format!("{}Inside a new zone called \"{}\":\n", pad, zone_name));
            for s in body.iter() {
                decompile_stmt(s, interner, out, indent + 1);
            }
        }
        Stmt::ReadFrom { var, .. } => {
            let var_name = interner.resolve(*var);
            out.push_str(&format!("{}Read {} from the console.\n", pad, var_name));
        }
        Stmt::WriteFile { content, path } => {
            let content_str = decompile_expr(content, interner);
            let path_str = decompile_expr(path, interner);
            out.push_str(&format!("{}Write {} to file {}.\n", pad, content_str, path_str));
        }
        Stmt::Sleep { milliseconds } => {
            let ms = decompile_expr(milliseconds, interner);
            out.push_str(&format!("{}Sleep {}.\n", pad, ms));
        }
        // CRDT mutations: a Shared struct the program mutates survives the
        // projection unfolded (the optimizer keeps the binding dynamic), so the
        // residual MUST re-emit these or it silently changes the program's value.
        Stmt::IncreaseCrdt { object, field, amount } => {
            let obj = decompile_expr(object, interner);
            let fld = interner.resolve(*field);
            let amt = decompile_expr(amount, interner);
            out.push_str(&format!("{}Increase {}'s {} by {}.\n", pad, obj, fld, amt));
        }
        Stmt::DecreaseCrdt { object, field, amount } => {
            let obj = decompile_expr(object, interner);
            let fld = interner.resolve(*field);
            let amt = decompile_expr(amount, interner);
            out.push_str(&format!("{}Decrease {}'s {} by {}.\n", pad, obj, fld, amt));
        }
        Stmt::MergeCrdt { source, target } => {
            let src = decompile_expr(source, interner);
            let tgt = decompile_expr(target, interner);
            out.push_str(&format!("{}Merge {} into {}.\n", pad, src, tgt));
        }
        Stmt::AppendToSequence { sequence, value } => {
            let seq = decompile_expr(sequence, interner);
            let val = decompile_expr(value, interner);
            out.push_str(&format!("{}Append {} to {}.\n", pad, val, seq));
        }
        Stmt::ResolveConflict { object, field, value } => {
            let obj = decompile_expr(object, interner);
            let fld = interner.resolve(*field);
            let val = decompile_expr(value, interner);
            out.push_str(&format!("{}Resolve {}'s {} to {}.\n", pad, obj, fld, val));
        }
        _ => {
            // Remaining system-level statements (networking, concurrency) are not
            // produced by the optimizer and don't appear in P1 residuals.
        }
    }
}

fn decompile_expr(expr: &Expr, interner: &Interner) -> String {
    match expr {
        Expr::Literal(lit) => match lit {
            Literal::Number(n) => n.to_string(),
            Literal::Float(f) => format!("{}", f),
            Literal::Boolean(b) => if *b { "true".to_string() } else { "false".to_string() },
            Literal::Text(s) => format!("\"{}\"", interner.resolve(*s)),
            Literal::Nothing => "nothing".to_string(),
            Literal::Char(c) => format!("'{}'", c),
            Literal::Duration(ns) => format!("{}", ns),
            Literal::Date(days) => format!("{}", days),
            Literal::Moment(ns) => format!("{}", ns),
            Literal::Span { months, days } => format!("{} months {} days", months, days),
            Literal::Time(ns) => format!("{}", ns),
        },
        Expr::Identifier(sym) => interner.resolve(*sym).to_string(),
        Expr::BinaryOp { op, left, right } => {
            let l = if matches!(left, Expr::BinaryOp { .. }) {
                format!("({})", decompile_expr(left, interner))
            } else {
                decompile_expr(left, interner)
            };
            let r = if matches!(right, Expr::BinaryOp { .. }) {
                format!("({})", decompile_expr(right, interner))
            } else {
                decompile_expr(right, interner)
            };
            // Shift operations are introduced by bit-strength optimization.
            // Map back to equivalent multiply/divide for LOGOS source.
            if matches!(op, BinaryOpKind::Shl) {
                // n << k = n * 2^k
                if let Expr::Literal(Literal::Number(k)) = right {
                    let multiplier = 1i64 << k;
                    return format!("{} * {}", l, multiplier);
                }
            }
            if matches!(op, BinaryOpKind::Shr) {
                // n >> k = n / 2^k
                if let Expr::Literal(Literal::Number(k)) = right {
                    let divisor = 1i64 << k;
                    return format!("{} / {}", l, divisor);
                }
            }
            let op_str = match op {
                BinaryOpKind::Add => "+",
                BinaryOpKind::Subtract => "-",
                BinaryOpKind::Multiply => "*",
                BinaryOpKind::Divide | BinaryOpKind::ExactDivide => "/",
                BinaryOpKind::FloorDivide => "//",
                BinaryOpKind::Modulo => "%",
                BinaryOpKind::Eq => "equals",
                BinaryOpKind::NotEq => "is not",
                BinaryOpKind::Lt => "is less than",
                BinaryOpKind::Gt => "is greater than",
                BinaryOpKind::LtEq => "is at most",
                BinaryOpKind::GtEq => "is at least",
                BinaryOpKind::And => "and",
                BinaryOpKind::Or => "or",
                BinaryOpKind::Concat => "+",
                BinaryOpKind::SeqConcat => "followed by",
                BinaryOpKind::ApproxEq => "is approximately",
                BinaryOpKind::Pow => "**",
                BinaryOpKind::BitXor => "+",
                BinaryOpKind::BitAnd => "&",
                BinaryOpKind::BitOr => "|",
                BinaryOpKind::Shl => "*",
                BinaryOpKind::Shr => "/",
            };
            format!("{} {} {}", l, op_str, r)
        }
        Expr::Not { operand } => {
            // Parenthesize the operand so the negation's scope survives a
            // re-parse of the residual: `not (a and b)` must NOT become
            // `(not a) and b`.
            let inner = decompile_expr(operand, interner);
            format!("not ({})", inner)
        }
        Expr::Call { function, args } => {
            let fn_name = interner.resolve(*function);
            let arg_strs: Vec<String> = args.iter().map(|a| decompile_expr(a, interner)).collect();
            if arg_strs.is_empty() {
                format!("{}()", fn_name)
            } else {
                format!("{}({})", fn_name, arg_strs.join(", "))
            }
        }
        Expr::Index { collection, index } => {
            let coll = decompile_expr(collection, interner);
            let idx = decompile_expr(index, interner);
            format!("item {} of {}", idx, coll)
        }
        Expr::Length { collection } => {
            let coll = decompile_expr(collection, interner);
            format!("length of {}", coll)
        }
        Expr::FieldAccess { object, field } => {
            let obj = decompile_expr(object, interner);
            let field_name = interner.resolve(*field);
            // Possessive `obj's field` is the canonical, universally-parseable
            // field-read surface form (the parsers produce FieldAccess only from
            // it). `field of obj` does not round-trip (e.g. after `Show`/`Add`).
            format!("{}'s {}", obj, field_name)
        }
        Expr::New { type_name, .. } => {
            let tn = interner.resolve(*type_name);
            format!("a new {}", tn)
        }
        Expr::NewVariant { variant, fields, .. } => {
            let vn = interner.resolve(*variant);
            if fields.is_empty() {
                format!("a new {}", vn)
            } else {
                let parts: Vec<String> = fields.iter().map(|(name, val)| {
                    let n = interner.resolve(*name);
                    let v = decompile_expr(val, interner);
                    format!("{} {}", n, v)
                }).collect();
                format!("a new {} with {}", vn, parts.join(" and "))
            }
        }
        Expr::InterpolatedString(parts) => {
            let mut result = String::new();
            for part in parts {
                match part {
                    StringPart::Literal(sym) => {
                        result.push_str(&interner.resolve(*sym));
                    }
                    StringPart::Expr { value, debug, .. } => {
                        let expr_str = decompile_expr(value, interner);
                        if *debug {
                            result.push_str(&format!("{{{}=}}", expr_str));
                        } else {
                            result.push_str(&format!("{{{}}}", expr_str));
                        }
                    }
                }
            }
            format!("\"{}\"", result)
        }
        Expr::Slice { collection, start, end } => {
            let coll = decompile_expr(collection, interner);
            let s = decompile_expr(start, interner);
            let e = decompile_expr(end, interner);
            format!("{} {} through {}", coll, s, e)
        }
        Expr::Copy { expr } => {
            let inner = decompile_expr(expr, interner);
            format!("copy of {}", inner)
        }
        Expr::Give { value } => {
            let inner = decompile_expr(value, interner);
            format!("Give {}", inner)
        }
        Expr::Contains { collection, value } => {
            let coll = decompile_expr(collection, interner);
            let val = decompile_expr(value, interner);
            format!("{} contains {}", coll, val)
        }
        Expr::Union { left, right } => {
            let l = decompile_expr(left, interner);
            let r = decompile_expr(right, interner);
            format!("{} union {}", l, r)
        }
        Expr::Intersection { left, right } => {
            let l = decompile_expr(left, interner);
            let r = decompile_expr(right, interner);
            format!("{} intersection {}", l, r)
        }
        Expr::List(elems) => {
            let parts: Vec<String> = elems.iter().map(|e| decompile_expr(e, interner)).collect();
            format!("[{}]", parts.join(", "))
        }
        Expr::Tuple(elems) => {
            let parts: Vec<String> = elems.iter().map(|e| decompile_expr(e, interner)).collect();
            format!("({})", parts.join(", "))
        }
        Expr::Range { start, end } => {
            let s = decompile_expr(start, interner);
            let e = decompile_expr(end, interner);
            format!("{} to {}", s, e)
        }
        Expr::OptionSome { value } => {
            let inner = decompile_expr(value, interner);
            format!("some {}", inner)
        }
        Expr::OptionNone => "none".to_string(),
        Expr::WithCapacity { value, capacity } => {
            let val = decompile_expr(value, interner);
            let cap = decompile_expr(capacity, interner);
            format!("{} with capacity {}", val, cap)
        }
        Expr::Escape { language, code } => {
            let lang = interner.resolve(*language);
            let src = interner.resolve(*code);
            format!("Escape to {}:\n{}", lang, src)
        }
        Expr::ManifestOf { zone } => {
            let z = decompile_expr(zone, interner);
            format!("the manifest of {}", z)
        }
        Expr::ChunkAt { index, zone } => {
            let idx = decompile_expr(index, interner);
            let z = decompile_expr(zone, interner);
            format!("the chunk at {} in {}", idx, z)
        }
        Expr::Closure { params, body, return_type } => {
            let param_strs: Vec<String> = params.iter().map(|(name, ty)| {
                let n = interner.resolve(*name);
                let t = decompile_type_expr(ty, interner);
                format!("{}: {}", n, t)
            }).collect();
            let ret = if let Some(rt) = return_type {
                format!(" -> {}", decompile_type_expr(rt, interner))
            } else {
                String::new()
            };
            match body {
                ClosureBody::Expression(expr) => {
                    let e = decompile_expr(expr, interner);
                    format!("({}){} -> {}", param_strs.join(", "), ret, e)
                }
                ClosureBody::Block(_) => {
                    format!("({}){} -> [block]", param_strs.join(", "), ret)
                }
            }
        }
        Expr::CallExpr { callee, args } => {
            let c = decompile_expr(callee, interner);
            let arg_strs: Vec<String> = args.iter().map(|a| decompile_expr(a, interner)).collect();
            format!("{}({})", c, arg_strs.join(", "))
        }
    }
}

fn decompile_type_expr(ty: &TypeExpr, interner: &Interner) -> String {
    match ty {
        TypeExpr::Primitive(sym) => interner.resolve(*sym).to_string(),
        TypeExpr::Named(sym) => interner.resolve(*sym).to_string(),
        TypeExpr::Generic { base, params } => {
            let base_str = interner.resolve(*base);
            let param_strs: Vec<String> = params.iter().map(|p| decompile_type_expr(p, interner)).collect();
            format!("{} of {}", base_str, param_strs.join(" and "))
        }
        TypeExpr::Function { inputs, output } => {
            let in_strs: Vec<String> = inputs.iter().map(|t| decompile_type_expr(t, interner)).collect();
            let out_str = decompile_type_expr(output, interner);
            format!("fn({}) -> {}", in_strs.join(", "), out_str)
        }
        TypeExpr::Refinement { base, .. } => {
            decompile_type_expr(base, interner)
        }
        TypeExpr::Persistent { inner } => {
            format!("Persistent {}", decompile_type_expr(inner, interner))
        }
        TypeExpr::Mutable { inner } => {
            format!("mutable {}", decompile_type_expr(inner, interner))
        }
    }
}

/// Verify that a LogicAffeine program has no interpretive overhead.
///
/// Checks the AST for patterns that indicate unresolved interpreter dispatch:
/// - Inspect on CStmt/CExpr/CVal variants
/// - References to Core constructor types (CInt, CShow, etc.)
/// - Environment lookups on literal strings
pub fn verify_no_overhead_source(source: &str) -> Result<(), String> {
    let mut interner = Interner::new();
    let mut lexer = Lexer::new(source, &mut interner);
    let tokens = lexer.tokenize();

    let type_registry = {
        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
        let result = discovery.run_full();
        result.types
    };

    let mut world_state = WorldState::new();
    let expr_arena = Arena::new();
    let term_arena = Arena::new();
    let np_arena = Arena::new();
    let sym_arena = Arena::new();
    let role_arena = Arena::new();
    let pp_arena = Arena::new();
    let stmt_arena: Arena<Stmt> = Arena::new();
    let imperative_expr_arena: Arena<Expr> = Arena::new();
    let type_expr_arena: Arena<TypeExpr> = Arena::new();

    let ast_ctx = AstContext::with_types(
        &expr_arena, &term_arena, &np_arena, &sym_arena,
        &role_arena, &pp_arena, &stmt_arena, &imperative_expr_arena,
        &type_expr_arena,
    );

    let mut parser = crate::parser::Parser::new(
        tokens, &mut world_state, &mut interner, ast_ctx, type_registry,
    );
    let stmts = parser.parse_program().map_err(|e| format!("Parse error: {:?}", e))?;

    verify_no_overhead_stmts(&stmts, &interner)
}

const CORE_VARIANT_NAMES: &[&str] = &[
    "CInt", "CBool", "CText", "CVar", "CBinOp", "CNot",
    "CCall", "CIndex", "CLen", "CMapGet",
    "CLet", "CSet", "CIf", "CWhile", "CReturn", "CShow",
    "CCallS", "CPush", "CSetIdx", "CMapSet",
    "CFuncDef", "CProg",
    "CManifestOf", "CChunkAt",
    "VInt", "VBool", "VText", "VSeq", "VMap", "VError", "VNothing",
];

/// Interpreter *carrier* type names — the umbrella data types the self-interpreter/PE thread
/// through their state. A Jones-optimal residual holds none of them: constructing
/// `a new Map of Text to CVal` (the environment), or binding a `CExpr`-typed variable, is
/// surviving interpreter state, not dissolved computation.
const CORE_TYPE_NAMES: &[&str] = &[
    "CVal", "CExpr", "CStmt", "CFunc", "CFuncDef", "CProgram", "CProg",
    "CoreOut", "CoreOutR", "PEState", "PEStateR", "PEMiniState", "PEMiniR",
];

fn verify_no_overhead_stmts(stmts: &[Stmt], interner: &Interner) -> Result<(), String> {
    for stmt in stmts {
        check_stmt_overhead(stmt, interner)?;
    }
    Ok(())
}

fn check_stmt_overhead(stmt: &Stmt, interner: &Interner) -> Result<(), String> {
    match stmt {
        Stmt::Inspect { arms, .. } => {
            for arm in arms {
                if let Some(variant) = arm.variant {
                    let variant_name = interner.resolve(variant);
                    if CORE_VARIANT_NAMES.contains(&variant_name) {
                        return Err(format!(
                            "Interpretive overhead: Inspect dispatches on Core variant '{}'",
                            variant_name
                        ));
                    }
                }
                for s in arm.body.iter() {
                    check_stmt_overhead(s, interner)?;
                }
            }
        }
        Stmt::If { cond, then_block, else_block } => {
            check_expr_overhead(cond, interner)?;
            for s in then_block.iter() {
                check_stmt_overhead(s, interner)?;
            }
            if let Some(els) = else_block {
                for s in els.iter() {
                    check_stmt_overhead(s, interner)?;
                }
            }
        }
        Stmt::While { cond, body, .. } => {
            check_expr_overhead(cond, interner)?;
            for s in body.iter() {
                check_stmt_overhead(s, interner)?;
            }
        }
        Stmt::FunctionDef { body, .. } => {
            for s in body.iter() {
                check_stmt_overhead(s, interner)?;
            }
        }
        Stmt::Repeat { body, .. } => {
            for s in body.iter() {
                check_stmt_overhead(s, interner)?;
            }
        }
        Stmt::Let { value, .. } | Stmt::Set { value, .. } | Stmt::Show { object: value, .. } => {
            check_expr_overhead(value, interner)?;
        }
        Stmt::Return { value } => {
            if let Some(v) = value {
                check_expr_overhead(v, interner)?;
            }
        }
        _ => {}
    }
    Ok(())
}

fn check_expr_overhead(expr: &Expr, interner: &Interner) -> Result<(), String> {
    match expr {
        Expr::Index { collection, index } => {
            // Check for `item X of env` where X is a literal string (env lookup overhead)
            if let Expr::Identifier(coll_sym) = collection {
                let coll_name = interner.resolve(*coll_sym);
                if coll_name == "env" {
                    if let Expr::Literal(Literal::Text(_)) = index {
                        return Err(
                            "Interpretive overhead: environment lookup 'item ... of env' on literal key".to_string()
                        );
                    }
                }
            }
            check_expr_overhead(collection, interner)?;
            check_expr_overhead(index, interner)?;
        }
        Expr::New { type_name, .. } => {
            let tn = interner.resolve(*type_name);
            if CORE_VARIANT_NAMES.contains(&tn) {
                return Err(format!(
                    "Interpretive overhead: Core type constructor 'new {}'", tn
                ));
            }
        }
        Expr::NewVariant { variant, .. } => {
            let vn = interner.resolve(*variant);
            if CORE_VARIANT_NAMES.contains(&vn) {
                return Err(format!(
                    "Interpretive overhead: Core variant constructor '{}'", vn
                ));
            }
        }
        Expr::Call { function, args } => {
            let fn_name = interner.resolve(*function);
            if CORE_VARIANT_NAMES.contains(&fn_name) {
                return Err(format!(
                    "Interpretive overhead: Core variant call '{}'", fn_name
                ));
            }
            for a in args {
                check_expr_overhead(a, interner)?;
            }
        }
        Expr::BinaryOp { left, right, .. } => {
            check_expr_overhead(left, interner)?;
            check_expr_overhead(right, interner)?;
        }
        Expr::Not { operand } => {
            check_expr_overhead(operand, interner)?;
        }
        Expr::Length { collection } => {
            check_expr_overhead(collection, interner)?;
        }
        Expr::FieldAccess { object, .. } => {
            check_expr_overhead(object, interner)?;
        }
        _ => {}
    }
    Ok(())
}

/// Names whose appearance as a call function in a residual betrays surviving
/// interpreter dispatch — the residual is still threading through the PE or the
/// self-interpreter instead of having been specialized away.
const DISPATCH_FN_NAMES: &[&str] = &[
    "peExpr", "peBlock", "coreEval", "coreExecBlock", "applyBinOp",
];

/// The Jones-optimality oracle: count the units of interpreter dispatch remaining
/// in a residual program.
///
/// A residual that is genuinely Jones-optimal has dissolved the interpreter entirely
/// and returns zero. One unit is counted for each of:
/// - an `Inspect` arm dispatching on a Core IR variant (`CInt`, `CIf`, …);
/// - an environment/function-map lookup `item <literal> of env` / `... of funcs`;
/// - a Core IR constructor (`new CInt`, a `CInt(...)` call, a `VInt` variant, …);
/// - a call to a known dispatch function ([`DISPATCH_FN_NAMES`]).
///
/// Unlike [`verify_no_overhead_source`], this walks the whole tree and accumulates a
/// count rather than short-circuiting on the first violation.
pub fn count_dispatch(source: &str) -> usize {
    let mut interner = Interner::new();
    let mut lexer = Lexer::new(source, &mut interner);
    let tokens = lexer.tokenize();

    let type_registry = {
        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
        let result = discovery.run_full();
        result.types
    };

    let mut world_state = WorldState::new();
    let expr_arena = Arena::new();
    let term_arena = Arena::new();
    let np_arena = Arena::new();
    let sym_arena = Arena::new();
    let role_arena = Arena::new();
    let pp_arena = Arena::new();
    let stmt_arena: Arena<Stmt> = Arena::new();
    let imperative_expr_arena: Arena<Expr> = Arena::new();
    let type_expr_arena: Arena<TypeExpr> = Arena::new();

    let ast_ctx = AstContext::with_types(
        &expr_arena, &term_arena, &np_arena, &sym_arena,
        &role_arena, &pp_arena, &stmt_arena, &imperative_expr_arena,
        &type_expr_arena,
    );

    let mut parser = crate::parser::Parser::new(
        tokens, &mut world_state, &mut interner, ast_ctx, type_registry,
    );
    let stmts = match parser.parse_program() {
        Ok(s) => s,
        // A residual we cannot parse cannot be asserted Jones-optimal; surface that as
        // a non-zero count rather than a false clean bill of health.
        Err(_) => return usize::MAX,
    };

    let mut count = 0usize;
    for stmt in &stmts {
        count_stmt_dispatch(stmt, &interner, &mut count);
    }
    count
}

fn count_block_dispatch(block: &[Stmt], interner: &Interner, count: &mut usize) {
    for s in block {
        count_stmt_dispatch(s, interner, count);
    }
}

/// Does a type expression name any interpreter carrier type ([`CORE_TYPE_NAMES`]) or Core
/// variant? Exhaustive over `TypeExpr` — a new type form stops the build until handled.
fn type_expr_mentions_core(t: &TypeExpr, interner: &Interner) -> bool {
    let is_core = |s| {
        let n = interner.resolve(s);
        CORE_TYPE_NAMES.contains(&n) || CORE_VARIANT_NAMES.contains(&n)
    };
    match t {
        TypeExpr::Primitive(s) | TypeExpr::Named(s) => is_core(*s),
        TypeExpr::Generic { base, params } => {
            is_core(*base) || params.iter().any(|p| type_expr_mentions_core(p, interner))
        }
        TypeExpr::Function { inputs, output } => {
            inputs.iter().any(|p| type_expr_mentions_core(p, interner))
                || type_expr_mentions_core(output, interner)
        }
        TypeExpr::Refinement { base, .. } => type_expr_mentions_core(base, interner),
        TypeExpr::Persistent { inner } | TypeExpr::Mutable { inner } => {
            type_expr_mentions_core(inner, interner)
        }
    }
}

/// Scan raw escaped foreign code for whole-word Core-IR / dispatch names. An `Escape`
/// block embedding `CInt(..)` or `coreEval(..)` is interpreter overhead the AST walk
/// cannot see inside, so it is flagged lexically.
fn count_escape_code_dispatch(text: &str, count: &mut usize) {
    for word in text.split(|c: char| !c.is_alphanumeric() && c != '_') {
        if !word.is_empty()
            && (CORE_VARIANT_NAMES.contains(&word) || DISPATCH_FN_NAMES.contains(&word))
        {
            *count += 1;
        }
    }
}

/// Exhaustive by construction — NO `_` arm. A new `Stmt` variant stops the build here
/// until it is classified, so the language cannot grow a statement that hides interpreter
/// dispatch from the Jones oracle.
fn count_stmt_dispatch(stmt: &Stmt, interner: &Interner, count: &mut usize) {
    match stmt {
        Stmt::Splice { body } => {
            for inner in body.iter() {
                count_stmt_dispatch(inner, interner, count);
            }
        }
        Stmt::Let { value, ty, .. } => {
            if let Some(t) = ty {
                if type_expr_mentions_core(t, interner) {
                    *count += 1;
                }
            }
            count_expr_dispatch(value, interner, count);
        }
        Stmt::Set { value, .. } => count_expr_dispatch(value, interner, count),
        Stmt::Call { function, args } => {
            let fn_name = interner.resolve(*function);
            if CORE_VARIANT_NAMES.contains(&fn_name) || DISPATCH_FN_NAMES.contains(&fn_name) {
                *count += 1;
            }
            for a in args {
                count_expr_dispatch(a, interner, count);
            }
        }
        Stmt::If { cond, then_block, else_block } => {
            count_expr_dispatch(cond, interner, count);
            count_block_dispatch(then_block, interner, count);
            if let Some(els) = else_block {
                count_block_dispatch(els, interner, count);
            }
        }
        Stmt::While { cond, body, decreasing } => {
            count_expr_dispatch(cond, interner, count);
            count_block_dispatch(body, interner, count);
            if let Some(d) = decreasing {
                count_expr_dispatch(d, interner, count);
            }
        }
        Stmt::Repeat { iterable, body, .. } => {
            count_expr_dispatch(iterable, interner, count);
            count_block_dispatch(body, interner, count);
        }
        Stmt::Return { value } => {
            if let Some(v) = value {
                count_expr_dispatch(v, interner, count);
            }
        }
        Stmt::RuntimeAssert { condition, .. } => count_expr_dispatch(condition, interner, count),
        Stmt::Give { object, recipient } | Stmt::Show { object, recipient } => {
            count_expr_dispatch(object, interner, count);
            count_expr_dispatch(recipient, interner, count);
        }
        Stmt::SetField { object, value, .. } => {
            count_expr_dispatch(object, interner, count);
            count_expr_dispatch(value, interner, count);
        }
        Stmt::FunctionDef { body, .. } => count_block_dispatch(body, interner, count),
        Stmt::Inspect { target, arms, .. } => {
            count_expr_dispatch(target, interner, count);
            for arm in arms {
                if let Some(variant) = arm.variant {
                    if CORE_VARIANT_NAMES.contains(&interner.resolve(variant)) {
                        *count += 1;
                    }
                }
                count_block_dispatch(arm.body, interner, count);
            }
        }
        Stmt::Push { value, collection }
        | Stmt::Add { value, collection }
        | Stmt::Remove { value, collection } => {
            count_expr_dispatch(value, interner, count);
            count_expr_dispatch(collection, interner, count);
        }
        Stmt::Pop { collection, .. } => count_expr_dispatch(collection, interner, count),
        Stmt::SetIndex { collection, index, value } => {
            count_expr_dispatch(collection, interner, count);
            count_expr_dispatch(index, interner, count);
            count_expr_dispatch(value, interner, count);
        }
        Stmt::Zone { body, .. } => count_block_dispatch(body, interner, count),
        Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => {
            count_block_dispatch(tasks, interner, count)
        }
        Stmt::ReadFrom { source, .. } => {
            if let ReadSource::File(path) = source {
                count_expr_dispatch(path, interner, count);
            }
        }
        Stmt::WriteFile { content, path } => {
            count_expr_dispatch(content, interner, count);
            count_expr_dispatch(path, interner, count);
        }
        Stmt::SendMessage { message, destination, .. } => {
            count_expr_dispatch(message, interner, count);
            count_expr_dispatch(destination, interner, count);
        }
        Stmt::AwaitMessage { source, .. } => count_expr_dispatch(source, interner, count),
        Stmt::StreamMessage { values, destination } => {
            count_expr_dispatch(values, interner, count);
            count_expr_dispatch(destination, interner, count);
        }
        Stmt::MergeCrdt { source, target } => {
            count_expr_dispatch(source, interner, count);
            count_expr_dispatch(target, interner, count);
        }
        Stmt::IncreaseCrdt { object, amount, .. } | Stmt::DecreaseCrdt { object, amount, .. } => {
            count_expr_dispatch(object, interner, count);
            count_expr_dispatch(amount, interner, count);
        }
        Stmt::AppendToSequence { sequence, value } => {
            count_expr_dispatch(sequence, interner, count);
            count_expr_dispatch(value, interner, count);
        }
        Stmt::ResolveConflict { object, value, .. } => {
            count_expr_dispatch(object, interner, count);
            count_expr_dispatch(value, interner, count);
        }
        Stmt::Listen { address, .. } | Stmt::ConnectTo { address, .. } | Stmt::LetPeerAgent { address, .. } => {
            count_expr_dispatch(address, interner, count)
        }
        Stmt::Sleep { milliseconds } => count_expr_dispatch(milliseconds, interner, count),
        Stmt::Sync { topic, .. } => count_expr_dispatch(topic, interner, count),
        Stmt::Mount { path, .. } => count_expr_dispatch(path, interner, count),
        Stmt::LaunchTask { function, args } | Stmt::LaunchTaskWithHandle { function, args, .. } => {
            let fn_name = interner.resolve(*function);
            if CORE_VARIANT_NAMES.contains(&fn_name) || DISPATCH_FN_NAMES.contains(&fn_name) {
                *count += 1;
            }
            for a in args {
                count_expr_dispatch(a, interner, count);
            }
        }
        Stmt::SendPipe { value, pipe } | Stmt::TrySendPipe { value, pipe, .. } => {
            count_expr_dispatch(value, interner, count);
            count_expr_dispatch(pipe, interner, count);
        }
        Stmt::ReceivePipe { pipe, .. } | Stmt::TryReceivePipe { pipe, .. } => {
            count_expr_dispatch(pipe, interner, count)
        }
        Stmt::StopTask { handle } => count_expr_dispatch(handle, interner, count),
        Stmt::Select { branches } => {
            for b in branches {
                match b {
                    SelectBranch::Receive { pipe, body, .. } => {
                        count_expr_dispatch(pipe, interner, count);
                        count_block_dispatch(body, interner, count);
                    }
                    SelectBranch::Timeout { milliseconds, body } => {
                        count_expr_dispatch(milliseconds, interner, count);
                        count_block_dispatch(body, interner, count);
                    }
                }
            }
        }
        Stmt::Escape { code, .. } => count_escape_code_dispatch(interner.resolve(*code), count),
        // Leaves and declarations: no executable `Expr` children reach the oracle.
        // `Assert`/`Trust` carry a `LogicExpr` (proof layer), not an executable `Expr`.
        Stmt::Break
        | Stmt::Assert { .. }
        | Stmt::Trust { .. }
        | Stmt::StructDef { .. }
        | Stmt::Spawn { .. }
        | Stmt::Check { .. }
        | Stmt::CreatePipe { .. }
        | Stmt::Theorem(_)
        | Stmt::Definition(_)
        | Stmt::Axiom(_)
        | Stmt::Theory(_)
        | Stmt::Require { .. } => {}
    }
}

/// Exhaustive by construction — NO `_` arm. Every sub-expression is recursed, so a Core
/// constructor or dispatch call cannot hide inside a container (`List`/`Tuple`), an
/// operator, a constructor field, an interpolant, or a closure body.
fn count_expr_dispatch(expr: &Expr, interner: &Interner, count: &mut usize) {
    match expr {
        Expr::Literal(_) | Expr::Identifier(_) | Expr::OptionNone => {}
        Expr::BinaryOp { left, right, .. }
        | Expr::Union { left, right }
        | Expr::Intersection { left, right } => {
            count_expr_dispatch(left, interner, count);
            count_expr_dispatch(right, interner, count);
        }
        Expr::Not { operand } => count_expr_dispatch(operand, interner, count),
        Expr::Call { function, args } => {
            let fn_name = interner.resolve(*function);
            if CORE_VARIANT_NAMES.contains(&fn_name) || DISPATCH_FN_NAMES.contains(&fn_name) {
                *count += 1;
            }
            for a in args {
                count_expr_dispatch(a, interner, count);
            }
        }
        Expr::Index { collection, index } => {
            // Any `item ... of env|funcs` is surviving interpreter-state threading, whatever
            // the key: a Jones-optimal residual holds no environment/function map at all.
            if let Expr::Identifier(coll_sym) = collection {
                let coll_name = interner.resolve(*coll_sym);
                if coll_name == "env" || coll_name == "funcs" {
                    *count += 1;
                }
            }
            count_expr_dispatch(collection, interner, count);
            count_expr_dispatch(index, interner, count);
        }
        Expr::Slice { collection, start, end } => {
            count_expr_dispatch(collection, interner, count);
            count_expr_dispatch(start, interner, count);
            count_expr_dispatch(end, interner, count);
        }
        Expr::Copy { expr: inner } => count_expr_dispatch(inner, interner, count),
        Expr::Give { value } => count_expr_dispatch(value, interner, count),
        Expr::Length { collection } => count_expr_dispatch(collection, interner, count),
        Expr::Contains { collection, value } => {
            count_expr_dispatch(collection, interner, count);
            count_expr_dispatch(value, interner, count);
        }
        Expr::ManifestOf { zone } => count_expr_dispatch(zone, interner, count),
        Expr::ChunkAt { index, zone } => {
            count_expr_dispatch(index, interner, count);
            count_expr_dispatch(zone, interner, count);
        }
        Expr::List(items) | Expr::Tuple(items) => {
            for e in items {
                count_expr_dispatch(e, interner, count);
            }
        }
        Expr::Range { start, end } => {
            count_expr_dispatch(start, interner, count);
            count_expr_dispatch(end, interner, count);
        }
        Expr::FieldAccess { object, .. } => count_expr_dispatch(object, interner, count),
        Expr::New { type_name, type_args, init_fields } => {
            let tn = interner.resolve(*type_name);
            if CORE_VARIANT_NAMES.contains(&tn) || CORE_TYPE_NAMES.contains(&tn) {
                *count += 1;
            }
            // A collection over a Core carrier type — `a new Map of Text to CVal` — is the
            // interpreter's environment/function map surviving in the residual.
            for ta in type_args {
                if type_expr_mentions_core(ta, interner) {
                    *count += 1;
                }
            }
            for (_, v) in init_fields {
                count_expr_dispatch(v, interner, count);
            }
        }
        Expr::NewVariant { variant, fields, .. } => {
            if CORE_VARIANT_NAMES.contains(&interner.resolve(*variant)) {
                *count += 1;
            }
            for (_, v) in fields {
                count_expr_dispatch(v, interner, count);
            }
        }
        Expr::Escape { code, .. } => count_escape_code_dispatch(interner.resolve(*code), count),
        Expr::OptionSome { value } => count_expr_dispatch(value, interner, count),
        Expr::WithCapacity { value, capacity } => {
            count_expr_dispatch(value, interner, count);
            count_expr_dispatch(capacity, interner, count);
        }
        Expr::Closure { body, .. } => match body {
            ClosureBody::Expression(e) => count_expr_dispatch(e, interner, count),
            ClosureBody::Block(b) => count_block_dispatch(b, interner, count),
        },
        Expr::CallExpr { callee, args } => {
            count_expr_dispatch(callee, interner, count);
            for a in args {
                count_expr_dispatch(a, interner, count);
            }
        }
        Expr::InterpolatedString(parts) => {
            for p in parts {
                if let StringPart::Expr { value, .. } = p {
                    count_expr_dispatch(value, interner, count);
                }
            }
        }
    }
}

/// Returns the source text of the partial evaluator written in LogicAffeine.
///
/// This PE operates on CProgram representations using explicit environments
/// and static dispatch. It is first-order (no closures) and uses only
/// literal string function names (no dynamic dispatch).
pub fn pe_source_text() -> &'static str {
    include_str!("optimize/pe_source.logos")
}

pub fn decompile_source_text() -> &'static str {
    include_str!("optimize/decompile_source.logos")
}

pub fn pe_bti_source_text() -> &'static str {
    include_str!("optimize/pe_bti_source.logos")
}

pub fn pe_mini_source_text() -> &'static str {
    include_str!("optimize/pe_mini_source.logos")
}

/// The canonical inductive type catalog the Futamura projections are built on
/// (`CStmt`/`CExpr`/`CVal`/…). Every statement the tree-walker executes has a
/// `C…` constructor here; the partial-evaluator dialects dispatch on it. Exposed
/// so cross-tier lock tests can prove this catalog and every tier stay in sync —
/// a statement added to the language must appear here or it is dropped from the
/// projections (see `tier_parity_lock.rs`).
pub fn core_types_for_pe_source() -> &'static str {
    CORE_TYPES_FOR_PE
}

const CORE_TYPES_FOR_PE: &str = r#"
## A CExpr is one of:
    A CInt with value Int.
    A CFloat with value Real.
    A CBool with value Bool.
    A CText with value Text.
    A CVar with name Text.
    A CBinOp with op Text and left CExpr and right CExpr.
    A CNot with inner CExpr.
    A CCall with name Text and args Seq of CExpr.
    A CIndex with coll CExpr and idx CExpr.
    A CLen with target CExpr.
    A CMapGet with target CExpr and key CExpr.
    A CNewSeq.
    A CNewVariant with tag Text and fnames Seq of Text and fvals Seq of CExpr.
    A CList with items Seq of CExpr.
    A CRange with start CExpr and end CExpr.
    A CSlice with coll CExpr and startIdx CExpr and endIdx CExpr.
    A CCopy with target CExpr.
    A CNewSet.
    A CContains with coll CExpr and elem CExpr.
    A CUnion with left CExpr and right CExpr.
    A CIntersection with left CExpr and right CExpr.
    A COptionSome with inner CExpr.
    A COptionNone.
    A CTuple with items Seq of CExpr.
    A CNew with typeName Text and fieldNames Seq of Text and fields Seq of CExpr.
    A CFieldAccess with target CExpr and field Text.
    A CClosure with params Seq of Text and body Seq of CStmt and captured Seq of Text.
    A CCallExpr with target CExpr and args Seq of CExpr.
    A CInterpolatedString with parts Seq of CStringPart.
    A CDuration with amount CExpr and unit Text.
    A CTimeNow.
    A CDateToday.
    A CEscExpr with code Text.
    A CManifestOf with zn CExpr.
    A CChunkAt with idx CExpr and zn CExpr.

## A CStringPart is one of:
    A CLiteralPart with value Text.
    A CExprPart with expr CExpr.

## A CStmt is one of:
    A CLet with name Text and expr CExpr.
    A CSet with name Text and expr CExpr.
    A CIf with cond CExpr and thenBlock Seq of CStmt and elseBlock Seq of CStmt.
    A CWhile with cond CExpr and body Seq of CStmt.
    A CReturn with expr CExpr.
    A CShow with expr CExpr.
    A CCallS with name Text and args Seq of CExpr.
    A CPush with expr CExpr and target Text.
    A CSetIdx with target Text and idx CExpr and val CExpr.
    A CMapSet with target Text and key CExpr and val CExpr.
    A CPop with target Text.
    A CRepeat with var Text and coll CExpr and body Seq of CStmt.
    A CRepeatRange with var Text and start CExpr and end CExpr and body Seq of CStmt.
    A CBreak.
    A CAdd with elem CExpr and target Text.
    A CRemove with elem CExpr and target Text.
    A CForceDynamic with name Text.
    A CSetField with target Text and field Text and val CExpr.
    A CStructDef with name Text and fieldNames Seq of Text.
    A CInspect with target CExpr and arms Seq of CMatchArm.
    A CEnumDef with name Text and variants Seq of Text.
    A CRuntimeAssert with cond CExpr and msg CExpr.
    A CHardAssert with cond CExpr and msg CExpr.
    A CGive with expr CExpr and target Text.
    A CEscStmt with code Text.
    A CSleep with duration CExpr.
    A CReadConsole with target Text.
    A CReadFile with path CExpr and target Text.
    A CWriteFile with path CExpr and content CExpr.
    A CCheck with predicate CExpr and msg CExpr.
    A CAssert with proposition CExpr.
    A CTrust with proposition CExpr and justification Text.
    A CRequire with dependency Text.
    A CMerge with target Text and other CExpr.
    A CIncrease with target Text and amount CExpr.
    A CDecrease with target Text and amount CExpr.
    A CAppendToSeq with target Text and value CExpr.
    A CResolve with target Text.
    A CSync with target Text and channel CExpr.
    A CMount with target Text and path CExpr.
    A CConcurrent with branches Seq of Seq of CStmt.
    A CParallel with branches Seq of Seq of CStmt.
    A CLaunchTask with body Seq of CStmt and handle Text.
    A CStopTask with handle CExpr.
    A CSelect with branches Seq of CSelectBranch.
    A CCreatePipe with name Text and capacity CExpr.
    A CSendPipe with chan Text and value CExpr.
    A CReceivePipe with chan Text and target Text.
    A CTrySendPipe with chan Text and value CExpr.
    A CTryReceivePipe with chan Text and target Text.
    A CSpawn with agentType Text and target Text.
    A CSendMessage with target CExpr and msg CExpr.
    A CStreamMessage with target CExpr and values CExpr.
    A CAwaitMessage with target Text.
    A CListen with addr CExpr and handler Text.
    A CConnectTo with addr CExpr and target Text.
    A CZone with name Text and kind Text and body Seq of CStmt.

## A CSelectBranch is one of:
    A CSelectRecv with chan Text and var Text and body Seq of CStmt.
    A CSelectTimeout with duration CExpr and body Seq of CStmt.

## A CMatchArm is one of:
    A CWhen with variantName Text and bindings Seq of Text and body Seq of CStmt.
    A COtherwise with body Seq of CStmt.

## A CFunc is one of:
    A CFuncDef with name Text and params Seq of Text and paramTypes Seq of Text and returnType Text and body Seq of CStmt.

## A CProgram is one of:
    A CProg with funcs Seq of CFunc and main Seq of CStmt.

## A PEState is one of:
    A PEStateR with env Map of Text to CVal and funcs Map of Text to CFunc and depth Int and staticEnv Map of Text to CExpr and specResults Map of Text to CExpr and onStack Seq of Text.

## A CVal is one of:
    A VInt with value Int.
    A VFloat with value Real.
    A VBool with value Bool.
    A VText with value Text.
    A VSeq with items Seq of CVal.
    A VMap with entries Map of Text to CVal.
    A VError with msg Text.
    A VNothing.
    A VSet with items Seq of CVal.
    A VOption with inner CVal and present Bool.
    A VTuple with items Seq of CVal.
    A VStruct with typeName Text and fields Map of Text to CVal.
    A VVariant with typeName Text and variantName Text and fields Seq of CVal.
    A VClosure with params Seq of Text and body Seq of CStmt and capturedEnv Map of Text to CVal.
    A VDuration with millis Int.
    A VDate with year Int and month Int and day Int.
    A VMoment with millis Int.
    A VSpan with startMillis Int and endMillis Int.
    A VTime with hour Int and minute Int and second Int.
    A VCrdt with kind Text and state Map of Text to CVal.
"#;

/// Encodes the partial evaluator as CProgram construction source code.
///
/// Returns PE function definitions (so peBlock etc. are callable) followed by
/// LOGOS statements that construct the PE's functions as CFunc data in
/// `encodedFuncMap` and its main block in `encodedMain`.
/// The parser handles `## To` blocks anywhere in the token stream, so
/// function definitions placed after `## Main` are parsed correctly.
pub fn quote_pe_source() -> Result<String, String> {
    let pe_source = pe_source_text();
    let full_source = format!("{}\n{}", CORE_TYPES_FOR_PE, pe_source);
    let encoded = encode_program_source(&full_source).map_err(|e| format!("Failed to encode PE: {:?}", e))?;
    Ok(format!("{}\n{}", pe_source, encoded))
}

/// Second Futamura Projection: PE(PE, interpreter) = compiler
///
/// Specializes the partial evaluator with respect to a fixed interpreter,
/// producing a compiler that takes any CProgram as input and produces
/// optimized residual CStmt/CExpr data.
///
/// For the Core self-interpreter (which is the identity evaluator on CProgram
/// data), PE(PE, int) resolves to the PE itself operating directly on program
/// data — the interpreter's dispatch loop is the CExpr/CStmt case analysis
/// that the PE already implements. The result is the PE with its entry points
/// renamed to compileExpr/compileBlock: these ARE the specialized compiler
/// functions with no PE dispatch overhead (BTA, memoization, etc. are absent
/// because the interpreter's representation IS the PE's representation).
///
/// NOTE: this is the renamed-PE REPRESENTATION of P2 — it ASSERTS the collapse by renaming. The
/// GENUINE projection that DEMONSTRATES it by actually running `PE(pe_source, pe_mini)` is
/// [`genuine_projection2_residual`] (and [`run_genuine_p2_on_target`]). Enforcement gates use the
/// genuine path; `shortcut_quarantine_lock` forbids any Jones-certifying gate from using this rename.
pub fn projection2_source() -> Result<String, String> {
    let pe_source = pe_source_text();

    let compiler_source = replace_word(&replace_word(&pe_source, "peExpr", "compileExpr"), "peBlock", "compileBlock");

    Ok(format!("{}\n{}", CORE_TYPES_FOR_PE, compiler_source))
}

/// Third Futamura Projection: PE(PE, PE) = compiler_generator
///
/// Specializes the partial evaluator with respect to itself, producing a
/// compiler generator (cogen). Feed it any interpreter → it produces a
/// compiler for that interpreter's language.
///
/// Chain: cogen(int) → compiler → compiler(P) → compiled
///
/// For the CExpr/CStmt representation, PE(PE, PE) yields the PE with entry
/// points renamed to cogenExpr/cogenBlock. This works because the PE's
/// self-application is idempotent: the PE already operates on the same
/// representation it would specialize, so PE(PE, PE) = PE (up to naming).
/// The cogen handles different interpreters (Core, RPN, etc.) by processing
/// their encoded CProgram representations.
///
/// NOTE: the renamed-PE REPRESENTATION of P3 (asserts the collapse by renaming). The GENUINE cogen
/// that actually runs `PE(pe_source, pe_bti)` is [`genuine_projection3_residual`]. Enforcement uses
/// the genuine path; `shortcut_quarantine_lock` keeps this rename out of any Jones certificate.
pub fn projection3_source() -> Result<String, String> {
    let pe_source = pe_source_text();

    let cogen_source = replace_word(&replace_word(&pe_source, "peExpr", "cogenExpr"), "peBlock", "cogenBlock");

    Ok(format!("{}\n{}", CORE_TYPES_FOR_PE, cogen_source))
}

/// Compile and run LOGOS source, returning stdout.
///
/// Uses the full compilation pipeline: LOGOS → Rust → binary → execute.
/// This is the library-side equivalent of the test infrastructure's `run_logos()`.
pub fn run_logos_source(source: &str) -> Result<String, String> {
    let compile_output = compile_program_full(source)
        .map_err(|e| format!("Compilation failed: {:?}", e))?;

    // Create temp directory using std (no tempfile crate needed)
    let temp_base = std::env::temp_dir().join("logos_run_source");
    std::fs::create_dir_all(&temp_base)
        .map_err(|e| format!("mkdir failed: {}", e))?;

    let pkg_name = format!(
        "logos_run_{}_{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    );
    let project_dir = temp_base.join(&pkg_name);

    // Find workspace root relative to this crate
    let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_root = manifest_dir.parent().unwrap().parent().unwrap();

    let cargo_toml = format!(
        r#"[package]
name = "{}"
version = "0.1.0"
edition = "2021"

[dependencies]
logicaffeine-data = {{ path = "{}/crates/logicaffeine_data" }}
logicaffeine-system = {{ path = "{}/crates/logicaffeine_system", features = ["full"] }}
tokio = {{ version = "1", features = ["rt-multi-thread", "macros"] }}
serde = {{ version = "1", features = ["derive"] }}
rayon = "1"
"#,
        pkg_name,
        workspace_root.display(),
        workspace_root.display(),
    );

    std::fs::create_dir_all(project_dir.join("src"))
        .map_err(|e| format!("mkdir failed: {}", e))?;
    std::fs::write(project_dir.join("Cargo.toml"), cargo_toml)
        .map_err(|e| format!("Write Cargo.toml failed: {}", e))?;
    std::fs::write(project_dir.join("src/main.rs"), &compile_output.rust_code)
        .map_err(|e| format!("Write main.rs failed: {}", e))?;
    // Pin dependency resolution to the workspace's lockfile: without it each
    // generated project re-resolves from the registry and a newly published
    // transitive version can break the build.
    std::fs::copy(
        workspace_root.join("Cargo.lock"),
        project_dir.join("Cargo.lock"),
    )
    .map_err(|e| format!("Seed Cargo.lock failed: {}", e))?;

    // Use a shared target dir for caching. Under cargo-nextest, shard by the
    // per-test slot (mirrors the test harness's get_shared_target_dir) so
    // concurrent generated builds never contend on Cargo's build-dir lock.
    let shard = std::env::var("NEXTEST_TEST_GROUP_SLOT")
        .ok()
        .and_then(|s| s.parse::<u64>().ok())
        .or_else(|| {
            std::env::var("NEXTEST_TEST_GLOBAL_SLOT")
                .ok()
                .and_then(|s| s.parse::<u64>().ok())
                .map(|n| n % 12)
        });
    let target_dir = match shard {
        Some(s) => std::env::temp_dir().join(format!("logos_e2e_cache_{s}")),
        None => std::env::temp_dir().join("logos_e2e_cache"),
    };
    std::fs::create_dir_all(&target_dir)
        .map_err(|e| format!("mkdir target failed: {}", e))?;

    let mut run_cmd = std::process::Command::new("cargo");
    run_cmd
        .args(["run", "--quiet"])
        .current_dir(&project_dir)
        .env("CARGO_TARGET_DIR", &target_dir)
        .env("RUST_MIN_STACK", "268435456");
    // Bootstrap-scope: when the compiler is running its own PE / self-interpreter
    // (a `ReferenceScope`), the AOT child it spawns must run that compile-time
    // Logos under reference semantics — the partial evaluator is self-applicable
    // and only specializes when its threaded state is mutated in place.
    if crate::semantics::collections::reference_scope_active() {
        run_cmd.env("LOGOS_VALUE_SEMANTICS", "0");
    }
    let output = run_cmd
        .output()
        .map_err(|e| format!("cargo run failed: {}", e))?;

    // Clean up temp project dir AND this project's artifacts in the shared
    // cache (unique package names would otherwise accrete one binary +
    // deps/incremental/fingerprint entries per run, forever — the shared
    // DEPENDENCY builds stay, which is the entire caching win).
    let _ = std::fs::remove_dir_all(&project_dir);
    {
        let stem = pkg_name.replace('-', "_");
        let debug = target_dir.join("debug");
        let _ = std::fs::remove_file(debug.join(&pkg_name));
        let _ = std::fs::remove_file(debug.join(format!("{pkg_name}.d")));
        for sub in ["deps", "incremental", ".fingerprint", "build"] {
            if let Ok(rd) = std::fs::read_dir(debug.join(sub)) {
                for e in rd.flatten() {
                    let name = e.file_name();
                    let n = name.to_string_lossy();
                    if n.starts_with(&format!("{stem}-"))
                        || n.starts_with(&format!("lib{stem}-"))
                    {
                        let path = e.path();
                        let _ = if path.is_dir() {
                            std::fs::remove_dir_all(&path)
                        } else {
                            std::fs::remove_file(&path)
                        };
                    }
                }
            }
        }
    }

    if !output.status.success() {
        return Err(format!(
            "Execution failed (status={:?} code={:?}):\nstderr: {}\nstdout: {}",
            output.status,
            output.status.code(),
            String::from_utf8_lossy(&output.stderr),
            String::from_utf8_lossy(&output.stdout),
        ));
    }

    Ok(String::from_utf8_lossy(&output.stdout).to_string())
}

/// Result of a genuine Futamura projection via self-application.
/// Contains the LOGOS source of the residual and the discovered entry points.
pub struct GenuineProjectionResult {
    /// The LOGOS source of the genuine residual — exactly as the PE produced it,
    /// including specialized function definitions and a ## Main block.
    pub source: String,
    /// The name of the block-level entry point (e.g., "peBlockM_d_vPEMiniR_...").
    /// This is the specialized function that takes a Seq of CStmt and returns Seq of CStmt.
    pub block_entry: String,
    /// The name of the expression-level entry point, if discovered.
    pub expr_entry: Option<String>,
}

/// Discover specialized entry points from a PE residual.
/// Searches for `## To {prefix}_...` function definitions in the residual source.
fn discover_entry_points(residual: &str, block_prefix: &str, expr_prefix: &str)
    -> (String, Option<String>)
{
    let mut block_entry = String::new();
    let mut expr_entry = None;
    for line in residual.lines() {
        let trimmed = line.trim();
        if let Some(rest) = trimmed.strip_prefix("## To ") {
            // Extract function name: everything before the first ' ('
            let name = rest.split(" (").next().unwrap_or("").trim();
            if name.starts_with(block_prefix) && block_entry.is_empty() {
                block_entry = name.to_string();
            } else if name.starts_with(expr_prefix) && expr_entry.is_none() {
                expr_entry = Some(name.to_string());
            }
        }
    }
    (block_entry, expr_entry)
}

/// Real Futamura Projection 1: pe(program) = compiled_program
///
/// Encodes the program as CProgram data, runs the LOGOS PE on it,
/// decompiles the residual back to LOGOS source.
pub fn projection1_source_real(core_types: &str, _interpreter: &str, program: &str) -> Result<String, String> {
    let full_source = if program.contains("## Main") || program.contains("## To ") {
        program.to_string()
    } else {
        format!("## Main\n{}", program)
    };

    // Step 1: Encode the program as CProgram construction source
    let encoded = encode_program_source(&full_source)
        .map_err(|e| format!("Failed to encode program: {:?}", e))?;

    // Step 2: Get PE source and decompile source
    let pe_source = pe_source_text();
    let decompile_source = decompile_source_text();

    // Step 3: Build the combined source
    let actual_core_types = if core_types.is_empty() { CORE_TYPES_FOR_PE } else { core_types };

    let driver = r#"
    Let state be makePeState(a new Map of Text to CVal, encodedFuncMap, 200).
    Let residual be peBlock(encodedMain, state).
    Let source be decompileBlock(residual, 0).
    Show source.
"#;

    let combined = format!(
        "{}\n{}\n{}\n## Main\n{}\n{}",
        actual_core_types,
        pe_source,
        decompile_source,
        encoded,
        driver,
    );

    // Step 4: Compile and run to get the decompiled residual
    let raw_residual = run_logos_source(&combined)?;
    let trimmed = raw_residual.trim();

    // Step 5: Wrap in ## Main if needed
    if trimmed.is_empty() {
        return Ok("## Main\n".to_string());
    }

    // Check if the residual already has function definitions
    if trimmed.contains("## To ") || trimmed.starts_with("## Main") {
        Ok(trimmed.to_string())
    } else {
        Ok(format!("## Main\n{}", trimmed))
    }
}

/// In-process variant of [`projection1_source_real`].
///
/// Identical in every respect except that the combined PE source is executed by the
/// tree-walking interpreter via [`interpret_program`] rather than compiled to Rust and
/// run through `cargo` ([`run_logos_source`]). This makes the genuine LOGOS partial
/// evaluator cheap enough to drive a generative/differential test corpus.
pub fn projection1_source_real_fast(core_types: &str, _interpreter: &str, program: &str) -> Result<String, String> {
    let combined = pe_combined_source(core_types, program)?;

    let raw_residual = interpret_program(&combined)
        .map_err(|e| format!("PE execution failed: {:?}", e))?;
    let residual = finish_projection1_residual(raw_residual)?;
    // The residual is statements-only (`## To` specialized funcs + `## Main`); re-attach the
    // program's TYPE DEFINITIONS so a `new <Struct>` in the residual can default-fill its
    // fields — e.g. a `Shared` struct's CRDT `SharedSet`/`SharedSequence` field, which has no
    // explicit constructor argument and is materialized solely from the definition.
    Ok(prepend_type_definitions(program, residual))
}

pub use crate::concurrency::marshal::{decode_value_raw, encode_value_raw};

/// The self-interpreter (`coreEval` / `coreExecBlock`) as a first-class committed artifact — the
/// Logos program the genuine P2/P3 projections specialize (Futamura: `pe(pe, coreEval)` is a
/// compiler). Promoted out of the `phase_futamura` test fixture so it is a real source file, not a
/// string constant; the fixture now `include_str!`s this exact file (parity is structural).
pub fn core_interp_source() -> &'static str {
    include_str!("optimize/core_interp.logos")
}

/// The compile-once native partial evaluator's SOURCE: the PE engine + decompiler + a driver
/// that reads its input `CProgram` from stdin (over the fast wire codec) instead of a baked-in
/// constructor. Compiled ONCE (content-addressed on this text) with `WireEncode`/`WireDecode`
/// emitted, it specializes any program handed to it as `program_to_core_wire_bytes` — the true
/// Futamura "compiler as an artifact", at native speed. The driver body is identical to
/// [`pe_combined_source`]'s (same transitive-decompile), only `encodedMain`/`encodedFuncMap`
/// come from `readWireProgram()` rather than the encoded program text.
/// The transitive-decompile driver logic shared by the resident-server PE (`pe_native_source`,
/// terminal statement writes the residual to stdout) and the in-process cdylib PE
/// (`pe_cdylib_source`, terminal statement `Return`s it). Everything up to that last statement is
/// identical — computing `output`, the Jones-optimal residual source, from `encodedMain` +
/// `encodedFuncMap`. Written at 0-base indent; the caller re-indents it under its enclosing arm.
const PE_DRIVER_CORE: &str = r#"Let state be makePeState(a new Map of Text to CVal, encodedFuncMap, 200).
Let residual be peBlock(encodedMain, state).
Let nl be chr(10).
Let mutable output be "".
Let specFuncs be peFuncs(state).
Let mutable allNames be collectCallNames(residual).
Let mutable emitted be a new Map of Text to Bool.
Let mutable changed be true.
While changed:
    Set changed to false.
    Let mutable toAdd be a new Seq of Text.
    Repeat for fnKey in allNames:
        Let fkStr be "{fnKey}".
        If emitted contains fkStr:
            Let skipE be true.
        Otherwise:
            Set item fkStr of emitted to true.
            Let fkStr2 be "{fnKey}".
            If specFuncs contains fkStr2:
                Let fdef be item fkStr2 of specFuncs.
                Inspect fdef:
                    When CFuncDef (fn0, ps0, pt0, rt0, body0):
                        Let children be collectCallNames(body0).
                        Repeat for child in children:
                            Let childStr be "{child}".
                            If not emitted contains childStr:
                                Push child to toAdd.
                                Set changed to true.
                    Otherwise:
                        Let skipF be true.
    Repeat for ta in toAdd:
        Push ta to allNames.
Repeat for fnKey in allNames:
    Let fkStr be "{fnKey}".
    If specFuncs contains fkStr:
        Let fdef be item fkStr of specFuncs.
        Let funcSrc be decompileFunc(fdef).
        If the length of funcSrc is greater than 0:
            Set output to "{output}{funcSrc}{nl}".
Let mainSrc be decompileBlock(residual, 0).
Set output to "{output}## Main{nl}{mainSrc}"."#;

/// The PE driver body with `last` appended as its terminal statement — the only line that differs
/// between the stdout-writing server and the value-returning cdylib entry.
fn pe_driver_body(last: &str) -> String {
    format!("{PE_DRIVER_CORE}\n{last}")
}

pub fn pe_native_source() -> String {
    let core = CORE_TYPES_FOR_PE;
    let pe = pe_source_text();
    let decompile = decompile_source_text();
    // The transitive-decompile driver body, written at 0-base indent — identical logic to
    // `pe_combined_source`. It is re-indented under the `When CProg` arm below so the CProg fields
    // (`LogosSeq`-typed, not the `Vec` a declared `Seq` return would be) stay in scope with the
    // right runtime type — sidestepping the return-type/field-type codegen mismatch.
    let driver_body = pe_driver_body("Let __wrn be writeWireResidual(output).");
    // Resident-server loop: `While true` reads one length-framed program per iteration
    // (`readWireProgram` exits the process on stdin EOF), specializes it, and writes the residual
    // back length-framed (`writeWireResidual`). Spawned ONCE by the host and reused — no per-call
    // process spawn. Indent the driver body to 16 spaces (inside the `When CProg` arm inside `While`).
    let indented: String = driver_body
        .lines()
        .map(|l| if l.is_empty() { String::new() } else { format!("                {l}") })
        .collect::<Vec<_>>()
        .join("\n");
    let main = format!(
        "    While true:\n        Let __prog be readWireProgram().\n        Inspect __prog:\n            When CProg (encFuncs, encMain):\n                Let encodedMain be encMain.\n                Let mutable encodedFuncMap be a new Map of Text to CFunc.\n                Repeat for __f in encFuncs:\n                    Inspect __f:\n                        When CFuncDef (__nm, __ps, __pt, __rt, __bd):\n                            Set item __nm of encodedFuncMap to __f.\n                        Otherwise:\n                            Let __skip be true.\n{indented}\n            Otherwise:\n                Let __wrn be writeWireResidual(\"\").\n"
    );
    format!("{}\n{}\n{}\n## Main\n{}", core, pe, decompile, main)
}

/// The PE as an IN-PROCESS cdylib entry: the identical engine to [`pe_native_source`], but the
/// driver is a single-shot `## To peSpecializeOnce (__prog: CProgram) -> Text` that RETURNS the
/// residual instead of writing it to stdout — no `readWireProgram`/`writeWireResidual`, no stdin
/// loop. The exported cdylib ([`build_native_pe_cdylib`]) decodes the wire bytes to a `CProgram` in
/// its `extern "C"` shim and calls this function directly, so the resident server's process/pipe
/// round-trip is gone. `## Main` is a trivial stub (a cdylib never runs it).
pub fn pe_cdylib_source() -> String {
    let core = CORE_TYPES_FOR_PE;
    let pe = pe_source_text();
    let decompile = decompile_source_text();
    // Same driver as the server, terminated by `Return output.`; re-indented to 12 spaces to sit
    // inside the `When CProg` arm of the function body (one level shallower than the server's
    // `While`-nested main).
    let driver_body = pe_driver_body("Return output.");
    let indented: String = driver_body
        .lines()
        .map(|l| if l.is_empty() { String::new() } else { format!("            {l}") })
        .collect::<Vec<_>>()
        .join("\n");
    let func = format!(
        "## To peSpecializeOnce (__prog: CProgram) -> Text:\n    Inspect __prog:\n        When CProg (encFuncs, encMain):\n            Let encodedMain be encMain.\n            Let mutable encodedFuncMap be a new Map of Text to CFunc.\n            Repeat for __f in encFuncs:\n                Inspect __f:\n                    When CFuncDef (__nm, __ps, __pt, __rt, __bd):\n                        Set item __nm of encodedFuncMap to __f.\n                    Otherwise:\n                        Let __skip be true.\n{indented}\n        Otherwise:\n            Return \"\".\n"
    );
    format!("{}\n{}\n{}\n{}\n## Main\n    Let __x be 0.\n", core, pe, decompile, func)
}

use crate::interpreter::RuntimeValue;

// ── Native Core-IR value builder ───────────────────────────────────────────────────────────
// Builds the `CProgram` VALUE directly in Rust — no interpreter, no re-parse of the 140-line
// CORE_TYPES type context (the marshal's dominant cost). Mirrors `encode_expr_src`/`encode_stmt_src`
// but emits `RuntimeValue::Inductive` (constructor + fields IN DECLARATION ORDER). The `inductive_type`
// is a placeholder: the native `CProgram::wire_decode` dispatches on the constructor and ignores the
// type name. Any construct not covered here returns `None`, and the caller falls back to the proven
// interpreter path — so a gap is slower, never wrong. Residual-equivalence with the interpreter path
// is locked by `native_pe_wire` + the `pe_jones_fuzz` corpus.

/// The Core-IR ENUM a constructor belongs to — so the built value's `inductive_type` matches what
/// the interpreter records (`a new CInt` → `Inductive{ inductive_type: "CExpr", constructor: "CInt" }`),
/// making the native builder's wire bytes byte-identical to the interpreter path. The native decoder
/// ignores this field, but matching it keeps every byte-level lock exact.
fn cv_enum(ctor: &str) -> &'static str {
    match ctor {
        "CProg" => "CProgram",
        "CFuncDef" => "CFunc",
        "CLiteralPart" | "CExprPart" => "CStringPart",
        "CInt" | "CBool" | "CText" | "CFloat" | "CVar" | "CBinOp" | "CNot" | "CCall" | "CIndex"
        | "CLen" | "CMapGet" | "CList" | "CTuple" | "CRange" | "CSlice" | "CCopy" | "CContains"
        | "CUnion" | "CIntersection" | "COptionSome" | "COptionNone" | "CNewSeq" | "CNewSet"
        | "CNew" | "CNewVariant" | "CInterpolatedString" | "CClosure" | "CDuration"
        | "CCallExpr" | "CChunkAt" | "CEscExpr" | "CManifestOf" => "CExpr",
        "CSelectRecv" | "CSelectTimeout" => "CSelectBranch",
        _ => "CStmt",
    }
}

fn cv_ind(ctor: &str, args: Vec<RuntimeValue>) -> RuntimeValue {
    RuntimeValue::Inductive(Box::new(crate::interpreter::InductiveValue {
        inductive_type: cv_enum(ctor).to_string(),
        constructor: ctor.to_string(),
        args,
    }))
}
fn cv_text(s: &str) -> RuntimeValue {
    RuntimeValue::Text(std::rc::Rc::new(s.to_string()))
}
fn cv_list(items: Vec<RuntimeValue>) -> RuntimeValue {
    RuntimeValue::List(std::rc::Rc::new(std::cell::RefCell::new(
        crate::interpreter::ListRepr::from_values(items),
    )))
}

/// The binary-operator spelling — IDENTICAL to `encode_expr_src`'s `op_str` (the residual re-parses it).
fn cv_binop_str(op: BinaryOpKind) -> &'static str {
    match op {
        BinaryOpKind::Add => "+",
        BinaryOpKind::Subtract => "-",
        BinaryOpKind::Multiply => "*",
        BinaryOpKind::Divide | BinaryOpKind::ExactDivide => "/",
        BinaryOpKind::FloorDivide => "//",
        BinaryOpKind::Modulo => "%",
        BinaryOpKind::Eq => "==",
        BinaryOpKind::NotEq => "!=",
        BinaryOpKind::Lt => "<",
        BinaryOpKind::Gt => ">",
        BinaryOpKind::LtEq => "<=",
        BinaryOpKind::GtEq => ">=",
        BinaryOpKind::And => "&&",
        BinaryOpKind::Or => "||",
        BinaryOpKind::Concat => "+",
        BinaryOpKind::SeqConcat => "followed by",
        BinaryOpKind::ApproxEq => "is approximately",
        BinaryOpKind::Pow => "**",
        BinaryOpKind::BitXor => "^",
        BinaryOpKind::BitAnd => "&",
        BinaryOpKind::BitOr => "|",
        BinaryOpKind::Shl => "<<",
        BinaryOpKind::Shr => ">>",
    }
}

type VCtors = std::collections::HashMap<String, Vec<String>>;

/// A backend for the Core-IR builder. ONE generic AST traversal (`expr_to_core` / `stmt_to_core` /
/// `build_core`) drives EITHER the reference tree builder ([`TreeSink`] → a `RuntimeValue`, the form
/// `encode_value_raw` serializes) OR the single-pass wire emitter ([`WireSink`] → exactly those
/// `encode_value_raw` bytes with NO intermediate `RuntimeValue` tree and NO second encode walk).
/// Byte-identity of the two backends is locked by `native_builder_is_byte_identical_to_the_interpreter`
/// and the single-pass tests — so there is no way for them to silently diverge.
trait CoreSink {
    type Val;
    fn int(n: i64) -> Self::Val;
    fn boolean(b: bool) -> Self::Val;
    fn float(f: f64) -> Self::Val;
    fn text(s: &str) -> Self::Val;
    fn list(items: Vec<Self::Val>) -> Self::Val;
    fn inductive(ctor: &str, args: Vec<Self::Val>) -> Self::Val;
}

/// Builds the reference `RuntimeValue` Core-IR tree (what `encode_value_raw` serializes).
struct TreeSink;
impl CoreSink for TreeSink {
    type Val = RuntimeValue;
    fn int(n: i64) -> RuntimeValue {
        RuntimeValue::Int(n)
    }
    fn boolean(b: bool) -> RuntimeValue {
        RuntimeValue::Bool(b)
    }
    fn float(f: f64) -> RuntimeValue {
        RuntimeValue::Float(f)
    }
    fn text(s: &str) -> RuntimeValue {
        cv_text(s)
    }
    fn list(items: Vec<RuntimeValue>) -> RuntimeValue {
        cv_list(items)
    }
    fn inductive(ctor: &str, args: Vec<RuntimeValue>) -> RuntimeValue {
        cv_ind(ctor, args)
    }
}

/// Emits the wire bytes DIRECTLY — byte-for-byte what `encode_value_raw` (flat lists, structure off,
/// dedup off) produces for the equivalent [`TreeSink`] value, but with no `RuntimeValue` allocation
/// and no second walk. Each node returns its own encoded bytes; a parent writes its header then
/// concatenates its children. The `logicaffeine_data::wire` primitives are proven byte-identical to
/// the peer `native_encode` by `peer_and_wire_core_produce_identical_bytes`.
struct WireSink;
impl CoreSink for WireSink {
    type Val = Vec<u8>;
    fn int(n: i64) -> Vec<u8> {
        let mut v = Vec::with_capacity(4);
        v.push(logicaffeine_data::wire::T_INT);
        logicaffeine_data::wire::write_uvarint(logicaffeine_data::wire::zigzag(n), &mut v);
        v
    }
    fn boolean(b: bool) -> Vec<u8> {
        vec![if b { logicaffeine_data::wire::T_TRUE } else { logicaffeine_data::wire::T_FALSE }]
    }
    fn float(f: f64) -> Vec<u8> {
        let mut v = Vec::with_capacity(9);
        v.push(logicaffeine_data::wire::T_FLOAT);
        v.extend_from_slice(&f.to_le_bytes());
        v
    }
    fn text(s: &str) -> Vec<u8> {
        let mut v = Vec::with_capacity(2 + s.len());
        v.push(logicaffeine_data::wire::T_TEXT);
        logicaffeine_data::wire::write_str(s, &mut v);
        v
    }
    fn list(items: Vec<Vec<u8>>) -> Vec<u8> {
        let mut v = Vec::new();
        v.push(logicaffeine_data::wire::T_LIST);
        logicaffeine_data::wire::write_uvarint(items.len() as u64, &mut v);
        for it in &items {
            v.extend_from_slice(it);
        }
        v
    }
    fn inductive(ctor: &str, args: Vec<Vec<u8>>) -> Vec<u8> {
        let mut v = Vec::new();
        logicaffeine_data::wire::write_inductive_header(&mut v, cv_enum(ctor), ctor, args.len() as u64);
        for a in &args {
            v.extend_from_slice(a);
        }
        v
    }
}

fn exprs_to_core<S: CoreSink>(args: &[&Expr], interner: &Interner, vctors: &VCtors) -> Option<Vec<S::Val>> {
    let mut out = Vec::with_capacity(args.len());
    for a in args {
        out.push(expr_to_core::<S>(a, interner, vctors)?);
    }
    Some(out)
}

fn expr_to_core<S: CoreSink>(expr: &Expr, interner: &Interner, vctors: &VCtors) -> Option<S::Val> {
    Some(match expr {
        Expr::Literal(Literal::Number(n)) => S::inductive("CInt", vec![S::int(*n)]),
        Expr::Literal(Literal::Boolean(b)) => S::inductive("CBool", vec![S::boolean(*b)]),
        Expr::Literal(Literal::Text(s)) => S::inductive("CText", vec![S::text(interner.resolve(*s))]),
        Expr::Literal(Literal::Float(f)) => S::inductive("CFloat", vec![S::float(*f)]),
        // A duration literal (`1 seconds`, `500 milliseconds`) → `CDuration{amount = CInt(ms), unit}`,
        // normalized to milliseconds exactly as the reference does (used by `Sleep` and `Select`'s
        // `After …` timeout).
        Expr::Literal(Literal::Duration(nanos)) => S::inductive(
            "CDuration",
            vec![S::inductive("CInt", vec![S::int(nanos / 1_000_000)]), S::text("milliseconds")],
        ),
        Expr::Literal(Literal::Nothing) => S::inductive("CText", vec![S::text("nothing")]),
        Expr::Identifier(sym) => S::inductive("CVar", vec![S::text(interner.resolve(*sym))]),
        Expr::BinaryOp { op, left, right } => S::inductive(
            "CBinOp",
            vec![S::text(cv_binop_str(*op)), expr_to_core::<S>(left, interner, vctors)?, expr_to_core::<S>(right, interner, vctors)?],
        ),
        Expr::Not { operand } => S::inductive("CNot", vec![expr_to_core::<S>(operand, interner, vctors)?]),
        Expr::Call { function, args } => {
            let fn_name = interner.resolve(*function);
            if let Some(field_names) = vctors.get(fn_name) {
                // Variant constructor call → CNewVariant (field names from the type registry).
                let mut fnames: Vec<S::Val> = Vec::with_capacity(args.len());
                let mut fvals: Vec<S::Val> = Vec::with_capacity(args.len());
                for (i, a) in args.iter().enumerate() {
                    fnames.push(S::text(field_names.get(i).map(|s| s.as_str()).unwrap_or("value")));
                    fvals.push(expr_to_core::<S>(a, interner, vctors)?);
                }
                S::inductive("CNewVariant", vec![S::text(fn_name), S::list(fnames), S::list(fvals)])
            } else {
                let avals = exprs_to_core::<S>(args, interner, vctors)?;
                S::inductive("CCall", vec![S::text(fn_name), S::list(avals)])
            }
        }
        Expr::Index { collection, index } => S::inductive(
            "CIndex",
            vec![expr_to_core::<S>(collection, interner, vctors)?, expr_to_core::<S>(index, interner, vctors)?],
        ),
        Expr::Length { collection } => S::inductive("CLen", vec![expr_to_core::<S>(collection, interner, vctors)?]),
        Expr::FieldAccess { object, field } => S::inductive(
            "CMapGet",
            vec![expr_to_core::<S>(object, interner, vctors)?, S::inductive("CText", vec![S::text(interner.resolve(*field))])],
        ),
        Expr::List(elems) => {
            let mut items: Vec<S::Val> = Vec::with_capacity(elems.len());
            for e in elems.iter() {
                items.push(expr_to_core::<S>(e, interner, vctors)?);
            }
            S::inductive("CList", vec![S::list(items)])
        }
        Expr::Tuple(elems) => {
            let mut items: Vec<S::Val> = Vec::with_capacity(elems.len());
            for e in elems.iter() {
                items.push(expr_to_core::<S>(e, interner, vctors)?);
            }
            S::inductive("CTuple", vec![S::list(items)])
        }
        Expr::Range { start, end } => S::inductive("CRange", vec![expr_to_core::<S>(start, interner, vctors)?, expr_to_core::<S>(end, interner, vctors)?]),
        Expr::Slice { collection, start, end } => S::inductive(
            "CSlice",
            vec![expr_to_core::<S>(collection, interner, vctors)?, expr_to_core::<S>(start, interner, vctors)?, expr_to_core::<S>(end, interner, vctors)?],
        ),
        Expr::Copy { expr } => S::inductive("CCopy", vec![expr_to_core::<S>(expr, interner, vctors)?]),
        Expr::Contains { collection, value } => S::inductive("CContains", vec![expr_to_core::<S>(collection, interner, vctors)?, expr_to_core::<S>(value, interner, vctors)?]),
        Expr::Union { left, right } => S::inductive("CUnion", vec![expr_to_core::<S>(left, interner, vctors)?, expr_to_core::<S>(right, interner, vctors)?]),
        Expr::Intersection { left, right } => S::inductive("CIntersection", vec![expr_to_core::<S>(left, interner, vctors)?, expr_to_core::<S>(right, interner, vctors)?]),
        Expr::OptionSome { value } => S::inductive("COptionSome", vec![expr_to_core::<S>(value, interner, vctors)?]),
        Expr::OptionNone => S::inductive("COptionNone", vec![]),
        Expr::InterpolatedString(parts) => {
            if parts.is_empty() {
                S::inductive("CText", vec![S::text("")])
            } else {
                let mut pvals: Vec<S::Val> = Vec::with_capacity(parts.len());
                for part in parts {
                    pvals.push(match part {
                        StringPart::Literal(sym) => S::inductive("CLiteralPart", vec![S::text(interner.resolve(*sym))]),
                        StringPart::Expr { value, .. } => S::inductive("CExprPart", vec![expr_to_core::<S>(value, interner, vctors)?]),
                    });
                }
                S::inductive("CInterpolatedString", vec![S::list(pvals)])
            }
        }
        Expr::NewVariant { variant, fields, .. } => {
            let mut fnames: Vec<S::Val> = Vec::with_capacity(fields.len());
            let mut fvals: Vec<S::Val> = Vec::with_capacity(fields.len());
            for (fname, fexpr) in fields {
                fnames.push(S::text(interner.resolve(*fname)));
                fvals.push(expr_to_core::<S>(fexpr, interner, vctors)?);
            }
            S::inductive("CNewVariant", vec![S::text(interner.resolve(*variant)), S::list(fnames), S::list(fvals)])
        }
        Expr::New { type_name, init_fields, .. } => {
            let tn = interner.resolve(*type_name);
            if tn == "Seq" || tn == "List" {
                S::inductive("CNewSeq", vec![])
            } else if tn == "Set" {
                S::inductive("CNewSet", vec![])
            } else if tn == "Map" || tn.starts_with("Map ") {
                S::inductive("CNew", vec![S::text("Map"), S::list(vec![]), S::list(vec![])])
            } else if init_fields.is_empty() {
                S::inductive("CNewVariant", vec![S::text(tn), S::list(vec![]), S::list(vec![])])
            } else {
                let mut fnames: Vec<S::Val> = Vec::with_capacity(init_fields.len());
                let mut fvals: Vec<S::Val> = Vec::with_capacity(init_fields.len());
                for (fname, fexpr) in init_fields {
                    fnames.push(S::text(interner.resolve(*fname)));
                    fvals.push(expr_to_core::<S>(fexpr, interner, vctors)?);
                }
                S::inductive("CNew", vec![S::text(tn), S::list(fnames), S::list(fvals)])
            }
        }
        // Closure: params (Seq Text), body (Seq CStmt), captured free vars (Seq Text, SORTED to
        // match the now-deterministic reference encoder). An expression body wraps as `CReturn e`.
        Expr::Closure { params, body, .. } => {
            let mut bound: std::collections::HashSet<String> = std::collections::HashSet::new();
            let mut param_vals: Vec<S::Val> = Vec::with_capacity(params.len());
            for (sym, _) in params {
                let name = interner.resolve(*sym);
                bound.insert(name.to_string());
                param_vals.push(S::text(name));
            }
            let body_vals: Vec<S::Val> = match body {
                ClosureBody::Expression(e) => {
                    vec![S::inductive("CReturn", vec![expr_to_core::<S>(e, interner, vctors)?])]
                }
                ClosureBody::Block(stmts) => {
                    let mut bv: Vec<S::Val> = Vec::with_capacity(stmts.len());
                    for s in stmts.iter() {
                        // The reference encodes body stmts with the single-stmt encoder, which
                        // defers Inspect/Repeat to empty; fall back rather than replicate that quirk.
                        if matches!(s, Stmt::Inspect { .. } | Stmt::Repeat { .. }) {
                            return None;
                        }
                        bv.push(stmt_to_core::<S>(s, interner, vctors)?);
                    }
                    bv
                }
            };
            let mut free: Vec<String> =
                collect_free_vars_expr(expr, interner, &bound).into_iter().collect();
            free.sort();
            let cap_vals: Vec<S::Val> = free.iter().map(|fv| S::text(fv)).collect();
            S::inductive("CClosure", vec![S::list(param_vals), S::list(body_vals), S::list(cap_vals)])
        }
        // A callee-expression call (`(f)(x)`) → `CCallExpr{target, args}`.
        Expr::CallExpr { callee, args } => {
            let mut avals: Vec<S::Val> = Vec::with_capacity(args.len());
            for a in args.iter() {
                avals.push(expr_to_core::<S>(a, interner, vctors)?);
            }
            S::inductive("CCallExpr", vec![expr_to_core::<S>(callee, interner, vctors)?, S::list(avals)])
        }
        Expr::ChunkAt { index, zone } => S::inductive(
            "CChunkAt",
            vec![expr_to_core::<S>(index, interner, vctors)?, expr_to_core::<S>(zone, interner, vctors)?],
        ),
        Expr::ManifestOf { zone } => S::inductive("CManifestOf", vec![expr_to_core::<S>(zone, interner, vctors)?]),
        Expr::Escape { code, .. } => S::inductive("CEscExpr", vec![S::text(interner.resolve(*code))]),
        // `Give`/`WithCapacity` are transparent: the reference encodes the inner value with no node
        // (an ownership move / an allocation hint the interpreter erases).
        Expr::Give { value } => expr_to_core::<S>(value, interner, vctors)?,
        Expr::WithCapacity { value, .. } => expr_to_core::<S>(value, interner, vctors)?,
        _ => return None,
    })
}

fn stmt_to_core<S: CoreSink>(stmt: &Stmt, interner: &Interner, vctors: &VCtors) -> Option<S::Val> {
    Some(match stmt {
        Stmt::Let { var, value, .. } => S::inductive("CLet", vec![S::text(interner.resolve(*var)), expr_to_core::<S>(value, interner, vctors)?]),
        Stmt::Set { target, value } => S::inductive("CSet", vec![S::text(interner.resolve(*target)), expr_to_core::<S>(value, interner, vctors)?]),
        Stmt::Show { object, .. } => S::inductive("CShow", vec![expr_to_core::<S>(object, interner, vctors)?]),
        Stmt::SetIndex { collection, index, value } => S::inductive(
            "CSetIdx",
            vec![S::text(&extract_ident_name(collection, interner)), expr_to_core::<S>(index, interner, vctors)?, expr_to_core::<S>(value, interner, vctors)?],
        ),
        Stmt::SetField { object, field, value } => S::inductive(
            "CMapSet",
            vec![
                S::text(&extract_ident_name(object, interner)),
                S::inductive("CText", vec![S::text(interner.resolve(*field))]),
                expr_to_core::<S>(value, interner, vctors)?,
            ],
        ),
        Stmt::Pop { collection, .. } => S::inductive("CPop", vec![S::text(&extract_ident_name(collection, interner))]),
        Stmt::Give { object, recipient } => S::inductive(
            "CGive",
            vec![expr_to_core::<S>(object, interner, vctors)?, S::text(&extract_ident_name(recipient, interner))],
        ),
        Stmt::Sleep { milliseconds } => S::inductive("CSleep", vec![expr_to_core::<S>(milliseconds, interner, vctors)?]),
        Stmt::RuntimeAssert { condition, hard } => S::inductive(
            if *hard { "CHardAssert" } else { "CRuntimeAssert" },
            vec![expr_to_core::<S>(condition, interner, vctors)?, S::inductive("CText", vec![S::text("assertion failed")])],
        ),
        Stmt::Return { value } => {
            let e = match value {
                Some(v) => expr_to_core::<S>(v, interner, vctors)?,
                None => S::inductive("CInt", vec![S::int(0)]),
            };
            S::inductive("CReturn", vec![e])
        }
        Stmt::Break => S::inductive("CBreak", vec![]),
        Stmt::If { cond, then_block, else_block } => {
            let cond_v = expr_to_core::<S>(cond, interner, vctors)?;
            let then_s: Vec<&Stmt> = then_block.iter().collect();
            let then_v = stmt_list_to_core::<S>(&then_s, interner, vctors)?;
            let else_v = match else_block {
                Some(els) => {
                    let else_s: Vec<&Stmt> = els.iter().collect();
                    stmt_list_to_core::<S>(&else_s, interner, vctors)?
                }
                None => S::list(vec![]),
            };
            S::inductive("CIf", vec![cond_v, then_v, else_v])
        }
        Stmt::While { cond, body, .. } => {
            let cond_v = expr_to_core::<S>(cond, interner, vctors)?;
            let body_s: Vec<&Stmt> = body.iter().collect();
            S::inductive("CWhile", vec![cond_v, stmt_list_to_core::<S>(&body_s, interner, vctors)?])
        }
        Stmt::Call { function, args } => {
            let mut avals: Vec<S::Val> = Vec::with_capacity(args.len());
            for a in args {
                avals.push(expr_to_core::<S>(a, interner, vctors)?);
            }
            S::inductive("CCallS", vec![S::text(interner.resolve(*function)), S::list(avals)])
        }
        Stmt::Push { value, collection } => S::inductive(
            "CPush",
            vec![expr_to_core::<S>(value, interner, vctors)?, S::text(&extract_ident_name(collection, interner))],
        ),
        Stmt::Repeat { pattern, iterable, body, .. } => {
            let loop_var = match pattern {
                Pattern::Identifier(sym) => interner.resolve(*sym).to_string(),
                Pattern::Tuple(syms) => syms.first().map(|s| interner.resolve(*s).to_string()).unwrap_or_else(|| "item".to_string()),
            };
            let body_s: Vec<&Stmt> = body.iter().collect();
            let body_v = stmt_list_to_core::<S>(&body_s, interner, vctors)?;
            if let Expr::Range { start, end } = iterable {
                S::inductive(
                    "CRepeatRange",
                    vec![S::text(&loop_var), expr_to_core::<S>(start, interner, vctors)?, expr_to_core::<S>(end, interner, vctors)?, body_v],
                )
            } else {
                S::inductive("CRepeat", vec![S::text(&loop_var), expr_to_core::<S>(iterable, interner, vctors)?, body_v])
            }
        }
        // CRDT ops (mirror `encode_stmt_src`; declaration order from CORE_TYPES_FOR_PE).
        Stmt::Add { value, collection } => S::inductive(
            "CAdd",
            vec![expr_to_core::<S>(value, interner, vctors)?, S::text(&extract_ident_name(collection, interner))],
        ),
        Stmt::Remove { value, collection } => S::inductive(
            "CRemove",
            vec![expr_to_core::<S>(value, interner, vctors)?, S::text(&extract_ident_name(collection, interner))],
        ),
        Stmt::MergeCrdt { source, target } => S::inductive(
            "CMerge",
            vec![S::text(&extract_ident_name(target, interner)), expr_to_core::<S>(source, interner, vctors)?],
        ),
        Stmt::IncreaseCrdt { object, field, amount } => S::inductive(
            "CIncrease",
            vec![
                S::text(&format!("{}'s {}", extract_ident_name(object, interner), interner.resolve(*field))),
                expr_to_core::<S>(amount, interner, vctors)?,
            ],
        ),
        Stmt::DecreaseCrdt { object, field, amount } => S::inductive(
            "CDecrease",
            vec![
                S::text(&format!("{}'s {}", extract_ident_name(object, interner), interner.resolve(*field))),
                expr_to_core::<S>(amount, interner, vctors)?,
            ],
        ),
        // Task launch (both handled forms; body is a single `CCallS`, handle defaults to `_task`).
        Stmt::LaunchTask { function, args } | Stmt::LaunchTaskWithHandle { function, args, .. } => {
            let func_name = interner.resolve(*function);
            let mut avals: Vec<S::Val> = Vec::with_capacity(args.len());
            for a in args {
                avals.push(expr_to_core::<S>(a, interner, vctors)?);
            }
            let call = S::inductive("CCallS", vec![S::text(func_name), S::list(avals)]);
            let body = S::list(vec![call]);
            let handle_name = if let Stmt::LaunchTaskWithHandle { handle, .. } = stmt {
                interner.resolve(*handle).to_string()
            } else {
                "_task".to_string()
            };
            S::inductive("CLaunchTask", vec![body, S::text(&handle_name)])
        }
        // Concurrency: one branch (Seq of CStmt) per task. The reference encodes each task with the
        // single-stmt encoder, which defers Inspect/Repeat to an EMPTY branch; rather than replicate
        // that quirk, fall back the whole program if a task is one of those.
        Stmt::Concurrent { tasks } => {
            let mut branches: Vec<S::Val> = Vec::with_capacity(tasks.len());
            for task in tasks.iter() {
                if matches!(task, Stmt::Inspect { .. } | Stmt::Repeat { .. }) {
                    return None;
                }
                branches.push(S::list(vec![stmt_to_core::<S>(task, interner, vctors)?]));
            }
            S::inductive("CConcurrent", vec![S::list(branches)])
        }
        Stmt::Parallel { tasks } => {
            let mut branches: Vec<S::Val> = Vec::with_capacity(tasks.len());
            for task in tasks.iter() {
                if matches!(task, Stmt::Inspect { .. } | Stmt::Repeat { .. }) {
                    return None;
                }
                branches.push(S::list(vec![stmt_to_core::<S>(task, interner, vctors)?]));
            }
            S::inductive("CParallel", vec![S::list(branches)])
        }
        // Sequence append (`Append x to d's lines`) — the base struct is forced dynamic at the list
        // level (see `stmt_list_to_vec`); here just the op. `target` round-trips as surface syntax.
        Stmt::AppendToSequence { sequence, value } => S::inductive(
            "CAppendToSeq",
            vec![S::text(&extract_ident_name(sequence, interner)), expr_to_core::<S>(value, interner, vctors)?],
        ),
        // Pipes / channels. Capacity is a `CInt` expression node (default 32, matching the reference).
        Stmt::CreatePipe { var: pipe_var, capacity, .. } => {
            let cap = capacity.unwrap_or(32);
            S::inductive(
                "CCreatePipe",
                vec![S::text(interner.resolve(*pipe_var)), S::inductive("CInt", vec![S::int(cap as i64)])],
            )
        }
        Stmt::SendPipe { value, pipe } => S::inductive(
            "CSendPipe",
            vec![S::text(&pipe_ident_name(pipe, interner)), expr_to_core::<S>(value, interner, vctors)?],
        ),
        Stmt::ReceivePipe { var: recv_var, pipe } => S::inductive(
            "CReceivePipe",
            vec![S::text(&pipe_ident_name(pipe, interner)), S::text(interner.resolve(*recv_var))],
        ),
        Stmt::TrySendPipe { value, pipe, .. } => S::inductive(
            "CTrySendPipe",
            vec![S::text(&pipe_ident_name(pipe, interner)), expr_to_core::<S>(value, interner, vctors)?],
        ),
        Stmt::TryReceivePipe { var: recv_var, pipe } => S::inductive(
            "CTryReceivePipe",
            vec![S::text(&pipe_ident_name(pipe, interner)), S::text(interner.resolve(*recv_var))],
        ),
        // Select over channels: one `CSelectRecv{chan,var,body}` or `CSelectTimeout{duration,body}`
        // per branch. Branch bodies use the single-stmt encoder (fall back on Inspect/Repeat).
        Stmt::Select { branches } => {
            let mut bvals: Vec<S::Val> = Vec::with_capacity(branches.len());
            for branch in branches.iter() {
                match branch {
                    SelectBranch::Receive { var: recv_var, pipe, body } => bvals.push(S::inductive(
                        "CSelectRecv",
                        vec![
                            S::text(&pipe_ident_name(pipe, interner)),
                            S::text(interner.resolve(*recv_var)),
                            select_body_to_core::<S>(body, interner, vctors)?,
                        ],
                    )),
                    SelectBranch::Timeout { milliseconds, body } => bvals.push(S::inductive(
                        "CSelectTimeout",
                        vec![
                            expr_to_core::<S>(milliseconds, interner, vctors)?,
                            select_body_to_core::<S>(body, interner, vctors)?,
                        ],
                    )),
                }
            }
            S::inductive("CSelect", vec![S::list(bvals)])
        }
        // Proof / verification directives — the proposition/predicate is erased to `CBool(true)`
        // (it has no runtime effect to specialize; only its shape survives into the residual).
        Stmt::Assert { .. } => S::inductive("CAssert", vec![S::inductive("CBool", vec![S::boolean(true)])]),
        Stmt::Check { source_text, .. } => S::inductive(
            "CCheck",
            vec![S::inductive("CBool", vec![S::boolean(true)]), S::inductive("CText", vec![S::text(source_text)])],
        ),
        Stmt::Trust { justification, .. } => S::inductive(
            "CTrust",
            vec![S::inductive("CBool", vec![S::boolean(true)]), S::text(interner.resolve(*justification))],
        ),
        Stmt::Require { crate_name, .. } => S::inductive("CRequire", vec![S::text(interner.resolve(*crate_name))]),
        // Inline-native escape hatch.
        Stmt::Escape { code, .. } => S::inductive("CEscStmt", vec![S::text(interner.resolve(*code))]),
        // `Splice` (unconditional inlined block) desugars to `CIf(true, body, [])`.
        Stmt::Splice { body } => {
            let body_refs: Vec<&Stmt> = body.iter().collect();
            S::inductive(
                "CIf",
                vec![
                    S::inductive("CBool", vec![S::boolean(true)]),
                    stmt_list_to_core::<S>(&body_refs, interner, vctors)?,
                    S::list(vec![]),
                ],
            )
        }
        // Task / actor control.
        Stmt::StopTask { handle } => S::inductive("CStopTask", vec![expr_to_core::<S>(handle, interner, vctors)?]),
        Stmt::Spawn { agent_type, name } => S::inductive(
            "CSpawn",
            vec![S::text(interner.resolve(*agent_type)), S::text(interner.resolve(*name))],
        ),
        // Structured-concurrency zone (kind fixed to "heap"); body via the single-stmt encoder.
        Stmt::Zone { name, body, .. } => S::inductive(
            "CZone",
            vec![S::text(interner.resolve(*name)), S::text("heap"), select_body_to_core::<S>(body, interner, vctors)?],
        ),
        // CRDT conflict resolution (base struct forced dynamic at the list level, like Increase/Merge).
        Stmt::ResolveConflict { object, field, .. } => S::inductive(
            "CResolve",
            vec![S::text(&format!("{}'s {}", extract_ident_name(object, interner), interner.resolve(*field)))],
        ),
        // Sync / mount.
        Stmt::Sync { var: sync_var, topic } => S::inductive(
            "CSync",
            vec![S::text(interner.resolve(*sync_var)), expr_to_core::<S>(topic, interner, vctors)?],
        ),
        Stmt::Mount { var: mount_var, path } => S::inductive(
            "CMount",
            vec![S::text(interner.resolve(*mount_var)), expr_to_core::<S>(path, interner, vctors)?],
        ),
        // IO.
        Stmt::ReadFrom { var: read_var, source } => {
            let var_name = interner.resolve(*read_var);
            match source {
                ReadSource::Console => S::inductive("CReadConsole", vec![S::text(var_name)]),
                ReadSource::File(path_expr) => S::inductive(
                    "CReadFile",
                    vec![expr_to_core::<S>(path_expr, interner, vctors)?, S::text(var_name)],
                ),
            }
        }
        Stmt::WriteFile { content, path } => S::inductive(
            "CWriteFile",
            vec![expr_to_core::<S>(path, interner, vctors)?, expr_to_core::<S>(content, interner, vctors)?],
        ),
        // Networking / messaging. (`LetPeerAgent` encodes as `CConnectTo` with the agent as target.)
        Stmt::ConnectTo { address, .. } => S::inductive(
            "CConnectTo",
            vec![expr_to_core::<S>(address, interner, vctors)?, S::text("conn")],
        ),
        Stmt::Listen { address, .. } => S::inductive(
            "CListen",
            vec![expr_to_core::<S>(address, interner, vctors)?, S::text("default")],
        ),
        Stmt::SendMessage { message, destination, .. } => S::inductive(
            "CSendMessage",
            vec![expr_to_core::<S>(destination, interner, vctors)?, expr_to_core::<S>(message, interner, vctors)?],
        ),
        Stmt::AwaitMessage { into, .. } => S::inductive("CAwaitMessage", vec![S::text(interner.resolve(*into))]),
        Stmt::StreamMessage { values, destination } => S::inductive(
            "CStreamMessage",
            vec![expr_to_core::<S>(destination, interner, vctors)?, expr_to_core::<S>(values, interner, vctors)?],
        ),
        Stmt::LetPeerAgent { var: pa_var, address } => S::inductive(
            "CConnectTo",
            vec![expr_to_core::<S>(address, interner, vctors)?, S::text(interner.resolve(*pa_var))],
        ),
        _ => return None,
    })
}

/// A channel name: a plain identifier, else the literal `"pipe"` (mirrors `encode_stmt_src`).
fn pipe_ident_name(pipe: &Expr, interner: &Interner) -> String {
    match pipe {
        Expr::Identifier(sym) => interner.resolve(*sym).to_string(),
        _ => "pipe".to_string(),
    }
}

/// A `Select` branch body: each statement via the SINGLE-statement encoder — the reference defers
/// Inspect/Repeat to empty here, so fall back rather than replicate that quirk.
fn select_body_to_core<S: CoreSink>(body: &[Stmt], interner: &Interner, vctors: &VCtors) -> Option<S::Val> {
    let mut items: Vec<S::Val> = Vec::with_capacity(body.len());
    for s in body.iter() {
        if matches!(s, Stmt::Inspect { .. } | Stmt::Repeat { .. }) {
            return None;
        }
        items.push(stmt_to_core::<S>(s, interner, vctors)?);
    }
    Some(S::list(items))
}

fn stmt_list_to_core<S: CoreSink>(stmts: &[&Stmt], interner: &Interner, vctors: &VCtors) -> Option<S::Val> {
    Some(S::list(stmt_list_to_vec::<S>(stmts, interner, vctors)?))
}

/// Flatten a statement list into Core-IR nodes. Most statements map 1:1 via `stmt_to_core`; an
/// `Inspect` DESUGARS in place ([`inspect_to_cif`]) into the exact flat `CIf` chain `encode_stmts_src`
/// emits — so the PE folds a statically-known match to its single arm, Jones-optimally.
fn stmt_list_to_vec<S: CoreSink>(stmts: &[&Stmt], interner: &Interner, vctors: &VCtors) -> Option<Vec<S::Val>> {
    let mut out: Vec<S::Val> = Vec::with_capacity(stmts.len());
    for s in stmts {
        match s {
            Stmt::Inspect { .. } => inspect_to_cif::<S>(s, &mut out, interner, vctors)?,
            // A CRDT op forces its base struct DYNAMIC first (so the PE cannot statically fold a
            // struct it then mutates), THEN emits the op — a list-level transform mirroring
            // `encode_stmts_src`. `crdt_base_var` is `None` for a plain-variable collection (a bare
            // `Add x to s`), so those emit no force, exactly like the reference.
            Stmt::Add { collection, .. } | Stmt::Remove { collection, .. } => {
                if let Some(base) = crdt_base_var(collection, interner) {
                    out.push(S::inductive("CForceDynamic", vec![S::text(&base)]));
                }
                out.push(stmt_to_core::<S>(s, interner, vctors)?);
            }
            Stmt::AppendToSequence { sequence, .. } => {
                if let Some(base) = crdt_base_var(sequence, interner) {
                    out.push(S::inductive("CForceDynamic", vec![S::text(&base)]));
                }
                out.push(stmt_to_core::<S>(s, interner, vctors)?);
            }
            Stmt::IncreaseCrdt { object, .. } | Stmt::DecreaseCrdt { object, .. } | Stmt::ResolveConflict { object, .. } => {
                if matches!(object, Expr::Identifier(_) | Expr::FieldAccess { .. }) {
                    out.push(S::inductive("CForceDynamic", vec![S::text(&crdt_base_var_root(object, interner))]));
                }
                out.push(stmt_to_core::<S>(s, interner, vctors)?);
            }
            Stmt::MergeCrdt { target, .. } => {
                if matches!(target, Expr::Identifier(_) | Expr::FieldAccess { .. }) {
                    out.push(S::inductive("CForceDynamic", vec![S::text(&crdt_base_var_root(target, interner))]));
                }
                out.push(stmt_to_core::<S>(s, interner, vctors)?);
            }
            _ => out.push(stmt_to_core::<S>(s, interner, vctors)?),
        }
    }
    Some(out)
}

thread_local! {
    /// Per-program index for the `Inspect`-with-`Otherwise` "did any arm match" flag. Reset at the
    /// start of every full-program encode ([`program_to_core`] AND `encode_program_source`); both the
    /// native builder and the interpreter reference increment it in the SAME traversal (functions in
    /// source order, then main; DFS into bodies), so the Nth such Inspect is named `__inspectMatched_N`
    /// identically in both — DETERMINISTIC and collision-free. (The reference formerly named it from
    /// its global intermediate counter, whose value the value-based builder cannot reproduce; this
    /// dedicated index is the reproducible replacement.)
    static INSPECT_OTHERWISE_IDX: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

fn reset_inspect_otherwise_idx() {
    INSPECT_OTHERWISE_IDX.with(|c| c.set(0));
}

/// The next `Inspect`-with-`Otherwise` flag index (post-increment). Called at the START of each such
/// Inspect's desugaring in BOTH encoders, so a nested Inspect gets a strictly higher index than its
/// enclosing one — no two live flags ever collide.
pub fn next_inspect_otherwise_idx() -> usize {
    INSPECT_OTHERWISE_IDX.with(|c| {
        let v = c.get();
        c.set(v + 1);
        v
    })
}

/// Desugar `Inspect target: When Variant(field→bind): body … [Otherwise: rest]` into the flat `CIf`
/// chain `encode_stmts_src` produces, byte-for-byte. Each variant arm →
/// `CIf(target's __tag == "Variant", [<set match flag if Otherwise>; binds; body], [])`; when the PE
/// knows the variant it folds the comparison and keeps only the matching arm (zero dispatch =
/// Jones-optimal). WITH an `Otherwise`, a `__inspectMatched_N` flag (N = [`next_inspect_otherwise_idx`],
/// deterministic in both encoders) is declared false, set true in each arm, and checked negated to run
/// the Otherwise body. An `Otherwise`-only inspect just inlines that body.
fn inspect_to_cif<S: CoreSink>(stmt: &Stmt, out: &mut Vec<S::Val>, interner: &Interner, vctors: &VCtors) -> Option<()> {
    let Stmt::Inspect { target, arms, .. } = stmt else {
        return None;
    };
    let has_otherwise = arms.iter().any(|a| a.variant.is_none());
    let has_variant = arms.iter().any(|a| a.variant.is_some());

    // No variant arms (empty or Otherwise-only): the reference inlines the Otherwise body directly.
    if !has_variant {
        for arm in arms {
            if arm.variant.is_none() {
                let body_refs: Vec<&Stmt> = arm.body.iter().collect();
                out.extend(stmt_list_to_vec::<S>(&body_refs, interner, vctors)?);
            }
        }
        return Some(());
    }

    // The match flag is created (and its index reserved) BEFORE the arms — so a nested Inspect in an
    // arm/otherwise body gets a strictly higher index, exactly as the reference does.
    let matched_name = if has_otherwise {
        let name = format!("__inspectMatched_{}", next_inspect_otherwise_idx());
        out.push(S::inductive(
            "CLet",
            vec![S::text(&name), S::inductive("CBool", vec![S::boolean(false)])],
        ));
        Some(name)
    } else {
        None
    };

    for arm in arms {
        if arm.variant.is_none() {
            continue;
        }
        let variant_name = interner.resolve(arm.variant.unwrap());
        let tag_get = S::inductive(
            "CMapGet",
            vec![expr_to_core::<S>(target, interner, vctors)?, S::inductive("CText", vec![S::text("__tag")])],
        );
        let cond = S::inductive(
            "CBinOp",
            vec![S::text("=="), tag_get, S::inductive("CText", vec![S::text(variant_name)])],
        );
        let mut then_items: Vec<S::Val> = Vec::new();
        if let Some(ref mname) = matched_name {
            then_items.push(S::inductive(
                "CSet",
                vec![S::text(mname), S::inductive("CBool", vec![S::boolean(true)])],
            ));
        }
        for (field_name, binding_name) in &arm.bindings {
            let field_str = interner.resolve(*field_name);
            let bind_str = interner.resolve(*binding_name);
            let fget = S::inductive(
                "CMapGet",
                vec![expr_to_core::<S>(target, interner, vctors)?, S::inductive("CText", vec![S::text(field_str)])],
            );
            then_items.push(S::inductive("CLet", vec![S::text(bind_str), fget]));
        }
        let body_refs: Vec<&Stmt> = arm.body.iter().collect();
        then_items.extend(stmt_list_to_vec::<S>(&body_refs, interner, vctors)?);
        out.push(S::inductive("CIf", vec![cond, S::list(then_items), S::list(vec![])]));
    }

    // Otherwise: `CIf(not __inspectMatched_N, otherwise_body, [])`.
    if let Some(ref mname) = matched_name {
        let not_matched = S::inductive("CNot", vec![S::inductive("CVar", vec![S::text(mname)])]);
        let mut otherwise_body: Vec<&Stmt> = Vec::new();
        for arm in arms {
            if arm.variant.is_none() {
                otherwise_body = arm.body.iter().collect();
            }
        }
        let ow = stmt_list_to_core::<S>(&otherwise_body, interner, vctors)?;
        out.push(S::inductive("CIf", vec![not_matched, ow, S::list(vec![])]));
    }
    Some(())
}

/// Whether the native Core-IR value builder covers `program` (the fast marshal path is taken, not
/// the interpreter fallback). For test coverage assertions.
pub fn program_covered_by_native_builder(program: &str) -> bool {
    program_to_core_value(program).is_some()
}

/// Build the whole `CProgram` value for `program` on the [`TreeSink`] backend, or `None` if it uses
/// any construct the native builder does not cover (caller falls back to the interpreter path).
fn program_to_core_value(program: &str) -> Option<RuntimeValue> {
    program_to_core::<TreeSink>(program)
}

/// Parse `program` and construct its Core-IR `CProg` on the sink `S` — the shared parse+build spine
/// behind both the `RuntimeValue` builder ([`program_to_core_value`], `S = TreeSink`) and the direct
/// single-pass wire marshal ([`program_to_core_wire_bytes`], `S = WireSink`). `None` if any construct
/// is uncovered. The parse (lex + discovery + `parse_program`) dominates; the sink chooses whether the
/// build allocates a `RuntimeValue` tree + a second encode walk or emits bytes in one pass.
fn program_to_core<S: CoreSink>(program: &str) -> Option<S::Val> {
    reset_inspect_otherwise_idx(); // match the reference's deterministic `__inspectMatched_N` numbering
    let full_source = if program.contains("## Main") || program.contains("## To ") {
        program.to_string()
    } else {
        format!("## Main\n{}", program)
    };
    let mut interner = Interner::new();
    let mut lexer = Lexer::new(&full_source, &mut interner);
    let tokens = lexer.tokenize();
    let type_registry = {
        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
        discovery.run_full().types
    };
    let mut vctors: VCtors = std::collections::HashMap::new();
    for (_t, def) in type_registry.iter_types() {
        if let crate::analysis::TypeDef::Enum { variants, .. } = def {
            for v in variants {
                let fnames: Vec<String> = v.fields.iter().map(|f| interner.resolve(f.name).to_string()).collect();
                vctors.insert(interner.resolve(v.name).to_string(), fnames);
            }
        }
    }
    let mut world_state = WorldState::new();
    let expr_arena = Arena::new();
    let term_arena = Arena::new();
    let np_arena = Arena::new();
    let sym_arena = Arena::new();
    let role_arena = Arena::new();
    let pp_arena = Arena::new();
    let stmt_arena: Arena<Stmt> = Arena::new();
    let imperative_expr_arena: Arena<Expr> = Arena::new();
    let type_expr_arena: Arena<TypeExpr> = Arena::new();
    let ast_ctx = AstContext::with_types(
        &expr_arena, &term_arena, &np_arena, &sym_arena, &role_arena, &pp_arena,
        &stmt_arena, &imperative_expr_arena, &type_expr_arena,
    );
    let mut parser = crate::parser::Parser::new(tokens, &mut world_state, &mut interner, ast_ctx, type_registry);
    let stmts = parser.parse_program().ok()?;
    build_core::<S>(&stmts, &interner, &vctors)
}

/// Construct the Core-IR `CProg` for an ALREADY-PARSED program on the sink `S`: partition top-level
/// statements into `## To` functions (`CFuncDef`) and the main block, then emit `CProg [funcs] main`.
/// This is the parse-free spine — an integrated caller that already holds the AST + interner + variant
/// table skips the ~90%-of-marshal parse entirely by calling [`stmts_to_core_wire_bytes`]. `None` if
/// any statement uses a construct the native builder does not cover.
fn build_core<S: CoreSink>(stmts: &[Stmt], interner: &Interner, vctors: &VCtors) -> Option<S::Val> {
    let mut funcs: Vec<S::Val> = Vec::new();
    let mut main_stmts: Vec<&Stmt> = Vec::new();
    for stmt in stmts {
        if let Stmt::FunctionDef { name, params, body, return_type, is_native, .. } = stmt {
            if *is_native {
                continue;
            }
            let fname = interner.resolve(*name).to_string();
            let pnames: Vec<S::Val> = params.iter().map(|(n, _)| S::text(interner.resolve(*n))).collect();
            let ptypes: Vec<S::Val> = params.iter().map(|(_, ty)| S::text(&decompile_type_expr(ty, interner))).collect();
            let ret = return_type.map(|rt| decompile_type_expr(rt, interner)).unwrap_or_else(|| "Nothing".to_string());
            let body_s: Vec<&Stmt> = body.iter().collect();
            let body_v = stmt_list_to_core::<S>(&body_s, interner, vctors)?;
            funcs.push(S::inductive("CFuncDef", vec![S::text(&fname), S::list(pnames), S::list(ptypes), S::text(&ret), body_v]));
        } else if matches!(
            stmt,
            Stmt::StructDef { .. } | Stmt::Theorem(_) | Stmt::Definition(_) | Stmt::Axiom(_) | Stmt::Theory(_)
        ) {
            // Declarations contribute NOTHING to the runtime statement list — they live in the type
            // catalog / proof layer, and the reference encoder drops them. Skipping them here (rather
            // than routing to `stmt_to_core` → `None` → fallback) lets programs that carry an enum /
            // `Shared` struct (the ones that use Inspect, CRDT counters, typed closures) still hit the
            // fast native builder. Byte-identical: the reference likewise emits nothing for these.
        } else {
            main_stmts.push(stmt);
        }
    }
    let main_v = stmt_list_to_core::<S>(&main_stmts, interner, vctors)?;
    Some(S::inductive("CProg", vec![S::list(funcs), main_v]))
}

/// Serialize a program's Core-IR `CProgram` (a `CProg` with its functions and main block) to the
/// plain wire form — the bytes a compile-once native partial evaluator reads on stdin. FAST PATH:
/// [`program_to_core`] on [`WireSink`] emits the wire bytes in ONE pass straight from the AST — no
/// intermediate `RuntimeValue` tree and no second `encode_value_raw` walk (byte-for-byte identical to
/// the old two-pass form; locked by `native_builder_is_byte_identical_to_the_interpreter`). FALLBACK:
/// for a construct the native builder does not cover, run the constructor source on the tree-walker
/// (`wireBytes`). Both are decoded identically by the native binary's generated `CProgram::wire_decode`.
pub fn program_to_core_wire_bytes(program: &str) -> Result<Vec<u8>, String> {
    if let Some(bytes) = program_to_core::<WireSink>(program) {
        return Ok(bytes);
    }
    program_to_core_wire_bytes_via_interpreter(program)
}

/// The PARSE-FREE marshal: emit a program's Core-IR wire bytes directly from an ALREADY-PARSED AST,
/// skipping the lex + discovery + `parse_program` that dominates [`program_to_core_wire_bytes`] (~90%
/// of a specialization). An integrated caller that parsed the program once for compilation reuses that
/// AST here to feed the native PE at a fraction of the cost. `variant_fields` maps each variant
/// constructor name to its ordered field names (the caller derives it from its type registry, as
/// [`program_to_core`] does). `None` if a construct is uncovered. Byte-identical to
/// [`program_to_core_wire_bytes`] on the same program — same [`build_core`]/[`WireSink`] spine.
pub fn stmts_to_core_wire_bytes(
    stmts: &[Stmt],
    interner: &Interner,
    variant_fields: &std::collections::HashMap<String, Vec<String>>,
) -> Option<Vec<u8>> {
    build_core::<WireSink>(stmts, interner, variant_fields)
}

/// The TWO-PASS marshal that [`program_to_core_wire_bytes`] replaced: build the full `RuntimeValue`
/// Core-IR tree ([`TreeSink`]) then `encode_value_raw` it. Kept as the correctness ORACLE and the
/// speed BASELINE for the single-pass ([`WireSink`]) form — the two are byte-identical by construction
/// (`WireSink` emits exactly what `encode_value_raw` would), and the single pass avoids the tree
/// allocation + the second encode walk. `None` if a construct is uncovered.
pub fn program_to_core_wire_bytes_two_pass(program: &str) -> Option<Vec<u8>> {
    program_to_core::<TreeSink>(program).and_then(|v| encode_value_raw(&v).ok())
}

/// The REFERENCE marshal: always the interpreter path (construct the `CProgram` via the tree-walker,
/// `wireBytes`-serialize it). The native builder's output must be BYTE-IDENTICAL to this — locked by
/// `native_pe_wire::native_builder_is_byte_identical_to_the_interpreter`. Kept public so the lock can
/// force the reference regardless of native-builder coverage.
pub fn program_to_core_wire_bytes_via_interpreter(program: &str) -> Result<Vec<u8>, String> {
    let full_source = if program.contains("## Main") || program.contains("## To ") {
        program.to_string()
    } else {
        format!("## Main\n{}", program)
    };
    let encoded = encode_program_source(&full_source).map_err(|e| format!("Failed to encode program: {:?}", e))?;
    let driver = "    Let prog be a new CProg with funcs encodedFuncSeq and main encodedMain.\n    Let wb be wireBytes(prog).\n    Repeat for b in wb:\n        Show \"{b}\".\n";
    let combined = format!("{}\n## Main\n{}\n{}", CORE_TYPES_FOR_PE, encoded, driver);
    let out = interpret_program(&combined).map_err(|e| format!("wire-encode run failed: {:?}", e))?;
    let mut bytes = Vec::new();
    for line in out.lines() {
        let t = line.trim();
        if t.is_empty() {
            continue;
        }
        let n: u16 = t.parse().map_err(|_| format!("wireBytes emitted a non-byte line: {:?}", t))?;
        bytes.push(n as u8);
    }
    Ok(bytes)
}

/// Build (once, content-addressed) the compile-once native PE binary and return its path. Keyed
/// on the generated Rust of [`pe_native_source`] + toolchain, so the one-time rustc compile of the
/// whole PE engine happens exactly once per PE version and is reused across every program and
/// session. This is the amortization that turns AOT from "recompile per program" into the 210x win.
#[cfg(not(target_arch = "wasm32"))]
thread_local! {
    /// The already-built native PE binary path for this process. Caching it avoids re-running
    /// `aot_cache_key` on every specialization — which spawns `rustc --version` (~15 ms) and
    /// re-hashes the 167 KB source. The path is stable for the process (the PE source doesn't
    /// change at runtime), so one lookup per process suffices.
    static NATIVE_PE_BIN: std::cell::RefCell<Option<std::path::PathBuf>> = const { std::cell::RefCell::new(None) };
}

#[cfg(not(target_arch = "wasm32"))]
pub fn build_native_pe_binary() -> Result<std::path::PathBuf, String> {
    // Warm path: the binary was already located/built this process — reuse it (no `rustc --version`
    // spawn, no re-hash) as long as it still exists on disk.
    if let Some(p) = NATIVE_PE_BIN.with(|c| c.borrow().clone()) {
        if p.exists() {
            return Ok(p);
        }
    }
    let src = pe_native_source();
    // Key on the (stable) PE SOURCE text + toolchain — NOT the generated Rust: computing the Rust
    // means recompiling the whole 167 KB engine, which would defeat the cache on every warm call.
    let key = aot_cache_key(&src);
    let base = std::env::temp_dir().join("logos_native_pe");
    std::fs::create_dir_all(&base).map_err(|e| e.to_string())?;
    let proj = base.join(format!("pe_{key}"));
    let bin = proj.join("target").join("release").join("logos_native_pe");
    if bin.exists() {
        NATIVE_PE_BIN.with(|c| *c.borrow_mut() = Some(bin.clone()));
        return Ok(bin);
    }
    let rust = compile_program_full_with_wire(&src)
        .map_err(|e| format!("native PE compile: {:?}", e))?
        .rust_code;
    std::fs::create_dir_all(proj.join("src")).map_err(|e| e.to_string())?;
    let manifest = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
    let root = manifest.parent().unwrap().parent().unwrap();
    std::fs::write(
        proj.join("Cargo.toml"),
        format!(
            "[package]\nname=\"logos_native_pe\"\nversion=\"0.1.0\"\nedition=\"2021\"\n[dependencies]\nlogicaffeine-data={{path=\"{r}/crates/logicaffeine_data\"}}\nlogicaffeine-system={{path=\"{r}/crates/logicaffeine_system\",features=[\"full\"]}}\ntokio={{version=\"1\",features=[\"rt-multi-thread\",\"macros\"]}}\nserde={{version=\"1\",features=[\"derive\"]}}\nrayon=\"1\"\n[profile.release]\nopt-level=3\n",
            r = root.display()
        ),
    )
    .map_err(|e| e.to_string())?;
    std::fs::write(proj.join("src/main.rs"), &rust).map_err(|e| e.to_string())?;
    std::fs::copy(root.join("Cargo.lock"), proj.join("Cargo.lock")).map_err(|e| e.to_string())?;
    let out = std::process::Command::new("cargo")
        .args(["build", "--release", "--quiet"])
        .current_dir(&proj)
        .env("CARGO_TARGET_DIR", proj.join("target"))
        .env("RUST_MIN_STACK", "268435456")
        .output()
        .map_err(|e| e.to_string())?;
    if !out.status.success() {
        return Err(format!(
            "native PE build failed:\n{}",
            String::from_utf8_lossy(&out.stderr)
        ));
    }
    if bin.exists() {
        NATIVE_PE_BIN.with(|c| *c.borrow_mut() = Some(bin.clone()));
        Ok(bin)
    } else {
        Err("native PE binary missing after a successful build".into())
    }
}

/// Specialize `program` on the compile-once native PE via the RESIDENT SERVER (the fallback path;
/// the default [`run_native_pe`] prefers the faster in-process cdylib): serialize it to wire bytes
/// ([`program_to_core_wire_bytes`]), stream them to the server, and return its Jones-optimal
/// residual. The server (the compiled PE binary) is spawned ONCE per thread and reused — length-
/// framed request/response over its stdin/stdout — so there is no per-call process spawn and no
/// per-call rustc: just the host marshal + native `peBlock`, plus one pipe round-trip.
///
/// The server persists in a thread-local; dropping it (thread end / on I/O error, which triggers a
/// respawn) closes its stdin, and `readWireProgram` exits the child cleanly on that EOF.
#[cfg(not(target_arch = "wasm32"))]
struct PeServer {
    child: std::process::Child,
    stdin: std::process::ChildStdin,
    stdout: std::io::BufReader<std::process::ChildStdout>,
}

#[cfg(not(target_arch = "wasm32"))]
impl Drop for PeServer {
    fn drop(&mut self) {
        // Reap the child so a long-lived host (or the test harness) never accumulates zombies.
        let _ = self.child.kill();
        let _ = self.child.wait();
    }
}

#[cfg(not(target_arch = "wasm32"))]
thread_local! {
    static PE_SERVER: std::cell::RefCell<Option<PeServer>> = const { std::cell::RefCell::new(None) };
}

#[cfg(not(target_arch = "wasm32"))]
pub fn run_native_pe_server(program: &str) -> Result<String, String> {
    use std::io::{Read, Write};
    let bytes = program_to_core_wire_bytes(program)?;
    let raw = PE_SERVER.with(|cell| -> Result<String, String> {
        // A single request/response over the resident server; on ANY I/O failure the server is
        // dropped (respawned next call) so a crashed child never wedges the pipeline.
        let attempt = |slot: &mut Option<PeServer>| -> Result<String, String> {
            if slot.is_none() {
                let bin = build_native_pe_binary()?;
                let mut child = std::process::Command::new(&bin)
                    .stdin(std::process::Stdio::piped())
                    .stdout(std::process::Stdio::piped())
                    .stderr(std::process::Stdio::null())
                    .env("RUST_MIN_STACK", "268435456")
                    .spawn()
                    .map_err(|e| format!("native PE server spawn: {e}"))?;
                let stdin = child.stdin.take().unwrap();
                let stdout = std::io::BufReader::new(child.stdout.take().unwrap());
                *slot = Some(PeServer { child, stdin, stdout });
            }
            let srv = slot.as_mut().unwrap();
            srv.stdin
                .write_all(&(bytes.len() as u32).to_le_bytes())
                .and_then(|_| srv.stdin.write_all(&bytes))
                .and_then(|_| srv.stdin.flush())
                .map_err(|e| format!("native PE server write: {e}"))?;
            let mut len = [0u8; 4];
            srv.stdout
                .read_exact(&mut len)
                .map_err(|e| format!("native PE server read length: {e}"))?;
            let n = u32::from_le_bytes(len) as usize;
            let mut buf = vec![0u8; n];
            srv.stdout
                .read_exact(&mut buf)
                .map_err(|e| format!("native PE server read residual: {e}"))?;
            String::from_utf8(buf).map_err(|e| format!("native PE residual not UTF-8: {e}"))
        };
        let mut slot = cell.borrow_mut();
        match attempt(&mut slot) {
            Ok(v) => Ok(v),
            Err(e) => {
                *slot = None; // drop the (possibly dead) server so the next call respawns
                Err(e)
            }
        }
    })?;
    let residual = finish_projection1_residual(raw)?;
    Ok(prepend_type_definitions(program, residual))
}

#[cfg(not(target_arch = "wasm32"))]
thread_local! {
    /// The already-built PE cdylib path for this process (see [`NATIVE_PE_BIN`]).
    static NATIVE_PE_CDYLIB: std::cell::RefCell<Option<std::path::PathBuf>> = const { std::cell::RefCell::new(None) };
}

/// The in-process FFI shim appended to the generated PE engine to form the cdylib's `lib.rs`. It
/// lives in the SAME crate-root module as the generated `pub enum CProgram` and the module-private
/// `fn peSpecializeOnce(CProgram) -> String`, so it can call both directly. `into_boxed_slice` gives
/// an allocation with capacity EXACTLY == len, so `logos_pe_free` reconstructs the identical
/// `Box<[u8]>` (reconstructing a `Vec` with cap==len would be UB if the allocator over-allocated).
#[cfg(not(target_arch = "wasm32"))]
const PE_CDYLIB_SHIM: &str = r#"

// ── in-process FFI entry (appended by build_native_pe_cdylib) ───────────────────────────────
#[no_mangle]
pub extern "C" fn logos_pe_specialize(ptr: *const u8, len: usize, out_len: *mut usize) -> *mut u8 {
    let bytes = unsafe { std::slice::from_raw_parts(ptr, len) };
    let prog = <CProgram as logicaffeine_data::wire::WireDecode>::wire_decode(bytes, &mut 0usize)
        .expect("logos_pe_specialize: decode CProgram");
    let out: String = peSpecializeOnce(prog);
    let boxed: Box<[u8]> = out.into_bytes().into_boxed_slice();
    let n = boxed.len();
    unsafe { *out_len = n; }
    Box::into_raw(boxed) as *mut u8
}

#[no_mangle]
pub extern "C" fn logos_pe_free(ptr: *mut u8, len: usize) {
    if !ptr.is_null() {
        unsafe { drop(Box::from_raw(std::slice::from_raw_parts_mut(ptr, len) as *mut [u8])); }
    }
}
"#;

/// Build (and cache) the PE compiled as an IN-PROCESS cdylib exporting `logos_pe_specialize`.
/// Mirrors [`build_native_pe_binary`] but emits a `cdylib` whose `lib.rs` is the generated PE engine
/// ([`pe_cdylib_source`]) plus a hand-written `extern "C"` shim ([`PE_CDYLIB_SHIM`]) that decodes the
/// wire `CProgram` and calls `peSpecializeOnce` directly — so the caller loads it once and
/// specializes with a plain function call, no process, no pipe. Content-addressed on the (stable)
/// cdylib PE source + shim + toolchain, so warm calls skip rustc.
#[cfg(not(target_arch = "wasm32"))]
pub fn build_native_pe_cdylib() -> Result<std::path::PathBuf, String> {
    if let Some(p) = NATIVE_PE_CDYLIB.with(|c| c.borrow().clone()) {
        if p.exists() {
            return Ok(p);
        }
    }
    let src = pe_cdylib_source();
    // Key on the PE source AND the FFI shim, so editing either invalidates the on-disk cache.
    let key = aot_cache_key(&format!("{src}\n{PE_CDYLIB_SHIM}"));
    let base = std::env::temp_dir().join("logos_native_pe_cdylib");
    std::fs::create_dir_all(&base).map_err(|e| e.to_string())?;
    let proj = base.join(format!("pe_{key}"));
    let so = proj.join("target").join("release").join(format!(
        "{}logos_native_pe_lib{}",
        std::env::consts::DLL_PREFIX,
        std::env::consts::DLL_SUFFIX
    ));
    if so.exists() {
        NATIVE_PE_CDYLIB.with(|c| *c.borrow_mut() = Some(so.clone()));
        return Ok(so);
    }
    let generated = compile_program_full_with_wire(&src)
        .map_err(|e| format!("native PE cdylib compile: {:?}", e))?
        .rust_code;
    let lib_rs = format!("{generated}\n{PE_CDYLIB_SHIM}");
    std::fs::create_dir_all(proj.join("src")).map_err(|e| e.to_string())?;
    let manifest = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
    let root = manifest.parent().unwrap().parent().unwrap();
    std::fs::write(
        proj.join("Cargo.toml"),
        format!(
            "[package]\nname=\"logos_native_pe_lib\"\nversion=\"0.1.0\"\nedition=\"2021\"\n[lib]\ncrate-type=[\"cdylib\"]\npath=\"src/lib.rs\"\n[dependencies]\nlogicaffeine-data={{path=\"{r}/crates/logicaffeine_data\"}}\nlogicaffeine-system={{path=\"{r}/crates/logicaffeine_system\",features=[\"full\"]}}\ntokio={{version=\"1\",features=[\"rt-multi-thread\",\"macros\"]}}\nserde={{version=\"1\",features=[\"derive\"]}}\nrayon=\"1\"\n[profile.release]\nopt-level=3\n",
            r = root.display()
        ),
    )
    .map_err(|e| e.to_string())?;
    std::fs::write(proj.join("src/lib.rs"), &lib_rs).map_err(|e| e.to_string())?;
    std::fs::copy(root.join("Cargo.lock"), proj.join("Cargo.lock")).map_err(|e| e.to_string())?;
    let out = std::process::Command::new("cargo")
        .args(["build", "--release", "--quiet"])
        .current_dir(&proj)
        .env("CARGO_TARGET_DIR", proj.join("target"))
        .env("RUST_MIN_STACK", "268435456")
        .output()
        .map_err(|e| e.to_string())?;
    if !out.status.success() {
        return Err(format!(
            "native PE cdylib build failed:\n{}",
            String::from_utf8_lossy(&out.stderr)
        ));
    }
    if so.exists() {
        NATIVE_PE_CDYLIB.with(|c| *c.borrow_mut() = Some(so.clone()));
        Ok(so)
    } else {
        Err("native PE cdylib missing after a successful build".into())
    }
}

/// The loaded PE cdylib for this thread: the `Library` kept alive alongside the raw entry-point
/// pointers derived from it (valid for as long as the `Library` is not unloaded, which is exactly
/// this struct's lifetime).
#[cfg(not(target_arch = "wasm32"))]
struct PeLib {
    _lib: libloading::Library,
    specialize: unsafe extern "C" fn(*const u8, usize, *mut usize) -> *mut u8,
    free: unsafe extern "C" fn(*mut u8, usize),
}

#[cfg(not(target_arch = "wasm32"))]
thread_local! {
    static PE_LIB: std::cell::RefCell<Option<PeLib>> = const { std::cell::RefCell::new(None) };
}

/// Specialize `program` on the compile-once native PE, IN PROCESS: marshal it to wire bytes, hand
/// them to the `dlopen`ed PE cdylib's `logos_pe_specialize` as a plain function call, and reclaim
/// the residual bytes. No child process, no pipe — the ~59 µs IPC round-trip of the resident server
/// is gone; all that remains is the host marshal + native `peBlock` + one FFI call. The cdylib is
/// built + loaded ONCE per thread and cached. Residual-identity with the server / tree-walker is
/// locked by `native_pe_wire`.
#[cfg(not(target_arch = "wasm32"))]
pub fn run_native_pe_inprocess(program: &str) -> Result<String, String> {
    let bytes = program_to_core_wire_bytes(program)?;
    let raw = PE_LIB.with(|cell| -> Result<String, String> {
        let mut slot = cell.borrow_mut();
        if slot.is_none() {
            let so = build_native_pe_cdylib()?;
            // SAFETY: the cdylib was just built from our own generated source; its exported symbols
            // have exactly the signatures declared here, and the raw pointers are stored alongside
            // the owning `Library` so they never outlive it.
            unsafe {
                let lib = libloading::Library::new(&so)
                    .map_err(|e| format!("native PE cdylib load: {e}"))?;
                let specialize: libloading::Symbol<
                    unsafe extern "C" fn(*const u8, usize, *mut usize) -> *mut u8,
                > = lib
                    .get(b"logos_pe_specialize")
                    .map_err(|e| format!("dlsym logos_pe_specialize: {e}"))?;
                let free: libloading::Symbol<unsafe extern "C" fn(*mut u8, usize)> = lib
                    .get(b"logos_pe_free")
                    .map_err(|e| format!("dlsym logos_pe_free: {e}"))?;
                let specialize = *specialize;
                let free = *free;
                *slot = Some(PeLib { _lib: lib, specialize, free });
            }
        }
        let pl = slot.as_ref().unwrap();
        let mut out_len: usize = 0;
        // SAFETY: `bytes` is a live slice for the duration of the call; the callee writes `out_len`
        // and returns a buffer of that length we own until `free`.
        let p = unsafe { (pl.specialize)(bytes.as_ptr(), bytes.len(), &mut out_len as *mut usize) };
        if p.is_null() {
            return Err("native PE cdylib returned a null residual".into());
        }
        let residual_bytes = unsafe { std::slice::from_raw_parts(p, out_len).to_vec() };
        unsafe { (pl.free)(p, out_len) };
        String::from_utf8(residual_bytes).map_err(|e| format!("native PE residual not UTF-8: {e}"))
    })?;
    let residual = finish_projection1_residual(raw)?;
    Ok(prepend_type_definitions(program, residual))
}

/// Specialize `program` on the compile-once native PE — the DEFAULT entry and the pit of success.
/// Prefers the IN-PROCESS cdylib path ([`run_native_pe_inprocess`]; no process/pipe boundary) and
/// falls back to the resident server ([`run_native_pe_server`]) only if the in-process build/load
/// fails (e.g. no toolchain), so the fast+correct route is what every caller gets by default. The
/// two paths are proven byte-identical by `native_pe_wire`.
#[cfg(not(target_arch = "wasm32"))]
pub fn run_native_pe(program: &str) -> Result<String, String> {
    match run_native_pe_inprocess(program) {
        Ok(v) => Ok(v),
        Err(_) => run_native_pe_server(program),
    }
}

/// VM-driven twin of [`projection1_source_real_fast`].
///
/// Executes the identical assembled PE program on the register bytecode VM
/// ([`vm_run_source`]) instead of the tree-walker. The PE engine is a fixed program —
/// only its `encodedMain` input varies per call — so the VM either supports the whole
/// engine or none of it; measured ~2× faster than the tree-walker with a byte-identical
/// residual. The corpus-wide equivalence is locked by `futamura_tier_lock`.
pub fn projection1_source_real_fast_on_vm(
    core_types: &str,
    _interpreter: &str,
    program: &str,
) -> Result<String, String> {
    let combined = pe_combined_source(core_types, program)?;

    let raw_residual = vm_run_source(&combined).map_err(|e| format!("PE VM execution failed: {e}"))?;
    let residual = finish_projection1_residual(raw_residual)?;
    Ok(prepend_type_definitions(program, residual))
}

/// Re-attach every original `## …` section that is NOT `## Main` and NOT a `## To` function
/// (the residual supplies its own Main + specialized functions). These are the type / struct
/// / policy definitions that make the residual a self-contained, re-runnable program.
fn prepend_type_definitions(program: &str, residual: String) -> String {
    let mut defs = String::new();
    let mut keep = false;
    for line in program.lines() {
        if let Some(header) = line.strip_prefix("## ") {
            keep = header != "Main" && !header.starts_with("To ");
        }
        if keep {
            defs.push_str(line);
            defs.push('\n');
        }
    }
    if defs.trim().is_empty() {
        residual
    } else {
        format!("{}{}", defs, residual)
    }
}

/// Assemble the full PE-run source (core types + PE + decompiler + encoded
/// input + driver) — the exact program [`projection1_source_real_fast`]
/// executes. Public so differential harnesses can run it on a specific engine.
pub fn pe_combined_source(core_types: &str, program: &str) -> Result<String, String> {
    let full_source = if program.contains("## Main") || program.contains("## To ") {
        program.to_string()
    } else {
        format!("## Main\n{}", program)
    };

    let encoded = encode_program_source(&full_source)
        .map_err(|e| format!("Failed to encode program: {:?}", e))?;

    let pe_source = pe_source_text();
    let decompile_source = decompile_source_text();

    let actual_core_types = if core_types.is_empty() { CORE_TYPES_FOR_PE } else { core_types };

    // Driver: run PE, then transitively decompile every referenced function (specialized
    // or original) so residual calls — e.g. an MSG-generalized recursive loop — resolve.
    // For fully-inlined residuals (no calls) this emits nothing and matches the bare form.
    let driver = r#"
    Let state be makePeState(a new Map of Text to CVal, encodedFuncMap, 200).
    Let residual be peBlock(encodedMain, state).
    Let nl be chr(10).
    Let mutable output be "".
    Let specFuncs be peFuncs(state).
    Let mutable allNames be collectCallNames(residual).
    Let mutable emitted be a new Map of Text to Bool.
    Let mutable changed be true.
    While changed:
        Set changed to false.
        Let mutable toAdd be a new Seq of Text.
        Repeat for fnKey in allNames:
            Let fkStr be "{fnKey}".
            If emitted contains fkStr:
                Let skipE be true.
            Otherwise:
                Set item fkStr of emitted to true.
                Let fkStr2 be "{fnKey}".
                If specFuncs contains fkStr2:
                    Let fdef be item fkStr2 of specFuncs.
                    Inspect fdef:
                        When CFuncDef (fn0, ps0, pt0, rt0, body0):
                            Let children be collectCallNames(body0).
                            Repeat for child in children:
                                Let childStr be "{child}".
                                If not emitted contains childStr:
                                    Push child to toAdd.
                                    Set changed to true.
                        Otherwise:
                            Let skipF be true.
        Repeat for ta in toAdd:
            Push ta to allNames.
    Repeat for fnKey in allNames:
        Let fkStr be "{fnKey}".
        If specFuncs contains fkStr:
            Let fdef be item fkStr of specFuncs.
            Let funcSrc be decompileFunc(fdef).
            If the length of funcSrc is greater than 0:
                Set output to "{output}{funcSrc}{nl}".
    Let mainSrc be decompileBlock(residual, 0).
    Set output to "{output}## Main{nl}{mainSrc}".
    Show output.
"#;

    let combined = format!(
        "{}\n{}\n{}\n## Main\n{}\n{}",
        actual_core_types,
        pe_source,
        decompile_source,
        encoded,
        driver,
    );

    Ok(combined)
}

/// The post-processing applied to a raw PE residual (the `Any`-type safety
/// net + `## Main` normalization).
pub fn finish_projection1_residual(raw_residual: String) -> Result<String, String> {
    // Safety net (mirrors `fix_decompiled_types` on the P2/P3 path): specialized functions
    // whose param/return types the PE could not propagate are emitted as `Any`, which the
    // parser rejects. The tree-walker is dynamically typed, so a concrete placeholder type
    // is cosmetic at runtime — rewrite `Any` annotations so the residual re-parses.
    let fixed = raw_residual
        .replace(": Any)", ": Int)")
        .replace("-> Any:", "-> Int:")
        .replace(" of Any", " of Int")
        .replace(" to Any", " to Int");
    let trimmed = fixed.trim();

    if trimmed.is_empty() {
        return Ok("## Main\n".to_string());
    }

    if trimmed.contains("## To ") || trimmed.starts_with("## Main") {
        Ok(trimmed.to_string())
    } else {
        Ok(format!("## Main\n{}", trimmed))
    }
}

/// Run genuine P2 on a specific target: PE(pe_source, pe_mini(target))
///
/// This is the real Futamura Projection 2 applied end-to-end:
/// 1. Build pe_mini applied to the target (pe_mini compiles the target)
/// 2. Encode the combined pe_mini+target as CProgram data
/// 3. Run pe_source on the encoded data (PE specializes pe_mini for this target)
/// 4. Decompile the residual to LOGOS source
/// 5. Execute the decompiled residual to get the target's output
///
/// No decompilation of specialized functions — the PE directly produces the compiled
/// target as CStmt data, which is decompiled to a simple LOGOS program and run.
pub fn run_genuine_p2_on_target(program: &str, core_types: &str, interpreter: &str) -> Result<String, String> {
    let pe_mini = pe_mini_source_text();
    let pe = pe_source_text();

    let full_source = if program.contains("## Main") || program.contains("## To ") {
        program.to_string()
    } else {
        format!("## Main\n{}", program)
    };

    // Build pe_mini applied to the specific target.
    // pe_mini ONLY COMPILES the target — produces CStmt data as output.
    // Build pe_mini + interpreter applied to the target.
    // pe_mini compiles the target, coreExecBlock runs the compiled result.
    let target_encoded = encode_program_source(&full_source)
        .map_err(|e| format!("Failed to encode target: {:?}", e))?;
    let pe_mini_prog = format!(
        "{}\n{}\n{}\n## Main\n{}\n\
         Let compileEnv be a new Map of Text to CVal.\n\
         Let compileState be makePeState(compileEnv, encodedFuncMap, 200).\n\
         Let compiled be peBlockM(encodedMain, compileState).\n\
         Let runEnv be a new Map of Text to CVal.\n\
         coreExecBlock(compiled, runEnv, encodedFuncMap).\n",
        core_types, pe_mini, interpreter, target_encoded
    );

    // Encode pe_mini+target as CProgram data for the outer PE
    let encoded = encode_program_source_compact(&pe_mini_prog)
        .map_err(|e| format!("Failed to encode pe_mini+target for P2: {:?}", e))?;

    // The driver runs PE on the encoded pe_mini+target, then executes the residual.
    // peFuncs(state) contains BOTH the PE-specialized functions AND the original
    // functions from the encoded program (including pe_mini, interpreter, and
    // target functions like factorial).
    let driver = r#"    Let state be makePeState(a new Map of Text to CVal, encodedFuncMap, 500).
    Let residual be peBlock(encodedMain, state).
    Let allFuncs be peFuncs(state).
    Let runEnv be a new Map of Text to CVal.
    coreExecBlock(residual, runEnv, allFuncs).
"#;
    let combined = format!(
        "{}\n{}\n{}\n## Main\n{}\n{}",
        CORE_TYPES_FOR_PE, pe, interpreter, encoded, driver
    );

    run_logos_source(&combined)
}

/// Run genuine P3 on a specific target: PE(pe_source, pe_bti(target))
pub fn run_genuine_p3_on_target(program: &str, core_types: &str, interpreter: &str) -> Result<String, String> {
    let pe_bti = pe_bti_source_text();
    let pe = pe_source_text();

    let full_source = if program.contains("## Main") || program.contains("## To ") {
        program.to_string()
    } else {
        format!("## Main\n{}", program)
    };

    let bti_types = CORE_TYPES_FOR_PE
        .replace("specResults", "memoCache")
        .replace("onStack", "callGuard");

    let target_encoded = encode_program_source(&full_source)
        .map_err(|e| format!("Failed to encode target: {:?}", e))?;
    let pe_bti_prog = format!(
        "{}\n{}\n{}\n## Main\n{}\n\
         Let compileEnv be a new Map of Text to CVal.\n\
         Let compileState be makePeState(compileEnv, encodedFuncMap, 200).\n\
         Let compiled be peBlockB(encodedMain, compileState).\n\
         Let runEnv be a new Map of Text to CVal.\n\
         coreExecBlock(compiled, runEnv, encodedFuncMap).\n",
        bti_types, pe_bti, interpreter, target_encoded
    );

    let encoded = encode_program_source_compact(&pe_bti_prog)
        .map_err(|e| format!("Failed to encode pe_bti+target for P3: {:?}", e))?;

    // Execute residual directly — no decompilation needed
    let driver = r#"    Let state be makePeState(a new Map of Text to CVal, encodedFuncMap, 200).
    Let residual be peBlock(encodedMain, state).
    Let runEnv be a new Map of Text to CVal.
    coreExecBlock(residual, runEnv, encodedFuncMap).
"#;
    let combined = format!(
        "{}\n{}\n{}\n## Main\n{}\n{}",
        CORE_TYPES_FOR_PE, pe, interpreter, encoded, driver
    );

    run_logos_source(&combined)
}

/// Genuine Futamura Projection 2 via self-application: PE(pe_source, pe_mini(targetStmts))
///
/// The outer PE (pe_source) specializes pe_mini's FULL BLOCK evaluator with known
/// state (empty env, empty funcs, depth 200). targetStmts is a free/dynamic variable;
/// state is fully static. The PE produces a specialized peBlockM_ function that IS
/// the compiler — handling all CStmt variants with specialized expression processing.
///
/// This eliminates the need for a Rust-generated block wrapper: the PE naturally
/// produces block-level dispatch through specialization of peBlockM.
pub fn projection2_source_real(_core_types: &str, _interpreter: &str) -> Result<GenuineProjectionResult, String> {
    let pe_mini = pe_mini_source_text();
    let pe = pe_source_text();
    let decompile = decompile_source_text();

    // Build pe_mini program with peBlockM as entry — FULL block-level specialization.
    // targetStmts = free/dynamic variable (program's main block).
    // targetFuncs = free/dynamic variable (program's function definitions).
    // env = static (empty — programs start with no bindings).
    // depth = static (200 — PE eliminates depth checks).
    // targetStmts is a free/dynamic variable. State is fully static (empty env,
    // empty funcs, depth 200). The PE specializes pe_mini's dispatch code completely.
    // The resulting compiler handles function definitions at USE time via the state
    // parameter provided by the test harness.
    let program = format!(
        "{}\n{}\n## Main\n    Let env be a new Map of Text to CVal.\n    Let funcs be a new Map of Text to CFunc.\n    Let state be makePeState(env, funcs, 200).\n    Let result be peBlockM(targetStmts, state).\n    Show \"done\".\n",
        CORE_TYPES_FOR_PE, pe_mini
    );

    // Encode pe_mini + driver as CProgram data (compact encoding)
    let encoded = encode_program_source_compact(&program)
        .map_err(|e| format!("Failed to encode pe_mini for P2: {:?}", e))?;

    // Driver: run PE, then decompile specialized functions transitively.
    // Fixpoint collection: discover all transitively-referenced specialized functions
    // at arbitrary depth, not limited to any fixed number of levels.
    let driver = r#"    Let state be makePeState(a new Map of Text to CVal, encodedFuncMap, 200).
    Let residual be peBlock(encodedMain, state).
    Let nl be chr(10).
    Let mutable output be "".
    Let specFuncs be peFuncs(state).
    Let mutable allNames be collectCallNames(residual).
    Let mutable emitted be a new Map of Text to Bool.
    Let mutable changed be true.
    While changed:
        Set changed to false.
        Let mutable toAdd be a new Seq of Text.
        Repeat for fnKey in allNames:
            Let fkStr be "{fnKey}".
            If emitted contains fkStr:
                Let skipE be true.
            Otherwise:
                Set item fkStr of emitted to true.
                Let fkStr2 be "{fnKey}".
                If specFuncs contains fkStr2:
                    Let fdef be item fkStr2 of specFuncs.
                    Inspect fdef:
                        When CFuncDef (fn0, ps0, pt0, rt0, body0):
                            Let children be collectCallNames(body0).
                            Repeat for child in children:
                                Let childStr be "{child}".
                                If not emitted contains childStr:
                                    Push child to toAdd.
                                    Set changed to true.
                        Otherwise:
                            Let skipF be true.
        Repeat for ta in toAdd:
            Push ta to allNames.
    Repeat for fnKey in allNames:
        Let fkStr be "{fnKey}".
        If specFuncs contains fkStr:
            Let fdef be item fkStr of specFuncs.
            Let funcSrc be decompileFunc(fdef).
            If the length of funcSrc is greater than 0:
                Set output to "{output}{funcSrc}{nl}".
    Let mainSrc be decompileBlock(residual, 0).
    Set output to "{output}## Main{nl}{mainSrc}".
    Show output.
"#;
    let combined = format!("{}\n{}\n{}\n## Main\n{}\n{}", CORE_TYPES_FOR_PE, pe, decompile, encoded, driver);

    let result = run_logos_source(&combined)?;

    // The decompiler now emits types from CFunc's paramTypes/returnType fields for
    // functions that carry type info. PE-generated specializations may still use "Any"
    // for types that couldn't be propagated through specialization. Apply type fixup
    // as a safety net for any remaining "Any" types in specialized function signatures.
    let result = fix_decompiled_types(&result, &[
        ("peExprM_", "(e: CExpr) -> CExpr:"),
        ("peBlockM_", "(stmts: Seq of CStmt) -> Seq of CStmt:"),
        ("checkLiteralM_", "(e: CExpr) -> Bool:"),
        ("exprToValM_", "(e: CExpr) -> CVal:"),
        ("valToExprM_", "(v: CVal) -> CExpr:"),
        ("evalBinOpM_", "(binOp: Text) and (lv: CVal) and (rv: CVal) -> CVal:"),
        ("isCopyPropSafeM_", "(e: CExpr) -> Bool:"),
        ("checkVNothingM_", "(v: CVal) -> Bool:"),
        ("hasReturnM_", "(stmts: Seq of CStmt) -> Bool:"),
        ("extractReturnM_", "(stmts: Seq of CStmt) -> CExpr:"),
        ("validateExtractReturnM_", "(result: CExpr) and (bodyStmts: Seq of CStmt) -> CExpr:"),
        ("makeKeyM_", "(fnName: Text) and (args: Seq of CExpr) -> Text:"),
        ("exprToKeyPartM_", "(e: CExpr) -> Text:"),
        ("collectSetVarsM_", "(stmts: Seq of CStmt) -> Seq of Text:"),
        ("peEnvM_", "(st: PEMiniState) -> Map of Text to CVal:"),
        ("peFuncsM_", "(st: PEMiniState) -> Map of Text to CFunc:"),
        ("peDepthM_", "(st: PEMiniState) -> Int:"),
        ("peStaticEnvM_", "(st: PEMiniState) -> Map of Text to CExpr:"),
        ("peMemoCacheM_", "(st: PEMiniState) -> Map of Text to CExpr:"),
        ("peStateWithEnvDepthM_", "(st: PEMiniState) and (newEnv: Map of Text to CVal) and (d: Int) -> PEMiniState:"),
        ("peStateWithEnvDepthStaticM_", "(st: PEMiniState) and (newEnv: Map of Text to CVal) and (d: Int) and (newSe: Map of Text to CExpr) -> PEMiniState:"),
    ]);

    // Discover the PE-generated block entry point — this IS the compiler.
    let (block_entry, expr_entry) = discover_entry_points(&result, "peBlockM_", "peExprM_");
    if block_entry.is_empty() {
        return Err("Genuine P2: no peBlockM_ entry found in residual".to_string());
    }

    // Strip the ## Main block from the residual — we only need the specialized function
    // definitions. The test harness provides its own ## Main.
    let func_defs_only = strip_main_block(&result);

    // The specialized functions call pe_mini's unspecialized helpers (checkLiteralM,
    // valToExprM, etc.) which the PE couldn't fold because their args are dynamic.
    // Include the original pe_mini source so these helpers are available.
    let pe_mini_helpers = pe_mini_source_text();

    // No Rust-generated block wrapper needed — the PE produced a specialized peBlockM_
    // function that handles all CStmt variants with specialized expression processing.
    // Generate a thin alias for backward compatibility.
    let alias = format!(
        "\n## To compileBlock (stmts: Seq of CStmt) -> Seq of CStmt:\n    Return {}(stmts).\n",
        block_entry
    );

    // Combine: pe_mini helpers first (authoritative), then specialized functions, then alias.
    // Deduplicate: if the decompiled residual redefines a pe_mini function (unspecialized),
    // the dedup removes the second definition, keeping the original pe_mini version.
    let combined = format!("{}\n{}\n{}", pe_mini_helpers, func_defs_only, alias);
    let full_source = deduplicate_functions(&combined);

    Ok(GenuineProjectionResult {
        source: full_source,
        block_entry: "compileBlock".to_string(),
        expr_entry,
    })
}

/// Run genuine PE(pe_source, pe_mini(targetStmts)) and return the specialized
/// compiler residual as LOGOS source code.
///
/// This is the actual Futamura Projection 2: the outer PE (pe_source) specializes
/// pe_mini's peBlockM with known state (empty env, empty funcs, depth 200).
/// The result is a specialized compiler function that takes target statements and
/// compiles them with pe_mini's dispatch logic partially evaluated away.
///
/// Returns the decompiled LOGOS source of the genuine P2 residual, including
/// specialized function definitions extracted from peFuncs.
pub fn genuine_projection2_residual() -> Result<String, String> {
    let pe_mini = pe_mini_source_text();
    let pe = pe_source_text();
    let decompile = decompile_source_text();

    // Build pe_mini program with peBlockM as entry — full block-level specialization
    let program = format!(
        "{}\n{}\n## Main\n    Let env be a new Map of Text to CVal.\n    Let funcs be a new Map of Text to CFunc.\n    Let state be makePeState(env, funcs, 200).\n    Let result be peBlockM(targetStmts, state).\n    Show \"done\".\n",
        CORE_TYPES_FOR_PE, pe_mini
    );

    // Encode pe_mini + driver as CProgram data (compact encoding)
    let encoded = encode_program_source_compact(&program)
        .map_err(|e| format!("Failed to encode pe_mini: {:?}", e))?;

    // Driver: run PE, then decompile residual + specialized functions
    let driver = r#"    Let state be makePeState(a new Map of Text to CVal, encodedFuncMap, 200).
    Let residual be peBlock(encodedMain, state).
    Let nl be chr(10).
    Let mutable output be "".
    Let specFuncs be peFuncs(state).
    Let specNames be collectCallNames(residual).
    Repeat for sn in specNames:
        Let snKey be "{sn}".
        If specFuncs contains snKey:
            Let fdef be item snKey of specFuncs.
            Let funcSrc be decompileFunc(fdef).
            If the length of funcSrc is greater than 0:
                Set output to "{output}{funcSrc}{nl}".
    Let mainSrc be decompileBlock(residual, 0).
    Set output to "{output}## Main{nl}{mainSrc}".
    Show output.
"#;
    let combined = format!("{}\n{}\n{}\n## Main\n{}\n{}", CORE_TYPES_FOR_PE, pe, decompile, encoded, driver);

    let result = run_logos_source(&combined)?;
    Ok(result)
}

/// Run genuine PE(pe_source, pe_bti(targetExpr)) and return the specialized
/// cogen residual as LOGOS source code.
///
/// This is the actual Futamura Projection 3: the outer PE (pe_source) specializes
/// pe_bti (a full PE with memoization) with known state (empty env, empty funcs,
/// depth 200). pe_bti is structurally identical to pe_source with renamed entry
/// points (peExprB, peBlockB, etc.) — so this is genuinely PE(PE, PE).
///
/// The result is a specialized cogen: pe_bti's dispatch partially evaluated away,
/// producing a program that takes a target CExpr and compiles it.
pub fn genuine_projection3_residual() -> Result<String, String> {
    let pe_bti = pe_bti_source_text();
    let pe = pe_source_text();
    let decompile = decompile_source_text();

    // pe_bti uses memoCache/callGuard instead of specResults/onStack
    let bti_types = CORE_TYPES_FOR_PE
        .replace("specResults", "memoCache")
        .replace("onStack", "callGuard");

    // Build pe_bti program with peBlockB as entry — full block-level specialization
    let program = format!(
        "{}\n{}\n## Main\n    Let env be a new Map of Text to CVal.\n    Let funcs be a new Map of Text to CFunc.\n    Let state be makePeState(env, funcs, 200).\n    Let result be peBlockB(targetStmts, state).\n    Show \"done\".\n",
        bti_types, pe_bti
    );

    // Encode pe_bti + driver as CProgram data (compact encoding)
    let encoded = encode_program_source_compact(&program)
        .map_err(|e| format!("Failed to encode pe_bti: {:?}", e))?;

    // Driver: run PE, then decompile residual + specialized functions
    let driver = r#"    Let state be makePeState(a new Map of Text to CVal, encodedFuncMap, 200).
    Let residual be peBlock(encodedMain, state).
    Let nl be chr(10).
    Let mutable output be "".
    Let specFuncs be peFuncs(state).
    Let specNames be collectCallNames(residual).
    Repeat for sn in specNames:
        Let snKey be "{sn}".
        If specFuncs contains snKey:
            Let fdef be item snKey of specFuncs.
            Let funcSrc be decompileFunc(fdef).
            If the length of funcSrc is greater than 0:
                Set output to "{output}{funcSrc}{nl}".
    Let mainSrc be decompileBlock(residual, 0).
    Set output to "{output}## Main{nl}{mainSrc}".
    Show output.
"#;
    let combined = format!("{}\n{}\n{}\n## Main\n{}\n{}", CORE_TYPES_FOR_PE, pe, decompile, encoded, driver);

    let result = run_logos_source(&combined)?;
    Ok(result)
}

/// Genuine Futamura Projection 3 via self-application: PE(pe_source, pe_bti(targetStmts))
///
/// The outer PE (pe_source) specializes pe_bti's FULL BLOCK evaluator (a full PE with
/// memoization, structurally identical to pe_source with renamed entry points) with
/// known state (empty env, empty funcs, depth 200). This is genuinely PE(PE, PE).
///
/// The result is a specialized cogen: the PE naturally produces block-level dispatch
/// through specialization of peBlockB, eliminating the need for a Rust-generated wrapper.
pub fn projection3_source_real(_core_types: &str) -> Result<GenuineProjectionResult, String> {
    let pe_bti = pe_bti_source_text();
    let pe = pe_source_text();
    let decompile = decompile_source_text();

    // pe_bti uses memoCache/callGuard instead of specResults/onStack
    let bti_types = CORE_TYPES_FOR_PE
        .replace("specResults", "memoCache")
        .replace("onStack", "callGuard");

    // Build pe_bti program with peBlockB as entry — FULL block-level specialization.
    let program = format!(
        "{}\n{}\n## Main\n    Let env be a new Map of Text to CVal.\n    Let funcs be a new Map of Text to CFunc.\n    Let state be makePeState(env, funcs, 200).\n    Let result be peBlockB(targetStmts, state).\n    Show \"done\".\n",
        bti_types, pe_bti
    );

    // Encode pe_bti + driver as CProgram data (compact encoding)
    let encoded = encode_program_source_compact(&program)
        .map_err(|e| format!("Failed to encode pe_bti for P3: {:?}", e))?;

    // Driver: fixpoint transitive collection (same algorithm as P2)
    let driver = r#"    Let state be makePeState(a new Map of Text to CVal, encodedFuncMap, 200).
    Let residual be peBlock(encodedMain, state).
    Let nl be chr(10).
    Let mutable output be "".
    Let specFuncs be peFuncs(state).
    Let mutable allNames be collectCallNames(residual).
    Let mutable emitted be a new Map of Text to Bool.
    Let mutable changed be true.
    While changed:
        Set changed to false.
        Let mutable toAdd be a new Seq of Text.
        Repeat for fnKey in allNames:
            Let fkStr be "{fnKey}".
            If emitted contains fkStr:
                Let skipE be true.
            Otherwise:
                Set item fkStr of emitted to true.
                Let fkStr2 be "{fnKey}".
                If specFuncs contains fkStr2:
                    Let fdef be item fkStr2 of specFuncs.
                    Inspect fdef:
                        When CFuncDef (fn0, ps0, pt0, rt0, body0):
                            Let children be collectCallNames(body0).
                            Repeat for child in children:
                                Let childStr be "{child}".
                                If not emitted contains childStr:
                                    Push child to toAdd.
                                    Set changed to true.
                        Otherwise:
                            Let skipF be true.
        Repeat for ta in toAdd:
            Push ta to allNames.
    Repeat for fnKey in allNames:
        Let fkStr be "{fnKey}".
        If specFuncs contains fkStr:
            Let fdef be item fkStr of specFuncs.
            Let funcSrc be decompileFunc(fdef).
            If the length of funcSrc is greater than 0:
                Set output to "{output}{funcSrc}{nl}".
    Let mainSrc be decompileBlock(residual, 0).
    Set output to "{output}## Main{nl}{mainSrc}".
    Show output.
"#;
    let combined = format!("{}\n{}\n{}\n## Main\n{}\n{}", CORE_TYPES_FOR_PE, pe, decompile, encoded, driver);

    let result = run_logos_source(&combined)?;

    // Fix decompiled types for pe_bti specialized functions (B suffix)
    // Fix decompiled types for pe_bti specialized functions (B suffix)
    let result = fix_decompiled_types(&result, &[
        ("peExprB_", "(e: CExpr) -> CExpr:"),
        ("peBlockB_", "(stmts: Seq of CStmt) -> Seq of CStmt:"),
        ("isStatic_", "(e: CExpr) -> Bool:"),
        ("isLiteral_", "(e: CExpr) -> Bool:"),
        ("allStatic_", "(args: Seq of CExpr) -> Bool:"),
        ("exprToVal_", "(e: CExpr) -> CVal:"),
        ("valToExpr_", "(v: CVal) -> CExpr:"),
        ("evalBinOp_", "(binOp: Text) and (lv: CVal) and (rv: CVal) -> CVal:"),
        ("isCopyPropSafe_", "(e: CExpr) -> Bool:"),
        ("isVNothing_", "(v: CVal) -> Bool:"),
        ("hasReturn_", "(stmts: Seq of CStmt) -> Bool:"),
        ("extractReturnB_", "(stmts: Seq of CStmt) -> CExpr:"),
        ("makeKey_", "(fnName: Text) and (args: Seq of CExpr) -> Text:"),
        ("exprToKeyPartB_", "(e: CExpr) -> Text:"),
        ("collectSetVars_", "(stmts: Seq of CStmt) -> Seq of Text:"),
    ]);

    // Discover the PE-generated block entry point — this IS the cogen.
    let (block_entry, expr_entry) = discover_entry_points(&result, "peBlockB_", "peExprB_");
    if block_entry.is_empty() {
        return Err("Genuine P3: no peBlockB_ entry found in residual".to_string());
    }

    // Strip the ## Main block — we only need the specialized function definitions
    let func_defs_only = strip_main_block(&result);

    // Include pe_bti helpers (unspecialized functions called by specialized ones)
    let pe_bti_helpers = pe_bti_source_text();

    // No Rust-generated block wrapper needed — the PE produced a specialized peBlockB_
    // function. Generate a thin alias for backward compatibility.
    let alias = format!(
        "\n## To cogenBlock (stmts: Seq of CStmt) -> Seq of CStmt:\n    Return {}(stmts).\n",
        block_entry
    );
    let combined = format!("{}\n{}\n{}", pe_bti_helpers, func_defs_only, alias);
    let full_source = deduplicate_functions(&combined);

    Ok(GenuineProjectionResult {
        source: full_source,
        block_entry: "cogenBlock".to_string(),
        expr_entry,
    })
}

/// Remove duplicate function definitions, keeping the first occurrence.
fn deduplicate_functions(source: &str) -> String {
    let mut seen = std::collections::HashSet::new();
    let mut result = String::with_capacity(source.len());
    let mut skip_until_next = false;
    for line in source.lines() {
        let trimmed = line.trim();
        if let Some(rest) = trimmed.strip_prefix("## To ") {
            let name = rest.split(' ').next().unwrap_or("");
            if !seen.insert(name.to_string()) {
                skip_until_next = true;
                continue;
            }
            skip_until_next = false;
        } else if trimmed.starts_with("## Main") {
            skip_until_next = false;
        } else if skip_until_next {
            // Skip body of duplicate function
            if !trimmed.starts_with("## ") {
                continue;
            }
            skip_until_next = false;
        }
        result.push_str(line);
        result.push('\n');
    }
    result
}

/// Strip the ## Main block from decompiled source, keeping only function definitions.
/// The genuine residual's ## Main references internal PE variables (targetExpr, blockResult)
/// that don't exist in the test context. We only need the specialized function definitions.
fn strip_main_block(source: &str) -> String {
    let mut result = String::with_capacity(source.len());
    let mut in_main = false;
    for line in source.lines() {
        let trimmed = line.trim();
        if trimmed == "## Main" {
            in_main = true;
            continue;
        }
        if in_main {
            // Main block ends when we hit another ## To definition or end of file
            if trimmed.starts_with("## To ") {
                in_main = false;
            } else {
                continue;
            }
        }
        result.push_str(line);
        result.push('\n');
    }
    result
}

/// Extract the ## Main block content from source.
fn extract_main_block(source: &str) -> String {
    let mut result = String::new();
    let mut in_main = false;
    for line in source.lines() {
        let trimmed = line.trim();
        if trimmed == "## Main" {
            in_main = true;
            continue;
        }
        if in_main {
            if trimmed.starts_with("## To ") {
                break;
            }
            result.push_str(line);
            result.push('\n');
        }
    }
    result
}

/// Fix decompiled function signatures: replace `(param: Any) -> Any:` with correct types.
/// PE-generated specializations still use "Any" for types the PE couldn't propagate.
/// This restores correct types based on function name prefixes.
fn fix_decompiled_types(source: &str, type_map: &[(&str, &str)]) -> String {
    let mut result = String::with_capacity(source.len());
    for line in source.lines() {
        let trimmed = line.trim();
        if let Some(rest) = trimmed.strip_prefix("## To ") {
            let name = rest.split(' ').next().unwrap_or("");
            let mut fixed = false;
            for (prefix, sig) in type_map {
                if name.starts_with(prefix) {
                    result.push_str(&format!("## To {} {}\n", name, sig));
                    fixed = true;
                    break;
                }
            }
            if !fixed {
                result.push_str(line);
                result.push('\n');
            }
        } else {
            result.push_str(line);
            result.push('\n');
        }
    }
    let result = result
        .replace("Seq of Any", "Seq of CExpr")
        .replace("Set of Any", "Set of CExpr")
        .replace(": Any)", ": CExpr)")
        .replace("-> Any:", "-> CExpr:");
    result
}

fn replace_word(source: &str, from: &str, to: &str) -> String {
    let mut result = String::with_capacity(source.len());
    let mut remaining = source;
    while let Some(pos) = remaining.find(from) {
        let before = if pos > 0 { remaining.as_bytes()[pos - 1] } else { b' ' };
        let after_pos = pos + from.len();
        let after = if after_pos < remaining.len() { remaining.as_bytes()[after_pos] } else { b' ' };
        let is_word = !before.is_ascii_alphanumeric() && before != b'_'
            && !after.is_ascii_alphanumeric() && after != b'_';
        result.push_str(&remaining[..pos]);
        if is_word {
            result.push_str(to);
        } else {
            result.push_str(from);
        }
        remaining = &remaining[after_pos..];
    }
    result.push_str(remaining);
    result
}

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

    #[test]
    fn test_compile_let_statement() {
        let source = "## Main\nLet x be 5.";
        let result = compile_to_rust(source);
        assert!(result.is_ok(), "Should compile: {:?}", result);
        let rust = result.unwrap();
        assert!(rust.contains("fn main()"));
        assert!(rust.contains("let x = 5;"));
    }

    #[test]
    fn test_compile_return_statement() {
        let source = "## Main\nReturn 42.";
        let result = compile_to_rust(source);
        assert!(result.is_ok(), "Should compile: {:?}", result);
        let rust = result.unwrap();
        assert!(rust.contains("return 42;"));
    }

    /// Run `src` through the RUN-PATH optimizer (`optimize_for_run`, which
    /// includes the indexed-load LICM) and then the pure-bytecode VM (no native
    /// tier → no forge dependency), capturing the outcome.
    fn optimized_vm_outcome_no_tier(src: &str, argv: &[String]) -> (String, Option<String>) {
        crate::ui_bridge::with_optimized_program(src, |parsed, interner| match parsed {
            Ok((stmts, types, policies)) => crate::vm::run_to_outcome_with_args(
                stmts,
                interner,
                Some(types),
                Some(&policies),
                argv,
                None,
            ),
            Err(advice) => (String::new(), Some(advice)),
        })
    }

    fn norm_lines(s: &str) -> String {
        s.lines()
            .map(|l| l.trim_end())
            .filter(|l| !l.is_empty())
            .collect::<Vec<_>>()
            .join("\n")
    }

    /// Task C SOUNDNESS, in-process: an inner loop reading a loop-invariant
    /// `item i of arr` (i = OUTER counter, arr never mutated in the loop) mixed
    /// with a variant `item j of arr` must produce the EXACT outcome the
    /// tree-walker produces once the invariant read is hoisted. The guarded
    /// hoist preserves WHEN the read runs, so the optimized VM matches the
    /// oracle bit-for-bit on a real, in-bounds nbody-shaped loop.
    #[test]
    fn licm_indexed_load_nbody_shape_matches_oracle_inprocess() {
        let src = "## Main\n\
                   Let arr be [10, 20, 30, 40, 50].\n\
                   Let mutable acc be 0.\n\
                   Let mutable i be 1.\n\
                   While i is at most 5:\n\
                   \x20   Let mutable j be 1.\n\
                   \x20   While j is at most 5:\n\
                   \x20       Let d be item i of arr - item j of arr.\n\
                   \x20       Set acc to acc + d * d.\n\
                   \x20       Set j to j + 1.\n\
                   \x20   Set i to i + 1.\n\
                   Show acc.\n";
        let argv: [String; 0] = [];
        let tw = tw_outcome_with_args(src, &argv);
        let (out, err) = optimized_vm_outcome_no_tier(src, &argv);
        assert_eq!(
            (norm_lines(&tw.output), &tw.error),
            ("10000".to_string(), &None),
            "oracle: sum of (a_i - a_j)^2"
        );
        assert_eq!(
            (norm_lines(&out), &err),
            (norm_lines(&tw.output), &tw.error),
            "optimized VM (LICM) must match the tree-walker on the nbody-shaped loop"
        );
    }

    /// SOUNDNESS GATE (forge-free): the OPTIMIZED bytecode VM — exercising the
    /// constant-pool sharing (Task B) and the indexed-load LICM (Task C) — must
    /// produce BIT-IDENTICAL output to the raw tree-walker on the whole
    /// benchmark corpus. This mirrors the `vm_opt_differential` integration
    /// test but runs without a native tier, so it stays inside this crate.
    #[test]
    fn corpus_optimized_vm_matches_treewalker_no_tier() {
        const CORPUS: &[(&str, &str)] = &[
            ("ackermann", "3"),
            ("array_fill", "2000"),
            ("array_reverse", "2000"),
            ("binary_trees", "6"),
            ("bubble_sort", "60"),
            ("coins", "500"),
            ("collatz", "300"),
            ("collect", "300"),
            ("counting_sort", "2000"),
            ("fannkuch", "5"),
            ("fib", "12"),
            ("fib_iterative", "500"),
            ("gcd", "60"),
            ("graph_bfs", "200"),
            ("heap_sort", "300"),
            ("histogram", "2000"),
            ("knapsack", "30"),
            ("loop_sum", "2000"),
            ("mandelbrot", "20"),
            ("matrix_mult", "8"),
            ("mergesort", "300"),
            ("nbody", "100"),
            ("nqueens", "5"),
            ("pi_leibniz", "2000"),
            ("prefix_sum", "2000"),
            ("primes", "500"),
            ("quicksort", "300"),
            ("sieve", "2000"),
            ("spectral_norm", "20"),
            ("string_search", "1200"),
            ("strings", "200"),
            ("two_sum", "300"),
        ];
        std::thread::Builder::new()
            .stack_size(256 * 1024 * 1024)
            .spawn(|| {
                for &(name, size) in CORPUS {
                    let path = format!(
                        "{}/../../benchmarks/programs/{}/main.lg",
                        env!("CARGO_MANIFEST_DIR"),
                        name
                    );
                    let src = std::fs::read_to_string(&path)
                        .unwrap_or_else(|e| panic!("cannot read {path}: {e}"));
                    let argv = vec!["bench".to_string(), size.to_string()];
                    let (out, err) = optimized_vm_outcome_no_tier(&src, &argv);
                    let tw = tw_outcome_with_args(&src, &argv);
                    assert_eq!(
                        (norm_lines(&out), &err),
                        (norm_lines(&tw.output), &tw.error),
                        "OPTIMIZED VM (no tier) diverged from the tree-walker on '{name}' at {size}"
                    );
                }
            })
            .expect("spawn")
            .join()
            .expect("corpus thread panicked");
    }
}