logicaffeine-compile 0.10.0

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
use std::collections::{HashMap, HashSet};
use std::fmt::Write;

use crate::analysis::registry::{FieldType, TypeDef, TypeRegistry};
use crate::analysis::types::RustNames;
use crate::ast::stmt::{BinaryOpKind, Expr, Literal, ReadSource, Stmt, TypeExpr};
use crate::intern::{Interner, Symbol};

use super::context::{RefinementContext, VariableCapabilities, emit_refinement_check, analyze_variable_capabilities};
use super::detection::{
    requires_async_stmt, calls_async_function, collect_mutable_vars, collect_mutable_vars_stmt,
    collect_crdt_register_fields, collect_boxed_fields, collect_expr_identifiers,
    collect_stmt_identifiers, expr_debug_prefix, expr_reads_any_collection,
    get_root_identifier_for_mutability, is_copy_type_expr, is_hashable_type,
    parse_aos_tag,
};
use super::expr::{
    codegen_expr, codegen_expr_with_async, codegen_expr_boxed,
    codegen_expr_boxed_with_strings, codegen_expr_boxed_with_types,
    codegen_expr_with_async_oracle, codegen_expr_boxed_with_types_oracle,
    codegen_expr_boxed_with_types_oracle_tolerant,
    codegen_interpolated_string, codegen_literal, codegen_assertion,
    codegen_expr_with_async_and_strings, is_definitely_string_expr_with_vars,
    is_definitely_string_expr, is_definitely_numeric_expr,
    collect_string_concat_operands, is_rational_expr,
};
use super::peephole::{
    try_emit_for_range_pattern, try_emit_vec_fill_pattern, try_emit_swap_pattern,
    try_emit_prefix_reverse,
    try_emit_seq_copy_pattern, try_emit_seq_from_slice_pattern,
    try_emit_vec_with_capacity_pattern, try_emit_merge_capacity_pattern,
    try_emit_rotate_left_pattern, try_emit_buffer_reuse_while,
    try_emit_drain_tail_in_while, try_emit_byte_compare_window,
    body_mutates_collection, body_modifies_var, exprs_equal, simplify_1based_index,
    plan_bounds_hints, emit_bounds_hint_preheader, emit_bounds_hint_header,
    is_counter_increment, collect_expr_symbols, BoundsHintPlan,
    body_has_early_exit, body_resizes_collection,
};
use super::types::{
    codegen_type_expr, infer_rust_type_from_expr, infer_numeric_type,
    infer_variant_type_annotation,
};
use super::i64_map::{dense_type_name, is_logos_map_type, map_rust_type};
use super::escape_rust_ident;

/// The `(Vec<T>, init-expr)` pair for a de-Rc'd Seq declaration, or `None`
/// when the initializer is not a fresh scalar-Seq allocation (in which case
/// the normal `LogosSeq` path runs). Mirrors `fresh_scalar_seq_elem` in the
/// de-Rc eligibility analysis — only those forms are ever marked de-Rc.
fn derc_vec_decl<'a>(
    value: &Expr<'a>,
    interner: &Interner,
    synced_vars: &HashSet<Symbol>,
    boxed_fields: &HashSet<(String, String, String)>,
    registry: &TypeRegistry,
    async_functions: &HashSet<Symbol>,
    ctx: &RefinementContext<'a>,
) -> Option<(String, String)> {
    match value {
        Expr::New { type_name, type_args, init_fields } if init_fields.is_empty() => {
            match interner.resolve(*type_name) {
                "Seq" | "List" | "Vec" => {
                    let elem = codegen_type_expr(type_args.first()?, interner);
                    Some((format!("Vec<{}>", elem), "Vec::new()".to_string()))
                }
                _ => None,
            }
        }
        Expr::WithCapacity { value: inner, capacity } => {
            if let Expr::New { type_name, type_args, .. } = inner {
                if matches!(interner.resolve(*type_name), "Seq" | "List" | "Vec") {
                    let elem = codegen_type_expr(type_args.first()?, interner);
                    let cap = codegen_expr_boxed_with_types(
                        capacity, interner, synced_vars, boxed_fields, registry,
                        async_functions, ctx.get_string_vars(), ctx.get_variable_types(), ctx.get_fast_div(),
                    );
                    return Some((
                        format!("Vec<{}>", elem),
                        format!("Vec::with_capacity(({}) as usize)", cap),
                    ));
                }
            }
            None
        }
        // Phase 4: `Let r be f(...)` where `f` returns an OWNED `Vec<T>` (its
        // return type already de-Rc'd in `fn_returns_map`). The result is a
        // uniquely-owned fresh value — bind it as `Vec<T>` so every later access
        // on `r` indexes directly instead of borrowing a RefCell.
        Expr::Call { function, .. } => {
            let ret = ctx.get_fn_return(function)?;
            if !ret.starts_with("Vec<") {
                return None;
            }
            let vec_ty = ret.clone();
            let init = codegen_expr_boxed_with_types(
                value, interner, synced_vars, boxed_fields, registry,
                async_functions, ctx.get_string_vars(), ctx.get_variable_types(), ctx.get_fast_div(),
            );
            Some((vec_ty, init))
        }
        // A homogeneous scalar-literal list de-Rc's to a plain `Vec<T>` literal — the NTT power
        // table + coefficient array, and any `[…]` of one scalar literal kind, indexed without a
        // RefCell borrow. Eligibility mirrors `fresh_scalar_seq_elem` via the shared helper.
        Expr::List(items) => {
            let elem = crate::codegen::detection::homogeneous_scalar_literal_elem(items)?;
            let item_strs: Vec<String> = items
                .iter()
                .map(|i| {
                    codegen_expr_boxed_with_types(
                        i, interner, synced_vars, boxed_fields, registry, async_functions,
                        ctx.get_string_vars(), ctx.get_variable_types(), ctx.get_fast_div(),
                    )
                })
                .collect();
            Some((format!("Vec<{}>", elem), format!("vec![{}]", item_strs.join(", "))))
        }
        _ => None,
    }
}

/// The `LogosI64Map` constructor for a `Map of Int to Int` declared via `value`
/// (`a new Map of Int to Int` or `… with capacity n`); `None` for any other
/// initializer (the normal `LogosMap` codegen runs). Only called when the alias
/// analysis already selected the variable for `LogosI64Map`.
fn i64_map_ctor<'a>(
    value: &Expr<'a>,
    ty: &str,
    dense_lo: Option<i64>,
    interner: &Interner,
    synced_vars: &HashSet<Symbol>,
    boxed_fields: &HashSet<(String, String, String)>,
    registry: &TypeRegistry,
    async_functions: &HashSet<Symbol>,
    ctx: &RefinementContext<'a>,
) -> Option<String> {
    match value {
        Expr::New { type_name, init_fields, .. }
            if init_fields.is_empty()
                && matches!(interner.resolve(*type_name), "Map" | "HashMap") =>
        {
            Some(format!("{}::new()", ty))
        }
        Expr::WithCapacity { value: inner, capacity } => {
            if let Expr::New { type_name, .. } = inner {
                if matches!(interner.resolve(*type_name), "Map" | "HashMap") {
                    let cap = codegen_expr_boxed_with_types(
                        capacity, interner, synced_vars, boxed_fields, registry,
                        async_functions, ctx.get_string_vars(), ctx.get_variable_types(), ctx.get_fast_div(),
                    );
                    // A dense map is a direct-addressed array offset by the proven
                    // window `lo` (currently 0) and sized `capacity + 1` slots: the
                    // bound proof gives `lo <= key <= lo + capacity`, so the highest
                    // index `key - lo` is `capacity`, which needs `capacity + 1`
                    // slots. A non-dense `LogosI64Map`/`Set` takes the plain capacity.
                    return Some(match dense_lo {
                        Some(lo) => {
                            format!("{}::with_bounds({}, (({}) + 1) as usize)", ty, lo, cap)
                        }
                        None => format!("{}::with_capacity(({}) as usize)", ty, cap),
                    });
                }
            }
            None
        }
        _ => None,
    }
}

/// O5: emit `assert_unchecked` bounds hints for every indexed access in `stmt`
/// the bounds-elision oracle proves in range (a relational induction bound
/// `i <= length(arr)` or a concrete interval). Paired with a `debug_assert!`
/// so an unsound proof panics loudly in debug. No-op when the oracle is absent.
/// Only Identifier collections (a name is needed for `.len()`).
fn emit_oracle_index_hints<'a>(
    stmt: &Stmt<'a>,
    ctx: &RefinementContext<'a>,
    interner: &Interner,
    indent_str: &str,
) -> String {
    // Kill switch (A/B): `LOGOS_ORACLE_HINTS=0` suppresses the oracle bounds
    // hints entirely (the access keeps its runtime bounds check).
    if !crate::optimize::active_config().is_on(crate::optimization::Opt::OracleHints) {
        return String::new();
    }
    let oracle = match ctx.oracle() {
        Some(o) => o,
        None => return String::new(),
    };
    let mut accesses: Vec<(&Expr, &Expr)> = Vec::new();
    collect_index_accesses_in_stmt(stmt, &mut accesses);
    if accesses.is_empty() {
        return String::new();
    }
    let names = RustNames::new(interner);
    let mut out = String::new();
    let mut seen: HashSet<usize> = HashSet::new();
    for (coll, idx) in accesses {
        let arr = match coll {
            Expr::Identifier(s) => *s,
            _ => continue,
        };
        // An affine read-only array is deleted — its reads are pure arithmetic,
        // so there is no `.len()` to bound-check and no hint to emit.
        if ctx.affine_array(arr).is_some() {
            continue;
        }
        // An AoS-interleaved member folds into a `[[T; W]; N]` backing. The hint
        // must name the BACKING (the member's own name no longer exists) and
        // bound its ROW dimension (`backing.len()` == N) — that elides the
        // rolled-regime row bounds-check just like C's, since the column is a
        // constant < W.
        let aos_backing = parse_aos_tag(ctx.get_variable_types().get(&arr)).map(|t| t.backing);
        if !seen.insert(idx as *const Expr as usize) {
            continue;
        }
        if !oracle.index_provably_in_bounds(coll, idx) {
            continue;
        }
        // Discharge any `% m` element-bound precondition this elision leaned on
        // with a hard `assert!(m > 0)` (LLVM hoists the loop-invariant check out
        // of the loop, so it costs one comparison per region entry). For
        // `m <= 0` the `% m`-filled array is empty and this access would be out
        // of bounds: the assert panics there — exactly where the program would
        // have — instead of the elision becoming UB.
        for &m in oracle.index_positivity_guards(idx) {
            let mn = names.ident(m);
            writeln!(
                out,
                "{}assert!(({mn}) > 0, \"LOGOS positivity guard: element bound on `% {mn}` requires {mn} > 0\");",
                indent_str, mn = mn
            )
            .unwrap();
        }
        // Match the ACCESS's 0-based index form: a `__zero_based_i64` counter
        // indexes directly (`arr[i]`), everything else is 1-based (`arr[i-1]`).
        // The oracle reasons about the 1-based source; codegen may rebase.
        let i0 = match idx {
            Expr::Identifier(c)
                if ctx
                    .get_variable_types()
                    .get(c)
                    .map_or(false, |t| t == "__zero_based_i64") =>
            {
                names.ident(*c)
            }
            _ => simplify_1based_index(idx, interner, false, ctx.get_variable_types()),
        };
        let arr_name = aos_backing.unwrap_or_else(|| names.ident(arr));
        let cond = format!("({}) >= 0 && ({}) < ({}.len() as i64)", i0, i0, arr_name);
        writeln!(out, "{}debug_assert!({}, \"LOGOS oracle bounds hint violated: indexing `{}` out of range\");", indent_str, cond, arr_name).unwrap();
        writeln!(out, "{}unsafe {{ std::hint::assert_unchecked({}); }}", indent_str, cond).unwrap();
    }
    if !out.is_empty() {
        crate::optimize::mark_fired(crate::optimization::Opt::OracleHints);
    }
    out
}

fn collect_index_accesses_in_stmt<'a>(stmt: &'a Stmt<'a>, out: &mut Vec<(&'a Expr<'a>, &'a Expr<'a>)>) {
    match stmt {
        Stmt::Let { value, .. } | Stmt::Set { value, .. } => collect_index_in_expr(value, out),
        Stmt::SetIndex { collection, index, value } => {
            out.push((collection, index));
            collect_index_in_expr(index, out);
            collect_index_in_expr(value, out);
        }
        Stmt::If { cond, .. } | Stmt::While { cond, .. } => collect_index_in_expr(cond, out),
        Stmt::Show { object, .. } | Stmt::Give { object, .. } => collect_index_in_expr(object, out),
        Stmt::Return { value: Some(e) } => collect_index_in_expr(e, out),
        Stmt::Push { value, .. } | Stmt::Add { value, .. } | Stmt::Remove { value, .. } => {
            collect_index_in_expr(value, out)
        }
        _ => {}
    }
}

fn collect_index_in_expr<'a>(e: &'a Expr<'a>, out: &mut Vec<(&'a Expr<'a>, &'a Expr<'a>)>) {
    match e {
        Expr::Index { collection, index } => {
            out.push((collection, index));
            collect_index_in_expr(collection, out);
            collect_index_in_expr(index, out);
        }
        Expr::BinaryOp { left, right, .. } => {
            collect_index_in_expr(left, out);
            collect_index_in_expr(right, out);
        }
        Expr::Not { operand } => collect_index_in_expr(operand, out),
        Expr::Call { args, .. } => {
            for a in args.iter() {
                collect_index_in_expr(a, out);
            }
        }
        Expr::Length { collection } => collect_index_in_expr(collection, out),
        _ => {}
    }
}

/// AOT BCE-hoist: a row-major affine-offset bounds guard for one array in one
/// loop. The index `item (offset + counter + 1) of arr` is BILINEAR (e.g.
/// `c[i*n+j]`) — the `i*n` product defeats the linear bounds prover — but from
/// the inner loop's view `offset` (`i*n`) is loop-INVARIANT, so the emitted
/// index `offset + counter` is monotone in the counter. A single preheader
/// `assert!` that `offset >= 0` and the MAX index `offset + (limit - 1) < len`
/// lets the per-iteration access be elided soundly with no static nonlinear
/// proof and no UB (it PANICS, never UB, on an out-of-range program).
pub(crate) struct AffineOffsetGuard<'a> {
    arr_sym: Symbol,
    /// The loop-invariant offset (`i * n`).
    offset: &'a Expr<'a>,
    /// The emitted index `offset + counter` (`i*n + j`), for the body hint.
    emitted_index: &'a Expr<'a>,
}

/// Match the 1-based row-major index `(offset + counter) + 1` whose emitted
/// index is `offset + counter`. Returns `(offset, offset_plus_counter)` where
/// `offset` is the operand that is NOT the bare counter.
fn match_affine_offset_index<'a>(
    index: &'a Expr<'a>,
    counter: Symbol,
) -> Option<(&'a Expr<'a>, &'a Expr<'a>)> {
    if let Expr::BinaryOp { op: BinaryOpKind::Add, left, right } = index {
        if matches!(right, Expr::Literal(Literal::Number(1))) {
            if let Expr::BinaryOp { op: BinaryOpKind::Add, left: a, right: b } = left {
                if matches!(b, Expr::Identifier(s) if *s == counter) {
                    return Some((a, left));
                }
                if matches!(a, Expr::Identifier(s) if *s == counter) {
                    return Some((b, left));
                }
            }
        }
    }
    None
}

/// Plan row-major affine-offset bounds guards for an exclusive `while counter <
/// limit` loop body. Soundness mirrors the O5a counter hints: the access must
/// be UNCONDITIONAL (top-level in the body), the array a `Vec`/slice that is
/// not resized or rebound, and the offset loop-invariant (not mentioning the
/// counter, none of its symbols mutated). v1 handles exclusive loops only (max
/// counter = limit - 1) and one guard per array.
pub(crate) fn plan_affine_offset_guards<'a>(
    body: &'a [Stmt<'a>],
    counter_sym: Symbol,
    is_exclusive: bool,
    var_types: &HashMap<Symbol, String>,
) -> Vec<AffineOffsetGuard<'a>> {
    if !is_exclusive || body_has_early_exit(body) {
        return Vec::new();
    }
    let mut guards: Vec<AffineOffsetGuard> = Vec::new();
    let mut seen: HashSet<Symbol> = HashSet::new();
    for stmt in body {
        let mut accesses: Vec<(&Expr, &Expr)> = Vec::new();
        collect_index_accesses_in_stmt(stmt, &mut accesses);
        for (coll, index) in accesses {
            let arr_sym = match coll {
                Expr::Identifier(s) => *s,
                _ => continue,
            };
            let Some((offset, emitted)) = match_affine_offset_index(index, counter_sym) else {
                continue;
            };
            let base_ty = var_types
                .get(&arr_sym)
                .map(|t| t.split("|__hl:").next().unwrap_or(t.as_str()));
            let qualifies = matches!(
                base_ty,
                Some(t) if t.starts_with("Vec<") || t.starts_with("LogosSeq")
                    || t.starts_with("&[") || t.starts_with("&mut [")
            );
            if !qualifies
                || body_resizes_collection(body, arr_sym)
                || body_modifies_var(body, arr_sym)
            {
                continue;
            }
            let mut osyms = Vec::new();
            collect_expr_symbols(offset, &mut osyms);
            if osyms.contains(&counter_sym)
                || osyms
                    .iter()
                    .any(|s| body_modifies_var(body, *s) || body_mutates_collection(body, *s))
            {
                continue;
            }
            if seen.insert(arr_sym) {
                guards.push(AffineOffsetGuard { arr_sym, offset, emitted_index: emitted });
            }
        }
    }
    guards
}

/// Emit the preheader anchor for each affine-offset guard: a length snapshot
/// plus a hard `assert!` that the MAX index (`offset + limit - 1`) is in range
/// and the offset is non-negative. Runs once per loop entry; PANICS (never UB)
/// if the array is too short, which is what licenses the body-side elision.
pub(crate) fn emit_affine_offset_preheader(
    guards: &[AffineOffsetGuard],
    limit_str: &str,
    interner: &Interner,
    synced_vars: &HashSet<Symbol>,
    async_functions: &HashSet<Symbol>,
    var_types: &HashMap<Symbol, String>,
    indent_str: &str,
    output: &mut String,
) {
    let names = RustNames::new(interner);
    for g in guards {
        let arr = names.ident(g.arr_sym);
        let off = codegen_expr_with_async(g.offset, interner, synced_vars, async_functions, var_types);
        writeln!(
            output,
            "{}assert!(({off}) >= 0 && (({off}) + ({lim}) - 1) < ({arr}.len() as i64), \"LOGOS bounds guard: indexing `{arr}` (row-major) out of range\");",
            indent_str, off = off, lim = limit_str, arr = arr
        ).unwrap();
    }
}

/// Emit the per-iteration `assert_unchecked` for each affine-offset guard, at
/// the top of the loop body. Sound because the preheader `assert!` proved the
/// max index in range and the index is monotone in the (non-negative) counter.
pub(crate) fn emit_affine_offset_header(
    guards: &[AffineOffsetGuard],
    interner: &Interner,
    synced_vars: &HashSet<Symbol>,
    async_functions: &HashSet<Symbol>,
    var_types: &HashMap<Symbol, String>,
    body_indent: &str,
    output: &mut String,
) {
    let names = RustNames::new(interner);
    for g in guards {
        let arr = names.ident(g.arr_sym);
        let e = codegen_expr_with_async(g.emitted_index, interner, synced_vars, async_functions, var_types);
        writeln!(
            output,
            "{}unsafe {{ std::hint::assert_unchecked(({e}) >= 0 && ({e}) < ({arr}.len() as i64)); }}",
            body_indent, e = e, arr = arr
        ).unwrap();
    }
}

/// Emit a `Select` as a raw `tokio::select!` — Mode A (free-running) and the
/// no-arm-ready fallback of Mode B. Verbatim today's lowering.
#[allow(clippy::too_many_arguments)]
fn write_tokio_select<'a>(
    output: &mut String,
    branches: &[crate::ast::stmt::SelectBranch<'a>],
    interner: &Interner,
    indent: usize,
    mutable_vars: &HashSet<Symbol>,
    ctx: &mut RefinementContext<'a>,
    lww_fields: &HashSet<(String, String)>,
    mv_fields: &HashSet<(String, String)>,
    synced_vars: &mut HashSet<Symbol>,
    var_caps: &HashMap<Symbol, VariableCapabilities>,
    async_functions: &HashSet<Symbol>,
    pipe_vars: &HashSet<Symbol>,
    boxed_fields: &HashSet<(String, String, String)>,
    registry: &TypeRegistry,
    type_env: &crate::analysis::types::TypeEnv,
) {
    use crate::ast::stmt::SelectBranch;
    let indent_str = "    ".repeat(indent);
    writeln!(output, "{}tokio::select! {{", indent_str).unwrap();
    for branch in branches {
        match branch {
            SelectBranch::Receive { var, pipe, body } => {
                let var_name = interner.resolve(*var);
                let pipe_str = codegen_expr_with_async(pipe, interner, synced_vars, async_functions, ctx.get_variable_types());
                let is_local_pipe = if let Expr::Identifier(sym) = pipe {
                    pipe_vars.contains(sym)
                } else {
                    false
                };
                let suffix = if is_local_pipe { "_rx" } else { "" };
                writeln!(output, "{}    {} = {}{}.recv() => {{", indent_str, var_name, pipe_str, suffix).unwrap();
                writeln!(output, "{}        if let Some({}) = {} {{", indent_str, var_name, var_name).unwrap();
                for stmt in *body {
                    let stmt_code = codegen_stmt(stmt, interner, indent + 3, mutable_vars, ctx, lww_fields, mv_fields, synced_vars, var_caps, async_functions, pipe_vars, boxed_fields, registry, type_env);
                    write!(output, "{}", stmt_code).unwrap();
                }
                writeln!(output, "{}        }}", indent_str).unwrap();
                writeln!(output, "{}    }}", indent_str).unwrap();
            }
            SelectBranch::Timeout { milliseconds, body } => {
                let dur = match milliseconds {
                    Expr::Literal(Literal::Duration(_)) => codegen_expr_with_async(
                        milliseconds, interner, synced_vars, async_functions,
                        ctx.get_variable_types(),
                    ),
                    Expr::Literal(Literal::Span { months, days }) => {
                        let secs = ((*months as i64) * 30 + (*days as i64)) * 86_400;
                        format!("std::time::Duration::from_secs({}u64)", secs.max(0))
                    }
                    _ => {
                        let n = codegen_expr_with_async(
                            milliseconds, interner, synced_vars, async_functions,
                            ctx.get_variable_types(),
                        );
                        format!("std::time::Duration::from_secs({} as u64)", n)
                    }
                };
                writeln!(output, "{}    _ = tokio::time::sleep({}) => {{", indent_str, dur).unwrap();
                for stmt in *body {
                    let stmt_code = codegen_stmt(stmt, interner, indent + 2, mutable_vars, ctx, lww_fields, mv_fields, synced_vars, var_caps, async_functions, pipe_vars, boxed_fields, registry, type_env);
                    write!(output, "{}", stmt_code).unwrap();
                }
                writeln!(output, "{}    }}", indent_str).unwrap();
            }
        }
    }
    writeln!(output, "{}}}", indent_str).unwrap();
}

