vox-lang 0.4.6

A systems level compiler for Vox (sentence based code)
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
use super::*;

impl CodeGenerator {
    pub fn generate(&mut self, program: &Program) -> String {
        // Collect function signatures BEFORE the pre-scan: prescan_expr_tag
        // classifies FunctionCall results via function_return_types, so it
        // must be populated for the pre-scan to prove (not widen) lists built
        // from declared-return functions. Signature collection only reads
        // FunctionDef.return_type from the AST, so this reorder is safe.
        self.collect_function_signatures(program);
        // The thing registry and the main line's thing variables, before the
        // label pass below sizes their `.bss` reservations from them.
        self.collect_things(program);
        // Resolve the library identity before any function is generated so the
        // `<lib>_<ver>_<func>` label is correct regardless of where the
        // `Library` declaration sits in the source. No-op outside shared mode.
        self.collect_library_identity(program);
        self.prescan_mixed_lists(&program.statements);
        self.collect_global_constants(program);
        self.collect_flag_schemas(program);

        self.global_var_labels.clear();
        self.global_var_counter = 0;
        self.collect_global_var_labels(&program.statements);

        let explicit_parse_idx = program
            .statements
            .iter()
            .position(|s| matches!(s, Statement::ParseFlags));
        let auto_parse_idx = program
            .statements
            .iter()
            .rposition(|s| matches!(s, Statement::FlagSchemaDecl { .. }))
            .map(|i| i + 1);
        let parse_insert_idx = explicit_parse_idx.or(auto_parse_idx);
        self.parsed_args_active = parse_insert_idx.is_some() && !self.flag_schemas.is_empty();

        for (idx, stmt) in program.statements.iter().enumerate() {
            if parse_insert_idx == Some(idx) {
                self.emit_flag_parse_routine();
            }
            self.generate_statement(stmt);
        }

        if parse_insert_idx == Some(program.statements.len()) {
            self.emit_flag_parse_routine();
        }

        // Frame setup for docs/BUGS_FOUND.md #25 (plan 318 §1): every
        // top-level name declared only inside a While/On error/for
        // each/Repeat body needs its type's default written before this
        // program's real body runs, in case that body's own path never
        // executes. The slots already exist (the walk above visited those
        // statements' VarDecl/BufferDecl nodes unconditionally, same as
        // codegen always does), so compute the defaults now and splice
        // them in ahead of the body already generated into `self.output`.
        let body_code = std::mem::take(&mut self.output);
        self.emit_conditional_decl_defaults(&program.statements);
        let defaults_code = std::mem::take(&mut self.output);
        self.output = defaults_code + &body_code;

        let mut result = String::new();
        
        result.push_str("; Generated by ec\n");
        result.push_str(&format!("; Target: {} Linux (NASM)\n\n", self.target_arch));
        
        // A shared library carries its own coreasm runtime so the .so is
        // self-contained and loadable from any host (C, Rust, Vox), not a
        // runtime-free pile of exports. It therefore emits the SAME
        // conditional include block as an executable, with two differences:
        // `default rel` is set (every reference must be RIP-relative so the
        // object can be relocated), and `args.asm` is excluded because it
        // reads the Linux loader's stack layout, which never exists in a
        // library. Function bodies are generated above into the functions
        // section, so the uses_* flags already reflect what the library
        // actually needs.
        if self.shared_lib_mode {
            result.push_str("default rel\n\n");
        }
        // Always needed: core
        result.push_str(&format!("%include \"coreasm/{}/core.asm\"\n", self.target_arch));
        // map.asm is included AFTER list.asm (it calls _list_print), so
        // its `__MAP_ASM_INCLUDED__` guard is not yet visible when
        // list.asm is assembled. Pre-define it here when maps are used so
        // list.asm's map-element print branch can call `_map_print`.
        if self.uses_maps {
            result.push_str("%define __MAP_ASM_INCLUDED__\n");
        }
        // Conditional includes based on usage
        // map.asm depends on io.asm (PRINT macros), string.asm (_str_eq),
        // and list.asm (_list_print), so uses_maps forces all three on.
        if self.uses_io || self.uses_maps {
            result.push_str(&format!("%include \"coreasm/{}/io.asm\"\n", self.target_arch));
        }
        if self.uses_files {
            result.push_str(&format!("%include \"coreasm/{}/file.asm\"\n", self.target_arch));
        }
        if self.uses_buffers || self.uses_files || self.uses_floats {
            result.push_str(&format!("%include \"coreasm/{}/resource.asm\"\n", self.target_arch));
        }
        if self.uses_ints {
            result.push_str(&format!("%include \"coreasm/{}/int.asm\"\n", self.target_arch));
        }
        if self.uses_floats {
            result.push_str(&format!("%include \"coreasm/{}/float.asm\"\n", self.target_arch));
        }
        if program.uses_heap {
            result.push_str(&format!("%include \"coreasm/{}/heap.asm\"\n", self.target_arch));
        }
        if program.uses_strings || self.uses_strings || self.uses_maps {
            result.push_str(&format!("%include \"coreasm/{}/string.asm\"\n", self.target_arch));
        }
        // args.asm parses the loader's stack (argc/argv/envp), which only an
        // executable receives - never a library - so it is excluded from
        // shared builds.
        if program.uses_args && !self.shared_lib_mode {
            result.push_str(&format!("%include \"coreasm/{}/args.asm\"\n", self.target_arch));
        }
        if self.uses_time {
            result.push_str(&format!("%include \"coreasm/{}/time.asm\"\n", self.target_arch));
        }
        if self.uses_format {
            result.push_str(&format!("%include \"coreasm/{}/format.asm\"\n", self.target_arch));
        }
        if self.uses_funcs {
            result.push_str(&format!("%include \"coreasm/{}/funcs.asm\"\n", self.target_arch));
        }
        if self.uses_lists || self.uses_maps {
            result.push_str(&format!("%include \"coreasm/{}/list.asm\"\n", self.target_arch));
        }
        if self.uses_maps {
            result.push_str(&format!("%include \"coreasm/{}/map.asm\"\n", self.target_arch));
        }
        result.push('\n');

        // Stage A4: one NASM extern per imported symbol. These are the
        // mangled <lib>_<ver>_<func> names resolve_see_import verified
        // against the .so's .dynsym; the .so itself is on the link line
        // (`main` adds it plus an rpath). No `see`, no imports, no lines —
        // non-importing builds are byte-identical.
        if !self.imported_symbols.is_empty() {
            for sym in &self.imported_symbols {
                result.push_str(&format!("extern {}\n", sym));
            }
            result.push('\n');
        }

        result.push_str("section .data\n");
        result.push_str(&self.data_section);
        result.push('\n');
        
        if !self.bss_section.is_empty() {
            result.push_str("section .bss\n");
            result.push_str(&self.bss_section);
            result.push('\n');
        }
        
        result.push_str("section .text\n");
        
        if self.shared_lib_mode {
            // A C/Rust host unloads the .so through libc's atexit -> _dl_fini,
            // which runs .fini_array. Register _cleanup_all there so the
            // library closes its tracked fds/buffers regardless of who loaded
            // it. A Vox host exits through sys_exit and never reaches
            // _dl_fini, so it must call cleanup explicitly before exit. Gate
            // the entry on the same condition that includes resource.asm,
            // where _cleanup_all is defined: a runtime-light library tracks
            // nothing and the symbol would otherwise be an undefined ref.
            if self.uses_buffers || self.uses_files || self.uses_floats {
                // `write` so ld can place the RELATIVE relocation here without
                // relaxing its read-only-segment check for the rest of the
                // .so — a targeted fix, not a blanket `-z notext`.
                result.push_str("section .fini_array progbits alloc write\n");
                result.push_str("    dq _cleanup_all\n\n");
                result.push_str("section .text\n");
            }

            // Shared library mode: export functions, no _start. The
            // `:function` type tag marks each export STT_FUNC: a NOTYPE
            // dynamic symbol resolves wrongly through the PLT and the first
            // cross-boundary call segfaults, so ld warns "type and size of
            // dynamic symbol ... are not defined" and the call traps.
            for func in &self.exported_functions {
                result.push_str(&format!("global {}:function\n", func));
            }
            result.push('\n');
            
            // Only include user-defined functions
            if !self.functions_section.is_empty() {
                result.push_str("; Exported library functions\n");
                result.push_str(&self.functions_section);
            }
        } else {
            // Executable mode: normal _start entry point
            result.push_str("global _start\n\n");
            result.push_str("_start:\n");
            
            // Save arguments BEFORE setting up stack frame (critical for correct argc/argv/envp capture)
            if program.uses_args {
                result.push_str("    ; Save command-line arguments and environment\n");
                result.push_str("    SAVE_ARGS\n\n");
            }
            
            result.push_str("    push rbp\n");
            result.push_str("    mov rbp, rsp\n");
            if self.stack_offset > 0 {
                result.push_str(&format!("    sub rsp, {}\n", (self.stack_offset + 15) & !15));
            }
            result.push('\n');
            
            result.push_str(&self.output);
            
            // Only cleanup if we used resources
            if self.uses_files || self.uses_buffers {
                result.push_str("\n    ; Cleanup all resources before exit\n");
                result.push_str("    call _cleanup_all\n");
            }
            result.push_str("\n    ; Exit program\n");
            result.push_str("    EXIT 0\n");
            
            // Append user-defined functions
            if !self.functions_section.is_empty() {
                result.push_str("\n; User-defined functions\n");
                result.push_str(&self.functions_section);
            }
        }
        
        result
    }