/// Emit a `Select` as the **Mode-B seeded winner-pick**. Reads every receive
/// arm's readiness (buffered `len()`, non-consuming); if any are ready, picks the
/// winner among them with the shared seeded chooser (matching the interpreter's
/// `below(n_ready)` over the same ready set in declaration order) and runs that
/// arm; otherwise falls back to `tokio::select!` (so timeouts and not-yet-ready
/// receives still block correctly).
#[allow(clippy::too_many_arguments)]
fn write_seeded_select<'a>(
    output: &mut String,
    branches: &[crate::ast::stmt::SelectBranch<'a>],
    interner: &Interner,
    indent: usize,
    mutable_vars: &HashSet<Symbol>,
    ctx: &mut RefinementContext<'a>,
    lww_fields: &HashSet<(String, String)>,
    mv_fields: &HashSet<(String, String)>,
    synced_vars: &mut HashSet<Symbol>,
    var_caps: &HashMap<Symbol, VariableCapabilities>,
    async_functions: &HashSet<Symbol>,
    pipe_vars: &HashSet<Symbol>,
    boxed_fields: &HashSet<(String, String, String)>,
    registry: &TypeRegistry,
    type_env: &crate::analysis::types::TypeEnv,
) {
    use crate::ast::stmt::SelectBranch;
    let indent_str = "    ".repeat(indent);
    writeln!(output, "{}{{", indent_str).unwrap();
    writeln!(output, "{}    let mut __logos_ready: Vec<usize> = Vec::new();", indent_str).unwrap();
    let mut recv_idx = 0usize;
    for branch in branches {
        if let SelectBranch::Receive { pipe, .. } = branch {
            let pipe_str = codegen_expr_with_async(pipe, interner, synced_vars, async_functions, ctx.get_variable_types());
            let is_local_pipe = if let Expr::Identifier(sym) = pipe {
                pipe_vars.contains(sym)
            } else {
                false
            };
            let suffix = if is_local_pipe { "_rx" } else { "" };
            writeln!(
                output,
                "{}    if {}{}.len() > 0 {{ __logos_ready.push({}); }}",
                indent_str, pipe_str, suffix, recv_idx
            ).unwrap();
            recv_idx += 1;
        }
    }
    writeln!(output, "{}    if __logos_ready.is_empty() {{", indent_str).unwrap();
    write_tokio_select(
        output, branches, interner, indent + 2, mutable_vars, ctx, lww_fields, mv_fields,
        synced_vars, var_caps, async_functions, pipe_vars, boxed_fields, registry, type_env,
    );
    writeln!(output, "{}    }} else {{", indent_str).unwrap();
    writeln!(
        output,
        "{}        let __logos_pick = __logos_ready[logicaffeine_system::concurrency::seeded_pick(__logos_ready.len())];",
        indent_str
    ).unwrap();
    writeln!(output, "{}        match __logos_pick {{", indent_str).unwrap();
    let mut recv_idx = 0usize;
    for branch in branches {
        if let SelectBranch::Receive { var, pipe, body } = branch {
            let var_name = interner.resolve(*var);
            let pipe_str = codegen_expr_with_async(pipe, interner, synced_vars, async_functions, ctx.get_variable_types());
            let is_local_pipe = if let Expr::Identifier(sym) = pipe {
                pipe_vars.contains(sym)
            } else {
                false
            };
            let suffix = if is_local_pipe { "_rx" } else { "" };
            writeln!(output, "{}            {} => {{", indent_str, recv_idx).unwrap();
            writeln!(
                output,
                "{}                if let Some({}) = {}{}.recv().await {{",
                indent_str, var_name, pipe_str, suffix
            ).unwrap();
            for stmt in *body {
                let stmt_code = codegen_stmt(stmt, interner, indent + 5, mutable_vars, ctx, lww_fields, mv_fields, synced_vars, var_caps, async_functions, pipe_vars, boxed_fields, registry, type_env);
                write!(output, "{}", stmt_code).unwrap();
            }
            writeln!(output, "{}                }}", indent_str).unwrap();
            writeln!(output, "{}            }}", indent_str).unwrap();
            recv_idx += 1;
        }
    }
    writeln!(output, "{}            _ => unreachable!(),", indent_str).unwrap();
    writeln!(output, "{}        }}", indent_str).unwrap();
    writeln!(output, "{}    }}", indent_str).unwrap();
    writeln!(output, "{}}}", indent_str).unwrap();
}

/// If `collection` names an OWNED real `LogosSeq`/`LogosMap` value binding, return
/// its Rust identifier so the caller can emit `<ident>.cow();` before an in-place
/// mutation (copy-on-write for mutable value semantics: the shared `Rc` is deep-
/// copied only if another handle observes it).
///
/// Returns `None` — no `cow()` — for every representation that is NOT a shared
/// `Rc<RefCell<…>>`:
/// - de-Rc'd plain `Vec`/`HashMap` locals (registered type starts `Vec`/`HashMap`),
/// - the specialized `LogosI64Map`/`LogosI32Map`/`LogosDense…`/set variants (no `Rc`),
/// - `FxHashSet` / `Set<T>` (Rust `Clone` already deep-copies a `HashSet`),
/// - a `mutable` collection parameter (a `&LogosSeq`/`&LogosMap` whose in-place
///   mutation is REQUIRED to reach the caller — and which cannot call `cow()`),
/// - a non-identifier collection expression (a field/temporary, not a value binding).
fn cow_target(
    collection: &Expr,
    ctx: &RefinementContext,
    names: &RustNames,
) -> Option<String> {
    let Expr::Identifier(sym) = collection else { return None };
    if ctx.is_mutable_collection_param(*sym) {
        return None;
    }
    let ty = ctx.get_variable_types().get(sym)?;
    // A hoisted-length suffix (`Vec<i64>|__hl:…`) only tags de-Rc'd Vecs; strip it
    // before the head match so those never reach the `LogosSeq`/`LogosMap` arm.
    let ty = ty.split("|__hl:").next().unwrap_or(ty.as_str());
    if ty.starts_with("LogosSeq") || ty.starts_with("LogosMap") {
        Some(names.ident(*sym))
    } else {
        None
    }
}

/// Emit a copy-on-write guard before an in-place mutation of `collection`, when it
/// is an owned real `LogosSeq`/`LogosMap` value binding (see [`cow_target`]).
///
/// Gated on [`value_semantics_enabled`]: under the historical reference semantics
/// (`LOGOS_VALUE_SEMANTICS=0`, or the compile-time PE reference scope) collections
/// share their allocation permanently and mutations ARE meant to alias, so no
/// `cow()` is emitted — the shared `Rc` is left untouched.
fn emit_cow(
    collection: &Expr,
    ctx: &RefinementContext,
    names: &RustNames,
    indent_str: &str,
    output: &mut String,
) {
    if !crate::semantics::collections::value_semantics_enabled() {
        return;
    }
    if let Some(name) = cow_target(collection, ctx, names) {
        writeln!(output, "{}{}.cow();", indent_str, name).unwrap();
    }
}

/// If a loop body's sole write to a registered scratch buffer identifies it, return that buffer and its
/// scalarization info. Only the buffer's own fill loop pushes it (post-fill reads are proven read-only by
/// `detect_scratch_buffers`), so any loop that pushes a registered scratch buffer IS its fill loop.
fn scratch_fill_target<'a>(
    body: &[Stmt<'a>],
    ctx: &RefinementContext<'a>,
) -> Option<(Symbol, super::affine_array::ScratchInfo)> {
    for s in body {
        if let Stmt::Push { collection: Expr::Identifier(c), .. } = s {
            if let Some(info) = ctx.scratch_buffer(*c) {
                return Some((*c, info.clone()));
            }
        }
    }
    None
}