    fn generate_statement(&mut self, stmt: &Statement) {
        match stmt {
            // A thing definition is compile-time only: it names a layout,
            // allocates nothing, and emits no instructions. Storage is
            // emitted where a thing is *declared*, not where it is defined.
            Statement::ThingDecl(_) => {}

            // A thing declaration reserves sized storage and writes its
            // defaults (plan 310 §9). It must precede the generic VarDecl arm
            // below, which treats a global's label as a one-quadword slot to
            // store a value into - for a thing the label is the storage
            // itself.
            Statement::VarDecl {
                name,
                var_type: Some(Type::Thing(thing)),
                value,
            } => {
                self.generate_thing_decl(name, thing, value.as_ref());
            }

            // `Set moved to origin.` on a name that already holds a thing:
            // storage exists, so this copies into it (plan 310 §5). It sits
            // before the generic VarDecl arm for the same reason the
            // declaration above does - that arm stores one quadword.
            Statement::VarDecl {
                name,
                var_type: None,
                value: Some(value),
            } if self.thing_assigned_to(name).is_some() => {
                let thing = self.thing_assigned_to(name).unwrap_or_default();
                self.generate_thing_assignment(name, &thing, value);
            }

            // `Set origin's x to 3.` and everything that desugars to it.
            Statement::SetThingField { base, path, value } => {
                self.generate_set_thing_field(base, path, value);
            }

            Statement::Print { value, without_newline } => {
                self.generate_print(value, *without_newline);
            }

            Statement::VarDecl { name, var_type, value } => {
                // Decide whether this statement updates a local stack slot or
                // the global BSS mirror.  A typed declaration (`a number called
                // x is ...`) always gets a local slot so it can shadow a
                // top-level variable of the same name.  A bare assignment
                // (`Set x to ...` / `the x is ...`) with no local in scope
                // writes the global BSS mirror directly, matching the read
                // path's local-then-global resolution.
                let had_existing_slot = self.variables.contains_key(name);
                let target = if had_existing_slot {
                    // A local slot already exists (branch-declared name, loop
                    // variable, function parameter, or local shadow).
                    VarTarget::Local(self.get_var(name).unwrap())
                } else if let Some(label) = self.global_var_label(name).cloned() {
                    // The name has a BSS mirror.  Use it for:
                    //   - bare assignments (`Set x to ...`, `the x is ...`)
                    //   - top-level typed declarations, `value` included (so
                    //     top-level code and functions share one storage; see
                    //     `global_value_tag_labels` for how a `value`'s tag
                    //     half stays paired with this payload half)
                    // Typed declarations inside a function still allocate a
                    // local slot to shadow the global. A `value` declared
                    // inside a function is included here too (`var_type` is
                    // `Some(Type::Value)`), so its runtime tag slot stays
                    // paired with the payload in the SAME frame
                    // (docs/BUGS_FOUND.md #4's local/shadowing case).
                    if var_type.is_some() && self.in_function_codegen {
                        self.stack_offset += 8;
                        self.variables.insert(name.clone(), self.stack_offset);
                        VarTarget::Local(self.stack_offset)
                    } else {
                        VarTarget::Global(label)
                    }
                } else {
                    // No global mirror (e.g. a branch-only declaration): local.
                    self.stack_offset += 8;
                    self.variables.insert(name.clone(), self.stack_offset);
                    VarTarget::Local(self.stack_offset)
                };

                // Track variable type from declaration
                if let Some(ref t) = var_type {
                    // Declared as something else: this name no longer holds a
                    // thing here, so it must not keep the label a top-level
                    // `a point called origin.` left in the table and be
                    // printed or compared as a point (plan 310 §7/§8). The
                    // analyzer drops the same label at the same point.
                    if !matches!(t, Type::Thing(_)) {
                        self.thing_vars.remove(name);
                    }
                    self.declared_types.insert(name.clone(), t.clone());
                    let vt = match t {
                        Type::String => VarType::String,
                        Type::Integer => VarType::Integer,
                        Type::Float => VarType::Float,
                        Type::Boolean => VarType::Boolean,
                        Type::Buffer => VarType::Buffer,
                        Type::List(_) => VarType::List,
                        Type::Map(_) => VarType::Map,
                        // A declared `value` local is a Mixed-typed scalar
                        // carrying its runtime tag in a shadow slot, exactly
                        // like a value parameter / for-each variable.
                        Type::Value => VarType::Mixed,
                        _ => VarType::Unknown,
                    };
                    self.variable_types.insert(name.clone(), vt);
                    if matches!(t, Type::Value) {
                        if matches!(target, VarTarget::Global(_)) {
                            // Top-level `value`: tag lives in BSS, paired with
                            // the payload's own global mirror.
                            self.ensure_global_value_tag_label(name);
                        } else if !self.mixed_tag_slots.contains_key(name) {
                            let tag_slot = self.alloc_var(&format!("{}_mixtag", name));
                            self.mixed_tag_slots.insert(name.clone(), tag_slot);
                        }
                    }
                }
                
                if let Some(val) = value {
                    // A declared `value` (Mixed) carries its runtime type in a
                    // shadow tag slot (local) or BSS tag byte (global), dispatched
                    // on at every read. Demoting it to a concrete type from the
                    // initializer's static shape would make later reads ignore the
                    // tag and dispatch on the static type instead — the
                    // tag/payload desync of BUGS_FOUND #15: a `value` holding 3.5
                    // reassigned to 1 printed 0.0 because `Print` emitted
                    // PRINT_FLOAT from the clobbered static type while the tag (and
                    // payload) said integer. The bare-assignment arm already skips
                    // this for value locals via `is_value_local`; this is the same
                    // guard for the declare and `Set x to` / `the x is` spellings,
                    // which also route through VarDecl.
                    let is_value_var = matches!(var_type, Some(Type::Value))
                        || self.variable_types.get(name) == Some(&VarType::Mixed)
                        || self.mixed_tag_slots.contains_key(name)
                        || self.global_value_tag_labels.contains_key(name);
                    // Track list type and element type for lists
                    if !is_value_var {
                        if let Expr::ListLit { elements } = val {
                        self.variable_types.insert(name.clone(), VarType::List);
                        // A nested map-literal element makes this a list-of-maps;
                        // the element type is Map so a for-each loop var prints
                        // via `_map_print` (stage 1e2).
                        if let Some(Expr::MapLit { .. }) = elements.first() {
                            self.list_element_types.insert(name.clone(), VarType::Map);
                        }
                        if self.mixed_lists.contains(name) {
                            // Pre-scan proved this list heterogeneous:
                            // element reads dispatch on runtime tags.
                            self.list_element_types.insert(name.clone(), VarType::Mixed);
                        }
                        // Track element type separately
                        else if let Some(first) = elements.first() {
                            let elem_type = match first {
                                Expr::StringLit(_) => VarType::String,
                                Expr::IntegerLit(_) => VarType::Integer,
                                Expr::FloatLit(_) => VarType::Float,
                                Expr::BoolLit(_) => VarType::Boolean,
                                // A nested list literal element means this is
                                // a list-of-lists; the element type is List
                                // (stage 1e1), so a for-each loop var prints
                                // via `_list_print`.
                                Expr::ListLit { .. } => VarType::List,
                                _ => VarType::Unknown,
                            };
                            self.list_element_types.insert(name.clone(), elem_type);
                        }
                    }
                    // Float literals set float type
                    else if self.is_float_expr(val) {
                        self.variable_types.insert(name.clone(), VarType::Float);
                    }
                    // ArgumentAll/ArgumentRaw produce lists of strings
                    else if matches!(val, Expr::ArgumentAll | Expr::ArgumentRaw) {
                        self.variable_types.insert(name.clone(), VarType::List);
                        self.list_element_types.insert(name.clone(), VarType::String);
                    }
                    // Argument/environment expressions return string pointers
                    else if matches!(val,
                        Expr::ArgumentAt { .. } | Expr::ArgumentName | Expr::ArgumentFirst |
                        Expr::ArgumentSecond | Expr::ArgumentLast |
                        Expr::EnvironmentVariable { .. } | Expr::EnvironmentVariableAt { .. } |
                        Expr::EnvironmentVariableFirst | Expr::EnvironmentVariableLast
                    ) {
                        self.variable_types.insert(name.clone(), VarType::String);
                    }
                    // A call to a `.lib` function declared `returning a
                    // list of <type>` carries a real element type (plan
                    // 296) — the symmetric case to `emit_function_call`'s
                    // parameter-side propagation above. Covers BOTH call
                    // shapes: an explicit `of`/`with` argument list
                    // (`Expr::FunctionCall`) and a bare zero-argument call
                    // (`Expr::Identifier`, see `call_label_for_list_return`).
                    // A call to anything else (a local function, an
                    // unannotated `.lib` return, a runtime helper) resolves
                    // to `Type::List(Unknown)` here, so this is a no-op for
                    // it, exactly today's behavior.
                    else if let Some(label) = self.call_label_for_list_return(val) {
                        if let Some(Type::List(inner)) = self.function_return_full_types.get(&label) {
                            if !matches!(**inner, Type::Unknown) {
                                self.list_element_types
                                    .insert(name.clone(), list_element_vartype(inner));
                            }
                        }
                    }
                    // Initializing from another variable: inherit its type
                    // (and element type, for lists) unless the declaration
                    // already pinned one. Without this, `a list called b
                    // is the a.` left "b" untyped and property access
                    // misrouted to the file fallback (_file_size).
                    else if var_type.is_none() || matches!(var_type, Some(Type::List(_))) {
                        let src_name = match val {
                            Expr::Identifier(src) => Some(src),
                            Expr::StringLit(src) if self.variables.contains_key(src) => Some(src),
                            _ => None,
                        };
                        if let Some(src) = src_name {
                            if let Some(vt) = self.variable_types.get(src).cloned() {
                                // A `value` (Mixed) source carries a runtime-tagged
                                // payload whose bits/pointer are reinterpreted as the
                                // destination's declared type, so it must NOT overwrite
                                // a concrete-typed declaration: `a list called xs is
                                // item.` with item: value would otherwise demote xs to
                                // Mixed, making `{xs}` print the raw pointer and
                                // `xs's length` route to the file fallback (-1). Only
                                // inherit the source's type when the destination has no
                                // concrete type of its own. The declare-with-initializer
                                // paths for float/map never enter this branch, which is
                                // why only the `list` arm was broken. Sibling of the
                                // v0.3.5 fix (COMPILER-ISSUES #5).
                                let dst_concrete = matches!(
                                    self.variable_types.get(name),
                                    Some(VarType::Integer | VarType::Float | VarType::String
                                        | VarType::Buffer | VarType::List | VarType::Map
                                        | VarType::Boolean)
                                );
                                if vt != VarType::Mixed || !dst_concrete {
                                    self.variable_types.insert(name.clone(), vt);
                                }
                            }
                            if let Some(et) = self.list_element_types.get(src).cloned() {
                                self.list_element_types.insert(name.clone(), et);
                            }
                        }
                        // Read-back from a parent list — `a list called
                        // "inner" is element 2 of nested.` / `... is nested's
                        // first.` The child list's elements are runtime-tagged
                        // (the parent may be mixed), so a for-each over `inner`
                        // must dispatch on each element's tag rather than
                        // assume a single static type; the tag-4 branch then
                        // renders nested lists. This is correct for both
                        // homogeneous and mixed inner lists (a homogeneous
                        // inner's uniform tags dispatch to the same printer).
                        let reads_element = matches!(val, Expr::ElementAccess { .. })
                            || matches!(
                                val,
                                Expr::PropertyAccess { property, .. }
                                    if matches!(
                                        property,
                                        ObjectProperty::First
                                            | ObjectProperty::Last
                                            | ObjectProperty::Keys
                                            | ObjectProperty::Values
                                    )
                            );
                        if matches!(var_type, Some(Type::List(_))) && reads_element {
                            let elem_type =
                                if matches!(
                                    val,
                                    Expr::PropertyAccess { property: ObjectProperty::Keys, .. }
                                ) {
                                    // `map's keys` always yields text pointers.
                                    VarType::String
                                } else {
                                    // `first`/`last`/`values` and element reads
                                    // carry runtime tags per slot.
                                    VarType::Mixed
                                };
                            self.list_element_types.insert(name.clone(), elem_type);
                        }
                    }
                    } // end `if !is_value_var` — a `value` keeps Mixed

                    // Special handling for buffer initialization/assignment with text/format/buffer source
                    let is_buffer_target = matches!(var_type, Some(Type::Buffer))
                        || self.variable_types.get(name) == Some(&VarType::Buffer);
                    if is_buffer_target {
                        if matches!(val, Expr::FunctionCall { .. }) {
                            // Buffer declarations initialized from function calls should take
                            // the returned buffer pointer directly (rax), not format-append it.
                            self.generate_expr(val);
                            self.uses_buffers = true;
                            self.emit_store_rax_to_target(
                                &target, &format!("buffer {}", name));
                            if target.global_label().is_some() {
                                self.initialized_globals.insert(name.clone());
                            }
                        } else {
                            // A *declaration* (`a buffer called b is ...`,
                            // which arrives with `var_type = Some(Buffer)`)
                            // allocates a fresh buffer struct here. A bare
                            // assignment (`Set b to ...` / `the b is ...`,
                            // `var_type = None` but the existing variable is
                            // already a buffer) must NOT re-allocate: it would
                            // replace a fixed-size, bounds-checked buffer with
                            // a dynamic auto-growing one and silently disable
                            // overflow detection (test 067). Assignments skip
                            // the alloc and reuse the existing buffer struct.
                            //
                            // A declaration allocates *unconditionally*, even
                            // when the name is already bound to a slot — the
                            // #28 fix. A buffer declared on a conditional path
                            // (an untaken If branch, or a While/for-each/Repeat
                            // body that never runs) claims its stack slot at
                            // codegen time but never initialises it at runtime,
                            // so the slot holds a null pointer. A later
                            // same-name declaration that reused the slot used
                            // to skip allocation and go straight to
                            // _buffer_clear on null, segfaulting. Allocating on
                            // every declaration guarantees a valid buffer
                            // before any clear/append.
                            //
                            // Sizedness is preserved exactly as the sized
                            // `BufferDecl` path already preserves it: a sized
                            // declaration (`is N bytes in size`) routes through
                            // BufferDecl, which branches on is_sized and emits
                            // `_alloc_buffer_sized`. This arm only ever sees
                            // *unsized* declarations (string/format/buffer-
                            // source initialisers), so it emits the dynamic
                            // `_alloc_buffer`; and an assignment does not
                            // allocate at all, so a previously sized buffer
                            // keeps its bounds and its overflow detection.
                            let is_declaration = matches!(var_type, Some(Type::Buffer));
                            if is_declaration {
                                self.emit_indent("mov rdi, 1024  ; default buffer size");
                                self.emit_indent("call _alloc_buffer");
                                self.emit_store_rax_to_target(
                                    &target, &format!("buffer {}", name));
                                self.uses_buffers = true;
                                if target.global_label().is_some() {
                                    self.initialized_globals.insert(name.clone());
                                }
                            }

                            if !self.emit_copy_expr_into_buffer_slot(
                                val,
                                true,
                                target.local_offset(),
                                target.global_label(),
                            ) {
                                // Clear before materializing the value: _buffer_clear
                                // returns the (possibly reallocated) buffer pointer in
                                // rax and would clobber a value loaded first.
                                self.emit_clear_buffer_target(&target);
                                self.generate_expr(val);
                                let fmt_spec = self.parse_format_spec(None);
                                self.emit_append_runtime_value_to_buffer_target(
                                    &target,
                                    self.infer_expr_type(val),
                                    fmt_spec,
                                );
                            }
                        }
                    } else {
                        self.generate_expr(val);
                        self.emit_store_rax_to_target(&target, &format!("{}", name));
                        // A declared `value` stores its runtime tag alongside
                        // the payload, in whichever storage (local shadow
                        // slot or global BSS mirror) the payload itself used.
                        if let Some(&tag_slot) = self.mixed_tag_slots.get(name) {
                            if target.local_offset().is_some() {
                                self.emit_load_value_tag(val);
                                self.emit_indent(&format!(
                                    "mov [rbp-{}], r11b  ; value local tag",
                                    tag_slot
                                ));
                            }
                        } else if let Some(tag_label) =
                            self.global_value_tag_labels.get(name).cloned()
                        {
                            self.emit_load_value_tag(val);
                            self.emit_indent(&format!(
                                "mov [rel {}], r11b  ; value global tag",
                                tag_label
                            ));
                        }
                    }
                } else {
                    // No initial value - initialize based on type.
                    if let Some(ref t) = var_type {
                        self.emit_type_default(t, &target, name);
                    } else {
                        // No type info - initialize to 0
                        self.emit_indent("xor rax, rax");
                        self.emit_store_rax_to_target(
                            &target, &format!("{}", name));
                    }
                }

                if let Some(offset) = target.local_offset() {
                    self.emit_mirror_stack_var_to_global_if_needed(name, offset);
                }
            }

            Statement::FlagSchemaDecl { name, value_type, default, .. } => {
                // Current bootstrap behavior: represent parsed flag value as a normal variable slot.
                // Runtime schema parsing/assignment is emitted in a later iteration.
                let offset = if let Some(&existing) = self.variables.get(name) {
                    existing
                } else {
                    self.stack_offset += 8;
                    self.variables.insert(name.clone(), self.stack_offset);
                    self.stack_offset
                };

                let vt = match value_type {
                    FlagValueType::Boolean => VarType::Boolean,
                    FlagValueType::Number => VarType::Integer,
                    FlagValueType::Text => VarType::String,
                };
                self.variable_types.insert(name.clone(), vt);

                if let Some(expr) = default {
                    self.generate_expr(expr);
                    self.emit_indent(&format!("mov [rbp-{}], rax", offset));
                } else if matches!(value_type, FlagValueType::Text) {
                    // A text flag with no default that the user does not
                    // supply must read as "" - not as a null pointer, which
                    // the first read (print, interpolation, 's length, ...)
                    // would dereference. LANGUAGE.md makes `with default`
                    // optional, so this is legal code and must not crash.
                    // This is bug #16's cure applied to the flag path, which
                    // it never reached: see `emit_type_default`'s Type::String
                    // arm in vars.rs, which points an uninitialised text at
                    // the same shared empty string (docs/BUGS_FOUND.md #31).
                    let label = self.get_empty_string_label();
                    self.emit_indent(&format!(
                        "lea rax, [rel {}]  ; empty text flag default", label));
                    self.emit_indent(&format!("mov [rbp-{}], rax", offset));
                    self.uses_strings = true;
                } else {
                    // boolean and number: zero is a meaningful default
                    // (false / 0), not a pointer.
                    self.emit_indent(&format!("mov qword [rbp-{}], 0", offset));
                }

                self.emit_mirror_stack_var_to_global_if_needed(name, offset);
            }

            Statement::ParseFlags => {
                // Explicit parse point is currently a no-op placeholder. Runtime parsing is
                // planned to be emitted around this marker in a subsequent iteration.
            }
            
            // `elsewhere is origin.` copies a whole thing into storage that
            // already exists (plan 310 §5).
            Statement::Assignment { name, value } if self.thing_assigned_to(name).is_some() => {
                let thing = self.thing_assigned_to(name).unwrap_or_default();
                self.generate_thing_assignment(name, &thing, value);
            }

            Statement::Assignment { name, value } => {
                if let Some(offset) = self.get_var(name) {
                    // A `value` local (declared `a value called r`) keeps its
                    // Mixed type across reassignment — overwriting it with the
                    // assigned value's static type would drop the shadow-tag
                    // discipline and mis-classify later reads.
                    let is_value_local = self.mixed_tag_slots.contains_key(name);
                    if self.variable_types.get(name) != Some(&VarType::Buffer)
                        && !is_value_local
                    {
                        if let Some(vt) = self.infer_expr_type(value) {
                            match vt {
                                VarType::Float => {
                                    self.variable_types.insert(name.clone(), VarType::Float);
                                }
                                VarType::Integer | VarType::Boolean | VarType::String | VarType::List
                                | VarType::Map => {
                                    self.variable_types.insert(name.clone(), vt);
                                }
                                // A `value` (Mixed) source carries a runtime-tagged
                                // payload whose bits/pointer are reinterpreted as the
                                // destination's existing type, so it must NOT demote a
                                // concrete-typed local: `the y is vf.` / `Set y to vf.`
                                // with y: float would otherwise print the raw IEEE bits
                                // (4615063718147915776) instead of 3.5. The destination
                                // keeps its declared type, exactly as the
                                // declare-with-initializer path does. The value-local
                                // reassignment case is already skipped via
                                // `is_value_local` above. Sibling of the v0.3.5 fix
                                // (COMPILER-ISSUES #5), which covered value->value tag
                                // retention but missed value->concrete extraction.
                                VarType::Buffer | VarType::Unknown | VarType::Mixed => {}
                            }
                        }
                    }
                    if self.variable_types.get(name) == Some(&VarType::Buffer) {
                        if !self.emit_copy_expr_into_buffer_slot(value, true, Some(offset), None) {
                            // Clear the buffer BEFORE materializing the value:
                            // _buffer_clear returns the (possibly reallocated)
                            // buffer pointer in rax, so generating the value
                            // first would leave append reading that pointer as
                            // the value. Clear, then load the value into rax,
                            // then append.
                            self.emit_clear_buffer_slot(offset);
                            self.generate_expr(value);
                            let fmt_spec = self.parse_format_spec(None);
                            self.emit_append_runtime_value_to_buffer_slot(offset, self.infer_expr_type(value), fmt_spec);
                        }
                    } else {
                        self.generate_expr(value);
                        self.emit_indent(&format!("mov [rbp-{}], rax", offset));
                        // Reassigning a `value` local must update its shadow tag
                        // slot too, or the runtime tag would go stale.
                        if let Some(&tag_slot) = self.mixed_tag_slots.get(name) {
                            self.emit_load_value_tag(value);
                            self.emit_indent(&format!(
                                "mov [rbp-{}], r11b  ; value local tag",
                                tag_slot
                            ));
                        }
                    }
                    self.emit_mirror_stack_var_to_global_if_needed(name, offset);
                } else if let Some(label) = self.global_var_label(name).cloned() {
                    if self.variable_types.get(name) == Some(&VarType::Buffer) {
                        // Reassigning an existing global buffer: copy/append the
                        // source into the buffer, preserving the allocated struct,
                        // rather than storing a raw string pointer over it.
                        if !self.emit_copy_expr_into_buffer_slot(
                            value,
                            true,
                            None,
                            Some(&label),
                        ) {
                            let target = VarTarget::Global(label);
                            self.emit_clear_buffer_target(&target);
                            self.generate_expr(value);
                            let fmt_spec = self.parse_format_spec(None);
                            self.emit_append_runtime_value_to_buffer_target(
                                &target,
                                self.infer_expr_type(value),
                                fmt_spec,
                            );
                        }
                    } else {
                        self.generate_expr(value);
                        self.emit_indent(
                            &format!("mov [rel {}], rax", label));
                        // A top-level `value` keeps its runtime tag paired
                        // with the payload in a parallel BSS byte, updated on
                        // every assignment exactly like the local `value`
                        // case above — including a reassignment from inside a
                        // function, which is the whole point of routing a
                        // `value` global through BSS instead of a stack slot.
                        if self.variable_types.get(name) == Some(&VarType::Mixed) {
                            let tag_label = self.ensure_global_value_tag_label(name);
                            self.emit_load_value_tag(value);
                            self.emit_indent(&format!(
                                "mov [rel {}], r11b  ; value global tag",
                                tag_label
                            ));
                        }
                    }
                } else {
                    self.generate_expr(value);
                    let offset = self.alloc_var(name);
                    self.emit_indent(&format!("mov [rbp-{}], rax", offset));
                }
            }

            Statement::ValueRetype { name, target_type } => {
                self.emit_value_retype(name, target_type);
            }

            Statement::If { condition, then_block, else_if_blocks, else_block } => {
                let end_label = self.new_label("if_end");
                let else_label = self.new_label("else");
                
                self.generate_condition(condition, &else_label);
                
                for s in then_block {
                    self.generate_statement(s);
                }
                self.emit_indent(&format!("jmp {}", end_label));
                
                self.emit(&format!("{}:", else_label));
                
                if !else_if_blocks.is_empty() {
                    for (i, (cond, block)) in else_if_blocks.iter().enumerate() {
                        let next_label = if i + 1 < else_if_blocks.len() || else_block.is_some() {
                            self.new_label("elif")
                        } else {
                            end_label.clone()
                        };
                        
                        self.generate_condition(cond, &next_label);
                        
                        for s in block {
                            self.generate_statement(s);
                        }
                        self.emit_indent(&format!("jmp {}", end_label));
                        if next_label != end_label {
                            self.emit(&format!("{}:", next_label));
                        }
                    }
                }
                
                if let Some(block) = else_block {
                    for s in block {
                        self.generate_statement(s);
                    }
                }
                
                self.emit(&format!("{}:", end_label));
            }
            
            Statement::While { condition, body } => {
                let start_label = self.new_label("while_start");
                let end_label = self.new_label("while_end");
                
                self.emit(&format!("{}:", start_label));
                self.generate_condition(condition, &end_label);

                self.loop_stack.push((start_label.clone(), end_label.clone()));
                
                for s in body {
                    self.generate_statement(s);
                }
                self.loop_stack.pop();
                
                self.emit_indent(&format!("jmp {}", start_label));
                self.emit(&format!("{}:", end_label));
            }
            
            Statement::ForRange { variable, range, body } => {
                let start_label = self.new_label("for_start");
                let continue_label = self.new_label("for_continue");
                let end_label = self.new_label("for_end");
                
                if let Expr::Range { start, end, inclusive } = range {
                    self.generate_expr(start);
                    let var_offset = self.alloc_var(variable);
                    self.variables.insert("_iter".to_string(), var_offset);
                    self.emit_indent(&format!("mov [rbp-{}], rax", var_offset));
                    
                    self.generate_expr(end);
                    let end_offset = self.alloc_var(&format!("{}_end", variable));
                    if *inclusive {
                        self.emit_indent("inc rax");
                    }
                    self.emit_indent(&format!("mov [rbp-{}], rax", end_offset));
                    
                    self.emit(&format!("{}:", start_label));
                    
                    self.emit_indent(&format!("mov rax, [rbp-{}]", var_offset));
                    self.emit_indent(&format!("cmp rax, [rbp-{}]", end_offset));
                    self.emit_indent(&format!("jge {}", end_label));

                    self.loop_stack.push((continue_label.clone(), end_label.clone()));
                    
                    for s in body {
                        self.generate_statement(s);
                    }
                    self.loop_stack.pop();

                    self.emit(&format!("{}:", continue_label));
                    
                    self.emit_indent(&format!("inc qword [rbp-{}]", var_offset));
                    self.emit_indent(&format!("jmp {}", start_label));
                    
                    self.emit(&format!("{}:", end_label));
                }
            }
            
            Statement::Repeat { count, body } => {
                let start_label = self.new_label("repeat_start");
                let continue_label = self.new_label("repeat_continue");
                let end_label = self.new_label("repeat_end");
                
                self.generate_expr(count);
                let counter_offset = self.alloc_var("_repeat_counter");
                self.emit_indent(&format!("mov [rbp-{}], rax", counter_offset));
                
                self.emit(&format!("{}:", start_label));
                
                self.emit_indent(&format!("cmp qword [rbp-{}], 0", counter_offset));
                self.emit_indent(&format!("jle {}", end_label));

                self.loop_stack.push((continue_label.clone(), end_label.clone()));
                
                for s in body {
                    self.generate_statement(s);
                }
                self.loop_stack.pop();

                self.emit(&format!("{}:", continue_label));
                
                self.emit_indent(&format!("dec qword [rbp-{}]", counter_offset));
                self.emit_indent(&format!("jmp {}", start_label));
                
                self.emit(&format!("{}:", end_label));
            }
            
            Statement::Allocate { name, size } => {
                self.generate_expr(size);
                self.emit_indent("HEAP_ALLOC rax");
                let offset = self.alloc_var(name);
                self.emit_indent(&format!("mov [rbp-{}], rax", offset));
            }
            
            Statement::Free { name } => {
                if let Some(offset) = self.get_var(name) {
                    self.emit_indent(&format!("mov rdi, [rbp-{}]", offset));
                    self.emit_indent("HEAP_FREE rdi");
                }
            }
            
            Statement::Increment { name } => {
                if let Some(offset) = self.get_var(name) {
                    self.emit_indent(&format!("inc qword [rbp-{}]", offset));
                    self.emit_mirror_stack_var_to_global_if_needed(name, offset);
                } else if let Some(label) = self.global_var_label(name).cloned() {
                    self.emit_indent(&format!("inc qword [rel {}]", label));
                }
            }
            
            Statement::Decrement { name } => {
                if let Some(offset) = self.get_var(name) {
                    self.emit_indent(&format!("dec qword [rbp-{}]", offset));
                    self.emit_mirror_stack_var_to_global_if_needed(name, offset);
                } else if let Some(label) = self.global_var_label(name).cloned() {
                    self.emit_indent(&format!("dec qword [rel {}]", label));
                }
            }
            
            Statement::Break => {
                self.emit_indent("; break");
                if let Some((_, break_label)) = self.loop_stack.last() {
                    self.emit_indent(&format!("jmp {}", break_label));
                }
            }
            
            Statement::Exit { code } => {
                self.emit_indent("; exit program");
                self.generate_expr(code);
                self.emit_indent("mov rdi, rax  ; exit code");
                if self.uses_files || self.uses_buffers {
                    self.emit_indent("push rdi      ; save exit code");
                    self.emit_indent("call _cleanup_all");
                    self.emit_indent("pop rdi       ; restore exit code");
                }
                self.emit_indent("EXIT rdi");
            }
            
            Statement::Continue => {
                self.emit_indent("; continue");
                if let Some((continue_label, _)) = self.loop_stack.last() {
                    self.emit_indent(&format!("jmp {}", continue_label));
                }
            }
            
            // `Return a point, start.` - the caller handed this function the
            // address it wants the thing written to, so the return copies
            // into it and answers with that same address (plan 310 §5).
            Statement::Return { value, .. } if self.current_thing_return_slot.is_some() => {
                let slot = self.current_thing_return_slot.unwrap_or_default();
                if let Some(v) = value {
                    if let Some(thing) = self.emit_thing_address(v) {
                        self.emit_indent("mov rsi, rax  ; the thing being returned");
                        self.emit_indent(&format!(
                            "mov rdi, [rbp-{}]  ; the caller's destination",
                            slot
                        ));
                        let size = self.thing_storage_size(&thing);
                        self.emit_thing_copy(size, &format!("the returned {}", thing));
                    }
                }
                self.emit_indent(&format!(
                    "mov rax, [rbp-{}]  ; the result's address",
                    slot
                ));
                if self.in_function_codegen {
                    self.emit_indent("push rax  ; save return value");
                    self.emit_indent("call _dec_call_depth");
                    self.emit_indent("pop rax  ; restore return value");
                }
                self.emit_indent("FUNC_EPILOGUE");
            }

            Statement::Return { value, .. } => {
                if let Some(v) = value {
                    self.generate_expr(v); // leaves return payload in RAX
                    // A `value` return carries its runtime tag in r11 for the
                    // caller. Load it AFTER generate_expr (which leaves r11=tag
                    // for fresh reads / value-returning calls, or nothing for a
                    // Mixed identifier). `_dec_call_depth` and `FUNC_EPILOGUE`
                    // (leave; ret) do not clobber r11, so no spill is needed.
                    if self.current_function_return_type == Some(Type::Value) {
                        self.emit_load_value_tag(v);
                    }
                }
                if self.in_function_codegen {
                    self.emit_indent("push rax  ; save return value");
                    self.emit_indent("call _dec_call_depth");
                    self.emit_indent("pop rax  ; restore return value");
                }
                self.emit_indent("FUNC_EPILOGUE");
            }
            
            Statement::FunctionCall { name, args } => {
                // Mark that we're using functions so funcs.asm gets included
                self.uses_funcs = true;
                self.emit_function_call(name, args);
            }
                        
            Statement::FunctionDef { name, params, body, return_type, .. } => {
                // Mark that we're using functions so funcs.asm gets included
                self.uses_funcs = true;
                
                let func_label = self.function_label(name);

                // Track exported functions for shared library mode
                if self.shared_lib_mode {
                    self.exported_functions.push(func_label.clone());
                }

                // Save outer codegen state
                let saved_output = std::mem::take(&mut self.output);
                let saved_vars = std::mem::take(&mut self.variables);
                let saved_stack = self.stack_offset;
                let saved_loop_stack = std::mem::take(&mut self.loop_stack);
                let saved_in_function_codegen = self.in_function_codegen;
                let saved_return_type = self.current_function_return_type.clone();
                // `variable_types`/`mixed_tag_slots` are a flat, unscoped
                // namespace (unlike `self.variables`, which resets to empty
                // per function): a function body still needs to resolve the
                // type of an already-declared global by name, so it cannot
                // start empty. Clone-and-restore instead, so this function's
                // OWN params/locals (registered into these maps below and
                // during body codegen) are visible while generating its body
                // but do not leak into whatever is generated after it. Before
                // this, a parameter name from one function (e.g. `aa`) stayed
                // in `variable_types` forever, so a later, unrelated string
                // literal that happened to equal that name (e.g. `"aa"` in a
                // call argument) inherited the stale parameter's type instead
                // of being read as literal text — see
                // tests/203_value_param_word_boundary.vox and
                // `emit_time_expr_tag`'s `Expr::StringLit` handling, which
                // trusts `variable_types` by name with no scope check.
                let saved_variable_types = self.variable_types.clone();
                let saved_declared_types = self.declared_types.clone();
                let saved_thing_vars = self.thing_vars.clone();
                let saved_mixed_tag_slots = self.mixed_tag_slots.clone();
                // `mixed_lists`/`unprovable_scalars` are a flat, unscoped set
                // just like `variable_types`, so they need the same
                // clone-and-restore isolation: a function's own locals must not
                // leak into whatever is generated after it. The pre-scan
                // already partitioned each function's locals into
                // `local_*`/`local_names` keyed by `func_label`; apply this
                // function's partition on top of the outer (global) state, first
                // dropping any names this function redeclares as locals so a
                // local shadowing a global takes its own verdict. `list_element_types`
                // and `file_writable` are maps overwritten per-VarDecl during
                // body codegen, so a plain save/restore is enough for them.
                let saved_mixed_lists = self.mixed_lists.clone();
                let saved_unprovable_scalars = self.unprovable_scalars.clone();
                let saved_list_element_types = self.list_element_types.clone();
                let saved_file_writable = self.file_writable.clone();
                if let Some(locals) = self.local_names.get(&func_label).cloned() {
                    for n in &locals {
                        self.mixed_lists.remove(n);
                        self.unprovable_scalars.remove(n);
                    }
                    if let Some(loc) = self.local_mixed_lists.get(&func_label) {
                        for n in loc {
                            self.mixed_lists.insert(n.clone());
                        }
                    }
                    if let Some(loc) = self.local_unprovable_scalars.get(&func_label) {
                        for n in loc {
                            self.unprovable_scalars.insert(n.clone());
                        }
                    }
                }

                // Fresh function-local state
                self.output = String::new();
                self.variables = std::collections::HashMap::new();
                self.stack_offset = 0;
                self.loop_stack = Vec::new();
                self.in_function_codegen = true;
                // Remember this function's declared return type so the `Return`
                // path knows to leave a `value` result's tag in r11.
                self.current_function_return_type = Some(return_type.clone());

                // ------------------------------------------------------------
                // PASS 1: Allocate stack slots for params, then generate body
                // into a temporary buffer to discover the true frame size.
                // ------------------------------------------------------------

                // A `value` parameter occupies two argument words (payload, tag).
                // The payload lives in the param's own slot; the tag lives in a
                // shadow `{name}_mixtag` slot, exactly like a for-each variable
                // over a mixed list, so the 1c predicates/print/append/forward
                // machinery all work on it unchanged.
                let word_count = |t: &Type| if matches!(t, Type::Value) { 2 } else { 1 };

                // A function returning a whole thing is handed the caller's
                // destination in a hidden first argument word (plan 310 §5).
                // Its slot is allocated before the parameters', so word 0 and
                // slot 0 line up on both sides of the call.
                let saved_thing_return_slot = self.current_thing_return_slot.take();
                if matches!(return_type, Type::Thing(_)) {
                    self.stack_offset += 8;
                    self.current_thing_return_slot = Some(self.stack_offset);
                }
                let hidden_words = if self.current_thing_return_slot.is_some() { 1 } else { 0 };
                let total_words: usize =
                    hidden_words + params.iter().map(|(_, t)| word_count(t)).sum::<usize>();

                // Allocate param stack slots FIRST so offsets are stable.
                // Also register param types so they're known in function body.
                for (param_name, param_type) in params.iter() {
                    self.declared_types.insert(param_name.clone(), param_type.clone());
                    let var_type = match param_type {
                        Type::Integer => VarType::Integer,
                        Type::Float => VarType::Float,
                        Type::String => VarType::String,
                        Type::Boolean => VarType::Boolean,
                        Type::List(_) => VarType::List,
                        Type::Buffer => VarType::Buffer,
                        // A `value` parameter is a Mixed-typed scalar carrying
                        // its runtime tag in a shadow slot.
                        Type::Value => VarType::Mixed,
                        _ => VarType::Unknown,
                    };
                    // A thing parameter's slot is the whole thing: the frame
                    // holds this function's own copy, so its fields address
                    // off rbp exactly like a thing declared in the body.
                    if let Type::Thing(thing) = param_type {
                        self.stack_offset += self.thing_storage_size(thing) as i64;
                        self.variables.insert(param_name.clone(), self.stack_offset);
                        self.thing_vars.insert(param_name.clone(), thing.clone());
                    } else {
                        self.alloc_var(param_name);
                    }
                    self.variable_types.insert(param_name.clone(), var_type);
                    if matches!(param_type, Type::Value) {
                        let tag_slot = self.alloc_var(&format!("{}_mixtag", param_name));
                        self.mixed_tag_slots.insert(param_name.clone(), tag_slot);
                    }
                }

                // Generate body into a temp buffer (this will call alloc_var for locals too)
                let mut has_return = false;

                let saved_tmp_out = std::mem::take(&mut self.output);
                self.output = String::new();

                for stmt in body {
                    if matches!(stmt, Statement::Return { .. }) {
                        has_return = true;
                    }
                    self.generate_statement(stmt);
                }

                // If no explicit return, add a default epilogue
                if !has_return {
                    // A thing-returning function that falls off its end still
                    // owes the caller the address it was given, or the caller
                    // would copy out of whatever rax happened to hold.
                    if let Some(slot) = self.current_thing_return_slot {
                        self.emit_indent(&format!(
                            "mov rax, [rbp-{}]  ; the caller's destination",
                            slot
                        ));
                    }
                    self.emit_indent("call _dec_call_depth");
                    self.emit_indent("FUNC_EPILOGUE");
                }

                let body_code = std::mem::take(&mut self.output);
                self.output = saved_tmp_out;

                // Now we KNOW the frame size needed (params + locals + temps)
                let frame_size = (self.stack_offset + 15) & !15;

                // ------------------------------------------------------------
                // PASS 2: Emit the real function with correct prologue + param stores,
                // then append the already-generated body code.
                // ------------------------------------------------------------

                self.emit(&format!("{}:", func_label));
                self.emit_indent(&format!("FUNC_PROLOGUE {}", frame_size));
                // Recursion depth guard - save the first 6 argument WORDS
                // (not 6 params: a `value` param contributes two words), check
                // depth, restore. `_check_call_depth` touches only rax, so the
                // saved words are intact.
                let reg_words = total_words.min(6);
                for i in 0..reg_words {
                    self.emit_indent(&format!("push {}  ; save arg word", ["rdi", "rsi", "rdx", "rcx", "r8", "r9"][i]));
                }
                self.emit_indent("call _check_call_depth");
                for i in (0..reg_words).rev() {
                    self.emit_indent(&format!("pop {}  ; restore arg word", ["rdi", "rsi", "rdx", "rcx", "r8", "r9"][i]));
                }

                // Store parameters after frame is allocated. Walk params in
                // order, tracking the running argument-word index: a scalar
                // param consumes one word, a `value` param consumes two
                // (payload at `word_index`, tag at `word_index + 1`).
                let param_regs = ["rdi", "rsi", "rdx", "rcx", "r8", "r9"];
                // The caller inserts an 8-byte alignment pad below the stack
                // args when their count is odd, so the first stack arg lives at
                // [rbp + 16 + pad_offset], not [rbp + 16]. Both sides derive the
                // pad from the same word count, so they agree.
                let stack_words = total_words.saturating_sub(param_regs.len());
                let pad_offset: usize = if stack_words % 2 == 0 { 0 } else { 8 };
                let read_argument_word = |w: usize| {
                    if w < param_regs.len() {
                        format!("mov rax, {}", param_regs[w])
                    } else {
                        let stack_arg_off = 16 + pad_offset + (w - param_regs.len()) * 8;
                        format!("mov rax, [rbp+{}]", stack_arg_off)
                    }
                };
                let mut word_index = 0usize;
                if let Some(slot) = self.current_thing_return_slot {
                    self.emit_indent(&read_argument_word(word_index));
                    self.emit_indent(&format!(
                        "mov [rbp-{}], rax  ; where the caller wants the result",
                        slot
                    ));
                    word_index += 1;
                }
                // A thing parameter's word is the address of the caller's
                // thing, parked in the first quadword of this frame's own
                // region until every argument word has been read out of its
                // register. Copying on the spot would clobber rsi/rdi/rcx
                // while later parameters are still living in them.
                let mut things_to_copy: Vec<(String, i64)> = Vec::new();
                for (param_name, param_type) in params.iter() {
                    let payload_off = self.get_var(param_name);
                    let tag_off = self.mixed_tag_slots.get(param_name).copied();
                    let is_value = matches!(param_type, Type::Value);

                    if let Some(offset) = payload_off {
                        // Payload word.
                        self.emit_indent(&read_argument_word(word_index));
                        self.emit_indent(&format!("mov [rbp-{}], rax  ; param payload", offset));
                        if let Type::Thing(thing) = param_type {
                            things_to_copy.push((thing.clone(), offset));
                        }
                        if is_value {
                            // Tag word (stored as a byte into the shadow slot).
                            if let Some(tag_slot) = tag_off {
                                self.emit_indent(&read_argument_word(word_index + 1));
                                self.emit_indent(&format!(
                                    "mov [rbp-{}], al  ; param value tag",
                                    tag_slot
                                ));
                            }
                            word_index += 2;
                        } else {
                            word_index += 1;
                        }
                    } else if is_value {
                        word_index += 2;
                    } else {
                        word_index += 1;
                    }
                }
                // The parameter IS the copy: reading the parked address first
                // and writing over it is safe, because the source is the
                // caller's storage and this region is a fresh frame's.
                for (thing, offset) in things_to_copy {
                    self.emit_indent(&format!("mov rsi, [rbp-{}]  ; the caller's {}", offset, thing));
                    self.emit_indent(&format!("lea rdi, [rbp-{}]", offset));
                    let size = self.thing_storage_size(&thing);
                    self.emit_thing_copy(size, &format!("a {} parameter", thing));
                }

                // Frame setup for docs/BUGS_FOUND.md #25 (plan 318 §1):
                // same treatment as the top-level program (see `generate`)
                // but for this function's own frame - a name declared only
                // inside a conditional body of ITS body needs its default
                // written before the body (already generated into
                // `body_code` above) runs, in case that body never does.
                self.emit_conditional_decl_defaults(body);

                // Append the already-generated body
                self.output.push_str(&body_code);
                self.emit("");

                // Capture the finished function code
                let func_code = std::mem::take(&mut self.output);

                // Restore outer codegen state
                self.output = saved_output;
                self.variables = saved_vars;
                self.stack_offset = saved_stack;
                self.loop_stack = saved_loop_stack;
                self.in_function_codegen = saved_in_function_codegen;
                self.current_function_return_type = saved_return_type;
                self.current_thing_return_slot = saved_thing_return_slot;
                self.variable_types = saved_variable_types;
                self.declared_types = saved_declared_types;
                self.thing_vars = saved_thing_vars;
                self.mixed_tag_slots = saved_mixed_tag_slots;
                self.mixed_lists = saved_mixed_lists;
                self.unprovable_scalars = saved_unprovable_scalars;
                self.list_element_types = saved_list_element_types;
                self.file_writable = saved_file_writable;

                // Append to functions section
                self.functions_section.push_str(&format!("; Function: {}\n", name));
                self.functions_section.push_str(&func_code);
            }

            
            Statement::ForEach { variable, collection, body } => {
                let start_label = self.new_label("foreach_start");
                let continue_label = self.new_label("foreach_continue");
                let end_label = self.new_label("foreach_end");
                
                // Special handling for arguments lists
                if matches!(collection, Expr::ArgumentAll | Expr::ArgumentRaw) {
                    if matches!(collection, Expr::ArgumentAll) {
                        self.emit_indent("call _get_parsed_argc");
                    } else {
                        self.emit_indent("call _get_raw_argc");
                    }
                    let argc_var = self.alloc_var(&format!("{}_argc", variable));
                    self.emit_indent(&format!("mov [rbp-{}], rax  ; arg count", argc_var));

                    // Initialize index to 0 (user-arg-relative)
                    let index_var = self.alloc_var(&format!("{}_idx", variable));
                    self.emit_indent(&format!("mov qword [rbp-{}], 0", index_var));
                    
                    // Allocate variable for current element
                    let elem_var = self.alloc_var(variable);
                    self.variables.insert(variable.clone(), elem_var);
                    self.variable_types.insert(variable.clone(), VarType::String);
                    
                    self.emit(&format!("{}:", start_label));
                    
                    // Check if index < count
                    self.emit_indent(&format!("mov rax, [rbp-{}]  ; index", index_var));
                    self.emit_indent(&format!("cmp rax, [rbp-{}]  ; compare with count", argc_var));
                    self.emit_indent(&format!("jge {}", end_label));
                    
                    // Get current argument pointer from selected view
                    self.emit_indent("mov rdi, rax");
                    if matches!(collection, Expr::ArgumentAll) {
                        self.emit_indent("call _get_parsed_arg");
                    } else {
                        self.emit_indent("call _get_raw_arg");
                    }
                    self.emit_indent(&format!("mov [rbp-{}], rax  ; store in {}", elem_var, variable));
                    
                    // Generate body
                    self.loop_stack.push((continue_label.clone(), end_label.clone()));
                    for s in body {
                        self.generate_statement(s);
                    }
                    self.loop_stack.pop();

                    self.emit(&format!("{}:", continue_label));
                    
                    // Increment index
                    self.emit_indent(&format!("inc qword [rbp-{}]", index_var));
                    self.emit_indent(&format!("jmp {}", start_label));
                    
                    self.emit(&format!("{}:", end_label));
                    return;
                }
                
                // Determine element type from list
                let elem_type = if let Expr::Identifier(list_name) = collection {
                    // A list parameter (or any list with no proven element type)
                    // stores a per-slot runtime tag, so widen the loop variable
                    // to Mixed and read the tag each iteration — see
                    // `list_expr_is_mixed`.
                    match self.list_element_types.get(list_name) {
                        None | Some(&VarType::Unknown) => VarType::Mixed,
                        Some(other) => other.clone(),
                    }
                } else if let Expr::PropertyAccess { object, property } = collection {
                    // `map's keys` yields a list of text pointers; `map's
                    // values` yields a mixed-tagged list (each value carries
                    // its own runtime tag). (stage 1e2)
                    match property {
                        ObjectProperty::Keys => VarType::String,
                        ObjectProperty::Values => VarType::Mixed,
                        // `first`/`last` of a list-of-maps -> each is a map.
                        ObjectProperty::First | ObjectProperty::Last => {
                            match self.list_element_types.get(object) {
                                Some(VarType::Map) => VarType::Map,
                                _ => VarType::Unknown,
                            }
                        }
                        _ => VarType::Unknown,
                    }
                } else if let Expr::ListLit { elements } = collection {
                    // Inline literal: classify every element, not just the
                    // first - two distinct types means Mixed.
                    let mut tags: Vec<u8> = Vec::new();
                    let mut any_unknown = false;
                    for e in elements {
                        match self.emit_time_expr_tag(e) {
                            Some(t) => {
                                if !tags.contains(&t) {
                                    tags.push(t);
                                }
                            }
                            None => any_unknown = true,
                        }
                    }
                    if tags.len() > 1 {
                        VarType::Mixed
                    } else if let Some(first) = elements.first() {
                        let _ = any_unknown;
                        match first {
                            Expr::StringLit(_) => VarType::String,
                            Expr::IntegerLit(_) => VarType::Integer,
                            Expr::BoolLit(_) => VarType::Boolean,
                            Expr::FloatLit(_) => VarType::Float,
                            // Homogeneous list-of-lists literal: each element
                            // is a list (tag 4), so the loop var is a List and
                            // prints via `_list_print` (stage 1e1).
                            Expr::ListLit { .. } => VarType::List,
                            _ => VarType::Unknown,
                        }
                    } else {
                        VarType::Unknown
                    }
                } else {
                    VarType::Unknown
                };
                
                // Get list pointer
                // List structure: [capacity:8][length:8][elem_size:8][data...]
                self.generate_expr(collection);
                let list_ptr = self.alloc_var(&format!("{}_list", variable));
                self.emit_indent(&format!("mov [rbp-{}], rax  ; list pointer", list_ptr));
                
                // Get list length (at offset 8)
                self.emit_indent("mov rax, [rax + 8]  ; get length (offset 8)");
                let list_len = self.alloc_var(&format!("{}_len", variable));
                self.emit_indent(&format!("mov [rbp-{}], rax  ; list length", list_len));
                
                // Initialize index to 0
                let index_var = self.alloc_var(&format!("{}_idx", variable));
                self.emit_indent(&format!("mov qword [rbp-{}], 0  ; index", index_var));
                
                // Allocate variable for current element and track its type
                let elem_var = self.alloc_var(variable);
                self.variables.insert(variable.clone(), elem_var);
                self.variable_types.insert(variable.clone(), elem_type.clone());

                // For mixed lists the element's runtime type tag shadows the
                // loop variable in its own stack slot, refreshed every
                // iteration and consulted wherever the variable is printed.
                let tag_slot = if elem_type == VarType::Mixed {
                    let slot = self.alloc_var(&format!("{}_mixtag", variable));
                    self.mixed_tag_slots.insert(variable.clone(), slot);
                    Some(slot)
                } else {
                    self.mixed_tag_slots.remove(variable);
                    None
                };
                
                self.emit(&format!("{}:", start_label));
                
                // Check if index < length
                self.emit_indent(&format!("mov rax, [rbp-{}]  ; index", index_var));
                self.emit_indent(&format!("cmp rax, [rbp-{}]  ; compare with length", list_len));
                self.emit_indent(&format!("jge {}", end_label));
                
                // Get current element: data starts at offset 24
                self.emit_indent(&format!("mov rbx, [rbp-{}]  ; list pointer", list_ptr));
                if let Some(slot) = tag_slot {
                    // tag_addr = base + 24 + capacity*8 + index
                    self.emit_indent("mov r11, [rbx]  ; capacity");
                    self.emit_indent("shl r11, 3  ; * element size (8)");
                    self.emit_indent("add r11, rax  ; + index");
                    self.emit_indent(&format!(
                        "movzx r11, byte [rbx + r11 + {}]  ; slot type tag",
                        LIST_DATA_OFFSET
                    ));
                    self.emit_indent(&format!("mov [rbp-{}], r11b  ; stash element's type tag", slot));
                }
                self.emit_indent("shl rax, 3  ; index * 8");
                self.emit_indent(&format!(
                    "add rax, {}  ; skip header ({} bytes)",
                    LIST_DATA_OFFSET, LIST_DATA_OFFSET
                ));
                self.emit_indent("add rbx, rax");
                self.emit_indent("mov rax, [rbx]  ; get element");
                self.emit_indent(&format!("mov [rbp-{}], rax  ; store in {}", elem_var, variable));
                
                // Generate body
                self.loop_stack.push((continue_label.clone(), end_label.clone()));
                for s in body {
                    self.generate_statement(s);
                }
                self.loop_stack.pop();

                self.emit(&format!("{}:", continue_label));
                
                // Increment index
                self.emit_indent(&format!("inc qword [rbp-{}]", index_var));
                self.emit_indent(&format!("jmp {}", start_label));
                
                self.emit(&format!("{}:", end_label));
            }
            
            // File I/O statements
            Statement::BufferDecl { name, size } => {
                // Reuse an existing slot for the same buffer name, exactly like
                // VarDecl reassignment. This ensures a buffer declared in both
                // branches of an if/otherwise pair shares a single stack slot,
                // so code after the branch reads the slot that was actually
                // written at runtime.
                let offset = if let Some(&existing) = self.variables.get(name) {
                    existing
                } else {
                    self.stack_offset += 8;
                    self.variables.insert(name.clone(), self.stack_offset);
                    self.stack_offset
                };
                self.variable_types.insert(name.clone(), VarType::Buffer);

                // Check if size is specified (non-zero)
                let is_sized = match size {
                    Expr::IntegerLit(0) => false,
                    Expr::IntegerLit(_) => true,
                    _ => true, // Any expression means sized
                };

                if is_sized {
                    // Fixed-size buffer (bounds checked, no auto-grow)
                    self.generate_expr(size);
                    self.emit_indent("mov rdi, rax  ; buffer size");
                    self.emit_indent("call _alloc_buffer_sized");
                } else {
                    // Dynamic buffer (auto-grows, tracked for cleanup)
                    self.emit_indent("call _alloc_buffer");
                }
                self.uses_buffers = true;
                self.emit_indent(&format!("mov [rbp-{}], rax  ; buffer struct pointer", offset));

                // Top-level/branch-declared buffers must be mirrored into BSS
                // so functions can read (and write) them via the global label.
                self.emit_mirror_stack_var_to_global_if_needed(name, offset);
            }
            
            Statement::ByteSet { buffer, index, value } => {
                let ok_label = self.new_label("bset_ok");
                let error_label = self.new_label("bset_err");
                let done_label = self.new_label("bset_done");
                let noupd_label = self.new_label("bset_noupd");

                self.emit_indent("; Set byte N of buffer to value (with bounds check)");
                // Get buffer pointer (local or global mirror)
                self.emit_load_named_var_addr(buffer);
                self.emit_indent("mov rbx, rax  ; buffer ptr");
                self.emit_indent("push rbx  ; save buffer pointer");
                // Get index
                self.generate_expr(index);
                self.emit_indent("mov rcx, rax  ; index in rcx (1-indexed)");
                self.emit_indent("pop rbx  ; buffer pointer in rbx");

                // Bounds check: index must be >= 1
                self.emit_indent("cmp rcx, 1");
                self.emit_indent(&format!("jl {}  ; index < 1 is error", error_label));
                self.emit_indent("mov rdx, [rbx]  ; get buffer capacity (offset 0)");
                self.emit_indent("cmp rcx, rdx");
                self.emit_indent(&format!("jle {}  ; index <= capacity is OK", ok_label));

                // Index beyond current capacity: dynamic buffers auto-grow,
                // fixed buffers are an error.
                self.emit_indent("mov rdx, [rbx + 16]  ; buffer flags");
                self.emit_indent("test rdx, 1  ; BUF_FLAG_FIXED");
                self.emit_indent(&format!("jnz {}  ; fixed buffer overflow", error_label));

                // Grow dynamic buffer so the 1-indexed position fits.
                self.emit_indent("push rcx  ; save index across grow call");
                self.emit_indent("mov rdi, rbx  ; buffer pointer");
                self.emit_indent("mov rsi, rcx  ; required capacity = index");
                self.emit_indent("call _grow_buffer");
                self.emit_indent("mov rbx, rax  ; new buffer pointer");
                self.emit_store_back_after_realloc(buffer, "rax");
                self.emit_indent("pop rcx  ; restore 1-indexed position");
                self.emit_indent(&format!("jmp {}  ; grown buffer now has space", ok_label));

                // Error path: out of bounds
                self.emit(&format!("{}:", error_label));
                self.emit_indent("mov qword [rel _last_error], 1  ; set error flag");
                self.emit_indent(&format!("jmp {}", done_label));

                // Success path: safe write
                self.emit(&format!("{}:", ok_label));
                self.emit_indent("mov qword [rel _last_error], 0  ; clear error on success");
                self.emit_indent("push rbx  ; save buffer pointer");
                self.emit_indent("push rcx  ; save 1-indexed position");
                // Get value
                self.generate_expr(value);
                self.emit_indent("mov rdx, rax  ; value in rdx");
                self.emit_indent("pop rcx  ; 1-indexed position in rcx");
                self.emit_indent("pop rbx  ; buffer pointer in rbx");
                // Update length = max(length, index) so reads see the written bytes
                self.emit_indent("cmp rcx, [rbx + 8]  ; compare index with current length");
                self.emit_indent(&format!("jle {}  ; skip if length already >= index", noupd_label));
                self.emit_indent("mov [rbx + 8], rcx  ; extend length to include this byte");
                self.emit(&format!("{}:", noupd_label));
                self.emit_indent("dec rcx  ; convert 1-indexed to 0-indexed");
                self.emit_indent(&format!("add rbx, {}  ; skip to buffer data area", BUF_DATA_OFFSET));
                self.emit_indent("mov [rbx + rcx], dl  ; write byte");

                self.emit(&format!("{}:", done_label));
            }
            
            Statement::ElementSet { list, index, value } => {
                let ok_label = self.new_label("eset_ok");
                let error_label = self.new_label("eset_err");
                let done_label = self.new_label("eset_done");

                self.emit_indent("; Set element N of list to value (with bounds check)");
                // Get list pointer (local or global mirror)
                self.emit_load_named_var_addr(list);
                self.emit_indent("mov rbx, rax  ; list ptr");
                self.emit_indent("push rbx  ; save list pointer");
                // Get index (1-indexed)
                self.generate_expr(index);
                self.emit_indent("mov rcx, rax  ; index in rcx (1-indexed)");
                self.emit_indent("pop rbx  ; list pointer in rbx");

                // Bounds check: index must be >= 1 and <= length
                self.emit_indent("cmp rcx, 1");
                self.emit_indent(&format!("jl {}  ; index < 1 is error", error_label));
                self.emit_indent("mov rdx, [rbx + 8]  ; get list length (offset 8)");
                self.emit_indent("cmp rcx, rdx");
                self.emit_indent(&format!("jle {}  ; index <= length is OK", ok_label));

                // Error path: out of bounds
                self.emit(&format!("{}:", error_label));
                self.emit_indent("mov qword [rel _last_error], 1  ; set error flag");
                self.emit_indent(&format!("jmp {}", done_label));

                // Success path: safe write
                self.emit(&format!("{}:", ok_label));
                self.emit_indent("mov qword [rel _last_error], 0  ; clear error on success");
                self.emit_indent("dec rcx  ; convert 1-indexed to 0-indexed");
                self.emit_indent("push rbx  ; save list pointer");
                self.emit_indent("push rcx  ; save index");
                // Get value
                self.generate_expr(value);
                self.emit_indent("mov r8, rax  ; value in r8");
                self.emit_indent("pop rcx  ; index in rcx");
                self.emit_indent("pop rbx  ; list pointer in rbx");
                // Write the slot's type tag:
                // tag_addr = base + 24 + capacity*elem_size + index
                self.emit_indent("mov rdx, [rbx]  ; capacity");
                self.emit_indent("imul rdx, [rbx + 16]  ; capacity * element_size");
                self.emit_indent("add rdx, rcx  ; + 0-based index");
                match self.emit_time_expr_tag(value) {
                    Some(tag) => {
                        self.emit_indent(&format!(
                            "mov byte [rbx + rdx + {0}], {1}  ; slot type tag",
                            LIST_DATA_OFFSET, tag
                        ));
                    }
                    None => {
                        if let Some(loc) = self.mixed_element_tag_slot(value) {
                            self.emit_indent(&format!(
                                "mov al, {}  ; runtime tag of mixed source",
                                loc.operand()
                            ));
                            self.emit_indent(&format!(
                                "mov [rbx + rdx + {}], al  ; slot type tag",
                                LIST_DATA_OFFSET
                            ));
                        } else {
                            self.emit_indent(&format!(
                                "mov byte [rbx + rdx + {}], 0  ; default integer tag",
                                LIST_DATA_OFFSET
                            ));
                        }
                    }
                }
                // Get element size (at offset 16 in list structure)
                self.emit_indent("mov rdx, [rbx + 16]  ; element size");
                // Calculate offset
                self.emit_indent("imul rcx, rdx  ; index * element_size");
                self.emit_indent(&format!(
                    "add rcx, {}  ; data starts at offset {}",
                    LIST_DATA_OFFSET, LIST_DATA_OFFSET
                ));
                // Write element
                self.emit_indent("mov [rbx + rcx], r8  ; write element");

                self.emit(&format!("{}:", done_label));
            }

            // Set map's "<key>" to value: insert or replace. _map_insert may
            // reallocate on growth, so the returned pointer is stored back
            // into the map variable's slot (mirroring ListAppend's store-back
            // — forgetting this corrupts the var after the first growth).
            // (stage 1e2, tag 5)
            Statement::MapSet { map, key, value } => {
                self.uses_maps = true;
                self.emit_indent("; Set map's key to value (insert/replace)");
                // map pointer -> stack
                self.emit_load_named_var_into_rax(map);
                self.emit_indent("push rax  ; save map pointer");
                // key -> stack (literal text; never a variable reference)
                self.generate_text_key(key);
                self.emit_indent("push rax  ; save key pointer");
                // value -> rdx
                self.generate_expr(value);
                self.emit_indent("mov rdx, rax  ; value");
                // tag -> rcx (forward runtime tag for mixed sources)
                match self.emit_time_expr_tag(value) {
                    Some(tag) => {
                        self.emit_indent(&format!("mov ecx, {}  ; value type tag", tag));
                    }
                    None => {
                        if let Some(loc) = self.mixed_element_tag_slot(value) {
                            self.emit_indent(&format!(
                                "movzx ecx, byte {}  ; runtime tag of mixed source",
                                loc.operand()
                            ));
                        } else if self.expr_leaves_tag_in_r11(value) {
                            self.emit_indent("mov ecx, r11d  ; forward runtime tag from r11");
                        } else {
                            self.emit_indent("xor ecx, ecx  ; default integer tag");
                        }
                    }
                }
                self.emit_indent("pop rsi  ; key pointer");
                self.emit_indent("pop rdi  ; map pointer");
                self.emit_indent("call _map_insert");
                // Store the (possibly reallocated) map pointer back.
                self.emit_store_back_after_realloc(map, "rax");
            }

            Statement::ListAppend { list, value } => {
                if self.variable_types.get(list) == Some(&VarType::Buffer) {
                    let dst_local = self.get_var(list);
                    let dst_global = self.global_var_label(list).cloned();
                    if dst_local.is_some() || dst_global.is_some() {
                        if !self.emit_copy_expr_into_buffer_slot(value, false, dst_local, dst_global.as_deref()) {
                            self.generate_expr(value);
                            let fmt_spec = self.parse_format_spec(None);
                            if let Some(offset) = dst_local {
                                self.emit_append_runtime_value_to_buffer_slot(offset, self.infer_expr_type(value), fmt_spec);
                            } else if let Some(ref label) = dst_global {
                                self.emit_indent("push rax  ; save source value across destination address load");
                                self.emit_load_named_var_addr(list);
                                self.emit_indent("mov rdi, rax");
                                self.emit_indent("pop rax  ; restore source value");
                                self.emit_append_runtime_value_to_buffer_ptr(self.infer_expr_type(value), fmt_spec);
                                self.emit_indent(&format!("mov [rel {}], rax", label));
                            }
                        }
                        // Top-level/branch-declared buffers live in both a stack
                        // slot and a BSS mirror. Any append that updated the stack
                        // slot must also update the mirror so functions see the
                        // possibly-reallocated pointer.
                        if let Some(offset) = dst_local {
                            self.emit_mirror_stack_var_to_global_if_needed(list, offset);
                        }
                    }
                    return;
                }

                self.uses_lists = true;
                self.emit_indent("; Append value to list");
                
                // Track element type from appended value if not already set
                if self.mixed_lists.contains(list) {
                    self.list_element_types.insert(list.clone(), VarType::Mixed);
                } else if !self.list_element_types.contains_key(list) {
                    let elem_type = match value {
                        Expr::StringLit(_) => VarType::String,
                        Expr::IntegerLit(_) => VarType::Integer,
                        Expr::FloatLit(_) => VarType::Float,
                        Expr::BoolLit(_) => VarType::Boolean,
                        // A type predicate result (and its negation) is a
                        // boolean element, mirroring `BoolLit` so a for-each
                        // variable over a list of predicate results is typed
                        // Boolean and `is a boolean` recognises it (stage 1c).
                        Expr::TypeCheck { .. } => VarType::Boolean,
                        Expr::UnaryOp { op: UnaryOperator::Not, .. } => VarType::Boolean,
                        Expr::Identifier(name) => {
                            // Buffer variables produce string elements when appended
                            match self.variable_types.get(name) {
                                Some(VarType::Buffer) => VarType::String,
                                Some(t) => t.clone(),
                                None => VarType::Unknown,
                            }
                        }
                        _ => VarType::Unknown,
                    };
                    if elem_type != VarType::Unknown {
                        self.list_element_types.insert(list.clone(), elem_type);
                    }
                }
                
                // Resolve list pointer (local slot or global mirror) and save it.
                let list_ptr_loaded = self.emit_load_named_var_addr(list);
                if list_ptr_loaded {
                    self.emit_indent("push rax  ; save list pointer");

                    // Check if the value is a buffer variable
                    let is_buffer_value = match value {
                        Expr::StringLit(name) | Expr::Identifier(name) => {
                            self.variable_types.get(name).map(|t| t == &VarType::Buffer).unwrap_or(false)
                        }
                        _ => false,
                    };

                    // Evaluate value to append
                    self.generate_expr(value);

                    if is_buffer_value {
                        // For buffer values, extract string data and duplicate it.
                        // Bounded by the buffer's own tracked length rather than
                        // scanning for NUL - see _strdup_bounded's comment for why
                        // (buffer content isn't reliably NUL-terminated at its
                        // logical end after a clear+shorter-rewrite).
                        self.uses_strings = true;
                        self.emit_indent("push rbx");
                        self.emit_indent("push r12");
                        self.emit_indent("mov rbx, rax  ; save buffer pointer");
                        self.emit_indent("mov rdi, rbx");
                        self.emit_indent("call _buffer_length");
                        self.emit_indent("mov r12, rax  ; save length");
                        self.emit_indent("mov rdi, rbx");
                        self.emit_indent("call _buffer_data  ; get data pointer");
                        self.emit_indent("mov rdi, rax  ; source string");
                        self.emit_indent("mov rsi, r12  ; max length");
                        self.emit_indent("call _strdup_bounded  ; duplicate string");
                        self.emit_indent("pop r12");
                        self.emit_indent("pop rbx");
                    }

                    self.emit_indent("push rax  ; save value to append");

                    // rdi = list pointer, rsi = value to append, dl = type tag
                    match self.emit_time_expr_tag(value) {
                        Some(tag) => {
                            self.emit_indent(&format!(
                                "mov edx, {}  ; element type tag",
                                tag
                            ));
                        }
                        None => {
                            // Mixed-typed source variable: forward its
                            // runtime tag from the shadow slot.
                            if let Some(loc) = self.mixed_element_tag_slot(value) {
                                self.emit_indent(&format!(
                                    "movzx edx, byte {}  ; runtime tag of mixed source",
                                    loc.operand()
                                ));
                            } else if self.expr_leaves_tag_in_r11(value) {
                                // A freshly-read mixed element or a value-returning
                                // function call left its tag in r11 — forward it
                                // instead of dropping it (which previously mis-
                                // tagged appended mixed elements as integers).
                                self.emit_indent("mov edx, r11d  ; forward runtime tag from r11");
                            } else {
                                self.emit_indent("xor edx, edx  ; default integer tag");
                            }
                        }
                    }
                    self.emit_indent("pop rsi  ; value to append");
                    self.emit_indent("pop rdi  ; list ptr");
                    self.emit_indent("call _list_append");

                    // Store potentially new list pointer back to wherever it came from
                    self.emit_store_back_after_realloc(list, "rax");
                }
            }

            Statement::BufferCopy { source, destination } => {
                let dst_local = self.get_var(destination);
                let dst_global = self.global_var_label(destination).cloned();
                if dst_local.is_some() || dst_global.is_some() {
                    if !self.emit_copy_expr_into_buffer_slot(source, true, dst_local, dst_global.as_deref()) {
                        // Fallback for non-buffer source expressions.
                        // Load destination pointer into rdi, clear it, then append.
                        self.emit_load_named_var_addr(destination);
                        self.emit_indent("mov rdi, rax  ; destination buffer");
                        self.emit_indent("push rdi");
                        self.emit_indent("call _buffer_clear");
                        self.emit_indent("mov rdi, rax");
                        self.emit_indent("push rdi");
                        self.generate_expr(source);
                        let src_type = self.infer_expr_type(source);
                        let fmt_spec = self.parse_format_spec(None);
                        self.emit_append_runtime_value_to_buffer_ptr(src_type, fmt_spec);
                        self.emit_indent("pop rdi  ; original destination buffer pointer");
                        if let Some(offset) = dst_local {
                            self.emit_indent(&format!("mov [rbp-{}], rax  ; updated destination pointer", offset));
                        } else if let Some(ref label) = dst_global {
                            self.emit_indent(&format!("mov [rel {}], rax  ; updated destination pointer", label));
                        }
                    }
                    // Mirror any stack-slot update back to the global BSS copy so
                    // functions see the (possibly reallocated) buffer pointer.
                    if let Some(offset) = dst_local {
                        self.emit_mirror_stack_var_to_global_if_needed(destination, offset);
                    }
                }
            }

            Statement::BufferClear { name } => {
                self.uses_buffers = true;
                self.emit_indent("; Clear buffer contents");
                self.emit_load_named_var_addr(name);
                self.emit_indent("mov rdi, rax  ; buffer");
                self.emit_indent("call _buffer_clear");
                if let Some(offset) = self.get_var(name) {
                    self.emit_indent(&format!("mov [rbp-{}], rax  ; buffer (unchanged pointer)", offset));
                    self.emit_mirror_stack_var_to_global_if_needed(name, offset);
                } else if let Some(label) = self.global_var_label(name).cloned() {
                    self.emit_indent(&format!("mov [rel {}], rax  ; buffer (unchanged pointer)", label));
                }
            }
            
            Statement::FileOpen { name, path, mode } => {
                self.uses_files = true;
                self.declared_types.insert(name.clone(), Type::File);
                let path_is_fd = self.is_fd_path_expr(path);
                
                // Track if file is writable based on mode
                let is_writable = matches!(mode, FileMode::Writing | FileMode::Appending);
                self.file_writable.insert(name.clone(), is_writable);

                // Reuse the existing slot when the handle name is already
                // known, exactly like VarDecl reassignment. Two Opens of the
                // same name in an if/otherwise pair must share one slot -
                // separate slots meant code after the branch read whichever
                // slot the LAST-generated branch owned, which the branch
                // actually taken at runtime never wrote.
                let offset = if let Some(existing) = self.get_var(name) {
                    existing
                } else {
                    self.alloc_var(name)
                };

                if path_is_fd {
                    let fd_ok_label = self.new_label("fd_ok");
                    let fd_invalid_label = self.new_label("fd_invalid");
                    let fd_done_label = self.new_label("fd_done");

                    self.generate_expr(path);
                    self.emit_indent("; Treat numeric open path as file descriptor");
                    self.emit_indent("cmp rax, 0");
                    self.emit_indent(&format!("jl {}", fd_invalid_label));
                    self.emit_indent("mov rcx, 2147483647  ; i32::MAX");
                    self.emit_indent("cmp rax, rcx");
                    self.emit_indent(&format!("jle {}", fd_ok_label));
                    self.emit_indent(&format!("jmp {}", fd_invalid_label));

                    self.emit(&format!("{}:", fd_ok_label));
                    self.emit_indent(&format!("mov [rbp-{}], rax  ; borrowed file descriptor", offset));
                    self.emit_indent("mov qword [rel _last_error], 0");
                    self.emit_indent(&format!("jmp {}", fd_done_label));

                    self.emit(&format!("{}:", fd_invalid_label));
                    self.emit_indent(&format!("mov qword [rbp-{}], -1  ; invalid fd", offset));
                    self.emit_indent("mov qword [rel _last_error], 22  ; EINVAL");

                    self.emit(&format!("{}:", fd_done_label));
                    self.emit_mirror_stack_var_to_global_if_needed(name, offset);
                    return;
                }

                // Generate path pointer for filesystem opens
                match path {
                    Expr::StringLit(s) => {
                        let label = self.add_string(s);
                        self.emit_indent(&format!("lea rdi, [rel {}]", label));
                    }
                    _ => {
                        self.generate_cstr_expr(path);
                        self.emit_indent("mov rdi, rax  ; path pointer");
                    }
                }
                
                // Open file with appropriate mode (path is in rdi)
                match mode {
                    FileMode::Reading => {
                        self.emit_indent("FILE_OPEN_READ rdi");
                    }
                    FileMode::Writing => {
                        self.emit_indent("FILE_OPEN_WRITE rdi");
                    }
                    FileMode::Appending => {
                        self.emit_indent("FILE_OPEN_APPEND rdi");
                    }
                }
                
                // Store file descriptor and register for tracking (only if valid)
                self.emit_indent(&format!("mov [rbp-{}], rax  ; file descriptor", offset));
                
                // Check for error (negative fd) and set _last_error
                let ok_label = self.new_label("file_ok");
                let done_label = self.new_label("file_done");
                self.emit_indent("test rax, rax");
                self.emit_indent(&format!("jns {}  ; jump if success (non-negative)", ok_label));
                
                // Error path: set _last_error
                self.emit_indent("neg rax  ; convert to positive errno");
                self.emit_indent("mov [rel _last_error], rax");
                self.emit_indent(&format!("jmp {}", done_label));
                
                // Success path: register fd for cleanup
                self.emit(&format!("{}:", ok_label));
                self.emit_indent("mov qword [rel _last_error], 0  ; clear error");
                self.emit_indent("mov rdi, rax");
                self.emit_indent("call _register_fd  ; track for auto-cleanup");
                
                self.emit(&format!("{}:", done_label));
                self.emit_mirror_stack_var_to_global_if_needed(name, offset);
            }
            
            Statement::FileRead { source, buffer } => {
                let source_fd = if source == "stdin" {
                    "0".to_string()  // STDIN
                } else if let Some(offset) = self.get_var(source) {
                    format!("[rbp-{}]", offset)
                } else if let Some(label) = self.global_var_label(source).cloned() {
                    format!("[rel {}]", label)
                } else {
                    "0".to_string()
                };

                let skip_label = self.new_label("skip_fd");
                self.emit_indent(&format!("mov rdi, {}", source_fd));
                // Skip read if fd is invalid (negative)
                self.emit_indent("test rdi, rdi");
                self.emit_indent(&format!("js {}  ; skip if invalid fd", skip_label));
                if self.emit_load_named_var_addr(buffer) {
                    self.emit_indent("mov rsi, rax  ; buffer struct");
                    // Reset buffer length before reading (read replaces, not appends)
                    self.emit_indent("mov qword [rsi + 8], 0  ; reset buffer length");
                    self.emit_indent("call _read_into_buffer  ; auto-grows if needed");
                    // Update buffer pointer (may have changed if grown)
                    self.emit_store_back_after_realloc(buffer, "rsi");
                }
                self.emit(&format!("{}:", skip_label));
            }

            Statement::FileReadLine { source, buffer } => {
                let source_fd = if source == "stdin" {
                    "0".to_string()
                } else if let Some(offset) = self.get_var(source) {
                    format!("[rbp-{}]", offset)
                } else if let Some(label) = self.global_var_label(source).cloned() {
                    format!("[rel {}]", label)
                } else {
                    "0".to_string()
                };

                let skip_label = self.new_label("skip_fd");
                let done_label = self.new_label("readline_done");
                self.emit_indent(&format!("mov rdi, {}", source_fd));
                self.emit_indent("test rdi, rdi");
                self.emit_indent(&format!("js {}  ; skip if invalid fd", skip_label));
                if self.emit_load_named_var_addr(buffer) {
                    self.emit_indent("mov rsi, rax  ; buffer struct");
                    self.emit_indent("mov qword [rsi + 8], 0  ; reset buffer length");
                    self.emit_indent("call _read_line_into_buffer");
                    // _read_line_into_buffer already sets _last_error (1=EOF, 2=read error)
                    // Update buffer pointer (may have changed if grown)
                    self.emit_store_back_after_realloc(buffer, "rsi");
                }
                self.emit_indent(&format!("jmp {}", done_label));
                self.emit(&format!("{}:", skip_label));
                // Invalid fd is an error - make On error fire
                self.emit_indent("mov qword [rel _last_error], 1");
                self.emit(&format!("{}:", done_label));
            }

            Statement::FileSeekLine { file, line } => {
                self.uses_files = true;

                let file_fd = if let Some(offset) = self.get_var(file) {
                    format!("[rbp-{}]", offset)
                } else if let Some(label) = self.global_var_label(file).cloned() {
                    format!("[rel {}]", label)
                } else {
                    "0".to_string()
                };

                self.generate_expr(line);
                self.emit_indent("mov rsi, rax  ; target line (1-indexed)");
                self.emit_indent(&format!("mov rdi, {}", file_fd));
                self.emit_indent("call _seek_fd_line");
                // _seek_fd_line sets _last_error on failure and returns -1.
                // Ensure _last_error is cleared on success so On error doesn't
                // fire spuriously.
                let ok_label = self.new_label("seek_line_ok");
                let done_label = self.new_label("seek_line_done");
                self.emit_indent("test rax, rax");
                self.emit_indent(&format!("jns {}", ok_label));
                // Already set by _seek_fd_line, but ensure non-zero
                self.emit_indent("mov qword [rel _last_error], 1");
                self.emit_indent(&format!("jmp {}", done_label));
                self.emit(&format!("{}:", ok_label));
                self.emit_indent("mov qword [rel _last_error], 0");
                self.emit(&format!("{}:", done_label));
            }

            Statement::FileSeekByte { file, byte } => {
                self.uses_files = true;

                let file_fd = if let Some(offset) = self.get_var(file) {
                    format!("[rbp-{}]", offset)
                } else if let Some(label) = self.global_var_label(file).cloned() {
                    format!("[rel {}]", label)
                } else {
                    "0".to_string()
                };

                self.generate_expr(byte);
                self.emit_indent("mov rsi, rax  ; target byte (1-indexed)");
                self.emit_indent(&format!("mov rdi, {}", file_fd));
                self.emit_indent("call _seek_fd_byte");
                // _seek_fd_byte sets _last_error on failure and returns -1.
                let ok_label = self.new_label("seek_byte_ok");
                let done_label = self.new_label("seek_byte_done");
                self.emit_indent("test rax, rax");
                self.emit_indent(&format!("jns {}", ok_label));
                self.emit_indent("mov qword [rel _last_error], 1");
                self.emit_indent(&format!("jmp {}", done_label));
                self.emit(&format!("{}:", ok_label));
                self.emit_indent("mov qword [rel _last_error], 0");
                self.emit(&format!("{}:", done_label));
            }
            
            Statement::FileWrite { file, value } => {
                // Get file fd
                let file_fd = if let Some(offset) = self.get_var(file) {
                    format!("[rbp-{}]", offset)
                } else if let Some(label) = self.global_var_label(file).cloned() {
                    format!("[rel {}]", label)
                } else {
                    "1".to_string()  // STDOUT as fallback
                };
                
                let skip_label = self.new_label("skip_fd");
                self.emit_indent(&format!("mov rdi, {}", file_fd));
                // Skip write if fd is invalid (negative)
                self.emit_indent("test rdi, rdi");
                self.emit_indent(&format!("js {}  ; skip if invalid fd", skip_label));
                
                match value {
                    Expr::StringLit(s) => {
                        let label = self.add_string(s);
                        self.emit_indent(&format!("FILE_WRITE_STR rdi, {}", label));
                    }
                    Expr::Identifier(name) => {
                        if let Some(offset) = self.get_var(name) {
                            let var_type = self.variable_types.get(name).cloned();
                            self.emit_indent(&format!("mov rsi, [rbp-{}]", offset));
                            if matches!(var_type, Some(VarType::Buffer)) {
                                self.emit_indent("FILE_WRITE_BUF rdi, rsi");
                            } else {
                                self.emit_indent("FILE_WRITE_STR rdi, rsi");
                            }
                        } else if let Some(label) = self.global_var_label(name).cloned() {
                            let var_type = self.variable_types.get(name).cloned();
                            self.emit_indent(&format!("mov rsi, [rel {}]", label));
                            if matches!(var_type, Some(VarType::Buffer)) {
                                self.emit_indent("FILE_WRITE_BUF rdi, rsi");
                            } else {
                                self.emit_indent("FILE_WRITE_STR rdi, rsi");
                            }
                        }
                    }
                    Expr::TreatingAs { value: inner_val, match_value, replacement } => {
                        // Check if inner value is a buffer
                        let is_buffer = if let Expr::Identifier(ref name) = **inner_val {
                            self.variable_types.get(name) == Some(&VarType::Buffer)
                        } else {
                            false
                        };
                        
                        if is_buffer {
                            // For buffers, we need different write macros for match vs no-match
                            let skip_label = self.new_label("treating_skip");
                            let done_label = self.new_label("treating_done");
                            
                            self.emit_indent("push rdi");  // save fd
                            
                            // Generate buffer value
                            self.generate_expr(inner_val);
                            self.emit_indent("push rax  ; save buffer struct ptr");
                            
                            // Get the buffer's tracked length and data pointer.
                            // Use _mem_eq rather than _str_eq to avoid the stale-byte
                            // bug: the buffer's data area may not be NUL-terminated at
                            // its logical end after a clear+shorter-rewrite.
                            self.emit_indent("mov rdi, rax");
                            self.emit_indent("call _buffer_length");
                            self.emit_indent("mov rdx, rax  ; len1 = buf length");
                            self.emit_indent("mov rdi, [rsp]  ; reload buf struct ptr");
                            self.emit_indent("call _buffer_data");
                            self.emit_indent("mov rdi, rax  ; ptr1 = buf data");
                            self.generate_expr(match_value);
                            self.emit_indent("mov rsi, rax  ; ptr2 = match string");
                            self.emit_indent("push rdi      ; save ptr1 across str_len call");
                            self.emit_indent("push rsi      ; save ptr2");
                            self.emit_indent("push rdx      ; save len1");
                            self.emit_indent("mov rdi, rsi");
                            self.emit_indent("call _str_len");
                            self.emit_indent("mov rcx, rax  ; len2 = match string len");
                            self.emit_indent("pop rdx       ; restore len1");
                            self.emit_indent("pop rsi       ; restore ptr2");
                            self.emit_indent("pop rdi       ; restore ptr1");
                            self.emit_indent("call _mem_eq");
                            self.emit_indent("test rax, rax");
                            self.emit_indent(&format!("jz {}", skip_label));
                            
                            // Match: write replacement string
                            self.emit_indent("add rsp, 8  ; discard buffer ptr");
                            self.emit_indent("pop rdi  ; restore fd");
                            self.generate_expr(replacement);
                            self.emit_indent("FILE_WRITE_STR rdi, rax");
                            self.emit_indent(&format!("jmp {}", done_label));
                            
                            // No match: write original buffer
                            self.emit(&format!("{}:", skip_label));
                            self.emit_indent("pop rsi  ; restore buffer ptr");
                            self.emit_indent("pop rdi  ; restore fd");
                            self.emit_indent("FILE_WRITE_BUF rdi, rsi");
                            
                            self.emit(&format!("{}:", done_label));
                        } else {
                            // For non-buffers, use standard treating logic
                            self.emit_indent("push rdi");  // save fd
                            self.generate_expr(value);
                            self.emit_indent("mov rsi, rax");
                            self.emit_indent("pop rdi");   // restore fd
                            self.emit_indent("FILE_WRITE_STR rdi, rsi");
                        }
                    }
                    _ => {
                        // For other expressions, generate and write
                        self.emit_indent("push rdi");  // save fd
                        self.generate_expr(value);
                        self.emit_indent("pop rdi");   // restore fd
                        self.emit_indent("FILE_WRITE_STR rdi, rax");
                    }
                }
                self.emit(&format!("{}:", skip_label));
            }
            
            Statement::FileWriteNewline { file } => {
                let file_fd = if let Some(offset) = self.get_var(file) {
                    format!("[rbp-{}]", offset)
                } else {
                    "1".to_string()
                };
                let skip_label = self.new_label("skip_fd");
                self.emit_indent(&format!("mov rdi, {}", file_fd));
                // Skip write if fd is invalid (negative)
                self.emit_indent("test rdi, rdi");
                self.emit_indent(&format!("js {}  ; skip if invalid fd", skip_label));
                self.emit_indent("FILE_WRITE_NEWLINE rdi");
                self.emit(&format!("{}:", skip_label));
            }
            
            Statement::FileClose { file } => {
                if let Some(offset) = self.get_var(file) {
                    let skip_label = self.new_label("skip_fd");
                    self.emit_indent(&format!("mov rdi, [rbp-{}]", offset));
                    // Skip close if fd is invalid (negative)
                    self.emit_indent("test rdi, rdi");
                    self.emit_indent(&format!("js {}  ; skip if invalid fd", skip_label));
                    self.emit_indent("call _unregister_fd  ; remove from tracking");
                    self.emit_indent(&format!("mov rdi, [rbp-{}]", offset));
                    self.emit_indent("FILE_CLOSE rdi");
                    self.emit(&format!("{}:", skip_label));
                }
            }
            
            Statement::FileDelete { path } => {
                self.uses_files = true;
                match path {
                    Expr::StringLit(s) => {
                        let label = self.add_string(s);
                        self.emit_indent(&format!("FILE_DELETE {}", label));
                    }
                    _ => {
                        self.generate_cstr_expr(path);
                        self.emit_indent("FILE_DELETE rax");
                    }
                }
            }

            Statement::Rmdir { path } => {
                self.uses_files = true;
                match path {
                    Expr::StringLit(s) => {
                        let label = self.add_string(s);
                        self.emit_indent(&format!("RMDIR {}", label));
                    }
                    _ => {
                        self.generate_cstr_expr(path);
                        self.emit_indent("RMDIR rax");
                    }
                }
            }

            Statement::Mkdir { path } => {
                self.uses_files = true;
                match path {
                    Expr::StringLit(s) => {
                        let label = self.add_string(s);
                        self.emit_indent(&format!("MKDIR {}", label));
                    }
                    _ => {
                        self.generate_cstr_expr(path);
                        self.emit_indent("MKDIR rax");
                    }
                }
            }

            Statement::Chdir { path } => {
                self.uses_files = true;
                match path {
                    Expr::StringLit(s) => {
                        let label = self.add_string(s);
                        self.emit_indent(&format!("CHDIR {}", label));
                    }
                    _ => {
                        self.generate_cstr_expr(path);
                        self.emit_indent("CHDIR rax");
                    }
                }
            }

            Statement::Mount { source, target, fstype, options } => {
                self.uses_files = true;

                // Detect the "move"/"bind" pseudo-mount pattern used for
                // relocating already-mounted filesystems to a new root
                // (fstype "none" + options "move"/"bind"): for these, the
                // real mount(2) syscall wants a NULL filesystemtype and
                // NULL data, with the operation encoded entirely in flags.
                let is_none_fstype = matches!(fstype, Expr::StringLit(s) if s == "none");
                let move_flag = matches!(options, Some(Expr::StringLit(s)) if s == "move");
                let bind_flag = matches!(options, Some(Expr::StringLit(s)) if s == "bind");
                let flags: i64 = if is_none_fstype && move_flag {
                    8192 // MS_MOVE
                } else if is_none_fstype && bind_flag {
                    4096 // MS_BIND
                } else {
                    0
                };
                let suppress_fstype_and_data = is_none_fstype && (move_flag || bind_flag);

                // Park each evaluated argument on the stack so later
                // expressions (function calls, format strings) cannot
                // clobber earlier results, then pop into the syscall
                // registers in reverse order.
                self.generate_cstr_expr(source);
                self.emit_indent("push rax  ; park source");

                self.generate_cstr_expr(target);
                self.emit_indent("push rax  ; park target");

                // fstype (NULL for move/bind pseudo-mounts)
                if suppress_fstype_and_data {
                    self.emit_indent("xor rax, rax  ; fstype = NULL (move/bind)");
                } else {
                    self.generate_cstr_expr(fstype);
                }
                self.emit_indent("push rax  ; park fstype");

                // options/data (NULL for move/bind pseudo-mounts, or if omitted)
                if suppress_fstype_and_data {
                    self.emit_indent("xor rax, rax  ; data = NULL (move/bind)");
                } else {
                    match options {
                        None => self.emit_indent("xor rax, rax  ; data = NULL (no options given)"),
                        Some(expr) => self.generate_cstr_expr(expr),
                    }
                }
                self.emit_indent("push rax  ; park data (options)");

                // NOTE: raw `syscall` uses r10 for arg4, NOT rcx (rcx/r11
                // get clobbered by the syscall instruction itself) -
                // matches the convention already established by the
                // existing MMAP macro in this file.
                self.emit_indent("pop r8   ; data (options)");
                self.emit_indent("pop rdx  ; fstype");
                self.emit_indent("pop rsi  ; target");
                self.emit_indent("pop rdi  ; source");
                self.emit_indent(&format!("mov r10, {}  ; mount flags", flags));
                self.emit_indent("MOUNT");
            }

            Statement::Shutdown => {
                self.uses_files = true;
                self.emit_indent("REBOOT_CMD 0x4321FEDC  ; LINUX_REBOOT_CMD_POWER_OFF");
            }

            Statement::Reboot => {
                self.uses_files = true;
                self.emit_indent("REBOOT_CMD 0x01234567  ; LINUX_REBOOT_CMD_RESTART");
            }

            Statement::Halt => {
                self.uses_files = true;
                self.emit_indent("REBOOT_CMD 0xCDEF0123  ; LINUX_REBOOT_CMD_HALT");
            }

            Statement::Unmount { target, lazy } => {
                self.uses_files = true;
                self.generate_cstr_expr(target);
                self.emit_indent("mov rdi, rax  ; mount target");
                let flags = if *lazy { 2 } else { 0 }; // MNT_DETACH = 2
                self.emit_indent(&format!(
                    "mov rsi, {}  ; flags{}",
                    flags,
                    if *lazy { " (MNT_DETACH)" } else { "" }
                ));
                self.emit_indent("UMOUNT");
            }

            Statement::PivotRoot { new_root, put_old } => {
                self.uses_files = true;
                self.emit_syscall_args(&[(new_root, "rdi"), (put_old, "rsi")]);
                self.emit_indent("PIVOT_ROOT");
            }

            Statement::Execute { path, args } => {
                self.uses_files = true;

                // A list variable (or any non-literal list expression):
                // argv is built at runtime by _list_to_argv, which sizes the
                // allocation and bounds the copy from a single read of the
                // list's length - the array cannot be overrun.
                let elements: &[Expr] = match args {
                    Expr::ListLit { elements } => elements,
                    other => {
                        self.uses_lists = true;
                        self.generate_expr(other);
                        self.emit_indent("push rax  ; park list pointer");
                        match path {
                            Expr::StringLit(s) => {
                                let label = self.add_string(s);
                                self.emit_indent(&format!("lea rax, [rel {}]", label));
                            }
                            _ => self.generate_cstr_expr(path),
                        }
                        self.emit_indent("mov rsi, rax  ; path (becomes argv[0])");
                        self.emit_indent("pop rdi  ; list pointer");
                        self.emit_indent("call _list_to_argv");
                        self.emit_indent("mov rsi, rax  ; argv array pointer");
                        self.emit_indent("mov rdi, [rsi]  ; path = argv[0]");
                        self.emit_indent("mov rdx, [rel _envp]  ; inherit the real environment");
                        self.emit_indent("EXECVE");
                        return;
                    }
                };

                let slot_count = elements.len() + 2; // path + args + NULL terminator
                let total_size = slot_count * 8;

                // Allocate the argv array via mmap (same pattern as list
                // literals elsewhere in this file), but WITHOUT the normal
                // Vox-list header - execve needs a plain C-style array.
                self.emit_indent("; Build argv array for execve");
                self.emit_indent("mov rdi, 0  ; addr = NULL");
                self.emit_indent(&format!("mov rsi, {}  ; size", total_size));
                self.emit_indent("mov rdx, 3  ; PROT_READ | PROT_WRITE");
                self.emit_indent("mov r10, 0x22  ; MAP_PRIVATE | MAP_ANONYMOUS");
                self.emit_indent("mov r8, -1  ; fd = -1");
                self.emit_indent("mov r9, 0  ; offset = 0");
                self.emit_indent("mov rax, 9  ; sys_mmap");
                self.emit_indent("syscall");
                let mmap_ok = self.new_label("execve_argv_mmap_ok");
                self.emit_indent("cmp rax, -4096  ; raw mmap returns -errno in [-4095,-1]");
                self.emit_indent(&format!("jbe {}", mmap_ok));
                self.emit_indent("mov rdi, 1");
                self.emit_indent("mov rax, 60");
                self.emit_indent("syscall");
                self.emit(&format!("{}:", mmap_ok));
                self.emit_indent("push rax  ; save argv array pointer");

                // Slot 0: path (also argv[0] by convention)
                match path {
                    Expr::StringLit(s) => {
                        let label = self.add_string(s);
                        self.emit_indent(&format!("mov rbx, {}", label));
                    }
                    _ => {
                        self.generate_cstr_expr(path);
                        self.emit_indent("mov rbx, rax");
                    }
                }
                self.emit_indent("mov rax, [rsp]  ; peek argv array pointer");
                self.emit_indent("mov [rax], rbx  ; argv[0] = path");

                // Slots 1..n: the rest of the arguments
                for (i, elem) in elements.iter().enumerate() {
                    match elem {
                        Expr::StringLit(s) => {
                            let label = self.add_string(s);
                            self.emit_indent(&format!("mov rbx, {}", label));
                        }
                        _ => {
                            self.generate_cstr_expr(elem);
                            self.emit_indent("mov rbx, rax");
                        }
                    }
                    self.emit_indent("mov rax, [rsp]  ; peek argv array pointer");
                    self.emit_indent(&format!("mov [rax+{}], rbx  ; argv[{}]", (i + 1) * 8, i + 1));
                }

                // Final slot: NULL terminator
                self.emit_indent("pop rax  ; argv array pointer");
                self.emit_indent(&format!("mov qword [rax+{}], 0  ; argv NULL terminator", (elements.len() + 1) * 8));

                // path -> rdi (argv[0], reloaded from the array, not re-generated)
                self.emit_indent("mov rsi, rax  ; argv array pointer");
                self.emit_indent("mov rdi, [rsi]  ; path = argv[0]");
                self.emit_indent("mov rdx, [rel _envp]  ; inherit the real environment");
                self.emit_indent("EXECVE");
            }

            Statement::SendSignal { signal, pid } => {
                self.uses_files = true;
                // kill(2): rdi = pid, rsi = signal. Evaluate both operands
                // through the stack-parking helper so a later expression
                // (function call, format string) cannot clobber an earlier
                // result while the syscall registers are being loaded.
                self.emit_syscall_args(&[(pid, "rdi"), (signal, "rsi")]);
                self.emit_indent("SEND_SIGNAL");
            }

            Statement::Symlink { target, linkpath } => {
                self.uses_files = true;
                self.emit_syscall_args(&[(target, "rdi"), (linkpath, "rsi")]);
                self.emit_indent("SYMLINK");
            }

            Statement::Mknod { path, node_type, major, minor } => {
                self.uses_files = true;

                // Path -> rdi
                match path {
                    Expr::StringLit(s) => {
                        let label = self.add_string(s);
                        self.emit_indent(&format!("lea rdi, [rel {}]", label));
                    }
                    _ => {
                        self.generate_cstr_expr(path);
                        self.emit_indent("mov rdi, rax  ; path pointer");
                    }
                }
                self.emit_indent("push rdi  ; save path pointer");

                // Mode = S_IFCHR|S_IFBLK|S_IFIFO + 0666 permissions -> rsi
                // S_IFCHR = 0o020000 = 8192, S_IFBLK = 0o060000 = 24576,
                // S_IFIFO = 0o010000 = 4096, 0666 = 438
                let mode = match node_type {
                    DeviceNodeType::Character => 8192 + 438,
                    DeviceNodeType::Block => 24576 + 438,
                    DeviceNodeType::Fifo => 4096 + 438,
                };

                // dev = (major << 8) | minor -> rdx
                self.generate_expr(major);
                self.emit_indent("push rax  ; save major");
                self.generate_expr(minor);
                self.emit_indent("mov rcx, rax  ; minor");
                self.emit_indent("pop rax  ; major");
                self.emit_indent("shl rax, 8");
                self.emit_indent("or rax, rcx");
                self.emit_indent("mov rdx, rax  ; dev = (major << 8) | minor");

                self.emit_indent(&format!("mov rsi, {}  ; mode", mode));
                self.emit_indent("pop rdi  ; restore path pointer");
                self.emit_indent("MKNOD");
            }

            Statement::OnError { actions } => {
                // Check if last operation had an error
                let skip_label = self.new_label("skip_error");
                self.emit_indent("mov rax, [rel _last_error]");
                self.emit_indent("test rax, rax");
                self.emit_indent(&format!("jz {}  ; skip if no error", skip_label));
                
                // Execute all error actions
                for action in actions {
                    self.generate_statement(action);
                }
                
                // Clear the error
                self.emit_indent("mov qword [rel _last_error], 0");
                
                self.emit(&format!("{}:", skip_label));
            }
            
            Statement::BufferResize { name, new_size } => {
                if self.emit_load_named_var_addr(name) {
                    self.emit_indent("mov rdi, rax  ; buffer pointer");
                    self.generate_expr(new_size);
                    self.emit_indent("mov rsi, rax  ; new size");
                    self.emit_indent("call _realloc_buffer");
                    self.emit_store_back_after_realloc(name, "rax");
                }
            }
            
            Statement::LibraryDecl { name, version } => {
                // A `Library` declaration sets the codegen's current library
                // identity. Every `FunctionDef` and intra-library call site
                // after this point resolves its label through it (in shared
                // mode), so the exported symbol becomes `<lib>_<ver>_<func>`.
                // `collect_library_identity` already stashed the first
                // declaration before generation began, so a forward call to a
                // function defined above this line still mangles correctly;
                // re-setting here keeps the identity current as the walk
                // passes each declaration (matters once A2 concatenates
                // several libraries into one unit).
                self.current_library = Some((name.clone(), version.clone()));
                self.emit(&format!("; Library: {} version {}", name, version));
            }
            
            Statement::See { path, lib_name, lib_version } => {
                // See statement - emit as comment for now
                // The actual file inclusion is handled by the compiler frontend
                let lib_info = match (lib_name, lib_version) {
                    (Some(n), Some(v)) => format!(" (library: {} version {})", n, v),
                    (Some(n), None) => format!(" (library: {})", n),
                    _ => String::new(),
                };
                self.emit(&format!("; See: {}{}", path, lib_info));
            }
            
            // Time and Timer statements
            Statement::TimerDecl { name } => {
                self.uses_time = true;
                self.declared_types.insert(name.clone(), Type::Timer);
                // Allocate the 8-byte name slot; the timer struct itself needs
                // TIMER_SIZE (56) bytes below it. Account for the full struct in
                // the frame size so later variables do not overlap the timer.
                let offset = self.alloc_var(name);
                self.variable_types.insert(name.clone(), VarType::Integer); // Track as integer for now
                self.stack_offset = std::cmp::max(self.stack_offset, offset + 48);
                self.emit_indent(&format!("; Timer declaration: {}", name));
                self.emit_indent(&format!("lea rax, [rbp - {}]", offset + 48)); // Point to timer area
                self.emit_indent("TIMER_INIT rax");
            }
            
            Statement::TimerStart { name } => {
                self.uses_time = true;
                if let Some(offset) = self.get_var(name) {
                    self.emit_indent(&format!("; Start timer: {}", name));
                    self.emit_indent(&format!("lea rax, [rbp - {}]", offset + 48));
                    self.emit_indent("TIMER_START rax");
                }
            }
            
            Statement::TimerStop { name } => {
                self.uses_time = true;
                if let Some(offset) = self.get_var(name) {
                    self.emit_indent(&format!("; Stop timer: {}", name));
                    self.emit_indent(&format!("lea rax, [rbp - {}]", offset + 48));
                    self.emit_indent("TIMER_STOP rax");
                }
            }
            
            Statement::Wait { duration, unit } => {
                self.uses_time = true;
                self.emit_indent("; Wait/Sleep");
                self.generate_expr(duration);
                match unit {
                    TimeUnit::Seconds => {
                        self.emit_indent("SLEEP_SECONDS rax");
                    }
                    TimeUnit::Milliseconds => {
                        self.emit_indent("SLEEP_MILLISECONDS rax");
                    }
                }
            }
            
            Statement::GetTime { into } => {
                self.uses_time = true;
                // Get current unix time and store in variable
                let offset = self.alloc_var(into);
                self.variable_types.insert(into.clone(), VarType::Integer);
                self.emit_indent(&format!("; Get current time into: {}", into));
                self.emit_indent("TIME_GET");
                self.emit_indent(&format!("mov [rbp - {}], rax", offset));
            }
        }
    }