pub fn codegen_stmt<'a>(
    stmt: &Stmt<'a>,
    interner: &Interner,
    indent: usize,
    mutable_vars: &HashSet<Symbol>,
    ctx: &mut RefinementContext<'a>,
    lww_fields: &HashSet<(String, String)>,
    mv_fields: &HashSet<(String, String)>,  // Phase 49b: MVRegister fields (no timestamp)
    synced_vars: &mut HashSet<Symbol>,  // Phase 52: Track synced variables
    var_caps: &HashMap<Symbol, VariableCapabilities>,  // Phase 56: Mount+Sync detection
    async_functions: &HashSet<Symbol>,  // Phase 54: Functions that are async
    pipe_vars: &HashSet<Symbol>,  // Phase 54: Pipe declarations (have _tx/_rx suffixes)
    boxed_fields: &HashSet<(String, String, String)>,  // Phase 102: Recursive enum fields
    registry: &TypeRegistry,  // Phase 103: For type annotations on polymorphic enums
    type_env: &crate::analysis::types::TypeEnv,
) -> String {
    let indent_str = "    ".repeat(indent);
    let mut output = String::new();
    let names = RustNames::new(interner);

    // OPT-1C: Take liveness snapshot before any recursion.
    // None = no liveness info → conservative clone.
    // Recursive calls (If/While/etc. bodies) see None → conservative clone.
    let live_vars_after: Option<HashSet<Symbol>> = ctx.take_live_vars_after();

    // Drop a scratch buffer's `new Seq` declaration at any nesting: its fill loop is rewritten in place
    // to `let w: [T; N] = from_fn(…)` (the `Stmt::Repeat` handler), which becomes the binding, so this
    // `Seq::default()` declaration would be a dead duplicate.
    if let Stmt::Let { var, .. } = stmt {
        if ctx.scratch_buffer(*var).is_some() {
            return output;
        }
    }

    // O5: prepend oracle-proven bounds-elision hints for this statement's
    // indexed accesses (the relational `i <= length(arr)` proofs O5a's for-range
    // counter hints cannot reach — e.g. a growing FIFO read by a cursor).
    output.push_str(&emit_oracle_index_hints(stmt, ctx, interner, &indent_str));

    match stmt {
        Stmt::Splice { body } => {
            // Scope-transparent desugar output: emit the statements FLAT —
            // no braces, same indent — so a multi-push lowers byte-identically
            // to the consecutive pushes it desugars from.
            for inner in body.iter() {
                output.push_str(&codegen_stmt(inner, interner, indent, mutable_vars, ctx, lww_fields, mv_fields, synced_vars, var_caps, async_functions, pipe_vars, boxed_fields, registry, type_env));
            }
        }
        Stmt::Let { var, ty, value, mutable } => {
            let var_name = names.ident(*var);

            // AoS interleaving: a co-indexed group member. Column 0 emits the
            // single fused `[[T; W]; N]` backing (reusing the first member's
            // name); the other columns' declarations are dropped — their storage
            // lives in the backing. Runs before the scalarization branch below.
            if matches!(value, Expr::New { .. }) {
                if let Some(tag) = parse_aos_tag(ctx.get_variable_types().get(var)) {
                    if tag.col == 0 {
                        let default = match tag.elem.as_str() {
                            "f64" => "0f64",
                            "bool" => "false",
                            _ => "0i64",
                        };
                        writeln!(
                            output,
                            "{}let mut {}: [[{}; {}]; {}] = [[{}; {}]; {}];",
                            indent_str, tag.backing, tag.elem, tag.width, tag.len, default, tag.width, tag.len
                        )
                        .unwrap();
                    }
                    return output;
                }
            }

            // O3: a fixed-size Seq pre-registered as `[T; N]` (scalarization)
            // — emit a stack array and let the init pushes fill it via indexed
            // writes. Must run before the `new Seq` type registration below,
            // which would otherwise overwrite the array type with LogosSeq.
            if ctx.is_scalarized_array(*var) && matches!(value, Expr::New { .. }) {
                if let Some(arr_ty) = ctx.get_variable_types().get(var).cloned() {
                    let inner = arr_ty.trim_start_matches('[').trim_end_matches(']');
                    let mut parts = inner.split("; ");
                    let elem = parts.next().unwrap_or("i64");
                    let n = parts.next().unwrap_or("0");
                    let default = match elem {
                        "f64" => "0f64",
                        "bool" => "false",
                        "Word8" => "word8(0)",
                        "Word16" => "word16(0)",
                        "Word32" => "word32(0)",
                        "Word64" => "word64(0)",
                        _ => "0i64",
                    };
                    writeln!(output, "{}let mut {}: {} = [{}; {}];",
                        indent_str, var_name, arr_ty, default, n).unwrap();
                    // A loop-built return buffer (the digest) fills through a RUNTIME cursor (the pushes
                    // live in a loop): declare it here; the `Push` handler emits `out[cursor]=v; cursor+=1`.
                    if let Some(cursor) = ctx.loop_fill_cursor(*var).map(|s| s.to_string()) {
                        writeln!(output, "{}let mut {}: usize = 0;", indent_str, cursor).unwrap();
                    }
                    ctx.init_array_fill(*var);
                    return output;
                }
            }

            // Affine read-only array (CSR offset array): deleted entirely. The
            // build push is suppressed and every `item _ of`/`length of` read
            // substitutes the closed form, so the declaration emits nothing. The
            // `__affine_array:...` type was registered in `codegen_program`.
            if matches!(value, Expr::New { .. }) && ctx.affine_array(*var).is_some() {
                return output;
            }

            // Append-only worklist: a de-Rc'd Seq frontier proven bounded by a
            // monotone visited-set guard. Emit a PRE-SIZED buffer + a register
            // tail counter; the pushes lower to `q[tail]=x; tail+=1` and
            // `length of q` to `tail`. This is C's frontier representation.
            if matches!(value, Expr::New { .. }) {
                if let Some((cap, default, tail)) =
                    ctx.worklist(*var).map(|w| (w.capacity.clone(), w.elem_default.clone(), w.tail_var.clone()))
                {
                    writeln!(output, "{}let mut {}: Vec<i64> = vec![{}; {}];", indent_str, var_name, default, cap).unwrap();
                    writeln!(output, "{}let mut {}: usize = 0;", indent_str, tail).unwrap();
                    // Encode the LOGICAL length (the tail) as a hoisted length so
                    // `length of q` reads `tail`, not the buffer size, while every
                    // other site strips the suffix and sees a plain `Vec<i64>`.
                    ctx.register_variable_type(*var, format!("Vec<i64>|__hl:({} as i64)", tail));
                    return output;
                }
            }

            // O2 de-Rc: a Seq proven to never need reference semantics is a
            // plain `Vec<T>` (no Rc/RefCell). Emit the owned-Vec declaration;
            // access sites dispatch on the `Vec<T>` type exactly as they do for
            // borrow-hoisted slices and materialized vecs.
            if ctx.is_de_rc(*var) {
                if let Some((vec_ty, init)) = derc_vec_decl(
                    value, interner, synced_vars, boxed_fields, registry, async_functions, ctx,
                ) {
                    let is_mut = *mutable || mutable_vars.contains(var);
                    let kw = if is_mut { "let mut" } else { "let" };
                    // Pre-size a push-built Vec the program later index-reads up to
                    // a bound: reserve once instead of reallocating as it grows
                    // (C sizes the buffer exactly). Capacity is a hint — sound.
                    let init = match (init.as_str(), ctx.get_vec_presize(*var)) {
                        ("Vec::new()", Some(cap)) => {
                            format!("Vec::with_capacity(({}) as usize)", cap)
                        }
                        _ => init,
                    };
                    // i64→i32 narrowing: a Seq of Int proven to hold only
                    // i32-range values is `Vec<i32>` (access sites convert).
                    let vec_ty = if ctx.is_narrowed(*var) && vec_ty == "Vec<i64>" {
                        "Vec<i32>".to_string()
                    } else {
                        vec_ty
                    };
                    writeln!(output, "{}{} {}: {} = {};", indent_str, kw, var_name, vec_ty, init).unwrap();
                    for g in ctx.narrow_guards(*var).to_vec() {
                        writeln!(output, "{}assert!({}, \"LOGOS i32-narrowing guard: element value must fit i32\");", indent_str, g).unwrap();
                    }
                    ctx.register_variable_type(*var, vec_ty);
                    return output;
                }
            }

            // Register collection type for direct indexing optimization.
            // Check explicit type annotation first, then infer from Expr::New.
            if let Some(TypeExpr::Generic { base, params }) = ty {
                let base_name = interner.resolve(*base);
                match base_name {
                    "Seq" | "List" | "Vec" => {
                        let rust_type = if !params.is_empty() {
                            format!("LogosSeq<{}>", codegen_type_expr(&params[0], interner))
                        } else {
                            "LogosSeq<()>".to_string()
                        };
                        ctx.register_variable_type(*var, rust_type);
                    }
                    "Map" | "HashMap" => {
                        let rust_type = if params.len() >= 2 {
                            map_rust_type(
                                &codegen_type_expr(&params[0], interner),
                                &codegen_type_expr(&params[1], interner),
                                *var,
                                ctx,
                            )
                        } else {
                            "LogosMap<String, String>".to_string()
                        };
                        ctx.register_variable_type(*var, rust_type);
                    }
                    _ => {}
                }
            } else if let Expr::New { type_name, type_args, .. } = value {
                let type_str = interner.resolve(*type_name);
                match type_str {
                    "Seq" | "List" | "Vec" => {
                        let rust_type = if !type_args.is_empty() {
                            format!("LogosSeq<{}>", codegen_type_expr(&type_args[0], interner))
                        } else {
                            "LogosSeq<()>".to_string()
                        };
                        ctx.register_variable_type(*var, rust_type);
                    }
                    "Map" | "HashMap" => {
                        let rust_type = if type_args.len() >= 2 {
                            map_rust_type(
                                &codegen_type_expr(&type_args[0], interner),
                                &codegen_type_expr(&type_args[1], interner),
                                *var,
                                ctx,
                            )
                        } else {
                            "LogosMap<String, String>".to_string()
                        };
                        ctx.register_variable_type(*var, rust_type);
                    }
                    _ => {}
                }
            } else if let Expr::List(items) = value {
                // Infer element type from first literal in the list for Copy elimination
                let elem_type = items.first()
                    .map(|e| infer_rust_type_from_expr(e, interner))
                    .unwrap_or_else(|| "_".to_string());
                ctx.register_variable_type(*var, format!("LogosSeq<{}>", elem_type));
            } else if let Expr::Identifier(src_sym) = value {
                // Propagate type from source variable: `Let result be arr` inherits arr's type.
                // For borrow params (&[T]), the copy becomes Vec<T> (owned).
                if let Some(src_type) = ctx.get_variable_types().get(src_sym).cloned() {
                    if src_type.starts_with("&[") {
                        // Propagate borrow type — rebinding the slice, not copying
                        ctx.register_variable_type(*var, src_type);
                    } else if src_type.starts_with("&mut [") {
                        // Mutable borrow param consumed into alias → propagate &mut [T]
                        // so the alias continues to be treated as the in-place mutable borrow.
                        ctx.register_variable_type(*var, src_type);
                    } else if !super::is_fn_role_slot(&src_type) {
                        ctx.register_variable_type(*var, src_type);
                    }
                }
            } else if let Expr::Copy { expr: inner } = value {
                // `Copy of items ... of arr` or `Copy of arr` produces same collection type
                let src_sym = match inner {
                    Expr::Slice { collection, .. } => {
                        if let Expr::Identifier(s) = collection { Some(*s) } else { None }
                    }
                    Expr::Identifier(s) => Some(*s),
                    _ => None,
                };
                if let Some(s) = src_sym {
                    if let Some(src_type) = ctx.get_variable_types().get(&s).cloned() {
                        if src_type.starts_with("LogosSeq") || src_type.starts_with("Vec") || src_type.starts_with("&[") {
                            let elem = if src_type.starts_with("LogosSeq<") {
                                src_type.strip_prefix("LogosSeq<").and_then(|t| t.strip_suffix('>')).unwrap_or("_")
                            } else if src_type.starts_with("Vec<") {
                                src_type.strip_prefix("Vec<").and_then(|t| t.strip_suffix('>')).unwrap_or("_")
                            } else {
                                src_type.strip_prefix("&[").and_then(|t| t.strip_suffix(']')).unwrap_or("_")
                            };
                            ctx.register_variable_type(*var, format!("LogosSeq<{}>", elem));
                        } else if src_type.starts_with("LogosMap") {
                            ctx.register_variable_type(*var, src_type);
                        }
                    }
                }
            }

            // Infer result type from function call return types
            if !ctx.get_variable_types().contains_key(var) {
                if let Expr::Call { function, .. } = value {
                    // The `decimal(..)` builtin yields an exact `LogosDecimal` — record it so
                    // later `+ − ×` over this binding take the exact decimal codegen path.
                    if interner.resolve(*function) == "decimal" {
                        ctx.register_variable_type(*var, "LogosDecimal".to_string());
                    } else if interner.resolve(*function) == "complex" {
                        ctx.register_variable_type(*var, "LogosComplex".to_string());
                    } else if interner.resolve(*function) == "modular" {
                        ctx.register_variable_type(*var, "LogosModular".to_string());
                    } else if matches!(interner.resolve(*function), "quantity" | "convert") {
                        // Both quantity builtins yield a `LogosQuantity`; record it so later
                        // `+ − × ÷` / comparison over this binding take the quantity codegen path.
                        ctx.register_variable_type(*var, "LogosQuantity".to_string());
                    } else if interner.resolve(*function) == "money" {
                        // `money(..)` yields a `LogosMoney`; record it so later `+ − × ÷` /
                        // comparison over this binding take the money codegen path.
                        ctx.register_variable_type(*var, "LogosMoney".to_string());
                    } else if matches!(
                        interner.resolve(*function),
                        "uuid" | "uuid_nil" | "uuid_max" | "uuid_v3" | "uuid_v5" | "uuid_dns"
                            | "uuid_url" | "uuid_oid" | "uuid_x500"
                    ) {
                        // Every UUID constructor yields a `LogosUuid`; record it so a later
                        // comparison over this binding takes the (Ord) UUID codegen path.
                        ctx.register_variable_type(*var, "LogosUuid".to_string());
                    } else if let Some(rt) = ctx.get_fn_return(function).cloned() {
                        ctx.register_variable_type(*var, rt);
                    }
                }
            }

            // Register scalar types for mixed Float*Int arithmetic coercion
            if !ctx.get_variable_types().contains_key(var) {
                let inferred = infer_rust_type_from_expr(value, interner);
                if inferred != "_" {
                    ctx.register_variable_type(*var, inferred);
                } else {
                    // Try deeper numeric type inference for expressions like `4.0 * pi * pi`
                    let numeric = infer_numeric_type(value, interner, ctx.get_variable_types());
                    if numeric != "unknown" {
                        ctx.register_variable_type(*var, numeric.to_string());
                    } else if let crate::analysis::types::LogosType::Map(k, v) =
                        super::types::infer_logos_type(value, interner, ctx.get_variable_types())
                    {
                        // A `{k: v, …}` map-literal binding: record its `Map<K, V>` type so a
                        // numeric-unified key lookup (`m contains 1.0` on an Int-keyed map) can
                        // coerce. Only Map is registered here — the narrowest change that closes
                        // the compiled key-coercion gap.
                        ctx.register_variable_type(
                            *var,
                            crate::analysis::types::LogosType::Map(k, v).to_rust_type(),
                        );
                    }
                }
            }

            // A nested list literal (`[[…], …]`) whose whole-program type only resolved to the
            // imprecise `LogosSeq<_>`: re-register the precise `LogosSeq<LogosSeq<…>>` so the
            // nested-write through-write fast path can specialise on the inner Seq. Narrowly gated
            // on the imprecise inner, so a de-Rc'd `Vec` or a specialised representation is untouched.
            if matches!(value, Expr::List(_))
                && ctx.get_variable_types().get(var).map_or(false, |t| t == "LogosSeq<_>")
            {
                if let crate::analysis::types::LogosType::Seq(inner) =
                    super::types::infer_logos_type(value, interner, ctx.get_variable_types())
                {
                    if matches!(*inner, crate::analysis::types::LogosType::Seq(_)) {
                        ctx.register_variable_type(
                            *var,
                            crate::analysis::types::LogosType::Seq(inner).to_rust_type(),
                        );
                    }
                }
            }

            // OPT: Single-char text variable → u8 byte.
            // If this variable is pre-registered as __single_char_u8, emit u8 instead of String.
            let is_single_char_u8 = ctx.get_variable_types().get(var)
                .map_or(false, |t| t == "__single_char_u8");

            if is_single_char_u8 {
                if let Expr::Literal(Literal::Text(sym)) = value {
                    let text = interner.resolve(*sym);
                    if text.len() == 1 {
                        let ch = text.as_bytes()[0];
                        let is_mutable = *mutable || mutable_vars.contains(var);
                        if is_mutable {
                            writeln!(output, "{}let mut {}: u8 = b'{}';", indent_str, var_name, ch as char).unwrap();
                        } else {
                            writeln!(output, "{}let {}: u8 = b'{}';", indent_str, var_name, ch as char).unwrap();
                        }
                        // Don't register as string var — it's a u8 now
                        return output;
                    }
                }
            }

            // Materialize Expr::Slice on LogosSeq as Vec<T> to avoid dangling
            // &[T] borrows from temporary Ref guards. Stored as Vec (not LogosSeq)
            // so that downstream `copy of` can wrap with LogosSeq::from_vec()
            // for zero-copy ownership transfer instead of deep_clone.
            if let Expr::Slice { collection, start, end } = value {
                if let Expr::Identifier(coll_sym) = collection {
                    if let Some(coll_type) = ctx.get_variable_types().get(coll_sym).cloned() {
                        if coll_type.starts_with("LogosSeq<") {
                            let elem_type = coll_type.strip_prefix("LogosSeq<")
                                .and_then(|t| t.strip_suffix('>'))
                                .unwrap_or("_");
                            let coll_name = names.ident(*coll_sym);
                            let start_str = codegen_expr_boxed_with_types(
                                start, interner, synced_vars, boxed_fields, registry, async_functions,
                                ctx.get_string_vars(), ctx.get_variable_types(), ctx.get_fast_div()
                            );
                            let end_str = codegen_expr_boxed_with_types(
                                end, interner, synced_vars, boxed_fields, registry, async_functions,
                                ctx.get_string_vars(), ctx.get_variable_types(), ctx.get_fast_div()
                            );
                            let is_mutable = *mutable || mutable_vars.contains(var);
                            let mutk = if is_mutable { "mut " } else { "" };
                            writeln!(output, "{}let {}{}: Vec<{}> = {}.borrow()[({} - 1) as usize..{} as usize].to_vec();",
                                indent_str, mutk, var_name, elem_type, coll_name, start_str, end_str).unwrap();
                            // Register as Vec<T> — indexing works directly, and `copy of`
                            // wraps with LogosSeq::from_vec(x.clone()) for one-copy semantics.
                            ctx.register_variable_type(*var, format!("Vec<{}>", elem_type));
                            if is_definitely_string_expr_with_vars(value, ctx.get_string_vars()) {
                                ctx.register_string_var(*var);
                            }
                            return output;
                        } else if coll_type.starts_with("&[") {
                            let elem_type = coll_type.strip_prefix("&[")
                                .and_then(|t| t.strip_suffix(']'))
                                .unwrap_or("_");
                            let coll_name = names.ident(*coll_sym);
                            let start_str = codegen_expr_boxed_with_types(
                                start, interner, synced_vars, boxed_fields, registry, async_functions,
                                ctx.get_string_vars(), ctx.get_variable_types(), ctx.get_fast_div()
                            );
                            let end_str = codegen_expr_boxed_with_types(
                                end, interner, synced_vars, boxed_fields, registry, async_functions,
                                ctx.get_string_vars(), ctx.get_variable_types(), ctx.get_fast_div()
                            );
                            let is_mutable = *mutable || mutable_vars.contains(var);
                            let mutk = if is_mutable { "mut " } else { "" };
                            // Direct slice of borrow param — no .borrow() needed
                            writeln!(output, "{}let {}{}: Vec<{}> = {}[({} - 1) as usize..{} as usize].to_vec();",
                                indent_str, mutk, var_name, elem_type, coll_name, start_str, end_str).unwrap();
                            ctx.register_variable_type(*var, format!("Vec<{}>", elem_type));
                            if is_definitely_string_expr_with_vars(value, ctx.get_string_vars()) {
                                ctx.register_string_var(*var);
                            }
                            return output;
                        }
                    }
                }
            }

            // Overflow-promoting Int binding: a promotion candidate whose initializer is an
            // integer expression is stored as `LogosInt` (not a bare `i64`), so a value that
            // exceeds i64 promotes instead of panicking. Register the `|__bigint` sentinel BEFORE
            // codegen so any self-reference in the RHS already reads as a LogosInt.
            let is_bigint_binding = ty.is_none()
                && ctx.is_promotable_candidate(*var)
                && crate::codegen::types::infer_numeric_type(value, interner, ctx.get_variable_types()) == "i64";
            if is_bigint_binding {
                ctx.register_variable_type(*var, "i64|__bigint".to_string());
            }

            // Phase 54+: Use codegen_expr_boxed with string+type tracking for proper codegen
            let mut value_str = if is_bigint_binding {
                // Tolerant (un-narrowed) RHS, coerced to LogosInt (`.into()` is identity when the
                // RHS is already a LogosInt, and promotes a plain `i64` otherwise).
                let raw = codegen_expr_boxed_with_types_oracle_tolerant(
                    value, interner, synced_vars, boxed_fields, registry, async_functions,
                    ctx.get_string_vars(), ctx.get_variable_types(), ctx.get_fast_div(), ctx.oracle(),
                );
                format!("logicaffeine_data::LogosInt::from({})", raw)
            } else {
                codegen_expr_boxed_with_types_oracle(
                    value, interner, synced_vars, boxed_fields, registry, async_functions,
                    ctx.get_string_vars(), ctx.get_variable_types(), ctx.get_fast_div(), ctx.oracle(),
                )
            };

            // Phase D: lower a non-aliased `Map of Int to Int` to the specialized
            // open-addressing `LogosI64Map`, or the keys-only `LogosI64Set` when
            // the value is never read (contains + insert only). Override the
            // constructor AND re-register the type so the two never disagree,
            // regardless of which `Let` initializer shape registered it above.
            if ctx.is_i64_map(*var) {
                // Densest tier first: a proven bounded key domain → a
                // direct-addressed array sized to the capacity hint, offset by the
                // proven window `lo`. Otherwise the open-addressing map/set.
                let dense = ctx.dense_info(*var);
                let i64_ty = if let Some(info) = dense {
                    dense_type_name(info.kind)
                } else if ctx.is_i32_set(*var) {
                    "LogosI32Set"
                } else if ctx.is_i32_map(*var) {
                    "LogosI32Map"
                } else if ctx.is_i64_set(*var) {
                    "LogosI64Set"
                } else {
                    "LogosI64Map"
                };
                if let Some(ctor) = i64_map_ctor(
                    value, i64_ty, dense.map(|i| i.lo), interner, synced_vars, boxed_fields,
                    registry, async_functions, ctx,
                ) {
                    value_str = ctor;
                    ctx.register_variable_type(*var, i64_ty.to_string());
                }
            }

            // Grand Challenge: Variable is mutable if explicitly marked OR if it's a Set target.
            // A `LogosI64Map` is mutated in place via `&mut self` (the analysis
            // requires ≥1 insert), so it must bind as `let mut`.
            let is_mutable = *mutable || mutable_vars.contains(var) || ctx.is_i64_map(*var);

            // Reference semantics: clone LogosSeq/LogosMap on assignment to share the Rc.
            // Borrow param (&[T]) assigned to mutable local → convert to owned.
            if let Expr::Identifier(src_sym) = value {
                if let Some(src_type) = ctx.get_variable_types().get(src_sym) {
                    if src_type.starts_with("LogosSeq") || src_type.starts_with("LogosMap") {
                        value_str = format!("{}.clone()", value_str);
                    } else if is_mutable && src_type.starts_with("&[") {
                        value_str = format!("{}.to_vec()", value_str);
                    }
                }
            }

            // Phase 103: Get explicit type annotation or infer for multi-param generic enums
            let type_annotation = if is_bigint_binding {
                Some("logicaffeine_data::LogosInt".to_string())
            } else {
                ty.map(|t| codegen_type_expr(t, interner))
                    .or_else(|| infer_variant_type_annotation(value, registry, interner))
            };

            // A `Rational`-typed binding whose RHS is a plain integer expression — a bare
            // `Let x: Rational be 5`, or the whole-valued constant fold `6 / 2 → 3` — must
            // coerce the i64 value to an exact `LogosRational` so the declared type matches.
            // An RHS that already produces a Rational (an `ExactDivide` chain) is left as-is.
            if type_annotation.as_deref() == Some("LogosRational") {
                if !is_rational_expr(value, ctx.get_variable_types()) {
                    value_str = format!("LogosRational::from_i64(({}) as i64)", value_str);
                }
                ctx.register_variable_type(*var, "LogosRational".to_string());
            }

            match (is_mutable, type_annotation) {
                (true, Some(t)) => writeln!(output, "{}let mut {}: {} = {};", indent_str, var_name, t, value_str).unwrap(),
                (true, None) => writeln!(output, "{}let mut {} = {};", indent_str, var_name, value_str).unwrap(),
                (false, Some(t)) => writeln!(output, "{}let {}: {} = {};", indent_str, var_name, t, value_str).unwrap(),
                (false, None) => writeln!(output, "{}let {} = {};", indent_str, var_name, value_str).unwrap(),
            }

            // O9 libdivide: if this binding is a loop-invariant positive divisor,
            // precompute its magic multiply ONCE here so every later `% n` / `/ n`
            // lowers to `helper.rem(..)` / `helper.div(..)`. Harmless if `n <= 0`
            // (the helper is only ever read inside loops that don't run there).
            if let Some(helper) = ctx.get_fast_div().get(var) {
                writeln!(
                    output,
                    "{}let {} = logicaffeine_data::LogosDivU64::new(({}) as u64);",
                    indent_str, helper, var_name
                )
                .unwrap();
            }

            // Track string variables for proper concatenation in subsequent expressions
            if is_definitely_string_expr_with_vars(value, ctx.get_string_vars()) {
                ctx.register_string_var(*var);
            }

            // Phase 43C: Handle refinement type
            if let Some(TypeExpr::Refinement { base: _, var: bound_var, predicate }) = ty {
                emit_refinement_check(&var_name, *bound_var, predicate, interner, &indent_str, &mut output);
                ctx.register(*var, *bound_var, predicate);
            }
        }

        Stmt::Set { target, value } => {
            let target_name = names.ident(*target);

            // Overflow-promoting Int target: assign an un-narrowed `LogosInt` (`.into()` is
            // identity when the RHS already is one, and promotes a plain `i64` otherwise), so a
            // running product/sum that exceeds i64 promotes to BigInt instead of panicking. A
            // bigint target is always a scalar integer, so none of the string/char/collection
            // special cases below apply.
            if ctx.is_bigint_var(*target) {
                let raw = codegen_expr_boxed_with_types_oracle_tolerant(
                    value, interner, synced_vars, boxed_fields, registry, async_functions,
                    ctx.get_string_vars(), ctx.get_variable_types(), ctx.get_fast_div(), ctx.oracle(),
                );
                writeln!(output, "{}{} = logicaffeine_data::LogosInt::from({});", indent_str, target_name, raw).unwrap();
                if let Some((bound_var, predicate)) = ctx.get_constraint(*target) {
                    emit_refinement_check(&target_name, bound_var, predicate, interner, &indent_str, &mut output);
                }
                return output;
            }

            // Cursor-indexed string build: `Set text to text + X` writes X at the
            // cursor in the pre-sized buffer (no push). The paired `Set c to c +
            // len(X)` that follows advances the cursor as usual. See
            // peephole::try_emit_indexed_string_build.
            if let Some(cursor) = ctx.indexed_string_build(*target).map(|c| c.to_string()) {
                if let Expr::BinaryOp { op: BinaryOpKind::Add, right, .. } = value {
                    match right {
                        Expr::Literal(Literal::Text(sym)) => {
                            let lit = interner.resolve(*sym);
                            let bytes: Vec<String> =
                                lit.bytes().map(|b| format!("{}u8", b)).collect();
                            writeln!(
                                output,
                                "{ind}unsafe {{ std::ptr::copy_nonoverlapping([{b}].as_ptr(), {t}.as_mut_vec().as_mut_ptr().add(({c}) as usize), {k}); }}",
                                ind = indent_str, t = target_name, c = cursor, k = lit.len(), b = bytes.join(", ")
                            )
                            .unwrap();
                            return output;
                        }
                        Expr::Identifier(v)
                            if ctx.get_variable_types().get(v).map(String::as_str)
                                == Some("__single_char_u8") =>
                        {
                            let vn = names.ident(*v);
                            writeln!(
                                output,
                                "{ind}unsafe {{ *{t}.as_mut_vec().as_mut_ptr().add(({c}) as usize) = {vn}; }}",
                                ind = indent_str, t = target_name, c = cursor
                            )
                            .unwrap();
                            return output;
                        }
                        _ => {}
                    }
                }
            }

            // O2 de-Rc: reassigning a de-Rc'd Seq to a FRESH allocation keeps
            // it a plain `Vec<T>` (`xs = Vec::new()`), not `Seq::default()`.
            if ctx.is_de_rc(*target) {
                if let Some((_, init)) = derc_vec_decl(
                    value, interner, synced_vars, boxed_fields, registry, async_functions, ctx,
                ) {
                    writeln!(output, "{}{} = {};", indent_str, target_name, init).unwrap();
                    return output;
                }
            }

            // OPT: Single-char u8 variable → emit byte literal assignment.
            let is_target_single_char_u8 = ctx.get_variable_types().get(target)
                .map_or(false, |t| t == "__single_char_u8");
            if is_target_single_char_u8 {
                if let Expr::Literal(Literal::Text(sym)) = value {
                    let text = interner.resolve(*sym);
                    if text.len() == 1 {
                        let ch = text.as_bytes()[0];
                        writeln!(output, "{}{} = b'{}';", indent_str, target_name, ch as char).unwrap();
                        return output;
                    }
                }
            }

            let string_vars = ctx.get_string_vars();
            let var_types = ctx.get_variable_types();

            // Optimization: detect self-append pattern (result = result + x + y)
            // and emit write!(result, "{}{}", x, y) instead of result = format!(...).
            // This is O(n) amortized (in-place append) vs O(n²) (full copy each iteration).
            let used_write = if ctx.is_string_var(*target)
                && is_definitely_string_expr_with_vars(value, string_vars)
            {
                let mut operands = Vec::new();
                collect_string_concat_operands(value, string_vars, &mut operands);

                // Need at least 2 operands, leftmost must be the target variable
                if operands.len() >= 2 && matches!(operands[0], Expr::Identifier(sym) if *sym == *target) {
                    // Check no other operand references target (would cause borrow conflict)
                    let tail = &operands[1..];
                    let mut tail_ids = HashSet::new();
                    for op in tail {
                        collect_expr_identifiers(op, &mut tail_ids);
                    }

                    if !tail_ids.contains(target) {
                        if tail.len() == 1 {
                            // Single operand: use push/push_str for zero-format-overhead append
                            let operand = tail[0];
                            if let Expr::Literal(Literal::Text(sym)) = operand {
                                let text = interner.resolve(*sym);
                                if text.len() == 1 {
                                    let ch = text.chars().next().unwrap();
                                    writeln!(output, "{}{}.push('{}');",
                                        indent_str, target_name, ch).unwrap();
                                } else {
                                    writeln!(output, "{}{}.push_str(\"{}\");",
                                        indent_str, target_name, text).unwrap();
                                }
                            } else if let Expr::Identifier(sym) = operand {
                                if var_types.get(sym).map_or(false, |t| t == "__single_char_u8") {
                                    // OPT: u8 single-char var → push(ch as char)
                                    let val_str = codegen_expr_boxed_with_types(
                                        operand, interner, synced_vars, boxed_fields, registry, async_functions,
                                        string_vars, var_types, ctx.get_fast_div()
                                    );
                                    writeln!(output, "{}{}.push({} as char);",
                                        indent_str, target_name, val_str).unwrap();
                                } else if string_vars.contains(sym) {
                                    let val_str = codegen_expr_boxed_with_types(
                                        operand, interner, synced_vars, boxed_fields, registry, async_functions,
                                        string_vars, var_types, ctx.get_fast_div()
                                    );
                                    writeln!(output, "{}{}.push_str(&{});",
                                        indent_str, target_name, val_str).unwrap();
                                } else {
                                    // Non-string single operand: use write!
                                    let val_str = codegen_expr_boxed_with_types(
                                        operand, interner, synced_vars, boxed_fields, registry, async_functions,
                                        string_vars, var_types, ctx.get_fast_div()
                                    );
                                    writeln!(output, "{}write!({}, \"{{}}\", {}).unwrap();",
                                        indent_str, target_name, val_str).unwrap();
                                }
                            } else {
                                // Non-string single operand: use write!
                                let val_str = codegen_expr_boxed_with_types(
                                    operand, interner, synced_vars, boxed_fields, registry, async_functions,
                                    string_vars, var_types, ctx.get_fast_div()
                                );
                                writeln!(output, "{}write!({}, \"{{}}\", {}).unwrap();",
                                    indent_str, target_name, val_str).unwrap();
                            }
                        } else {
                            // Multiple operands: use write!() with format string
                            let placeholders: String = tail.iter().map(|_| "{}").collect::<Vec<_>>().join("");
                            let values: Vec<String> = tail.iter().map(|e| {
                                if let Expr::Literal(Literal::Text(sym)) = e {
                                    format!("\"{}\"", interner.resolve(*sym))
                                } else {
                                    codegen_expr_boxed_with_types(
                                        e, interner, synced_vars, boxed_fields, registry, async_functions,
                                        string_vars, var_types, ctx.get_fast_div()
                                    )
                                }
                            }).collect();
                            writeln!(output, "{}write!({}, \"{}\", {}).unwrap();",
                                indent_str, target_name, placeholders, values.join(", ")).unwrap();
                        }
                        true
                    } else {
                        false
                    }
                } else {
                    false
                }
            } else {
                false
            };

            if !used_write {
                // &mut borrow call-site transformation:
                // `Set x to f(x, ...)` where f has fn_mut_borrow at the target position
                // → `f(&mut x, ...)` (no assignment, mutation is in-place)
                let mut used_mut_borrow = false;
                if let Expr::Call { function, args } = value {
                    let callee_mut_borrow_indices: HashSet<usize> =
                        super::fn_role_indices(var_types.get(function), super::FnRole::MutBorrow);
                    if !callee_mut_borrow_indices.is_empty() {
                        // Check if target is at a mut_borrow position
                        let target_at_mut_borrow = args.iter().enumerate()
                            .any(|(i, a)| {
                                callee_mut_borrow_indices.contains(&i)
                                    && matches!(a, Expr::Identifier(sym) if *sym == *target)
                            });
                        if target_at_mut_borrow {
                            let callee_borrow_indices: HashSet<usize> =
                                super::fn_role_indices(var_types.get(function), super::FnRole::Borrow);
                            let func_name = names.ident(*function);
                            let args_str: Vec<String> = args.iter().enumerate()
                                .map(|(i, a)| {
                                    let s = codegen_expr_boxed_with_types(
                                        a, interner, synced_vars, boxed_fields, registry,
                                        async_functions, string_vars, var_types, ctx.get_fast_div()
                                    );
                                    if callee_mut_borrow_indices.contains(&i) {
                                        // Mut borrow param: pass &mut [T] reference
                                        if let Expr::Identifier(sym) = a {
                                            if let Some(ty) = var_types.get(sym) {
                                                let ty = ty.split("|__hl:").next().unwrap_or(ty.as_str());
                                                if ty.starts_with("&mut [") {
                                                    return s; // Already &mut slice
                                                }
                                                // Phase 3b: a de-Rc'd `Vec` lends `&mut x`
                                                // directly — no RefCell to borrow_mut.
                                                if ty.starts_with("Vec<") {
                                                    return format!("&mut {}", s);
                                                }
                                                if ty.starts_with("LogosSeq") {
                                                    return format!("&mut *{}.borrow_mut()", s);
                                                }
                                            }
                                            // Unknown type — default to LogosSeq
                                            return format!("&mut *{}.borrow_mut()", s);
                                        }
                                        format!("&mut {}", s)
                                    } else if callee_borrow_indices.contains(&i) {
                                        if let Expr::Identifier(sym) = a {
                                            if let Some(ty) = var_types.get(sym) {
                                                let ty = ty.split("|__hl:").next().unwrap_or(ty.as_str());
                                                if ty.starts_with("&[") || ty.starts_with("&mut [") {
                                                    return s;
                                                }
                                                if ty.starts_with("Vec<") {
                                                    return format!("&{}", s);
                                                }
                                                if ty.starts_with('[') {
                                                    // Const-table stack array [T; N] coerces to &[T].
                                                    return format!("&{}", s);
                                                }
                                                if ty.starts_with("LogosSeq") {
                                                    return format!("&*{}.borrow()", s);
                                                }
                                            }
                                            // Unknown type — default to LogosSeq
                                            return format!("&*{}.borrow()", s);
                                        }
                                        format!("&*{}.borrow()", s)
                                    } else {
                                        s
                                    }
                                })
                                .collect();
                            // Value semantics: make each lent handle's buffer
                            // UNIQUE before the in-place call — an alias keeps
                            // the pre-call value, the callee's writes land on
                            // ours alone. Amortized free: a refcount-1 cow is
                            // a branch, only a genuinely shared buffer copies.
                            if crate::semantics::collections::value_semantics_enabled() {
                                for (i, a) in args.iter().enumerate() {
                                    if !callee_mut_borrow_indices.contains(&i) {
                                        continue;
                                    }
                                    if let Expr::Identifier(sym) = a {
                                        let lends_refcell = match var_types.get(sym) {
                                            Some(t) => t
                                                .split("|__hl:")
                                                .next()
                                                .unwrap_or(t.as_str())
                                                .starts_with("LogosSeq"),
                                            None => true, // unknown type lowers via borrow_mut above
                                        };
                                        if lends_refcell {
                                            writeln!(output, "{}{}.cow();", indent_str, names.ident(*sym)).unwrap();
                                        }
                                    }
                                }
                            }
                            let await_suffix = if async_functions.contains(function) { ".await" } else { "" };
                            writeln!(output, "{}{}({}){};", indent_str, func_name, args_str.join(", "), await_suffix).unwrap();
                            used_mut_borrow = true;
                        }
                    }
                }

                // OPT-1B: Last-use clone elimination for `Set x to f(x, ...)`.
                // When the target variable appears as a direct non-borrow argument
                // and doesn't appear in other arg sub-expressions, skip cloning it
                // since the old value is immediately overwritten by the result.
                let value_str = if used_mut_borrow {
                    String::new() // Already emitted above
                } else if let Expr::Call { function, args } = value {
                    let target_positions: Vec<usize> = args.iter().enumerate()
                        .filter(|(_, a)| matches!(a, Expr::Identifier(sym) if *sym == *target))
                        .map(|(i, _)| i)
                        .collect();

                    let mut other_ids = HashSet::new();
                    for (i, a) in args.iter().enumerate() {
                        if target_positions.contains(&i) { continue; }
                        collect_expr_identifiers(a, &mut other_ids);
                    }
                    let target_in_others = other_ids.contains(target);

                    let callee_borrow_indices: HashSet<usize> =
                        super::fn_role_indices(var_types.get(function), super::FnRole::Borrow);

                    let can_move = target_positions.len() == 1
                        && !callee_borrow_indices.contains(&target_positions[0])
                        && !target_in_others
                        && var_types.get(target).map_or(false, |t| !is_copy_type(t));

                    if can_move {
                        let func_name = names.ident(*function);
                        let move_pos = target_positions[0];
                        let args_str: Vec<String> = args.iter().enumerate()
                            .map(|(i, a)| {
                                let s = codegen_expr_boxed_with_types(
                                    a, interner, synced_vars, boxed_fields, registry,
                                    async_functions, string_vars, var_types, ctx.get_fast_div()
                                );
                                if callee_borrow_indices.contains(&i) {
                                    if let Expr::Identifier(sym) = a {
                                        if let Some(ty) = var_types.get(sym) {
                                            let ty = ty.split("|__hl:").next().unwrap_or(ty.as_str());
                                            if ty.starts_with("&[") || ty.starts_with("&mut [") {
                                                return s;
                                            }
                                            if ty.starts_with("Vec<") {
                                                return format!("&{}", s);
                                            }
                                            if ty.starts_with('[') {
                                                // Const-table stack array [T; N] coerces to &[T].
                                                // A const table is read-only, never the assign target.
                                                return format!("&{}", s);
                                            }
                                            if ty.starts_with("LogosSeq") {
                                                if *sym == *target {
                                                    return format!("&*{}.clone().borrow()", s);
                                                }
                                                return format!("&*{}.borrow()", s);
                                            }
                                        }
                                        if *sym == *target {
                                            return format!("&*{}.clone().borrow()", s);
                                        }
                                        return format!("&*{}.borrow()", s);
                                    }
                                    format!("&*{}.borrow()", s)
                                } else if i == move_pos {
                                    s // Move: no .clone()
                                } else {
                                    if let Expr::Identifier(sym) = a {
                                        if let Some(ty) = var_types.get(sym) {
                                            if !is_copy_type(ty) {
                                                return format!("{}.clone()", s);
                                            }
                                        }
                                    }
                                    s
                                }
                            })
                            .collect();
                        if async_functions.contains(function) {
                            format!("{}({}).await", func_name, args_str.join(", "))
                        } else {
                            format!("{}({})", func_name, args_str.join(", "))
                        }
                    } else {
                        // OPT-1C: Cross-variable last-use move.
                        // Build the call manually so we can move args that are not live
                        // after this statement instead of cloning them.
                        //
                        // Safety conditions for moving arg at position i:
                        //   1. Liveness info is available (live_vars_after is Some)
                        //   2. The variable is NOT live after this statement
                        //   3. The variable does NOT appear in any other arg expression
                        //      (moving it first would invalidate a borrow in a later arg)
                        let func_name = names.ident(*function);
                        let args_str: Vec<String> = args.iter().enumerate()
                            .map(|(i, a)| {
                                let s = codegen_expr_boxed_with_types(
                                    a, interner, synced_vars, boxed_fields, registry,
                                    async_functions, string_vars, var_types, ctx.get_fast_div()
                                );
                                if callee_borrow_indices.contains(&i) {
                                    if let Expr::Identifier(sym) = a {
                                        if let Some(ty) = var_types.get(sym) {
                                            let ty = ty.split("|__hl:").next().unwrap_or(ty.as_str());
                                            if ty.starts_with("&[") || ty.starts_with("&mut [") {
                                                return s;
                                            }
                                            if ty.starts_with("Vec<") {
                                                return format!("&{}", s);
                                            }
                                            if ty.starts_with('[') {
                                                // Const-table stack array [T; N] coerces to &[T].
                                                // A const table is read-only, never the assign target.
                                                return format!("&{}", s);
                                            }
                                            if ty.starts_with("LogosSeq") {
                                                if *sym == *target {
                                                    return format!("&*{}.clone().borrow()", s);
                                                }
                                                return format!("&*{}.borrow()", s);
                                            }
                                        }
                                        if *sym == *target {
                                            return format!("&*{}.clone().borrow()", s);
                                        }
                                        return format!("&*{}.borrow()", s);
                                    }
                                    format!("&*{}.borrow()", s)
                                } else if let Expr::Identifier(sym) = a {
                                    if let Some(ty) = var_types.get(sym) {
                                        if !is_copy_type(ty) {
                                            // Can move only when liveness says it's dead AND
                                            // the variable isn't referenced in any other arg.
                                            let can_move_opt1c = live_vars_after
                                                .as_ref()
                                                .map(|live| {
                                                    if live.contains(sym) {
                                                        return false;
                                                    }
                                                    // Check it doesn't appear in other args
                                                    let mut other_ids = HashSet::new();
                                                    for (j, other_a) in args.iter().enumerate() {
                                                        if j == i { continue; }
                                                        collect_expr_identifiers(other_a, &mut other_ids);
                                                    }
                                                    !other_ids.contains(sym)
                                                })
                                                .unwrap_or(false);
                                            if can_move_opt1c {
                                                return s; // Move: dead after this stmt, safe
                                            }
                                            return format!("{}.clone()", s);
                                        }
                                    }
                                    s
                                } else {
                                    s
                                }
                            })
                            .collect();
                        if async_functions.contains(function) {
                            format!("{}({}).await", func_name, args_str.join(", "))
                        } else {
                            format!("{}({})", func_name, args_str.join(", "))
                        }
                    }
                } else {
                    let mut vs = codegen_expr_boxed_with_types(
                        value, interner, synced_vars, boxed_fields, registry,
                        async_functions, string_vars, var_types, ctx.get_fast_div()
                    );
                    // Reference semantics: clone LogosSeq/LogosMap on assignment to share the Rc.
                    if let Expr::Identifier(src_sym) = value {
                        if let Some(src_type) = var_types.get(src_sym) {
                            if src_type.starts_with("LogosSeq") || src_type.starts_with("LogosMap") {
                                vs = format!("{}.clone()", vs);
                            }
                        }
                    }
                    vs
                };
                if !used_mut_borrow {
                    writeln!(output, "{}{} = {};", indent_str, target_name, value_str).unwrap();
                }
            }

            // Phase 43C: Check if this variable has a refinement constraint
            if let Some((bound_var, predicate)) = ctx.get_constraint(*target) {
                emit_refinement_check(&target_name, bound_var, predicate, interner, &indent_str, &mut output);
            }
        }

        Stmt::Call { function, args } => {
            let func_name = names.ident(*function);
            let variable_types = ctx.get_variable_types();
            // Callee param-role indices (packed one slot per function): a readonly
            // borrow, an element `&mut` borrow, and a value-semantics `mutable`
            // collection param can co-exist, so read each role independently.
            let callee_slot = variable_types.get(function);
            let callee_borrow_indices: HashSet<usize> =
                super::fn_role_indices(callee_slot, super::FnRole::Borrow);
            let callee_mut_borrow_indices: HashSet<usize> =
                super::fn_role_indices(callee_slot, super::FnRole::MutBorrow);
            // `mutable` collection params (value semantics): pass the caller's
            // LogosSeq/Map by shared reference (no clone) so the callee mutates it
            // in place — the explicit propagation escape hatch.
            let callee_value_mutable: HashSet<usize> =
                super::fn_role_indices(callee_slot, super::FnRole::ValueMutable);
            let args_str: Vec<String> = args.iter().enumerate().map(|(i, a)| {
                let s = codegen_expr_with_async(a, interner, synced_vars, async_functions, variable_types);
                if callee_value_mutable.contains(&i) {
                    // Pass by shared reference (no clone). If already a reference
                    // (a `mutable` param threaded through a nested call), pass as-is.
                    if let Expr::Identifier(sym) = a {
                        if variable_types.get(sym).is_some_and(|t| t.starts_with('&')) {
                            return s;
                        }
                    }
                    return format!("&{}", s);
                }
                if callee_mut_borrow_indices.contains(&i) {
                    // Mut borrow param: pass &mut [T] reference
                    if let Expr::Identifier(sym) = a {
                        if let Some(ty) = variable_types.get(sym) {
                            let ty = ty.split("|__hl:").next().unwrap_or(ty.as_str());
                            if ty.starts_with("&mut [") {
                                return s; // Already &mut slice
                            }
                            // Phase 3b: a de-Rc'd `Vec` lends `&mut x` directly.
                            if ty.starts_with("Vec<") {
                                return format!("&mut {}", s);
                            }
                            if ty.starts_with("LogosSeq") {
                                return format!("&mut *{}.borrow_mut()", s);
                            }
                        }
                        // Unknown type — default to LogosSeq
                        return format!("&mut *{}.borrow_mut()", s);
                    }
                    format!("&mut {}", s)
                } else if callee_borrow_indices.contains(&i) {
                    // Borrow param: pass &[T] reference instead of moving
                    if let Expr::Identifier(sym) = a {
                        if let Some(ty) = variable_types.get(sym) {
                            let ty = ty.split("|__hl:").next().unwrap_or(ty.as_str());
                            if ty.starts_with("&[") || ty.starts_with("&mut [") {
                                return s; // Already a slice — pass through
                            }
                            if ty.starts_with("Vec<") {
                                return format!("&{}", s);
                            }
                            if ty.starts_with('[') {
                                // Const-table stack array [T; N] coerces to &[T].
                                return format!("&{}", s);
                            }
                            if ty.starts_with("LogosSeq") {
                                return format!("&*{}.borrow()", s);
                            }
                        }
                        // Unknown type — default to LogosSeq
                        return format!("&*{}.borrow()", s);
                    }
                    format!("&*{}.borrow()", s)
                } else {
                    // Regular param: clone non-Copy identifiers to avoid move-after-use.
                    // LogosSeq/LogosMap .clone() is O(1) Rc clone — exactly what we want
                    // for reference semantics.
                    if let Expr::Identifier(sym) = a {
                        if let Some(ty) = variable_types.get(sym) {
                            if !is_copy_type(ty) {
                                return format!("{}.clone()", s);
                            }
                        }
                    }
                    s
                }
            }).collect();
            // Add .await if calling an async function
            let await_suffix = if async_functions.contains(function) { ".await" } else { "" };
            writeln!(output, "{}{}({}){};", indent_str, func_name, args_str.join(", "), await_suffix).unwrap();
        }

        Stmt::If { cond, then_block, else_block } => {
            let cond_str = codegen_expr_with_async_oracle(cond, interner, synced_vars, async_functions, ctx.get_variable_types(), ctx.oracle());
            let cond_str = truthy_cond_wrap(cond, cond_str, interner, ctx.get_variable_types());
            writeln!(output, "{}if {} {{", indent_str, cond_str).unwrap();
            ctx.push_scope();
            {
                let block_refs: Vec<&Stmt> = then_block.iter().collect();
                let mut bi = 0;
                while bi < block_refs.len() {
                    if let Some((code, skip)) = super::peephole::try_block_peepholes(&block_refs, bi, interner, indent + 1, mutable_vars, ctx, lww_fields, mv_fields, synced_vars, var_caps, async_functions, pipe_vars, boxed_fields, registry, type_env) {
                        output.push_str(&code);
                        bi += 1 + skip;
                        continue;
                    }
                    output.push_str(&codegen_stmt(block_refs[bi], interner, indent + 1, mutable_vars, ctx, lww_fields, mv_fields, synced_vars, var_caps, async_functions, pipe_vars, boxed_fields, registry, type_env));
                    bi += 1;
                }
            }
            ctx.pop_scope();
            if let Some(else_stmts) = else_block {
                writeln!(output, "{}}} else {{", indent_str).unwrap();
                ctx.push_scope();
                {
                    let block_refs: Vec<&Stmt> = else_stmts.iter().collect();
                    let mut bi = 0;
                    while bi < block_refs.len() {
                        if let Some((code, skip)) = super::peephole::try_block_peepholes(&block_refs, bi, interner, indent + 1, mutable_vars, ctx, lww_fields, mv_fields, synced_vars, var_caps, async_functions, pipe_vars, boxed_fields, registry, type_env) {
                            output.push_str(&code);
                            bi += 1 + skip;
                            continue;
                        }
                        output.push_str(&codegen_stmt(block_refs[bi], interner, indent + 1, mutable_vars, ctx, lww_fields, mv_fields, synced_vars, var_caps, async_functions, pipe_vars, boxed_fields, registry, type_env));
                        bi += 1;
                    }
                }
                ctx.pop_scope();
            }
            writeln!(output, "{}}}", indent_str).unwrap();
        }

        Stmt::While { cond, body, decreasing: _ } => {
            // bcmp idiom: a fixed-window byte-compare loop collapses to a slice
            // inequality (LLVM `bcmp`) — try it before the scalar while codegen.
            if let Some(code) = try_emit_byte_compare_window(stmt, interner, indent, ctx.get_variable_types(), ctx.oracle()) {
                return code;
            }
            // decreasing is compile-time only, ignored at runtime

            // OPT: Loop bounds hoisting.
            // Collect all `length of X` symbols from condition AND body where X is
            // not modified in the loop. Emit hoisted `let x_len = (x.len() as i64);`
            // bindings before the loop. Register a sentinel in variable_types so that
            // Expr::Length codegen emits the hoisted name directly (no string replacement).
            let mut all_length_syms_raw = extract_length_expr_syms(cond);
            collect_length_syms_from_stmts(body, &mut all_length_syms_raw);
            let mut seen = HashSet::new();
            let all_length_syms: Vec<Symbol> = all_length_syms_raw
                .into_iter()
                .filter(|s| seen.insert(*s))
                .collect();

            let mut hoisted_syms: Vec<(Symbol, Option<String>)> = Vec::new();
            for len_sym in &all_length_syms {
                // An affine read-only array is deleted; `length of` it is its trip
                // count (no `.len()` to hoist). Leave its `__affine_array:` tag intact.
                if ctx.affine_array(*len_sym).is_some() {
                    continue;
                }
                if !body_mutates_collection(body, *len_sym) && !body_modifies_var(body, *len_sym) {
                    let name = interner.resolve(*len_sym);
                    let hoisted_name = format!("{}_len", name);
                    writeln!(output, "{}let {} = ({}.len() as i64);", indent_str, hoisted_name, name).unwrap();
                    let old_type = ctx.get_variable_types().get(len_sym).cloned();
                    // Append hoisted sentinel to existing type string. Expr::Length checks
                    // for |__hl: suffix to emit the hoisted name. All other type checks
                    // use starts_with() so the suffix doesn't interfere.
                    let new_type = match &old_type {
                        Some(existing) => format!("{}|__hl:{}", existing, hoisted_name),
                        None => format!("|__hl:{}", hoisted_name),
                    };
                    ctx.register_variable_type(*len_sym, new_type);
                    hoisted_syms.push((*len_sym, old_type));
                }
            }

            // OPT-9: bounds hints for arrays indexed by a unit-stepping while
            // counter (`while counter <= bound:` / `< bound:`). Unlike the
            // for-range site, this loop shape guarantees nothing by
            // construction, so everything plan_bounds_hints assumes must be
            // checked here: the counter takes every value up to the bound
            // (unit increment last, no other counter writes) and the bound is
            // loop-invariant.
            let mut while_bounds_hints: Vec<BoundsHintPlan> = Vec::new();
            let mut affine_guards: Vec<AffineOffsetGuard> = Vec::new();
            if let Expr::BinaryOp { op: op @ (BinaryOpKind::LtEq | BinaryOpKind::Lt), left: Expr::Identifier(counter_sym), right: bound_expr } = cond {
                let body_sans_inc = if !body.is_empty()
                    && is_counter_increment(&body[body.len() - 1], *counter_sym)
                {
                    Some(&body[..body.len() - 1])
                } else {
                    None
                };
                if let Some(body_sans_inc) = body_sans_inc {
                    let counter_clean = !body_modifies_var(body_sans_inc, *counter_sym);
                    let mut bound_syms = Vec::new();
                    collect_expr_symbols(bound_expr, &mut bound_syms);
                    let bound_invariant = bound_syms.iter().all(|s| {
                        !body_modifies_var(body, *s) && !body_mutates_collection(body, *s)
                    });
                    if counter_clean && bound_invariant {
                        let bound_str = codegen_expr_with_async(bound_expr, interner, synced_vars, async_functions, ctx.get_variable_types());
                        while_bounds_hints = plan_bounds_hints(
                            body_sans_inc,
                            *counter_sym,
                            matches!(op, BinaryOpKind::Lt),
                            false,
                            bound_expr,
                            &bound_str,
                            ctx.get_variable_types(),
                        );
                        emit_bounds_hint_preheader(&while_bounds_hints, interner, &indent_str, &mut output);

                        // AOT BCE-hoist: row-major affine-offset guards. One
                        // preheader `assert!` per array proves the MAX index
                        // (`offset + limit - 1`) in range; the per-iteration
                        // access is then elided soundly in the body.
                        affine_guards = plan_affine_offset_guards(
                            body_sans_inc,
                            *counter_sym,
                            matches!(op, BinaryOpKind::Lt),
                            ctx.get_variable_types(),
                        );
                        emit_affine_offset_preheader(&affine_guards, &bound_str, interner, synced_vars, async_functions, ctx.get_variable_types(), &indent_str, &mut output);
                    }
                }
            }

            // Scratch-buffer allocation hoisting: a loop-local buffer that is
            // freshly allocated, fully overwritten by a copy of a source slice,
            // used/mutated in place, and never escapes the iteration is hoisted
            // to ONE allocation before the loop and reused (`clear()` +
            // `extend_from_slice`) each iteration — eliminating one malloc/free
            // per iteration (fannkuch's `perm`: ~n! of them). Value-identical to
            // the per-iteration `.to_vec()`; gated on the de-Rc non-escape proof.
            let scratch_hoisted: Vec<Symbol> =
                super::peephole::detect_scratch_hoist_in_body(body, interner, ctx)
                    .into_iter()
                    .map(|(dst, elem_type)| {
                        writeln!(output, "{}let mut {}: Vec<{}> = Vec::new();",
                            indent_str, interner.resolve(dst), elem_type).unwrap();
                        ctx.register_variable_type(dst, format!("Vec<{}>", elem_type));
                        ctx.register_scratch_hoist(dst);
                        dst
                    })
                    .collect();

            // O1: scope-extract per-handle borrows around the whole while
            // loop when the alias oracle proves it sound. The cond is part of
            // the access scan; opened before cond emission so the condition
            // also indexes slices.
            let hoist_plan = super::hoist::plan_borrow_hoist(stmt, Some(cond), body, ctx, interner);
            super::hoist::emit_hoist_open(&hoist_plan, interner, &indent_str, ctx, &mut output);

            let cond_str = codegen_expr_with_async_oracle(cond, interner, synced_vars, async_functions, ctx.get_variable_types(), ctx.oracle());
            let cond_str = truthy_cond_wrap(cond, cond_str, interner, ctx.get_variable_types());
            writeln!(output, "{}while {} {{", indent_str, cond_str).unwrap();
            emit_bounds_hint_header(&while_bounds_hints, interner, &"    ".repeat(indent + 1), &mut output);
            emit_affine_offset_header(&affine_guards, interner, synced_vars, async_functions, ctx.get_variable_types(), &"    ".repeat(indent + 1), &mut output);
            ctx.push_scope();

            // OPT-5: Extract sentinel context from while condition.
            // For `While counter < limit:`, detect `Set counter to limit` inside If blocks
            // as sentinel exits and replace with `break`.
            let sentinel_ctx: Option<(Symbol, &Expr)> = match cond {
                Expr::BinaryOp { op: BinaryOpKind::Lt, left, right } => {
                    if let Expr::Identifier(sym) = left {
                        Some((*sym, *right))
                    } else {
                        None
                    }
                }
                _ => None,
            };

            // Peephole: process body statements with peephole optimizations.
            let body_refs: Vec<&Stmt> = body.iter().collect();
            let mut bi = 0;
            while bi < body_refs.len() {
                if let Some((code, skip)) = super::peephole::try_block_peepholes(&body_refs, bi, interner, indent + 1, mutable_vars, ctx, lww_fields, mv_fields, synced_vars, var_caps, async_functions, pipe_vars, boxed_fields, registry, type_env) {
                    output.push_str(&code);
                    bi += 1 + skip;
                    continue;
                }
                // Drain-tail optimization: If a branch in the while body is a
                // loop-invariant sequential drain (push-from-array + increment), emit
                // extend_from_slice + break instead of element-by-element push.
                if let Some(code) = try_emit_drain_tail_in_while(
                    body_refs[bi], cond, interner, indent + 1,
                    mutable_vars, ctx, lww_fields, mv_fields, synced_vars, var_caps,
                    async_functions, pipe_vars, boxed_fields, registry, type_env,
                ) {
                    output.push_str(&code);
                    bi += 1;
                    continue;
                }
                // OPT-5: Sentinel → break transformation.
                // If this statement is an If whose then_block ends with `Set counter to limit`,
                // emit break instead of the sentinel set.
                if let Some((counter_sym, limit_expr)) = &sentinel_ctx {
                    if let Some(code) = try_emit_sentinel_break(
                        body_refs[bi], *counter_sym, limit_expr, interner, indent + 1,
                        mutable_vars, ctx, lww_fields, mv_fields, synced_vars, var_caps,
                        async_functions, pipe_vars, boxed_fields, registry, type_env,
                    ) {
                        // This peephole emits the If inline (bypassing codegen_stmt),
                        // so the oracle bounds hints for index accesses in its guard
                        // (string_search's `text[i+j]`) must be emitted here too.
                        output.push_str(&emit_oracle_index_hints(
                            body_refs[bi], ctx, interner, &"    ".repeat(indent + 1),
                        ));
                        output.push_str(&code);
                        bi += 1;
                        continue;
                    }
                }
                output.push_str(&codegen_stmt(body_refs[bi], interner, indent + 1, mutable_vars, ctx, lww_fields, mv_fields, synced_vars, var_caps, async_functions, pipe_vars, boxed_fields, registry, type_env));
                bi += 1;
            }
            ctx.pop_scope();

            // Restore original variable_types for hoisted symbols.
            // variable_types is a flat HashMap (not scoped), so push/pop_scope doesn't clean it.
            for (sym, old_type) in hoisted_syms {
                if let Some(old) = old_type {
                    ctx.register_variable_type(sym, old);
                } else {
                    ctx.get_variable_types_mut().remove(&sym);
                }
            }

            // Stop treating the hoisted scratch buffers as reused once their
            // loop closes, so a same-named buffer in a sibling loop is not
            // mis-rewritten into a refill of a buffer that was never hoisted.
            for dst in scratch_hoisted {
                ctx.clear_scratch_hoist(dst);
            }

            writeln!(output, "{}}}", indent_str).unwrap();
            // Close the borrow-hoist scope and restore slice-shadowed types.
            super::hoist::emit_hoist_close(&hoist_plan, &indent_str, ctx, &mut output);
        }

        Stmt::Repeat { pattern, iterable, body } => {
            use crate::ast::stmt::Pattern;

            // Generate pattern string for Rust code
            let pattern_str = match pattern {
                Pattern::Identifier(sym) => interner.resolve(*sym).to_string(),
                Pattern::Tuple(syms) => {
                    let names = syms.iter()
                        .map(|s| interner.resolve(*s))
                        .collect::<Vec<_>>()
                        .join(", ");
                    format!("({})", names)
                }
            };

            // Indexed-buffer zero-init loop: dropped — the `let mut buf: [T; N] = [0; N]` the O3 `Let`
            // handler already emitted zeroes every slot, and the subsequent `Set item i of buf` writes hit
            // the array directly. (A push-fill of a `[T; N]` array would be wrong: the fill counter is
            // compile-time, so a runtime loop would set slot 0 repeatedly.)
            if super::affine_array::is_indexed_init_loop(body, |s| ctx.is_indexed_buffer(s)) {
                return output;
            }

            // Scratch-buffer scalarization: a counted loop whose sole job is to fill a registered
            // fixed-size, non-escaping buffer is emitted in place as `let w: [T; N] = from_fn(|__k| { let
            // j = LO + __k; <body-lets>; <push-val> })` — a single stack array — instead of a `Vec` that a
            // per-entry push loop reallocates on every entry. All non-push body statements (intermediate
            // `Let`s) become the closure's leading `let`s; the sole `Push`'s value is the tail expression.
            if let Pattern::Identifier(loop_var) = pattern {
                if let Some((w, info)) = scratch_fill_target(body, ctx) {
                    let wname = names.ident(w);
                    writeln!(output, "{}let {}: [{}; {}] = ::std::array::from_fn(|__k: usize| {{",
                        indent_str, wname, info.elem_ty, info.len).unwrap();
                    writeln!(output, "{}    let {} = ({} as i64) + (__k as i64);",
                        indent_str, interner.resolve(*loop_var), info.lo).unwrap();
                    ctx.push_scope();
                    ctx.register_variable_type(*loop_var, "i64".to_string());
                    let mut push_val: Option<&Expr> = None;
                    for s in body.iter() {
                        match s {
                            Stmt::Push { collection: Expr::Identifier(c), value } if *c == w => {
                                push_val = Some(value);
                            }
                            other => output.push_str(&codegen_stmt(
                                other, interner, indent + 1, mutable_vars, ctx, lww_fields, mv_fields,
                                synced_vars, var_caps, async_functions, pipe_vars, boxed_fields, registry, type_env)),
                        }
                    }
                    let val = codegen_expr_boxed_with_types_oracle(
                        push_val.expect("scratch fill loop has exactly one push"),
                        interner, synced_vars, boxed_fields, registry, async_functions,
                        ctx.get_string_vars(), ctx.get_variable_types(), ctx.get_fast_div(), ctx.oracle());
                    writeln!(output, "{}    {}", indent_str, val).unwrap();
                    ctx.pop_scope();
                    writeln!(output, "{}}});", indent_str).unwrap();
                    return output;
                }
            }

            let iter_str = codegen_expr_with_async(iterable, interner, synced_vars, async_functions, ctx.get_variable_types());

            // OPT-PAR: Automatic parallelization for commutative reduction patterns.
            // Detect: Repeat for x in coll: Set acc = acc + expr(x)
            // Emit: acc += coll.par_iter().copied().map(|x| expr).sum::<i64>()
            let par_emitted = if let Pattern::Identifier(var_sym) = pattern {
                if let Some(par_code) = try_emit_parallel_reduction(
                    *var_sym, &pattern_str, &iter_str, iterable, body,
                    interner, indent, ctx,
                    synced_vars, async_functions,
                ) {
                    output.push_str(&par_code);
                    true
                } else {
                    false
                }
            } else {
                false
            };

            if par_emitted {
                // Parallel code already emitted — skip normal loop codegen
            } else if body.iter().any(|s| {
                requires_async_stmt(s) || calls_async_function(s, async_functions)
            }) {
                // Use while-let with explicit iterator for async compatibility
                writeln!(output, "{}let mut __iter = ({}).into_iter();", indent_str, iter_str).unwrap();
                writeln!(output, "{}while let Some({}) = __iter.next() {{", indent_str, pattern_str).unwrap();
            } else {
                // Determine iteration strategy based on collection type
                let is_logos_seq = if let Expr::Identifier(coll_sym) = iterable {
                    ctx.get_variable_types().get(coll_sym)
                        .map(|s| s.split("|__hl:").next().unwrap_or(s.as_str()))
                        .map_or(false, |t| t.starts_with("LogosSeq"))
                } else {
                    false
                };

                if is_logos_seq {
                    // LogosSeq: snapshot the inner vec for iteration.
                    // .to_vec() returns an owned Vec<T> — safe to iterate while
                    // allowing mutations to the LogosSeq during/after the loop.
                    writeln!(output, "{}for {} in {}.to_vec() {{", indent_str, pattern_str, iter_str).unwrap();
                } else {
                // Optimization: for known Vec<T>/&[T] with Copy element type,
                // use .iter().copied() instead of .clone() to avoid copying the entire collection.
                // For slices, must use .iter() since .clone() on &[T] clones the reference, not the data.
                let (use_iter_copied, use_iter_cloned) = if let Expr::Identifier(coll_sym) = iterable {
                    if let Some(coll_type_raw) = ctx.get_variable_types().get(coll_sym) {
                        // Strip |__hl: hoisting suffix so strip_suffix(']') works correctly.
                        let coll_type = coll_type_raw.split("|__hl:").next().unwrap_or(coll_type_raw.as_str());
                        if coll_type.starts_with('[') {
                            // O3 fixed array `[T; N]` — iterate by borrow so the array is not consumed.
                            let elem = coll_type.strip_prefix('[').and_then(|s| s.split(';').next()).unwrap_or("_").trim();
                            if is_copy_type(elem) {
                                (true, false)
                            } else {
                                (false, true)
                            }
                        } else if coll_type.starts_with("&[") {
                            // Borrowed slice `&[T]` or fixed-array ref `&[T; N]`: must use .iter() (can't
                            // move/clone a borrowed slice). Take the element type before any `; N` length so
                            // a `&[i64; 3]` param iterates by `.copied()` exactly like the `&[i64]` slice.
                            let inner = coll_type.strip_prefix("&[").and_then(|s| s.strip_suffix(']')).unwrap_or("_");
                            let elem = inner.split(';').next().unwrap_or(inner).trim();
                            if is_copy_type(elem) {
                                (true, false)
                            } else {
                                (false, true)
                            }
                        } else if coll_type.starts_with("Vec") && has_copy_element_type(coll_type)
                            && !body_mutates_collection(body, *coll_sym)
                        {
                            (true, false)
                        } else if coll_type.starts_with("Vec")
                            && !body_mutates_collection(body, *coll_sym)
                        {
                            // Non-Copy element type, but body doesn't mutate the collection:
                            // use .iter().cloned() for lazy per-element cloning instead of
                            // .clone() which copies the entire collection upfront.
                            (false, true)
                        } else {
                            (false, false)
                        }
                    } else {
                        (false, false)
                    }
                } else {
                    (false, false)
                };

                if use_iter_copied {
                    writeln!(output, "{}for {} in {}.iter().copied() {{", indent_str, pattern_str, iter_str).unwrap();
                } else if use_iter_cloned {
                    writeln!(output, "{}for {} in {}.iter().cloned() {{", indent_str, pattern_str, iter_str).unwrap();
                } else {
                    // Clone the collection before iterating to avoid moving it.
                    // This allows the collection to be reused after the loop.
                    writeln!(output, "{}for {} in {}.clone() {{", indent_str, pattern_str, iter_str).unwrap();
                }
                }
            }
            if !par_emitted {
                ctx.push_scope();
                // Peephole: process body statements with swap, seq-copy, and rotate-left detection
                {
                    let body_refs: Vec<&Stmt> = body.iter().collect();
                    let mut bi = 0;
                    while bi < body_refs.len() {
                        if let Some((code, skip)) = super::peephole::try_block_peepholes(&body_refs, bi, interner, indent + 1, mutable_vars, ctx, lww_fields, mv_fields, synced_vars, var_caps, async_functions, pipe_vars, boxed_fields, registry, type_env) {
                            output.push_str(&code);
                            bi += 1 + skip;
                            continue;
                        }
                        output.push_str(&codegen_stmt(body_refs[bi], interner, indent + 1, mutable_vars, ctx, lww_fields, mv_fields, synced_vars, var_caps, async_functions, pipe_vars, boxed_fields, registry, type_env));
                        bi += 1;
                    }
                }
                ctx.pop_scope();
                writeln!(output, "{}}}", indent_str).unwrap();
            }
        }

        Stmt::Return { value } => {
            if let Some(v) = value {
                // A `-> LogosInt` function returns its value un-narrowed (`.into()` is identity for a
                // LogosInt, and promotes a plain `i64`), so an overflowing result stays a BigInt.
                if ctx.returns_bigint() {
                    let raw = codegen_expr_boxed_with_types_oracle_tolerant(v, interner, synced_vars, boxed_fields, registry, async_functions, ctx.get_string_vars(), ctx.get_variable_types(), ctx.get_fast_div(), ctx.oracle());
                    writeln!(output, "{}return logicaffeine_data::LogosInt::from({});", indent_str, raw).unwrap();
                    return output;
                }
                let value_str = codegen_expr_boxed_with_types_oracle(v, interner, synced_vars, boxed_fields, registry, async_functions, ctx.get_string_vars(), ctx.get_variable_types(), ctx.get_fast_div(), ctx.oracle());
                // If returning a borrowed slice param (or copy of one), wrap in LogosSeq
                let slice_sym = match v {
                    Expr::Identifier(sym) => Some(*sym),
                    Expr::Copy { expr: inner } => {
                        if let Expr::Identifier(sym) = inner { Some(*sym) } else { None }
                    }
                    _ => None,
                };
                let needs_to_vec = slice_sym
                    .and_then(|sym| ctx.get_variable_types().get(&sym))
                    .map(|t| t.starts_with("&["))
                    .unwrap_or(false);
                // If returning a &mut borrow param, the mutation was in-place — just return
                let is_mut_borrow_return = if let Expr::Identifier(sym) = v {
                    ctx.get_variable_types().get(sym)
                        .map(|t| t.starts_with("&mut ["))
                        .unwrap_or(false)
                } else {
                    false
                };
                if is_mut_borrow_return {
                    writeln!(output, "{}return;", indent_str).unwrap();
                } else if needs_to_vec && ctx.returns_vec() {
                    // Phase 4: the function returns owned `Vec<T>` — return the
                    // owned copy directly, no `LogosSeq::from_vec(...)` wrapper.
                    writeln!(output, "{}return {}.to_vec();", indent_str, value_str).unwrap();
                } else if needs_to_vec {
                    writeln!(output, "{}return LogosSeq::from_vec({}.to_vec());", indent_str, value_str).unwrap();
                } else {
                    writeln!(output, "{}return {};", indent_str, value_str).unwrap();
                }
            } else {
                writeln!(output, "{}return;", indent_str).unwrap();
            }
        }

        Stmt::Break => {
            writeln!(output, "{}break;", indent_str).unwrap();
        }

        Stmt::Assert { proposition } => {
            let condition = codegen_assertion(proposition, interner);
            writeln!(output, "{}debug_assert!({});", indent_str, condition).unwrap();
        }

        // Phase 35: Trust with documented justification
        Stmt::Trust { proposition, justification } => {
            let reason = interner.resolve(*justification);
            // Strip quotes if present (string literals include their quotes)
            let reason_clean = reason.trim_matches('"');
            writeln!(output, "{}// TRUST: {}", indent_str, reason_clean).unwrap();
            let condition = codegen_assertion(proposition, interner);
            writeln!(output, "{}debug_assert!({});", indent_str, condition).unwrap();
        }

        Stmt::RuntimeAssert { condition, hard } => {
            let cond_str = codegen_expr_with_async_oracle(condition, interner, synced_vars, async_functions, ctx.get_variable_types(), ctx.oracle());
            // `Require` → `assert!` (enforced, survives release); `Assert` →
            // `debug_assert!` (a development check, stripped in release).
            let macro_name = if *hard { "assert!" } else { "debug_assert!" };
            writeln!(output, "{}{}({});", indent_str, macro_name, cond_str).unwrap();
        }

        // Phase 50: Security Check - mandatory runtime guard (NEVER optimized out)
        Stmt::Check { subject, predicate, is_capability, object, source_text, span } => {
            let subj_name = interner.resolve(*subject);
            let pred_name = interner.resolve(*predicate).to_lowercase();

            let call = if *is_capability {
                let obj_sym = object.expect("capability must have object");
                let obj_word = interner.resolve(obj_sym);

                // Phase 50: Type-based resolution
                // "Check that user can publish the document" -> find variable of type Document
                // First try to find a variable whose type matches the object word
                let obj_name = ctx.find_variable_by_type(obj_word, interner)
                    .unwrap_or_else(|| obj_word.to_string());

                format!("{}.can_{}(&{})", subj_name, pred_name, obj_name)
            } else {
                format!("{}.is_{}()", subj_name, pred_name)
            };

            writeln!(output, "{}if !({}) {{", indent_str, call).unwrap();
            writeln!(output, "{}    logicaffeine_system::panic_with(\"Security Check Failed at line {}: {}\");",
                     indent_str, span.start, source_text).unwrap();
            writeln!(output, "{}}}", indent_str).unwrap();
        }

        // Phase 51: P2P Networking - Listen on network address
        Stmt::Listen { address, secure } => {
            // The PNP one-time pad is wired only into the interpreter's channel seam; the native-AOT
            // transpile backend does not carry that seam yet, so fail loud (never silently drop crypto).
            if secure.is_some() {
                writeln!(output, "{}compile_error!(\"the PNP one-time pad (`with pad`) is only supported by the interpreter tier, not the native-AOT/transpile backend\");", indent_str).unwrap();
                return output;
            }
            let addr_str = codegen_expr_with_async(address, interner, synced_vars, async_functions, ctx.get_variable_types());
            // Pass &str instead of String
            writeln!(output, "{}logicaffeine_system::network::listen(&{}).await.expect(\"Failed to listen\");",
                     indent_str, addr_str).unwrap();
        }

        // Phase 51: P2P Networking - Connect to remote peer
        Stmt::ConnectTo { address, secure } => {
            if secure.is_some() {
                writeln!(output, "{}compile_error!(\"the PNP one-time pad (`with pad`) is only supported by the interpreter tier, not the native-AOT/transpile backend\");", indent_str).unwrap();
                return output;
            }
            let addr_str = codegen_expr_with_async(address, interner, synced_vars, async_functions, ctx.get_variable_types());
            // Pass &str instead of String
            writeln!(output, "{}logicaffeine_system::network::connect(&{}).await.expect(\"Failed to connect\");",
                     indent_str, addr_str).unwrap();
        }

        // Phase 51: P2P Networking - Create PeerAgent remote handle
        Stmt::LetPeerAgent { var, address } => {
            let var_name = interner.resolve(*var);
            let addr_str = codegen_expr_with_async(address, interner, synced_vars, async_functions, ctx.get_variable_types());
            // Pass &str instead of String
            writeln!(output, "{}let {} = logicaffeine_system::network::PeerAgent::new(&{}).expect(\"Invalid address\");",
                     indent_str, var_name, addr_str).unwrap();
        }

        // Phase 51: Sleep - supports Duration literals or milliseconds
        Stmt::Sleep { milliseconds } => {
            let expr_str = codegen_expr_with_async(milliseconds, interner, synced_vars, async_functions, ctx.get_variable_types());
            let inferred_type = infer_rust_type_from_expr(milliseconds, interner);

            if inferred_type == "std::time::Duration" {
                // Duration type: use directly (already a std::time::Duration)
                writeln!(output, "{}tokio::time::sleep({}).await;",
                         indent_str, expr_str).unwrap();
            } else {
                // Assume milliseconds (integer) - legacy behavior
                writeln!(output, "{}tokio::time::sleep(std::time::Duration::from_millis({} as u64)).await;",
                         indent_str, expr_str).unwrap();
            }
        }

        // Phase 52/56: Sync CRDT variable on topic
        Stmt::Sync { var, topic } => {
            let var_name = interner.resolve(*var);
            let topic_str = codegen_expr_with_async(topic, interner, synced_vars, async_functions, ctx.get_variable_types());

            // Phase 56: Check if this variable is also mounted
            if let Some(caps) = var_caps.get(var) {
                if caps.mounted {
                    // Both Mount and Sync: use Distributed<T>
                    // Mount statement will handle the Distributed::mount call
                    // Here we just track it as synced
                    synced_vars.insert(*var);
                    return output;  // Skip - Mount will emit Distributed<T>
                }
            }

            // Sync-only: use Synced<T>
            writeln!(
                output,
                "{}let {} = logicaffeine_system::crdt::Synced::new({}, &{}).await;",
                indent_str, var_name, var_name, topic_str
            ).unwrap();
            synced_vars.insert(*var);
        }

        // Phase 53/56: Mount persistent CRDT from journal
        Stmt::Mount { var, path } => {
            let var_name = interner.resolve(*var);
            let path_str = codegen_expr_with_async(path, interner, synced_vars, async_functions, ctx.get_variable_types());

            // Phase 56: Check if this variable is also synced
            if let Some(caps) = var_caps.get(var) {
                if caps.synced {
                    // Both Mount and Sync: use Distributed<T>
                    let topic_str = caps.sync_topic.as_ref()
                        .map(|s| s.as_str())
                        .unwrap_or("\"default\"");
                    writeln!(
                        output,
                        "{}let {} = logicaffeine_system::distributed::Distributed::mount(vfs.clone(), &{}, Some({}.to_string())).await.expect(\"Failed to mount\");",
                        indent_str, var_name, path_str, topic_str
                    ).unwrap();
                    synced_vars.insert(*var);
                    return output;
                }
            }

            // Mount-only: use Persistent<T>
            writeln!(
                output,
                "{}let {} = logicaffeine_system::storage::Persistent::mount(vfs.clone(), &{}).await.expect(\"Failed to mount\");",
                indent_str, var_name, path_str
            ).unwrap();
            synced_vars.insert(*var);
        }

        // =====================================================================
        // Phase 54: Go-like Concurrency Codegen
        // =====================================================================

        Stmt::LaunchTask { function, args } => {
            let fn_name = names.ident(*function);
            // Phase 54: When passing a pipe variable, pass the sender (_tx)
            let args_str: Vec<String> = args.iter()
                .map(|a| {
                    if let Expr::Identifier(sym) = a {
                        if pipe_vars.contains(sym) {
                            return format!("{}_tx.clone()", interner.resolve(*sym));
                        }
                    }
                    codegen_expr_with_async(a, interner, synced_vars, async_functions, ctx.get_variable_types())
                })
                .collect();
            // Phase 54: Add .await only if the function is async
            let await_suffix = if async_functions.contains(function) { ".await" } else { "" };
            writeln!(
                output,
                "{}tokio::spawn(async move {{ {}({}){await_suffix}; }});",
                indent_str, fn_name, args_str.join(", ")
            ).unwrap();
        }

        Stmt::LaunchTaskWithHandle { handle, function, args } => {
            let handle_name = interner.resolve(*handle);
            let fn_name = names.ident(*function);
            // Phase 54: When passing a pipe variable, pass the sender (_tx)
            let args_str: Vec<String> = args.iter()
                .map(|a| {
                    if let Expr::Identifier(sym) = a {
                        if pipe_vars.contains(sym) {
                            return format!("{}_tx.clone()", interner.resolve(*sym));
                        }
                    }
                    codegen_expr_with_async(a, interner, synced_vars, async_functions, ctx.get_variable_types())
                })
                .collect();
            // Phase 54: Add .await only if the function is async
            let await_suffix = if async_functions.contains(function) { ".await" } else { "" };
            writeln!(
                output,
                "{}let {} = tokio::spawn(async move {{ {}({}){await_suffix} }});",
                indent_str, handle_name, fn_name, args_str.join(", ")
            ).unwrap();
        }

        Stmt::CreatePipe { var, element_type, capacity } => {
            let var_name = interner.resolve(*var);
            let type_name = interner.resolve(*element_type);
            let cap = capacity.unwrap_or(32);
            // Map LOGOS types to Rust types
            let rust_type = match type_name {
                "Int" => "i64",
                "Nat" => "u64",
                "Text" => "String",
                "Bool" => "bool",
                _ => type_name,
            };
            writeln!(
                output,
                "{}let ({}_tx, mut {}_rx) = tokio::sync::mpsc::channel::<{}>({});",
                indent_str, var_name, var_name, rust_type, cap
            ).unwrap();
        }

        Stmt::SendPipe { value, pipe } => {
            let val_str = codegen_expr_boxed_with_types_oracle(value, interner, synced_vars, boxed_fields, registry, async_functions, ctx.get_string_vars(), ctx.get_variable_types(), ctx.get_fast_div(), ctx.oracle());
            let pipe_str = codegen_expr_with_async(pipe, interner, synced_vars, async_functions, ctx.get_variable_types());
            // Phase 54: Check if pipe is a local declaration (has _tx suffix) or parameter (no suffix)
            let is_local_pipe = if let Expr::Identifier(sym) = pipe {
                pipe_vars.contains(sym)
            } else {
                false
            };
            if is_local_pipe {
                writeln!(
                    output,
                    "{}{}_tx.send({}).await.expect(\"pipe send failed\");",
                    indent_str, pipe_str, val_str
                ).unwrap();
            } else {
                writeln!(
                    output,
                    "{}{}.send({}).await.expect(\"pipe send failed\");",
                    indent_str, pipe_str, val_str
                ).unwrap();
            }
        }

        Stmt::ReceivePipe { var, pipe } => {
            let var_name = interner.resolve(*var);
            let pipe_str = codegen_expr_with_async(pipe, interner, synced_vars, async_functions, ctx.get_variable_types());
            // Phase 54: Check if pipe is a local declaration (has _rx suffix) or parameter (no suffix)
            let is_local_pipe = if let Expr::Identifier(sym) = pipe {
                pipe_vars.contains(sym)
            } else {
                false
            };
            if is_local_pipe {
                writeln!(
                    output,
                    "{}let {} = {}_rx.recv().await.expect(\"pipe closed\");",
                    indent_str, var_name, pipe_str
                ).unwrap();
            } else {
                writeln!(
                    output,
                    "{}let {} = {}.recv().await.expect(\"pipe closed\");",
                    indent_str, var_name, pipe_str
                ).unwrap();
            }
        }

        Stmt::TrySendPipe { value, pipe, result } => {
            let val_str = codegen_expr_boxed_with_types_oracle(value, interner, synced_vars, boxed_fields, registry, async_functions, ctx.get_string_vars(), ctx.get_variable_types(), ctx.get_fast_div(), ctx.oracle());
            let pipe_str = codegen_expr_with_async(pipe, interner, synced_vars, async_functions, ctx.get_variable_types());
            // Phase 54: Check if pipe is a local declaration
            let is_local_pipe = if let Expr::Identifier(sym) = pipe {
                pipe_vars.contains(sym)
            } else {
                false
            };
            let suffix = if is_local_pipe { "_tx" } else { "" };
            if let Some(res) = result {
                let res_name = interner.resolve(*res);
                writeln!(
                    output,
                    "{}let {} = {}{}.try_send({}).is_ok();",
                    indent_str, res_name, pipe_str, suffix, val_str
                ).unwrap();
            } else {
                writeln!(
                    output,
                    "{}let _ = {}{}.try_send({});",
                    indent_str, pipe_str, suffix, val_str
                ).unwrap();
            }
        }

        Stmt::TryReceivePipe { var, pipe } => {
            let var_name = interner.resolve(*var);
            let pipe_str = codegen_expr_with_async(pipe, interner, synced_vars, async_functions, ctx.get_variable_types());
            // Phase 54: Check if pipe is a local declaration
            let is_local_pipe = if let Expr::Identifier(sym) = pipe {
                pipe_vars.contains(sym)
            } else {
                false
            };
            let suffix = if is_local_pipe { "_rx" } else { "" };
            writeln!(
                output,
                "{}let {} = {}{}.try_recv().ok();",
                indent_str, var_name, pipe_str, suffix
            ).unwrap();
        }

        Stmt::StopTask { handle } => {
            let handle_str = codegen_expr_with_async(handle, interner, synced_vars, async_functions, ctx.get_variable_types());
            writeln!(output, "{}{}.abort();", indent_str, handle_str).unwrap();
        }

        Stmt::Select { branches } => {
            // Mode A (default): raw `tokio::select!`, byte-identical to today.
            // Mode B (`--deterministic`): the seeded winner-pick sharing the
            // interpreter's choice function. The gate is compile-global, so Mode-A
            // emission never carries any seeded machinery.
            if crate::codegen::seeded_select_enabled() {
                write_seeded_select(
                    &mut output, branches, interner, indent, mutable_vars, ctx, lww_fields,
                    mv_fields, synced_vars, var_caps, async_functions, pipe_vars, boxed_fields,
                    registry, type_env,
                );
            } else {
                write_tokio_select(
                    &mut output, branches, interner, indent, mutable_vars, ctx, lww_fields,
                    mv_fields, synced_vars, var_caps, async_functions, pipe_vars, boxed_fields,
                    registry, type_env,
                );
            }
        }

        Stmt::Give { object, recipient } => {
            // Move semantics: pass ownership without borrowing
            let obj_str = codegen_expr_with_async(object, interner, synced_vars, async_functions, ctx.get_variable_types());
            let recv_str = codegen_expr_with_async(recipient, interner, synced_vars, async_functions, ctx.get_variable_types());
            writeln!(output, "{}{}({});", indent_str, recv_str, obj_str).unwrap();
        }

        Stmt::Show { object, recipient } => {
            // OPT: Show single-char u8 variable → println!("{}", ch as char)
            if let Expr::Identifier(sym) = object {
                if ctx.get_variable_types().get(sym).map_or(false, |t| t == "__single_char_u8") {
                    let var_name = names.ident(*sym);
                    writeln!(output, "{}println!(\"{{}}\", {} as char);", indent_str, var_name).unwrap();
                    return output;
                }
            }
            // Optimization: Show with InterpolatedString → println! directly
            if let Expr::InterpolatedString(parts) = object {
                let recv_name = if let Expr::Identifier(sym) = recipient {
                    interner.resolve(*sym).to_string()
                } else {
                    String::new()
                };
                if recv_name == "show" {
                    // Emit println! directly — no intermediate String allocation
                    let mut fmt_str = String::new();
                    let mut args = Vec::new();
                    for part in parts {
                        match part {
                            crate::ast::stmt::StringPart::Literal(sym) => {
                                let text = interner.resolve(*sym);
                                for ch in text.chars() {
                                    match ch {
                                        '{' => fmt_str.push_str("{{"),
                                        '}' => fmt_str.push_str("}}"),
                                        '\n' => fmt_str.push_str("\\n"),
                                        '\t' => fmt_str.push_str("\\t"),
                                        '\r' => fmt_str.push_str("\\r"),
                                        _ => fmt_str.push(ch),
                                    }
                                }
                            }
                            crate::ast::stmt::StringPart::Expr { value, format_spec, debug } => {
                                if *debug {
                                    let debug_prefix = expr_debug_prefix(value, interner);
                                    for ch in debug_prefix.chars() {
                                        match ch {
                                            '{' => fmt_str.push_str("{{"),
                                            '}' => fmt_str.push_str("}}"),
                                            _ => fmt_str.push(ch),
                                        }
                                    }
                                    fmt_str.push('=');
                                }
                                let needs_float_cast = if let Some(spec) = format_spec {
                                    let spec_str = interner.resolve(*spec);
                                    if spec_str == "$" {
                                        fmt_str.push('$');
                                        fmt_str.push_str("{:.2}");
                                        true
                                    } else if spec_str.starts_with('.') {
                                        fmt_str.push_str(&format!("{{:{}}}", spec_str));
                                        true
                                    } else {
                                        fmt_str.push_str(&format!("{{:{}}}", spec_str));
                                        false
                                    }
                                } else {
                                    fmt_str.push_str("{}");
                                    false
                                };
                                let arg_str = codegen_expr_with_async_and_strings(value, interner, synced_vars, async_functions, ctx.get_string_vars(), ctx.get_variable_types(), ctx.get_fast_div());
                                if needs_float_cast {
                                    args.push(format!("{} as f64", arg_str));
                                } else {
                                    args.push(arg_str);
                                }
                            }
                        }
                    }
                    writeln!(output, "{}println!(\"{}\"{});", indent_str, fmt_str,
                        args.iter().map(|a| format!(", {}", a)).collect::<String>()).unwrap();
                } else {
                    let obj_str = codegen_expr_with_async_and_strings(object, interner, synced_vars, async_functions, ctx.get_string_vars(), ctx.get_variable_types(), ctx.get_fast_div());
                    let recv_str = codegen_expr_with_async(recipient, interner, synced_vars, async_functions, ctx.get_variable_types());
                    writeln!(output, "{}{}(&{});", indent_str, recv_str, obj_str).unwrap();
                }
            } else {
                // Borrow semantics: pass immutable reference
                // Use string_vars for proper concatenation of string variables
                let obj_str = codegen_expr_with_async_and_strings(object, interner, synced_vars, async_functions, ctx.get_string_vars(), ctx.get_variable_types(), ctx.get_fast_div());
                let recv_str = codegen_expr_with_async(recipient, interner, synced_vars, async_functions, ctx.get_variable_types());
                writeln!(output, "{}{}(&{});", indent_str, recv_str, obj_str).unwrap();
            }
        }

        Stmt::SetField { object, field, value } => {
            let obj_str = codegen_expr_with_async(object, interner, synced_vars, async_functions, ctx.get_variable_types());
            let field_name = interner.resolve(*field);
            let value_str = codegen_expr_boxed_with_types_oracle(value, interner, synced_vars, boxed_fields, registry, async_functions, ctx.get_string_vars(), ctx.get_variable_types(), ctx.get_fast_div(), ctx.oracle());

            // Phase 49: Check if this field is an LWWRegister or MVRegister
            // LWW needs .set(value, timestamp), MV needs .set(value)
            let is_lww = lww_fields.iter().any(|(_, f)| f == field_name);
            let is_mv = mv_fields.iter().any(|(_, f)| f == field_name);
            if is_lww {
                // LWWRegister needs a timestamp - use current system time in microseconds
                writeln!(output, "{}{}.{}.set({}, std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_micros() as u64);", indent_str, obj_str, field_name, value_str).unwrap();
            } else if is_mv {
                // MVRegister just needs the value
                writeln!(output, "{}{}.{}.set({});", indent_str, obj_str, field_name, value_str).unwrap();
            } else {
                writeln!(output, "{}{}.{} = {};", indent_str, obj_str, field_name, value_str).unwrap();
            }
        }

        Stmt::StructDef { .. } => {
            // Struct definitions are handled in codegen_program, not here
        }

        Stmt::FunctionDef { .. } => {
            // Function definitions are handled in codegen_program, not here
        }

        Stmt::Inspect { target, arms, .. } => {
            let target_str = codegen_expr_with_async(target, interner, synced_vars, async_functions, ctx.get_variable_types());

            writeln!(output, "{}match {} {{", indent_str, target_str).unwrap();

            for arm in arms {
                // Phase 102: Track which bindings come from boxed fields for inner Inspects
                // Use NAMES (strings) not symbols, because parser may create different symbols
                // for the same identifier in different syntactic positions.
                // Must be per-arm so bindings from other arms don't leak into this arm's scope.
                let mut inner_boxed_binding_names: HashSet<String> = HashSet::new();
                if let Some(variant) = arm.variant {
                    let variant_name = interner.resolve(variant);
                    // Get the enum name from the arm, or fallback to just variant name
                    let enum_name_str = arm.enum_name.map(|e| interner.resolve(e));
                    let enum_prefix = enum_name_str
                        .map(|e| format!("{}::", e))
                        .unwrap_or_default();

                    if arm.bindings.is_empty() {
                        // Unit variant pattern
                        writeln!(output, "{}    {}{} => {{", indent_str, enum_prefix, variant_name).unwrap();
                    } else {
                        // Pattern with bindings
                        // Phase 102: Check which bindings are from boxed fields
                        let bindings_str: Vec<String> = arm.bindings.iter()
                            .map(|(field, binding)| {
                                let field_name = interner.resolve(*field);
                                let binding_name = interner.resolve(*binding);

                                // Check if this field is boxed
                                if let Some(enum_name) = enum_name_str {
                                    let key = (enum_name.to_string(), variant_name.to_string(), field_name.to_string());
                                    if boxed_fields.contains(&key) {
                                        inner_boxed_binding_names.insert(binding_name.to_string());
                                    }
                                }

                                if field_name == binding_name {
                                    format!("ref {}", field_name)
                                } else {
                                    format!("{}: ref {}", field_name, binding_name)
                                }
                            })
                            .collect();
                        writeln!(output, "{}    {}{} {{ {} }} => {{", indent_str, enum_prefix, variant_name, bindings_str.join(", ")).unwrap();
                    }
                } else {
                    // Otherwise (wildcard) pattern
                    writeln!(output, "{}    _ => {{", indent_str).unwrap();
                }

                ctx.push_scope();

                // Register pattern-bound variable types from Inspect arms so that
                // type inference (e.g. for mixed Int/Real coercion) works correctly.
                if let Some(variant_sym) = arm.variant {
                    if let Some((_enum_name, variant_def)) = registry.find_variant(variant_sym) {
                        for (field_sym, binding_sym) in &arm.bindings {
                            if let Some(field_def) = variant_def.fields.iter().find(|f| f.name == *field_sym) {
                                let rust_type = super::types::codegen_field_type(&field_def.ty, interner);
                                ctx.register_variable_type(*binding_sym, rust_type);
                            }
                        }
                    }
                }

                // Generate explicit dereferences for boxed bindings at the start of the arm
                // With ref bindings, boxed fields need double deref: ref -> Box -> inner
                for binding_name in &inner_boxed_binding_names {
                    writeln!(output, "{}        let {} = (**{}).clone();", indent_str, binding_name, binding_name).unwrap();
                }

                // Clone non-boxed ref bindings to get owned values
                if let Some(_) = arm.variant {
                    for (_field, binding) in &arm.bindings {
                        let binding_name = interner.resolve(*binding);
                        if !inner_boxed_binding_names.contains(binding_name) {
                            writeln!(output, "{}        let {} = {}.clone();", indent_str, binding_name, binding_name).unwrap();
                        }
                    }
                }

                for stmt in arm.body {
                    // Phase 102: Handle inner Inspect statements with boxed bindings
                    // Note: Since we now dereference boxed bindings at the start of the arm,
                    // inner matches don't need the `*` dereference operator.
                    let inner_stmt_code = if let Stmt::Inspect { target: inner_target, .. } = stmt {
                        // Check if the inner target is a boxed binding (already dereferenced above)
                        // Use name comparison since symbols may differ between binding and reference
                        if let Expr::Identifier(sym) = inner_target {
                            let target_name = interner.resolve(*sym);
                            if inner_boxed_binding_names.contains(target_name) {
                                // Generate match (binding was already dereferenced at arm start)
                                let mut inner_output = String::new();
                                writeln!(inner_output, "{}match {} {{", "    ".repeat(indent + 2), target_name).unwrap();

                                if let Stmt::Inspect { arms: inner_arms, .. } = stmt {
                                    for inner_arm in inner_arms.iter() {
                                        if let Some(v) = inner_arm.variant {
                                            let v_name = interner.resolve(v);
                                            let inner_enum_prefix = inner_arm.enum_name
                                                .map(|e| format!("{}::", interner.resolve(e)))
                                                .unwrap_or_default();

                                            if inner_arm.bindings.is_empty() {
                                                writeln!(inner_output, "{}    {}{} => {{", "    ".repeat(indent + 2), inner_enum_prefix, v_name).unwrap();
                                            } else {
                                                let bindings: Vec<String> = inner_arm.bindings.iter()
                                                    .map(|(f, b)| {
                                                        let fn_name = interner.resolve(*f);
                                                        let bn_name = interner.resolve(*b);
                                                        if fn_name == bn_name { format!("ref {}", fn_name) }
                                                        else { format!("{}: ref {}", fn_name, bn_name) }
                                                    })
                                                    .collect();
                                                writeln!(inner_output, "{}    {}{} {{ {} }} => {{", "    ".repeat(indent + 2), inner_enum_prefix, v_name, bindings.join(", ")).unwrap();
                                            }
                                        } else {
                                            writeln!(inner_output, "{}    _ => {{", "    ".repeat(indent + 2)).unwrap();
                                        }

                                        ctx.push_scope();
                                        for inner_stmt in inner_arm.body {
                                            inner_output.push_str(&codegen_stmt(inner_stmt, interner, indent + 4, mutable_vars, ctx, lww_fields, mv_fields, synced_vars, var_caps, async_functions, pipe_vars, boxed_fields, registry, type_env));
                                        }
                                        ctx.pop_scope();
                                        writeln!(inner_output, "{}    }}", "    ".repeat(indent + 2)).unwrap();
                                    }
                                }
                                writeln!(inner_output, "{}}}", "    ".repeat(indent + 2)).unwrap();
                                inner_output
                            } else {
                                codegen_stmt(stmt, interner, indent + 2, mutable_vars, ctx, lww_fields, mv_fields, synced_vars, var_caps, async_functions, pipe_vars, boxed_fields, registry, type_env)
                            }
                        } else {
                            codegen_stmt(stmt, interner, indent + 2, mutable_vars, ctx, lww_fields, mv_fields, synced_vars, var_caps, async_functions, pipe_vars, boxed_fields, registry, type_env)
                        }
                    } else {
                        codegen_stmt(stmt, interner, indent + 2, mutable_vars, ctx, lww_fields, mv_fields, synced_vars, var_caps, async_functions, pipe_vars, boxed_fields, registry, type_env)
                    };
                    output.push_str(&inner_stmt_code);
                }
                ctx.pop_scope();
                writeln!(output, "{}    }}", indent_str).unwrap();
            }

            writeln!(output, "{}}}", indent_str).unwrap();
        }

        Stmt::Push { value, collection } => {
            // O3: an init push into a scalarized `[T; N]` array becomes an
            // indexed store at the next fill position (detection proved
            // exactly N straight-line pushes precede any other use).
            if let Expr::Identifier(coll_sym) = collection {
                // Loop-built `[T; N]` return buffer (the digest): a push in the fill loop becomes a store
                // through the RUNTIME cursor — `out[cursor] = value; cursor += 1` — not the compile-time O3
                // fill (which would write slot 0 every iteration).
                if let Some(cursor) = ctx.loop_fill_cursor(*coll_sym).map(|s| s.to_string()) {
                    let val_str = codegen_expr_boxed_with_types_oracle(value, interner, synced_vars, boxed_fields, registry, async_functions, ctx.get_string_vars(), ctx.get_variable_types(), ctx.get_fast_div(), ctx.oracle());
                    let coll_name = names.ident(*coll_sym);
                    writeln!(output, "{}{}[{}] = {}; {} += 1;", indent_str, coll_name, cursor, val_str, cursor).unwrap();
                    return output;
                }
                // Affine read-only array: the array is deleted, so its build push
                // emits nothing (reads substitute the closed form instead).
                if ctx.affine_array(*coll_sym).is_some() {
                    return output;
                }
                // AoS interleaving: the k-th round-robin push of a member becomes
                // an indexed store into the backing's k-th row at this column.
                if let Some(tag) = parse_aos_tag(ctx.get_variable_types().get(coll_sym)) {
                    let val_str = codegen_expr_boxed_with_types_oracle(value, interner, synced_vars, boxed_fields, registry, async_functions, ctx.get_string_vars(), ctx.get_variable_types(), ctx.get_fast_div(), ctx.oracle());
                    let k = ctx.next_array_fill(*coll_sym);
                    writeln!(output, "{}{}[{}][{}] = {};", indent_str, tag.backing, k, tag.col, val_str).unwrap();
                    return output;
                }
                if ctx.is_scalarized_array(*coll_sym) {
                    let val_str = codegen_expr_boxed_with_types_oracle(value, interner, synced_vars, boxed_fields, registry, async_functions, ctx.get_string_vars(), ctx.get_variable_types(), ctx.get_fast_div(), ctx.oracle());
                    let k = ctx.next_array_fill(*coll_sym);
                    let coll_name = names.ident(*coll_sym);
                    writeln!(output, "{}{}[{}] = {};", indent_str, coll_name, k, val_str).unwrap();
                    return output;
                }
                // A1: inside a fill loop, the counted push of a sized
                // buffer-reuse buffer becomes an indexed write `buf[counter] =
                // val` (the buffer was `resize`d to the loop's trip count).
                if let Some((buf, counter)) = ctx.fill_loop().map(|(b, c)| (b, c.to_string())) {
                    if buf == *coll_sym {
                        let val_str = codegen_expr_boxed_with_types_oracle(value, interner, synced_vars, boxed_fields, registry, async_functions, ctx.get_string_vars(), ctx.get_variable_types(), ctx.get_fast_div(), ctx.oracle());
                        let coll_name = names.ident(*coll_sym);
                        // The buffer was `resize`d to this fill loop's trip count and
                        // `counter` is its 0-based induction variable, so `counter < len`
                        // holds by construction (a split-fill resizes to the full column
                        // count, so every sub-loop counter stays under it). Hint it so LLVM
                        // elides the bounds check on the DP-scan store — the "indexed
                        // unchecked write" this transform is meant to be, matching the
                        // append-only worklist path below. The `debug_assert` trips loudly
                        // in tests if a future detection change ever breaks the invariant,
                        // rather than the `assert_unchecked` going silently unsound.
                        writeln!(output, "{}debug_assert!(({} as usize) < {}.len(), \"LOGOS fill-loop store out of range\");", indent_str, counter, coll_name).unwrap();
                        writeln!(output, "{}unsafe {{ std::hint::assert_unchecked(({} as usize) < {}.len()); }}", indent_str, counter, coll_name).unwrap();
                        writeln!(output, "{}{}[{} as usize] = {};", indent_str, coll_name, counter, val_str).unwrap();
                        return output;
                    }
                }
                // Append-only worklist: `q.push(x)` becomes a pre-sized buffer
                // write at a register tail — `q[tail] = x; tail += 1` — with NO
                // capacity check (the monotone visited-set bound proved
                // `tail < q.len()`). This is C's exact frontier code.
                if let Some(tail) = ctx.worklist(*coll_sym).map(|w| w.tail_var.clone()) {
                    let val_str = codegen_expr_boxed_with_types_oracle(value, interner, synced_vars, boxed_fields, registry, async_functions, ctx.get_string_vars(), ctx.get_variable_types(), ctx.get_fast_div(), ctx.oracle());
                    let coll_name = names.ident(*coll_sym);
                    writeln!(output, "{}unsafe {{ std::hint::assert_unchecked({tail} < {coll_name}.len()); }}", indent_str).unwrap();
                    writeln!(output, "{}{coll_name}[{tail}] = {val_str};", indent_str).unwrap();
                    writeln!(output, "{}{tail} += 1;", indent_str).unwrap();
                    return output;
                }
            }
            let val_str = codegen_expr_boxed_with_types_oracle(value, interner, synced_vars, boxed_fields, registry, async_functions, ctx.get_string_vars(), ctx.get_variable_types(), ctx.get_fast_div(), ctx.oracle());
            let coll_str = codegen_expr_with_async(collection, interner, synced_vars, async_functions, ctx.get_variable_types());
            // MVS copy-on-write: a shared `LogosSeq` is deep-copied before this
            // in-place push so a value-semantics sibling is not mutated.
            emit_cow(collection, ctx, &names, &indent_str, &mut output);
            // A narrowed (`Vec<i32>`) sequence truncates on store — lossless,
            // since narrowing proved every pushed value fits i32.
            let narrowed_push = matches!(collection, Expr::Identifier(c) if ctx.is_narrowed(*c));
            if narrowed_push {
                writeln!(output, "{}{}.push(({}) as i32);", indent_str, coll_str, val_str).unwrap();
            } else {
                writeln!(output, "{}{}.push({});", indent_str, coll_str, val_str).unwrap();
            }
        }

        Stmt::Pop { collection, into } => {
            let coll_str = codegen_expr_with_async(collection, interner, synced_vars, async_functions, ctx.get_variable_types());
            // MVS copy-on-write before the in-place pop (mutates the buffer).
            emit_cow(collection, ctx, &names, &indent_str, &mut output);
            match into {
                Some(var) => {
                    let var_name = names.ident(*var);
                    // Unwrap the Option returned by pop() - panics if empty
                    writeln!(output, "{}let {} = {}.pop().expect(\"Pop from empty collection\");", indent_str, var_name, coll_str).unwrap();
                }
                None => {
                    writeln!(output, "{}{}.pop();", indent_str, coll_str).unwrap();
                }
            }
        }

        Stmt::Add { value, collection } => {
            let val_str = codegen_expr_boxed_with_types_oracle(value, interner, synced_vars, boxed_fields, registry, async_functions, ctx.get_string_vars(), ctx.get_variable_types(), ctx.get_fast_div(), ctx.oracle());
            let coll_str = codegen_expr_with_async(collection, interner, synced_vars, async_functions, ctx.get_variable_types());
            // MVS copy-on-write before the in-place insert (a `LogosMap`; a plain
            // `FxHashSet`/`Set` is already value-semantic and yields no `cow`).
            emit_cow(collection, ctx, &names, &indent_str, &mut output);
            writeln!(output, "{}{}.insert({});", indent_str, coll_str, val_str).unwrap();
        }

        Stmt::Remove { value, collection } => {
            let val_str = codegen_expr_boxed_with_types_oracle(value, interner, synced_vars, boxed_fields, registry, async_functions, ctx.get_string_vars(), ctx.get_variable_types(), ctx.get_fast_div(), ctx.oracle());
            let coll_str = codegen_expr_with_async(collection, interner, synced_vars, async_functions, ctx.get_variable_types());
            // MVS copy-on-write before the in-place remove.
            emit_cow(collection, ctx, &names, &indent_str, &mut output);
            // Order-preserving removal: a `Set` is an IndexSet, whose plain
            // `remove` is a swap_remove — `shift_remove` keeps insertion
            // order (`LogosMap::remove` already shifts internally).
            let is_set = matches!(collection, Expr::Identifier(sym)
                if ctx.get_variable_types().get(sym).is_some_and(|t| t.starts_with("Set<") || t.starts_with("FxHashSet<")));
            let method = if is_set { "shift_remove" } else { "remove" };
            writeln!(output, "{}{}.{}(&{});", indent_str, coll_str, method, val_str).unwrap();
        }

        Stmt::SetIndex { collection, index, value } => {
            // Nested value-semantic THROUGH-WRITE `grid[k][i] = v` (a fused place-write, see
            // splice_fuse): cow the outer grid, then `set_nested` cow's the ROW only if it is shared
            // — O(1) when uniquely owned, versus the desugar's unconditional full-row clone. Scoped
            // to a `LogosSeq<LogosSeq<…>>` base (the nested-array case); any other nested shape falls
            // through to the general handling below, and the compiled-vs-interpreted differential
            // guards value-semantics soundness for every shape.
            if let Expr::Index { collection: base, index: outer_idx } = collection {
                if let Expr::Identifier(base_sym) = base {
                    let is_nested_seq = ctx.get_variable_types().get(base_sym).map_or(false, |t| {
                        t.split("|__hl:").next().unwrap_or(t).starts_with("LogosSeq<LogosSeq")
                    });
                    if is_nested_seq {
                        let value_str = codegen_expr_boxed_with_types_oracle(value, interner, synced_vars, boxed_fields, registry, async_functions, ctx.get_string_vars(), ctx.get_variable_types(), ctx.get_fast_div(), ctx.oracle());
                        let usize_index = |ix: &Expr| -> String {
                            if let Expr::Identifier(s) = ix {
                                if ctx.get_variable_types().get(s).map_or(false, |t| t == "__zero_based_i64") {
                                    return format!("{} as usize", codegen_expr_with_async(ix, interner, synced_vars, async_functions, ctx.get_variable_types()));
                                }
                            }
                            simplify_1based_index(ix, interner, true, ctx.get_variable_types())
                        };
                        let k_idx = usize_index(outer_idx);
                        let i_idx = usize_index(index);
                        emit_cow(base, ctx, &names, &indent_str, &mut output);
                        writeln!(output, "{}{}.set_nested({}, {}, {});", indent_str, names.ident(*base_sym), k_idx, i_idx, value_str).unwrap();
                        return output;
                    }
                }
            }
            // AoS interleaving: `Set item i of member to v` → `backing[(i-1)][col] = v`.
            if let Expr::Identifier(sym) = collection {
                if let Some(tag) = parse_aos_tag(ctx.get_variable_types().get(sym)) {
                    let value_str = codegen_expr_boxed_with_types_oracle(value, interner, synced_vars, boxed_fields, registry, async_functions, ctx.get_string_vars(), ctx.get_variable_types(), ctx.get_fast_div(), ctx.oracle());
                    let is_zb = matches!(index, Expr::Identifier(s) if ctx.get_variable_types().get(s).map_or(false, |t| t == "__zero_based_i64"));
                    let idx_part = if is_zb {
                        format!("{} as usize", codegen_expr_with_async(index, interner, synced_vars, async_functions, ctx.get_variable_types()))
                    } else {
                        simplify_1based_index(index, interner, true, ctx.get_variable_types())
                    };
                    writeln!(output, "{}{}[{}][{}] = {};", indent_str, tag.backing, idx_part, tag.col, value_str).unwrap();
                    return output;
                }
            }
            let coll_str = codegen_expr_with_async(collection, interner, synced_vars, async_functions, ctx.get_variable_types());
            let value_str = codegen_expr_boxed_with_types_oracle(value, interner, synced_vars, boxed_fields, registry, async_functions, ctx.get_string_vars(), ctx.get_variable_types(), ctx.get_fast_div(), ctx.oracle());

            // MVS copy-on-write before the in-place indexed store / map insert.
            // A no-op for the `Vec`/slice/array and `FxHashMap` arms below (they
            // are not shared `Rc`s); fires only for a real `LogosSeq`/`LogosMap`.
            emit_cow(collection, ctx, &names, &indent_str, &mut output);

            // Direct indexing for known collection types (avoids trait dispatch)
            // Strip |__hl: hoisting suffix so type matching works correctly.
            let known_type = if let Expr::Identifier(sym) = collection {
                ctx.get_variable_types().get(sym).map(|s| s.split("|__hl:").next().unwrap_or(s.as_str()))
            } else {
                None
            };

            match known_type {
                Some(t) if t.starts_with("LogosSeq") => {
                    // Use borrow_mut() for interior mutability — no &mut needed on the variable.
                    let is_zero_based_counter = if let Expr::Identifier(idx_sym) = index {
                        ctx.get_variable_types().get(idx_sym).map_or(false, |t| t == "__zero_based_i64")
                    } else {
                        false
                    };
                    let index_part = if is_zero_based_counter {
                        let idx_name = codegen_expr_with_async(index, interner, synced_vars, async_functions, ctx.get_variable_types());
                        format!("{} as usize", idx_name)
                    } else {
                        simplify_1based_index(index, interner, true, ctx.get_variable_types())
                    };
                    // BCE: when the oracle proves the store index in range, emit
                    // an unchecked store through the borrow (no bounds branch)
                    // with a `debug_assert!` net — the value-semantic analog of
                    // the `Vec` path below. Soundness: the kernel-LIA proof + the
                    // function entry precondition. `LOGOS_ORACLE_UNCHECKED=0` forces
                    // checked. The `borrow_mut()` sees the owned buffer (a `cow()`
                    // was emitted before this store for value bindings).
                    let store_unchecked = crate::optimize::active_config()
                        .is_on(crate::optimization::Opt::Unchecked)
                        && ctx.oracle().map_or(false, |o| o.index_provably_in_bounds(collection, index));
                    // If the RHS borrows ANY collection, evaluate it into a temp
                    // first: under reference semantics that collection may alias
                    // the target (e.g. `prev` after `Set prev to curr`), and a
                    // live borrow() across the target's borrow_mut() panics.
                    let needs_tmp = store_unchecked || expr_reads_any_collection(value);
                    if store_unchecked {
                        crate::optimize::mark_fired(crate::optimization::Opt::Unchecked);
                        let i0 = if is_zero_based_counter {
                            codegen_expr_with_async(index, interner, synced_vars, async_functions, ctx.get_variable_types())
                        } else {
                            simplify_1based_index(index, interner, false, ctx.get_variable_types())
                        };
                        writeln!(output, "{}debug_assert!(({}) >= 0 && ({}) < ({}.len() as i64), \"LOGOS oracle BCE: store out of range\");", indent_str, i0, i0, coll_str).unwrap();
                        writeln!(output, "{}let __set_val = {};", indent_str, value_str).unwrap();
                        writeln!(output, "{}unsafe {{ *{}.borrow_mut().get_unchecked_mut({}) = __set_val; }}", indent_str, coll_str, index_part).unwrap();
                    } else if needs_tmp {
                        writeln!(output, "{}let __set_val = {};", indent_str, value_str).unwrap();
                        writeln!(output, "{}{}.borrow_mut()[{}] = __set_val;", indent_str, coll_str, index_part).unwrap();
                    } else {
                        writeln!(output, "{}{}.borrow_mut()[{}] = {};", indent_str, coll_str, index_part, value_str).unwrap();
                    }
                }
                Some(t) if is_logos_map_type(t) => {
                    let index_str = codegen_expr_with_async(index, interner, synced_vars, async_functions, ctx.get_variable_types());
                    writeln!(output, "{}{}.insert({}, {});", indent_str, coll_str, index_str, value_str).unwrap();
                }
                Some(t) if t.starts_with("Vec") || t.starts_with("&mut [") || t.starts_with("&[") || t.starts_with('[') => {
                    // Vec / slice / fixed array (O3) — direct indexed store.
                    // OPT-8: Check if index is a zero-based counter
                    let is_zero_based_counter = if let Expr::Identifier(idx_sym) = index {
                        ctx.get_variable_types().get(idx_sym).map_or(false, |t| t == "__zero_based_i64")
                    } else {
                        false
                    };
                    let index_part = if is_zero_based_counter {
                        let idx_name = codegen_expr_with_async(index, interner, synced_vars, async_functions, ctx.get_variable_types());
                        format!("{} as usize", idx_name)
                    } else {
                        simplify_1based_index(index, interner, true, ctx.get_variable_types())
                    };
                    // A narrowed (`Vec<i32>`) sequence truncates on store — lossless,
                    // since narrowing proved every stored value fits i32.
                    let narrowed = matches!(collection, Expr::Identifier(c) if ctx.is_narrowed(*c));
                    let value_str = if narrowed { format!("(({}) as i32)", value_str) } else { value_str };
                    // BCE: when the oracle proves the store index in range, emit an
                    // unchecked store (no bounds branch) with a `debug_assert!` net.
                    // Soundness: the kernel-LIA proof + the function's entry
                    // precondition guard. `LOGOS_ORACLE_UNCHECKED=0` forces checked.
                    let store_unchecked = crate::optimize::active_config().is_on(crate::optimization::Opt::Unchecked)
                        && ctx.oracle().map_or(false, |o| o.index_provably_in_bounds(collection, index));
                    if store_unchecked {
                        crate::optimize::mark_fired(crate::optimization::Opt::Unchecked);
                        let i0 = if is_zero_based_counter {
                            codegen_expr_with_async(index, interner, synced_vars, async_functions, ctx.get_variable_types())
                        } else {
                            simplify_1based_index(index, interner, false, ctx.get_variable_types())
                        };
                        writeln!(output, "{}debug_assert!(({}) >= 0 && ({}) < ({}.len() as i64), \"LOGOS oracle BCE: store out of range\");", indent_str, i0, i0, coll_str).unwrap();
                        // Bind the value to a temp first: it may itself be a proven
                        // `get_unchecked` read of the same slice (the partition swap),
                        // so evaluating it before the `&mut` access avoids both a
                        // nested `unsafe` block and an aliasing borrow.
                        writeln!(output, "{}let __set_val = {};", indent_str, value_str).unwrap();
                        writeln!(output, "{}unsafe {{ *{}.get_unchecked_mut({}) = __set_val; }}", indent_str, coll_str, index_part).unwrap();
                    } else {
                        writeln!(output, "{}{}[{}] = {};", indent_str, coll_str, index_part, value_str).unwrap();
                    }
                }
                Some(t) if t.starts_with("std::collections::HashMap") || t.starts_with("HashMap") || t.starts_with("rustc_hash::FxHashMap") || t.starts_with("FxHashMap") => {
                    let index_str = codegen_expr_with_async(index, interner, synced_vars, async_functions, ctx.get_variable_types());
                    writeln!(output, "{}{}.insert({}, {});", indent_str, coll_str, index_str, value_str).unwrap();
                }
                _ => {
                    let index_str = codegen_expr_with_async(index, interner, synced_vars, async_functions, ctx.get_variable_types());
                    // Fallback: polymorphic indexing via trait.
                    // If the value expression reads ANY collection, bind it to a
                    // temp first: that collection may alias the one being written
                    // (reference semantics), and a live borrow across the mutable
                    // access would conflict.
                    let needs_tmp = expr_reads_any_collection(value);
                    if needs_tmp {
                        writeln!(output, "{}let __set_tmp = {};", indent_str, value_str).unwrap();
                        writeln!(output, "{}LogosIndexMut::logos_set(&mut {}, {}, __set_tmp);", indent_str, coll_str, index_str).unwrap();
                    } else {
                        writeln!(output, "{}LogosIndexMut::logos_set(&mut {}, {}, {});", indent_str, coll_str, index_str, value_str).unwrap();
                    }
                }
            }
        }

        // Phase 8.5: Zone (memory arena) block
        Stmt::Zone { name, capacity, source_file, body } => {
            let zone_name = interner.resolve(*name);

            // Generate zone creation based on type
            if let Some(src) = source_file {
                // Memory-mapped file zone — literal path is quoted; a variable path
                // is passed by reference (`new_mapped` takes `AsRef<Path>`).
                use crate::ast::stmt::ZoneSource;
                let path_expr = match src {
                    ZoneSource::Literal(p) => format!("\"{}\"", interner.resolve(*p)),
                    ZoneSource::Variable(v) => format!("&{}", interner.resolve(*v)),
                };
                writeln!(
                    output,
                    "{}let {} = logicaffeine_system::memory::Zone::new_mapped({}).expect(\"Failed to map file\");",
                    indent_str, zone_name, path_expr
                ).unwrap();
            } else {
                // Heap arena zone
                let cap = capacity.unwrap_or(4096); // Default 4KB
                writeln!(
                    output,
                    "{}let {} = logicaffeine_system::memory::Zone::new_heap({});",
                    indent_str, zone_name, cap
                ).unwrap();
            }

            // Open block scope
            writeln!(output, "{}{{", indent_str).unwrap();
            ctx.push_scope();

            // Generate body statements
            for stmt in *body {
                output.push_str(&codegen_stmt(stmt, interner, indent + 1, mutable_vars, ctx, lww_fields, mv_fields, synced_vars, var_caps, async_functions, pipe_vars, boxed_fields, registry, type_env));
            }

            ctx.pop_scope();
            writeln!(output, "{}}}", indent_str).unwrap();
        }

        // Phase 9: Concurrent execution block (async, I/O-bound)
        // Generates tokio::join! for concurrent task execution
        // Phase 51: Variables used across multiple tasks are cloned to avoid move issues
        Stmt::Concurrent { tasks } => {
            // Collect Let statements to generate tuple destructuring
            let let_bindings: Vec<_> = tasks.iter().filter_map(|s| {
                if let Stmt::Let { var, .. } = s {
                    Some(interner.resolve(*var).to_string())
                } else {
                    None
                }
            }).collect();

            // Collect variables DEFINED in this block (to exclude from cloning)
            let defined_vars: HashSet<Symbol> = tasks.iter().filter_map(|s| {
                if let Stmt::Let { var, .. } = s {
                    Some(*var)
                } else {
                    None
                }
            }).collect();

            // Check if there are intra-block dependencies (a later task uses a var from earlier task)
            // If so, fall back to sequential execution
            let mut has_intra_dependency = false;
            let mut seen_defs: HashSet<Symbol> = HashSet::new();
            for s in *tasks {
                // Check if this task uses any variable defined by previous tasks in this block
                let mut used_in_task: HashSet<Symbol> = HashSet::new();
                collect_stmt_identifiers(s, &mut used_in_task);
                for used_var in &used_in_task {
                    if seen_defs.contains(used_var) {
                        has_intra_dependency = true;
                        break;
                    }
                }
                // Track variables defined by this task
                if let Stmt::Let { var, .. } = s {
                    seen_defs.insert(*var);
                }
                if has_intra_dependency {
                    break;
                }
            }

            // Collect ALL variables used in task expressions (not just Call args)
            // Exclude variables defined within this block
            let mut used_syms: HashSet<Symbol> = HashSet::new();
            for s in *tasks {
                collect_stmt_identifiers(s, &mut used_syms);
            }
            // Remove variables that are defined in this block
            for def_var in &defined_vars {
                used_syms.remove(def_var);
            }
            let used_vars: HashSet<String> = used_syms.iter()
                .map(|sym| interner.resolve(*sym).to_string())
                .collect();

            // If there are intra-block dependencies, execute sequentially
            if has_intra_dependency {
                // Generate sequential Let bindings
                for stmt in *tasks {
                    output.push_str(&codegen_stmt(stmt, interner, indent, mutable_vars, ctx, lww_fields, mv_fields, synced_vars, var_caps, async_functions, pipe_vars, boxed_fields, registry, type_env));
                }
            } else {
                // Generate concurrent execution with tokio::join!
                if !let_bindings.is_empty() {
                    // Generate tuple destructuring for concurrent Let bindings
                    writeln!(output, "{}let ({}) = tokio::join!(", indent_str, let_bindings.join(", ")).unwrap();
                } else {
                    writeln!(output, "{}tokio::join!(", indent_str).unwrap();
                }

                for (i, stmt) in tasks.iter().enumerate() {
                    // For Let statements, generate only the VALUE so the async block returns it
                    // For Call statements, generate the call with .await
                    let inner_code = match stmt {
                        Stmt::Let { value, .. } => {
                            // Return the value expression directly (not "let x = value;")
                            // Phase 54+: Use codegen_expr_with_async to handle all nested async calls
                            codegen_expr_with_async(value, interner, synced_vars, async_functions, ctx.get_variable_types())
                        }
                        Stmt::Call { function, args } => {
                            let func_name = interner.resolve(*function);
                            let args_str: Vec<String> = args.iter()
                                .map(|a| codegen_expr_with_async(a, interner, synced_vars, async_functions, ctx.get_variable_types()))
                                .collect();
                            // Only add .await for async functions
                            let await_suffix = if async_functions.contains(function) { ".await" } else { "" };
                            format!("{}({}){}", func_name, args_str.join(", "), await_suffix)
                        }
                        _ => {
                            // Fallback for other statement types
                            let inner = codegen_stmt(stmt, interner, indent + 1, mutable_vars, ctx, lww_fields, mv_fields, synced_vars, var_caps, async_functions, pipe_vars, boxed_fields, registry, type_env);
                            inner.trim().to_string()
                        }
                    };

                    // For tasks that use shared variables, wrap in a block that clones them
                    if !used_vars.is_empty() && i < tasks.len() - 1 {
                        // Clone variables for all tasks except the last one
                        let clones: Vec<String> = used_vars.iter()
                            .map(|v| format!("let {} = {}.clone();", v, v))
                            .collect();
                        write!(output, "{}    {{ {} async move {{ {} }} }}",
                               indent_str, clones.join(" "), inner_code).unwrap();
                    } else {
                        // Last task can use original variables
                        write!(output, "{}    async {{ {} }}", indent_str, inner_code).unwrap();
                    }

                    if i < tasks.len() - 1 {
                        writeln!(output, ",").unwrap();
                    } else {
                        writeln!(output).unwrap();
                    }
                }

                writeln!(output, "{});", indent_str).unwrap();
            }
        }

        // Phase 9: Parallel execution block (CPU-bound)
        // Generates rayon::join for two tasks, or thread::spawn for 3+ tasks
        Stmt::Parallel { tasks } => {
            // Collect Let statements to generate tuple destructuring
            let let_bindings: Vec<_> = tasks.iter().filter_map(|s| {
                if let Stmt::Let { var, .. } = s {
                    Some(interner.resolve(*var).to_string())
                } else {
                    None
                }
            }).collect();

            if tasks.len() == 2 {
                // Use rayon::join for exactly 2 tasks
                if !let_bindings.is_empty() {
                    writeln!(output, "{}let ({}) = rayon::join(", indent_str, let_bindings.join(", ")).unwrap();
                } else {
                    writeln!(output, "{}rayon::join(", indent_str).unwrap();
                }

                for (i, stmt) in tasks.iter().enumerate() {
                    // For Let statements, generate only the VALUE so the closure returns it
                    let inner_code = match stmt {
                        Stmt::Let { value, .. } => {
                            // Return the value expression directly (not "let x = value;")
                            codegen_expr_with_async(value, interner, synced_vars, async_functions, ctx.get_variable_types())
                        }
                        Stmt::Call { function, args } => {
                            let func_name = interner.resolve(*function);
                            let variable_types = ctx.get_variable_types();
                            let callee_borrow_indices: HashSet<usize> =
                                super::fn_role_indices(variable_types.get(function), super::FnRole::Borrow);
                            let args_str: Vec<String> = args.iter().enumerate()
                                .map(|(idx, a)| {
                                    let s = codegen_expr_with_async(a, interner, synced_vars, async_functions, variable_types);
                                    if callee_borrow_indices.contains(&idx) {
                                        if let Expr::Identifier(sym) = a {
                                            if let Some(ty) = variable_types.get(sym) {
                                                if ty.starts_with("&[") {
                                                    return s;
                                                }
                                            }
                                        }
                                        format!("&{}", s)
                                    } else { s }
                                })
                                .collect();
                            format!("{}({})", func_name, args_str.join(", "))
                        }
                        _ => {
                            // Fallback for other statement types
                            let inner = codegen_stmt(stmt, interner, indent + 1, mutable_vars, ctx, lww_fields, mv_fields, synced_vars, var_caps, async_functions, pipe_vars, boxed_fields, registry, type_env);
                            inner.trim().to_string()
                        }
                    };
                    write!(output, "{}    || {{ {} }}", indent_str, inner_code).unwrap();
                    if i == 0 {
                        writeln!(output, ",").unwrap();
                    } else {
                        writeln!(output).unwrap();
                    }
                }
                writeln!(output, "{});", indent_str).unwrap();
            } else {
                // For 3+ tasks, use thread::spawn pattern
                writeln!(output, "{}{{", indent_str).unwrap();
                writeln!(output, "{}    let handles: Vec<_> = vec![", indent_str).unwrap();
                for stmt in *tasks {
                    // For Let statements, generate only the VALUE so the closure returns it
                    let inner_code = match stmt {
                        Stmt::Let { value, .. } => {
                            codegen_expr_with_async(value, interner, synced_vars, async_functions, ctx.get_variable_types())
                        }
                        Stmt::Call { function, args } => {
                            let func_name = interner.resolve(*function);
                            let variable_types = ctx.get_variable_types();
                            let callee_borrow_indices: HashSet<usize> =
                                super::fn_role_indices(variable_types.get(function), super::FnRole::Borrow);
                            let args_str: Vec<String> = args.iter().enumerate()
                                .map(|(idx, a)| {
                                    let s = codegen_expr_with_async(a, interner, synced_vars, async_functions, variable_types);
                                    if callee_borrow_indices.contains(&idx) {
                                        if let Expr::Identifier(sym) = a {
                                            if let Some(ty) = variable_types.get(sym) {
                                                if ty.starts_with("&[") {
                                                    return s;
                                                }
                                            }
                                        }
                                        format!("&{}", s)
                                    } else { s }
                                })
                                .collect();
                            format!("{}({})", func_name, args_str.join(", "))
                        }
                        _ => {
                            let inner = codegen_stmt(stmt, interner, indent + 2, mutable_vars, ctx, lww_fields, mv_fields, synced_vars, var_caps, async_functions, pipe_vars, boxed_fields, registry, type_env);
                            inner.trim().to_string()
                        }
                    };
                    writeln!(output, "{}        std::thread::spawn(move || {{ {} }}),",
                             indent_str, inner_code).unwrap();
                }
                writeln!(output, "{}    ];", indent_str).unwrap();
                writeln!(output, "{}    for h in handles {{ h.join().unwrap(); }}", indent_str).unwrap();
                writeln!(output, "{}}}", indent_str).unwrap();
            }
        }

        // Phase 10: Read from console or file
        // Phase 53: File reads now use async VFS
        Stmt::ReadFrom { var, source } => {
            let var_name = interner.resolve(*var);
            match source {
                ReadSource::Console => {
                    writeln!(output, "{}let {} = logicaffeine_system::io::read_line();", indent_str, var_name).unwrap();
                }
                ReadSource::File(path_expr) => {
                    let path_str = codegen_expr_with_async(path_expr, interner, synced_vars, async_functions, ctx.get_variable_types());
                    // Phase 53: Use VFS with async
                    writeln!(
                        output,
                        "{}let {} = vfs.read_to_string(&{}).await.expect(\"Failed to read file\");",
                        indent_str, var_name, path_str
                    ).unwrap();
                }
            }
        }

        // Phase 10: Write to file
        // Phase 53: File writes now use async VFS
        Stmt::WriteFile { content, path } => {
            let content_str = codegen_expr_with_async(content, interner, synced_vars, async_functions, ctx.get_variable_types());
            let path_str = codegen_expr_with_async(path, interner, synced_vars, async_functions, ctx.get_variable_types());
            // Phase 53: Use VFS with async
            writeln!(
                output,
                "{}vfs.write(&{}, {}.as_bytes()).await.expect(\"Failed to write file\");",
                indent_str, path_str, content_str
            ).unwrap();
        }

        // Phase 46: Spawn an agent
        Stmt::Spawn { agent_type, name } => {
            let type_name = interner.resolve(*agent_type);
            let agent_name = interner.resolve(*name);
            // Generate agent spawn with tokio channel
            writeln!(
                output,
                "{}let {} = tokio::spawn(async move {{ /* {} agent loop */ }});",
                indent_str, agent_name, type_name
            ).unwrap();
        }

        // Phase 46: Send message to agent
        Stmt::SendMessage { message, destination, .. } => {
            let msg_str = codegen_expr_with_async(message, interner, synced_vars, async_functions, ctx.get_variable_types());
            let dest_str = codegen_expr_with_async(destination, interner, synced_vars, async_functions, ctx.get_variable_types());
            writeln!(
                output,
                "{}{}.send({}).await.expect(\"Failed to send message\");",
                indent_str, dest_str, msg_str
            ).unwrap();
        }

        // Streaming is a tree-walker feature (the relay receive runs in the interpreter); the AOT
        // path does not lower it yet — emit a marker rather than silently dropping it.
        Stmt::StreamMessage { .. } => {
            writeln!(output, "{}// Stream: interpreter-only (not yet lowered to AOT)", indent_str).unwrap();
        }

        // Phase 46: Await response from agent. (`view` is a tree-walker zero-copy receive hint;
        // the compiled path decodes eagerly to the same values.)
        Stmt::AwaitMessage { source, into, view: _, stream: _ } => {
            let src_str = codegen_expr_with_async(source, interner, synced_vars, async_functions, ctx.get_variable_types());
            let var_name = interner.resolve(*into);
            writeln!(
                output,
                "{}let {} = {}.recv().await.expect(\"Failed to receive message\");",
                indent_str, var_name, src_str
            ).unwrap();
        }

        // Phase 49: Merge CRDT state
        Stmt::MergeCrdt { source, target } => {
            let src_str = codegen_expr_with_async(source, interner, synced_vars, async_functions, ctx.get_variable_types());
            let tgt_str = codegen_expr_with_async(target, interner, synced_vars, async_functions, ctx.get_variable_types());
            writeln!(
                output,
                "{}{}.merge(&{});",
                indent_str, tgt_str, src_str
            ).unwrap();
        }

        // Phase 49: Increment GCounter
        // Phase 52: If object is synced, wrap in .mutate() for auto-publish
        Stmt::IncreaseCrdt { object, field, amount } => {
            let field_name = interner.resolve(*field);
            let amount_str = codegen_expr_with_async(amount, interner, synced_vars, async_functions, ctx.get_variable_types());

            // Check if the root object is synced
            let root_sym = get_root_identifier(object);
            if let Some(sym) = root_sym {
                if synced_vars.contains(&sym) {
                    // Synced: use .mutate() for auto-publish
                    let obj_name = interner.resolve(sym);
                    writeln!(
                        output,
                        "{}{}.mutate(|inner| inner.{}.increment({} as u64)).await;",
                        indent_str, obj_name, field_name, amount_str
                    ).unwrap();
                    return output;
                }
            }

            // Not synced: direct access
            let obj_str = codegen_expr_with_async(object, interner, synced_vars, async_functions, ctx.get_variable_types());
            writeln!(
                output,
                "{}{}.{}.increment({} as u64);",
                indent_str, obj_str, field_name, amount_str
            ).unwrap();
        }

        // Phase 49b: Decrement PNCounter
        Stmt::DecreaseCrdt { object, field, amount } => {
            let field_name = interner.resolve(*field);
            let amount_str = codegen_expr_with_async(amount, interner, synced_vars, async_functions, ctx.get_variable_types());

            // Check if the root object is synced
            let root_sym = get_root_identifier(object);
            if let Some(sym) = root_sym {
                if synced_vars.contains(&sym) {
                    // Synced: use .mutate() for auto-publish
                    let obj_name = interner.resolve(sym);
                    writeln!(
                        output,
                        "{}{}.mutate(|inner| inner.{}.decrement({} as u64)).await;",
                        indent_str, obj_name, field_name, amount_str
                    ).unwrap();
                    return output;
                }
            }

            // Not synced: direct access
            let obj_str = codegen_expr_with_async(object, interner, synced_vars, async_functions, ctx.get_variable_types());
            writeln!(
                output,
                "{}{}.{}.decrement({} as u64);",
                indent_str, obj_str, field_name, amount_str
            ).unwrap();
        }

        // Phase 49b: Append to SharedSequence (RGA)
        Stmt::AppendToSequence { sequence, value } => {
            let seq_str = codegen_expr_with_async(sequence, interner, synced_vars, async_functions, ctx.get_variable_types());
            let val_str = codegen_expr_boxed_with_types_oracle(value, interner, synced_vars, boxed_fields, registry, async_functions, ctx.get_string_vars(), ctx.get_variable_types(), ctx.get_fast_div(), ctx.oracle());
            writeln!(
                output,
                "{}{}.append({});",
                indent_str, seq_str, val_str
            ).unwrap();
        }

        // Phase 49b: Resolve MVRegister conflicts
        Stmt::ResolveConflict { object, field, value } => {
            let field_name = interner.resolve(*field);
            let val_str = codegen_expr_boxed_with_types_oracle(value, interner, synced_vars, boxed_fields, registry, async_functions, ctx.get_string_vars(), ctx.get_variable_types(), ctx.get_fast_div(), ctx.oracle());
            let obj_str = codegen_expr_with_async(object, interner, synced_vars, async_functions, ctx.get_variable_types());
            writeln!(
                output,
                "{}{}.{}.resolve({});",
                indent_str, obj_str, field_name, val_str
            ).unwrap();
        }

        // Escape hatch: emit raw foreign code wrapped in braces for scope isolation
        Stmt::Escape { code, .. } => {
            let raw_code = interner.resolve(*code);
            write!(output, "{}{{\n", indent_str).unwrap();
            for line in raw_code.lines() {
                write!(output, "{}    {}\n", indent_str, line).unwrap();
            }
            write!(output, "{}}}\n", indent_str).unwrap();
        }

        // Dependencies are metadata; no Rust code emitted.
        Stmt::Require { .. } => {}

        // Theorems and definitions are proof-layer declarations verified at
        // compile-time; they generate no runtime code (handled separately by the
        // theorem pipeline at the meta-level).
        Stmt::Theorem(_) | Stmt::Definition(_) | Stmt::Axiom(_) | Stmt::Theory(_) => {}
    }

    output
}

/// OPT-5: Sentinel → break transformation.
///
/// Detects `If cond then: ...; Set counter to limit.` inside a `While counter < limit:` loop
/// and replaces the sentinel set with `break;`. This gives LLVM a clean early-exit edge
/// instead of an opaque counter assignment that forces one more condition check.
///
/// Returns the generated code if the pattern matches, or None.
fn try_emit_sentinel_break<'a>(
    stmt: &Stmt<'a>,
    counter_sym: Symbol,
    limit_expr: &Expr<'a>,
    interner: &Interner,
    indent: usize,
    mutable_vars: &HashSet<Symbol>,
    ctx: &mut RefinementContext<'a>,
    lww_fields: &HashSet<(String, String)>,
    mv_fields: &HashSet<(String, String)>,
    synced_vars: &mut HashSet<Symbol>,
    var_caps: &HashMap<Symbol, VariableCapabilities>,
    async_functions: &HashSet<Symbol>,
    pipe_vars: &HashSet<Symbol>,
    boxed_fields: &HashSet<(String, String, String)>,
    registry: &TypeRegistry,
    type_env: &crate::analysis::types::TypeEnv,
) -> Option<String> {
    // Match: If cond then: ...; Set counter to limit. (no else block)
    let (if_cond, then_block, else_block) = match stmt {
        Stmt::If { cond, then_block, else_block } => (cond, then_block, else_block),
        _ => return None,
    };

    if else_block.is_some() {
        return None;
    }

    if then_block.is_empty() {
        return None;
    }

    // Last statement in then_block must be `Set counter to limit`
    let last = &then_block[then_block.len() - 1];
    match last {
        Stmt::Set { target, value, .. } => {
            if *target != counter_sym || !exprs_equal(value, limit_expr) {
                return None;
            }
        }
        _ => return None,
    }

    // Pattern matched! Emit if block with break instead of sentinel set.
    let indent_str = "    ".repeat(indent);
    let var_types = ctx.get_variable_types();
    let cond_str = codegen_expr_with_async(if_cond, interner, synced_vars, async_functions, var_types);
    let mut output = String::new();
    writeln!(output, "{}if {} {{", indent_str, cond_str).unwrap();

    // Emit all then_block statements except the last (the sentinel set)
    for s in &then_block[..then_block.len() - 1] {
        output.push_str(&codegen_stmt(
            s, interner, indent + 1, mutable_vars, ctx,
            lww_fields, mv_fields, synced_vars, var_caps,
            async_functions, pipe_vars, boxed_fields, registry, type_env,
        ));
    }

    // Emit break instead of the sentinel set
    writeln!(output, "{}    break;", indent_str).unwrap();
    writeln!(output, "{}}}", indent_str).unwrap();

    Some(output)
}