    fn generate_condition(&mut self, condition: &Expr, false_label: &str) {
        match condition {
            Expr::PropertyCheck { value, property } => {
                self.generate_expr(value);
                match property {
                    Property::Even => {
                        self.emit_indent("test rax, 1");
                        self.emit_indent(&format!("jnz {}", false_label));
                    }
                    Property::Odd => {
                        self.emit_indent("test rax, 1");
                        self.emit_indent(&format!("jz {}", false_label));
                    }
                    Property::Zero => {
                        self.emit_indent("test rax, rax");
                        self.emit_indent(&format!("jnz {}", false_label));
                    }
                    Property::Positive => {
                        self.emit_indent("cmp rax, 0");
                        self.emit_indent(&format!("jle {}", false_label));
                    }
                    Property::Negative => {
                        self.emit_indent("cmp rax, 0");
                        self.emit_indent(&format!("jge {}", false_label));
                    }
                    Property::Empty => {
                        // Twin of the expression form in expr.rs - see the
                        // comment there. Buffers/lists test their length;
                        // a text tests its first byte, since its pointer is
                        // never null and `"" is empty` was always false
                        // (docs/BUGS_FOUND.md #33). A string literal is
                        // data, never a name, so it always takes the text
                        // path.
                        let is_buffer_or_list = match value.as_ref() {
                            Expr::Identifier(s) => {
                                matches!(self.variable_types.get(s), Some(VarType::Buffer) | Some(VarType::List))
                            }
                            _ => false,
                        };
                        let is_text = match value.as_ref() {
                            Expr::StringLit(_) => true,
                            Expr::Identifier(s) => {
                                matches!(self.variable_types.get(s), Some(VarType::String))
                            }
                            _ => false,
                        };
                        if is_buffer_or_list {
                            self.emit_indent("mov rax, [rax + 8]  ; get size/length");
                        } else if is_text {
                            let label = self.get_empty_string_label();
                            self.emit_indent(&format!("lea rcx, [rel {}]  ; \"\" stands in for a null text", label));
                            self.emit_indent("test rax, rax");
                            self.emit_indent("cmovz rax, rcx");
                            self.emit_indent("movzx rax, byte [rax]  ; first byte: NUL means empty");
                        }
                        self.emit_indent("test rax, rax");
                        self.emit_indent(&format!("jnz {}", false_label));
                    }
                }
            }

            // Runtime type predicate (stage 1c) — branch form: jump to
            // false_label when the predicate is false. Folds statically; a
            // statically-true predicate falls through (no jump), a
            // statically-false one jumps straight to false_label.
            Expr::TypeCheck { value, type_noun } => {
                let target = type_to_tag(type_noun).expect("type predicate noun is scalar");
                let noun = type_noun_name(type_noun);
                match self.predicate_static_tag(value) {
                    Some(t) => {
                        if t != target {
                            self.emit_indent(&format!(
                                "jmp {}  ; is a {} statically false (static tag {})",
                                false_label, noun, t
                            ));
                        }
                        // t == target: statically true -> fall through to then.
                    }
                    None => {
                        self.generate_expr(value);
                        match self.runtime_tag_source(value) {
                            Some(src) => {
                                if let Some(operand) = src.shadow_operand() {
                                    self.emit_indent(&format!(
                                        "movzx r11, byte {}  ; load mixed element tag",
                                        operand
                                    ));
                                }
                                self.emit_indent(&format!(
                                    "cmp r11, {}  ; is a {}?", target, noun
                                ));
                                self.emit_indent(&format!(
                                    "jne {}  ; not a {}", false_label, noun
                                ));
                            }
                            // No tag to compare (see the value form above).
                            None if target != TAG_INTEGER => {
                                self.emit_indent(&format!(
                                    "jmp {}  ; is a {}: no runtime tag, treated as number",
                                    false_label, noun
                                ));
                            }
                            None => {}
                        }
                    }
                }
            }

            Expr::FileAvailable { path } => {
                self.uses_files = true;
                self.generate_cstr_expr(path);
                self.emit_indent("FILE_AVAILABLE");
                self.emit_indent("test rax, rax");
                self.emit_indent(&format!("jz {}", false_label));
            }

            Expr::BinaryOp { left, op, right } => {
                match op {
                    BinaryOperator::And => {
                        self.generate_condition(left, false_label);
                        self.generate_condition(right, false_label);
                    }
                    BinaryOperator::Or => {
                        let true_label = self.new_label("or_true");
                        self.generate_expr(left);
                        self.emit_indent("test rax, rax");
                        self.emit_indent(&format!("jnz {}", true_label));
                        self.generate_condition(right, false_label);
                        self.emit(&format!("{}:", true_label));
                    }
                    // `origin is marker` between two of the same thing: one
                    // comparison per field, recursing through nesting (plan
                    // 310 §8). This precedes every other equality arm because
                    // a thing's slot holds bytes, not a value any of them
                    // could read - and the analyzer has already rejected the
                    // cross-type and ordering spellings.
                    BinaryOperator::Equal | BinaryOperator::NotEqual
                        if self.thing_compared(left, right).is_some() =>
                    {
                        self.emit_thing_equality(
                            left,
                            right,
                            matches!(op, BinaryOperator::NotEqual),
                        );
                        self.emit_indent("test rax, rax");
                        self.emit_indent(&format!("jz {}  ; 1=holds", false_label));
                    }
                    // `x is nothing` / `x is not nothing` (stage 1e3): tag-6
                    // equality. Two values are equal-as-nothing iff BOTH have
                    // runtime tag 6 (payloads are ignored). This guard MUST
                    // precede the stringy and numeric equality arms: without
                    // it, `0 is nothing` would fall into the numeric arm
                    // (`cmp rax, rbx` on payloads) and wrongly be true, since
                    // nothing's payload is 0. Modelled on the `TypeCheck`
                    // runtime path (~line 4940): generate the non-nothing
                    // side, load its tag into r11 (shadow slot for a Mixed
                    // identifier, else r11 already holds it from an element
                    // read / `_map_lookup` / `value` call), and compare to 6.
                    BinaryOperator::Equal | BinaryOperator::NotEqual
                        if self.is_nothing_expr(left) || self.is_nothing_expr(right) =>
                    {
                        let equal = matches!(op, BinaryOperator::Equal);
                        if self.is_nothing_expr(left) && self.is_nothing_expr(right) {
                            // `nothing is nothing`: tag 6 == tag 6.
                            if !equal {
                                self.emit_indent(&format!("jmp {}  ; nothing is not nothing -> false", false_label));
                            }
                        } else {
                            let value = if self.is_nothing_expr(left) { right } else { left };
                            match self.emit_time_expr_tag(value) {
                                Some(t) => {
                                    // Folded: equal iff the static tag is 6.
                                    let holds = if equal { t == TAG_NOTHING } else { t != TAG_NOTHING };
                                    if !holds {
                                        self.emit_indent(&format!(
                                            "jmp {}  ; is {}nothing folded (static tag {})",
                                            false_label, if equal { "not " } else { "" }, t
                                        ));
                                    }
                                }
                                None => {
                                    self.generate_expr(value);
                                    match self.runtime_tag_source(value) {
                                        Some(src) => {
                                            if let Some(operand) = src.shadow_operand() {
                                                self.emit_indent(&format!(
                                                    "movzx r11, byte {}  ; load mixed element tag",
                                                    operand
                                                ));
                                            }
                                            self.emit_indent("xor rax, rax");
                                            self.emit_indent(&format!(
                                                "cmp r11, {}  ; is nothing?", TAG_NOTHING
                                            ));
                                            self.emit_indent(
                                                if equal { "sete al" } else { "setne al" },
                                            );
                                            self.emit_indent("movzx rax, al");
                                            self.emit_indent("test rax, rax");
                                            self.emit_indent(&format!("jz {}", false_label));
                                        }
                                        // No tag anywhere and r11 holds
                                        // unrelated data, so the operand cannot
                                        // be shown to be nothing - decide
                                        // statically rather than read garbage.
                                        None if equal => self.emit_indent(&format!(
                                            "jmp {}  ; is nothing: operand carries no tag",
                                            false_label
                                        )),
                                        None => {}
                                    }
                                }
                            }
                        }
                    }
                    BinaryOperator::Equal | BinaryOperator::NotEqual
                        if self.is_stringy_type_mismatch(left, right) =>
                    {
                        // Stringy vs a provably non-stringy operand
                        // (BUGS_FOUND #20): the two representations can
                        // never be byte-equal. Fold to a compile-time
                        // constant without evaluating (and dereferencing)
                        // either operand - the old, wider guard below
                        // treated the non-stringy operand's raw value as a
                        // C-string pointer and dereferenced it.
                        if matches!(op, BinaryOperator::Equal) {
                            self.emit_indent(&format!(
                                "jmp {}  ; stringy vs non-stringy operand: never equal",
                                false_label
                            ));
                        }
                        // `is not equal to` is always true here - the
                        // condition holds, so fall through with no jump.
                    }
                    BinaryOperator::Equal | BinaryOperator::NotEqual
                        if self.is_stringy_expr(left) || self.is_stringy_expr(right) =>
                    {
                        // Content comparison - see emit_stringy_equality for
                        // why _mem_eq is used when either side is a buffer.
                        // Reached when both sides are stringy, or one side
                        // is stringy and the other is `value`/Mixed (whose
                        // runtime tag might be text - the mismatch arm
                        // above only fires for a PROVABLY non-stringy type).
                        self.emit_stringy_equality(left, right);
                        self.emit_indent("test rax, rax");
                        let jmp = if matches!(op, BinaryOperator::Equal) { "jz" } else { "jnz" };
                        self.emit_indent(&format!("{} {}  ; 1=equal", jmp, false_label));
                    }
                    BinaryOperator::Equal | BinaryOperator::NotEqual |
                    BinaryOperator::Greater | BinaryOperator::Less |
                    BinaryOperator::GreaterEqual | BinaryOperator::LessEqual => {
                        let is_float = self.is_float_expr(left) || self.is_float_expr(right);

                        if is_float {
                            // Float comparison using SSE2. Use the helper macros so that
                            // NaN/unordered results behave like Vox comparisons: ordered
                            // comparisons are false when either operand is NaN, and != is
                            // true for NaN. The macro leaves a 0/1 result in rax.
                            self.generate_expr(right);
                            self.emit_indent("push rax");
                            self.generate_expr(left);
                            self.emit_indent("movq xmm0, rax");       // left in xmm0
                            self.emit_indent("pop rax");
                            self.emit_indent("movq xmm1, rax");       // right in xmm1

                            let macro_name = match op {
                                BinaryOperator::Equal => "FLOAT_EQ",
                                BinaryOperator::NotEqual => "FLOAT_NE",
                                BinaryOperator::Greater => "FLOAT_GT",
                                BinaryOperator::Less => "FLOAT_LT",
                                BinaryOperator::GreaterEqual => "FLOAT_GE",
                                BinaryOperator::LessEqual => "FLOAT_LE",
                                _ => unreachable!(),
                            };
                            self.emit_indent(macro_name);
                            self.emit_indent("test rax, rax");
                            self.emit_indent(&format!("jz {}", false_label));
                        } else {
                            // Integer comparison
                            self.generate_expr(right);
                            self.emit_indent("push rax");
                            self.generate_expr(left);
                            self.emit_indent("pop rbx");
                            self.emit_indent("cmp rax, rbx");
                            
                            let jmp = match op {
                                BinaryOperator::Equal => "jne",
                                BinaryOperator::NotEqual => "je",
                                BinaryOperator::Greater => "jle",
                                BinaryOperator::Less => "jge",
                                BinaryOperator::GreaterEqual => "jl",
                                BinaryOperator::LessEqual => "jg",
                                _ => unreachable!(),
                            };
                            self.emit_indent(&format!("{} {}", jmp, false_label));
                        }
                    }
                    _ => {
                        self.generate_expr(condition);
                        self.emit_indent("test rax, rax");
                        self.emit_indent(&format!("jz {}", false_label));
                    }
                }
            }
            
            Expr::UnaryOp { op: UnaryOperator::Not, operand } => {
                let true_label = self.new_label("not_true");
                self.generate_condition(operand, &true_label);
                self.emit_indent(&format!("jmp {}", false_label));
                self.emit(&format!("{}:", true_label));
            }
            
            _ => {
                self.generate_expr(condition);
                self.emit_indent("test rax, rax");
                self.emit_indent(&format!("jz {}", false_label));
            }
        }
    }

}