/// Phase 52: Extract the root identifier from an expression.
/// For `x.field.subfield`, returns `x`.
pub(crate) fn get_root_identifier(expr: &Expr) -> Option<Symbol> {
    match expr {
        Expr::Identifier(sym) => Some(*sym),
        Expr::FieldAccess { object, .. } => get_root_identifier(object),
        _ => None,
    }
}

/// Extract all symbols from `Expr::Length { collection: Expr::Identifier(sym) }` nodes
/// in an expression tree. Used for loop bounds hoisting.
pub(crate) fn extract_length_expr_syms(expr: &Expr) -> Vec<Symbol> {
    let mut out = Vec::new();
    collect_length_syms_from_expr(expr, &mut out);
    out
}

fn collect_length_syms_from_expr(expr: &Expr, out: &mut Vec<Symbol>) {
    match expr {
        Expr::Length { collection } => {
            if let Expr::Identifier(sym) = collection {
                out.push(*sym);
            }
        }
        Expr::BinaryOp { left, right, .. } => {
            collect_length_syms_from_expr(left, out);
            collect_length_syms_from_expr(right, out);
        }
        Expr::Not { operand } => collect_length_syms_from_expr(operand, out),
        Expr::Index { collection, index } => {
            collect_length_syms_from_expr(collection, out);
            collect_length_syms_from_expr(index, out);
        }
        Expr::Call { args, .. } => {
            for arg in args.iter() {
                collect_length_syms_from_expr(arg, out);
            }
        }
        _ => {}
    }
}

/// Collect all `Expr::Length { Identifier(sym) }` symbols from a statement list (recursively).
pub(crate) fn collect_length_syms_from_stmts(stmts: &[Stmt], out: &mut Vec<Symbol>) {
    for stmt in stmts {
        collect_length_syms_from_stmt(stmt, out);
    }
}

fn collect_length_syms_from_stmt(stmt: &Stmt, out: &mut Vec<Symbol>) {
    match stmt {
        Stmt::Let { value, .. } => collect_length_syms_from_expr(value, out),
        Stmt::Set { value, .. } => collect_length_syms_from_expr(value, out),
        Stmt::Show { object, .. } => collect_length_syms_from_expr(object, out),
        Stmt::Push { value, collection } => {
            collect_length_syms_from_expr(value, out);
            collect_length_syms_from_expr(collection, out);
        }
        Stmt::SetIndex { collection, index, value } => {
            collect_length_syms_from_expr(collection, out);
            collect_length_syms_from_expr(index, out);
            collect_length_syms_from_expr(value, out);
        }
        Stmt::If { cond, then_block, else_block } => {
            collect_length_syms_from_expr(cond, out);
            collect_length_syms_from_stmts(then_block, out);
            if let Some(else_stmts) = else_block {
                collect_length_syms_from_stmts(else_stmts, out);
            }
        }
        Stmt::While { cond, body, .. } => {
            collect_length_syms_from_expr(cond, out);
            collect_length_syms_from_stmts(body, out);
        }
        Stmt::Repeat { body, .. } => {
            collect_length_syms_from_stmts(body, out);
        }
        Stmt::Return { value } => {
            if let Some(v) = value {
                collect_length_syms_from_expr(v, out);
            }
        }
        Stmt::Call { args, .. } => {
            for arg in args.iter() {
                collect_length_syms_from_expr(arg, out);
            }
        }
        _ => {}
    }
}

/// Check if a type string represents a Copy type (no .clone() needed).
/// Delegates to `LogosType::is_copy()` — single source of truth.
pub(crate) fn is_copy_type(ty: &str) -> bool {
    crate::analysis::types::LogosType::from_rust_type_str(ty).is_copy()
}

/// Wrap an `If`/`While` condition in `logos_truthy` unless it's statically
/// Bool — `If xs:` on a Seq tests emptiness, `If 0.0:` is false, exactly the
/// interpreter's truthiness. Bool conditions emit untouched (hot paths pay
/// nothing); an imprecisely-inferred Bool still works (`Truthy` covers bool).
fn truthy_cond_wrap(
    cond: &Expr,
    cond_str: String,
    interner: &Interner,
    variable_types: &HashMap<Symbol, String>,
) -> String {
    if matches!(
        super::types::infer_logos_type(cond, interner, variable_types),
        crate::analysis::types::LogosType::Bool
    ) {
        cond_str
    } else {
        format!("logos_truthy(&({}))", cond_str)
    }
}

/// Check if a Vec<T> type has a Copy element type.
/// Delegates to `LogosType::element_type().is_copy()` — single source of truth.
pub(crate) fn has_copy_element_type(vec_type: &str) -> bool {
    crate::analysis::types::LogosType::from_rust_type_str(vec_type)
        .element_type()
        .map_or(false, |e| e.is_copy())
}

/// Check if a HashMap<K, V> type has a Copy value type.
/// Delegates to `LogosType::value_type().is_copy()` — single source of truth.
pub(crate) fn has_copy_value_type(map_type: &str) -> bool {
    crate::analysis::types::LogosType::from_rust_type_str(map_type)
        .value_type()
        .map_or(false, |v| v.is_copy())
}

/// Detect commutative reduction patterns in Repeat loops and emit par_iter() code.
///
/// Pattern: `Repeat for x in coll: Set acc = acc + expr(x)`
/// Emits:
/// ```text
/// if coll.len() >= 10000 {
///     acc += coll.par_iter().copied().map(|x| expr).sum::<i64>();
/// } else {
///     for x in coll.iter().copied() { acc = acc + expr; }
/// }
/// ```
fn try_emit_parallel_reduction<'a>(
    var_sym: Symbol,
    pattern_str: &str,
    iter_str: &str,
    iterable: &'a Expr<'a>,
    body: &'a [Stmt<'a>],
    interner: &Interner,
    indent: usize,
    ctx: &RefinementContext<'a>,
    synced_vars: &HashSet<Symbol>,
    async_functions: &HashSet<Symbol>,
) -> Option<String> {
    // Body must be exactly 1 statement: Set acc = acc OP expr
    if body.len() != 1 { return None; }

    let (acc_sym, op, increment_expr) = match &body[0] {
        Stmt::Set { target, value } => {
            if let Expr::BinaryOp { op, left, right } = value {
                match op {
                    BinaryOpKind::Add => {
                        // acc = acc + expr  OR  acc = expr + acc
                        if let Expr::Identifier(lhs) = left {
                            if *lhs == *target {
                                Some((*target, BinaryOpKind::Add, *right))
                            } else {
                                None
                            }
                        } else if let Expr::Identifier(rhs) = right {
                            if *rhs == *target {
                                Some((*target, BinaryOpKind::Add, *left))
                            } else {
                                None
                            }
                        } else {
                            None
                        }
                    }
                    _ => None,
                }
            } else {
                None
            }
        }
        _ => None,
    }?;

    // The increment expression must only involve the loop variable and literals
    if !expr_is_pure_of(increment_expr, var_sym) {
        return None;
    }

    // The collection must be a typed Vec (for .par_iter().copied())
    let is_vec_i64 = if let Expr::Identifier(coll_sym) = iterable {
        ctx.get_variable_types().get(coll_sym)
            .map(|t| {
                let t = t.split("|__hl:").next().unwrap_or(t.as_str());
                (t.starts_with("LogosSeq<") || t.starts_with("Vec<") || t.starts_with("&[")) && has_copy_element_type(t)
            })
            .unwrap_or(false)
    } else {
        false
    };

    if !is_vec_i64 { return None; }

    let indent_str = "    ".repeat(indent);
    let acc_name = interner.resolve(acc_sym);

    // The parallel reduction's `.sum::<T>()` must match the accumulator's type,
    // not a hardcoded i64 (a float reduction needs `f64`). Decline the
    // optimization for any non-numeric accumulator so we never emit a sum that
    // fails to type-check.
    let acc_ty = ctx
        .get_variable_types()
        .get(&acc_sym)
        .map(|s| s.split("|__hl:").next().unwrap_or(s.as_str()))
        .unwrap_or("i64");
    let sum_ty = match acc_ty {
        "i64" | "f64" | "u64" | "i32" | "u32" | "usize" | "isize" => acc_ty,
        _ => return None,
    };

    // Generate the increment expression as Rust code
    let incr_code = codegen_expr_with_async(
        increment_expr, interner, synced_vars, async_functions,
        ctx.get_variable_types(),
    );

    // Determine if we need a .map() or can use .sum() directly
    let needs_map = !matches!(increment_expr, Expr::Identifier(s) if *s == var_sym);

    let mut out = String::new();

    // Emit parallel reduction with runtime threshold
    // LogosSeq needs .borrow() to access the inner Vec for .par_iter()/.iter()
    // &[T] and Vec<T> can be used directly without .borrow()
    let (borrow_expr, len_expr) = if let Expr::Identifier(coll_sym) = iterable {
        let ty = ctx.get_variable_types().get(coll_sym).map(|s| s.split("|__hl:").next().unwrap_or(s.as_str()));
        if matches!(ty, Some(t) if t.starts_with("LogosSeq")) {
            (format!("{}.borrow()", iter_str), format!("{}.len()", iter_str))
        } else {
            (iter_str.to_string(), format!("{}.len()", iter_str))
        }
    } else {
        (format!("{}.borrow()", iter_str), format!("{}.len()", iter_str))
    };
    writeln!(out, "{}if {} >= 10000 {{", indent_str, len_expr).unwrap();
    writeln!(out, "{}    use rayon::prelude::*;", indent_str).unwrap();
    writeln!(out, "{}    let __par_ref = {};", indent_str, borrow_expr).unwrap();
    if needs_map {
        writeln!(out, "{}    {} += __par_ref.par_iter().copied().map(|{}| {}).sum::<{}>();",
            indent_str, acc_name, pattern_str, incr_code, sum_ty).unwrap();
    } else {
        writeln!(out, "{}    {} += __par_ref.par_iter().copied().sum::<{}>();",
            indent_str, acc_name, sum_ty).unwrap();
    }
    writeln!(out, "{}}} else {{", indent_str).unwrap();
    writeln!(out, "{}    for {} in {}.to_vec() {{", indent_str, pattern_str, iter_str).unwrap();

    match op {
        BinaryOpKind::Add => {
            writeln!(out, "{}        {} += {};", indent_str, acc_name, incr_code).unwrap();
        }
        _ => {
            writeln!(out, "{}        {} = {} {:?} {};", indent_str, acc_name, acc_name, op, incr_code).unwrap();
        }
    }
    writeln!(out, "{}    }}", indent_str).unwrap();
    writeln!(out, "{}}}", indent_str).unwrap();

    Some(out)
}

/// Check if an expression only involves the given symbol and literals (no side effects).
fn expr_is_pure_of(expr: &Expr, allowed_sym: Symbol) -> bool {
    match expr {
        Expr::Identifier(s) => *s == allowed_sym,
        Expr::Literal(_) => true,
        Expr::BinaryOp { left, right, .. } => {
            expr_is_pure_of(left, allowed_sym) && expr_is_pure_of(right, allowed_sym)
        }
        Expr::Not { operand } => expr_is_pure_of(operand, allowed_sym),
        _ => false,
    }
}