oxdock-parser 0.17.0-alpha

Parser and AST definitions for the OxDock DSL.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
use crate::ast::{
    Arg, Expr, Guard, GuardExpr, IoBinding, IoStream, ModuleTable, PipeTarget, PlatformGuard, Step,
    StepKind,
};
use crate::command::ArgType;
use crate::constants::{
    KEYWORD_EXPORT, KEYWORD_IMPORT, KEYWORD_INSPECT, MODULE_SEPARATOR, SCRIPT_MODULE_NAME, qualify,
    split_qualified,
};
use crate::error::{ParseError, ParseResult, SpanContext};
use crate::lexer::{self, RawToken, Rule, parse_pest_error, refine_span, span_for_line, span_of};
use pest::iterators::Pair;
use std::cell::RefCell;
use std::collections::{HashSet, VecDeque};

/// Lowering context threaded through every grammar rule that can contain a
/// block or a `FUNC` definition (issue #146).
///
/// This replaces the bare `lower: &dyn Fn` parameter the free lowering
/// functions used to take. Bundling matters: `FUNC` duplicate and shadow
/// validation needs the exact pest `SpanContext` at the definition site
/// (post-parse AST walks only see the end of file), so the per-scope
/// `FUNC` names ride alongside the dispatcher instead of a second pass.
pub(super) struct LowerCtx<'a> {
    /// Production command dispatcher (`lower_command`).
    pub lower: &'a dyn Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
    /// Host-registered function names for parse-time shadow rejection.
    /// Empty when hosts are unknown at parse time; the runtime
    /// `define_func` guard still rejects those redefinitions.
    pub reserved_names: &'a HashSet<String>,
    /// Shared per-scope defined `FUNC` names. The `RefCell` lets every free
    /// lowering function share one scope stack through plain `&LowerCtx`
    /// references: `parse()` owns the stack plus the top-level scope, and
    /// each `LowerCtx` is built fresh per statement so no `&self` borrow is
    /// ever held across a `&mut self` call.
    func_scopes: &'a RefCell<Vec<HashSet<String>>>,
    /// Module provenance table for static call resolution.
    modules: &'a ModuleTable,
    /// Import frames mirroring scope structure, each holding imported
    /// module names in `IMPORT` order. Chained lookup like var scopes:
    /// inner frames see outer imports, frames drop on scope exit.
    import_scopes: &'a RefCell<Vec<Vec<String>>>,
}

impl<'a> LowerCtx<'a> {
    pub(super) fn new(
        lower: &'a dyn Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
        reserved_names: &'a HashSet<String>,
        func_scopes: &'a RefCell<Vec<HashSet<String>>>,
        modules: &'a ModuleTable,
        import_scopes: &'a RefCell<Vec<Vec<String>>>,
    ) -> Self {
        Self {
            lower,
            reserved_names,
            func_scopes,
            modules,
            import_scopes,
        }
    }

    pub(super) fn enter_scope(&self) {
        self.func_scopes.borrow_mut().push(HashSet::new());
        self.import_scopes.borrow_mut().push(Vec::new());
    }

    pub(super) fn exit_scope(&self) {
        self.func_scopes.borrow_mut().pop();
        self.import_scopes.borrow_mut().pop();
    }

    /// Record a `FUNC` name in the innermost scope. Returns false when the
    /// name was already defined in that same scope (nested shadowing of an
    /// outer DSL name stays allowed).
    pub(super) fn declare_func(&self, name: &str) -> bool {
        let mut scopes = self.func_scopes.borrow_mut();
        match scopes.last_mut() {
            Some(current) => current.insert(name.to_string()),
            None => true,
        }
    }

    /// Record `IMPORT`ed modules in the innermost import frame.
    pub(super) fn import_modules(&self, ctx: &SpanContext, modules: &[String]) -> ParseResult<()> {
        let mut known: Vec<String> = self.modules.modules.keys().cloned().collect();
        known.sort();
        for module in modules {
            if !self.modules.modules.contains_key(module) {
                return Err(ParseError::validation(
                    KEYWORD_IMPORT,
                    format!(
                        "unknown module `{module}`; known modules: {}",
                        known.join(", ")
                    ),
                    ctx,
                ));
            }
            let mut frames = self.import_scopes.borrow_mut();
            match frames.last_mut() {
                Some(frame) => {
                    if !frame.contains(module) {
                        frame.push(module.clone());
                    }
                }
                None => {
                    frames.push(vec![module.clone()]);
                }
            }
        }
        Ok(())
    }

    /// Resolve a call name to its qualified `MODULE::NAME` form.
    ///
    /// Qualified names check module membership directly (opaque modules pass
    /// through for runtime checking). Bare names resolve to `SCRIPT` defs
    /// first, then to exactly one exporting module across all visible
    /// import frames; zero or several matches fail. `INSPECT` passes
    /// through untouched: it is a dedicated AST node, not a registry entry.
    pub(super) fn resolve_call(&self, ctx: &SpanContext, name: &str) -> ParseResult<String> {
        if let Some((module, base)) = split_qualified(name) {
            if base == KEYWORD_INSPECT {
                return Err(ParseError::validation(
                    "FUNC",
                    "INSPECT is a builtin keyword and cannot be module-qualified".to_string(),
                    ctx,
                ));
            }
            check_func_ident(ctx, module)?;
            check_func_ident(ctx, base)?;
            match self.modules.modules.get(module) {
                None => {
                    let mut known: Vec<String> = self.modules.modules.keys().cloned().collect();
                    known.sort();
                    Err(ParseError::validation(
                        "FUNC",
                        format!(
                            "unknown module `{module}`; known modules: {}",
                            known.join(", ")
                        ),
                        ctx,
                    ))
                }
                Some(None) => Ok(name.to_string()),
                Some(Some(funcs)) => {
                    if funcs.functions.contains(base) {
                        Ok(qualify(module, base))
                    } else {
                        Err(ParseError::validation(
                            "FUNC",
                            format!("unknown function `{module}::{base}`"),
                            ctx,
                        ))
                    }
                }
            }
        } else {
            if name == KEYWORD_IMPORT || name == KEYWORD_EXPORT {
                return Err(ParseError::validation(
                    "FUNC",
                    format!("`{name}` is a directive, not a function"),
                    ctx,
                ));
            }
            if name == KEYWORD_INSPECT {
                return Ok(name.to_string());
            }
            let scopes = self.func_scopes.borrow();
            if scopes.iter().rev().any(|scope| scope.contains(name)) {
                return Ok(qualify(SCRIPT_MODULE_NAME, name));
            }
            drop(scopes);
            // Distinct exporting modules across all visible import frames.
            // Several matches fail instead of shadowing silently: qualify it.
            let frames = self.import_scopes.borrow();
            let mut known_matches: Vec<String> = Vec::new();
            let mut opaque_matches: Vec<String> = Vec::new();
            for frame in frames.iter() {
                for module in frame {
                    match self.modules.modules.get(module) {
                        Some(Some(funcs)) => {
                            if funcs.functions.contains(name) && !known_matches.contains(module) {
                                known_matches.push(module.clone());
                            }
                        }
                        Some(None) if !opaque_matches.contains(module) => {
                            opaque_matches.push(module.clone());
                        }
                        Some(None) | None => {}
                    }
                }
            }
            drop(frames);
            if known_matches.len() > 1 {
                known_matches.sort();
                return Err(ParseError::validation(
                    "FUNC",
                    format!(
                        "ambiguous function `{name}`: exported by {}; qualify it (e.g. `{}::{name}`)",
                        known_matches.join(", "),
                        known_matches[0],
                    ),
                    ctx,
                ));
            }
            if let Some(module) = known_matches.pop() {
                return Ok(qualify(&module, name));
            }
            if opaque_matches.len() > 1 {
                opaque_matches.sort();
                return Err(ParseError::validation(
                    "FUNC",
                    format!(
                        "ambiguous function `{name}`: imported opaque modules {}; qualify it",
                        opaque_matches.join(", "),
                    ),
                    ctx,
                ));
            }
            if let Some(module) = opaque_matches.pop() {
                return Ok(qualify(&module, name));
            }
            // Nothing in scope: point at the fix when a known module
            // exports the name but was never imported.
            let mut exporters: Vec<String> = self
                .modules
                .modules
                .iter()
                .filter_map(|(module, funcs)| match funcs {
                    Some(funcs) if funcs.functions.contains(name) => Some(module.clone()),
                    _ => None,
                })
                .collect();
            exporters.sort();
            if let Some(first) = exporters.first() {
                return Err(ParseError::validation(
                    "FUNC",
                    format!(
                        "unknown function `{name}`; qualify it (`{first}::{name}`) or add `IMPORT [{first}]`"
                    ),
                    ctx,
                ));
            }
            Err(ParseError::validation(
                "FUNC",
                format!("unknown function `{name}`"),
                ctx,
            ))
        }
    }

    /// Base names exported by every known module. Backs the `FUNC` shadow
    /// check alongside the flat reserved set.
    pub(super) fn module_base_names(&self) -> HashSet<String> {
        self.modules.reserved_base_names()
    }

    /// Snapshot of everything visible at this point: `FUNC` names unioned
    /// across frames plus imports flattened outer-to-inner. Snippet
    /// re-parses (async inner commands) seed their base frames with this so
    /// lookup behaves identically; snippets never define, only read.
    fn visible_snapshot(&self) -> (HashSet<String>, Vec<String>) {
        let mut funcs = HashSet::new();
        for scope in self.func_scopes.borrow().iter() {
            funcs.extend(scope.iter().cloned());
        }
        let mut imports = Vec::new();
        for frame in self.import_scopes.borrow().iter() {
            for module in frame {
                if !imports.contains(module) {
                    imports.push(module.clone());
                }
            }
        }
        (funcs, imports)
    }
}

#[derive(Clone)]
struct ScopeFrame {
    line_no: usize,
    had_command: bool,
}

#[derive(Clone)]
struct PendingIoBlock<'a> {
    line_no: usize,
    span: SpanContext<'a>,
    bindings: Vec<IoBinding>,
    guards: Option<GuardExpr>,
}

#[derive(Clone)]
struct IoScopeFrame {
    line_no: usize,
    had_command: bool,
    bindings: Vec<IoBinding>,
    guards: Option<GuardExpr>,
    /// Step index where this block's first command will land. Used to mark
    /// scope boundaries so WITH_IO block bodies scope LET/ENV/WORKDIR like
    /// every other braced block (only pipes leak).
    first_step: usize,
}

#[derive(Clone, Copy, Debug)]
enum BlockKind {
    Guard,
    Io,
}

#[derive(Default)]
struct IoBindingSet {
    stdin: Option<IoBinding>,
    stdout: Option<IoBinding>,
    stderr: Option<IoBinding>,
}

impl IoBindingSet {
    fn insert(&mut self, binding: IoBinding) {
        match binding.stream {
            IoStream::Stdin => self.stdin = Some(binding),
            IoStream::Stdout => self.stdout = Some(binding),
            IoStream::Stderr => self.stderr = Some(binding),
        }
    }

    fn into_vec(self) -> Vec<IoBinding> {
        let mut out = Vec::new();
        if let Some(binding) = self.stdin {
            out.push(binding);
        }
        if let Some(binding) = self.stdout {
            out.push(binding);
        }
        if let Some(binding) = self.stderr {
            out.push(binding);
        }
        out
    }
}

pub struct ScriptParser<'a, F: Fn(&str, Vec<Arg>) -> ParseResult<StepKind>> {
    input: &'a str,
    tokens: VecDeque<RawToken<'a>>,
    steps: Vec<Step>,
    guard_stack: Vec<Option<GuardExpr>>,
    pending_guards: Option<GuardExpr>,
    pending_inline_guards: Option<GuardExpr>,
    pending_can_open_block: bool,
    pending_scope_enters: usize,
    scope_stack: Vec<ScopeFrame>,
    pending_io_block: Option<PendingIoBlock<'a>>,
    io_scope_stack: Vec<IoScopeFrame>,
    block_stack: Vec<BlockKind>,
    lower: F,
    /// Host-registered function names, consulted by the post-parse scope
    /// validation so `FUNC` cannot shadow runtime hosts. Empty when hosts
    /// are unknown at parse time (e.g. compile-time macros); the runtime
    /// `define_func` guard still rejects those redefinitions.
    reserved_names: HashSet<String>,
    /// Module provenance table for static call resolution. Empty when
    /// modules are unknown at parse time; resolved calls stay qualified
    /// only against this table.
    modules: ModuleTable,
    /// Seed for the base import frame, from an enclosing parse's visible
    /// imports (snippet re-parses). Empty for top-level parses.
    preseed_imports: Vec<String>,
    /// Seed for the base `FUNC` scope, from an enclosing parse's visible
    /// definitions (snippet re-parses). Empty for top-level parses.
    preseed_funcs: HashSet<String>,
}

impl<'a, F: Fn(&str, Vec<Arg>) -> ParseResult<StepKind>> ScriptParser<'a, F> {
    pub fn new(input: &'a str, lower: F) -> ParseResult<Self> {
        Self::new_with_hosts(input, lower, HashSet::new())
    }

    pub fn new_with_hosts(
        input: &'a str,
        lower: F,
        reserved_names: HashSet<String>,
    ) -> ParseResult<Self> {
        Self::new_with_modules(input, lower, reserved_names, ModuleTable::default())
    }

    pub fn new_with_modules(
        input: &'a str,
        lower: F,
        reserved_names: HashSet<String>,
        modules: ModuleTable,
    ) -> ParseResult<Self> {
        Self::new_with_preseed(
            input,
            lower,
            reserved_names,
            modules,
            HashSet::new(),
            Vec::new(),
        )
    }

    pub fn new_with_preseed(
        input: &'a str,
        lower: F,
        reserved_names: HashSet<String>,
        modules: ModuleTable,
        preseed_funcs: HashSet<String>,
        preseed_imports: Vec<String>,
    ) -> ParseResult<Self> {
        let tokens = VecDeque::from(lexer::tokenize(input)?);
        Ok(Self {
            input,
            tokens,
            steps: Vec::new(),
            guard_stack: vec![None],
            pending_guards: None,
            pending_inline_guards: None,
            pending_can_open_block: false,
            pending_scope_enters: 0,
            scope_stack: Vec::new(),
            pending_io_block: None,
            io_scope_stack: Vec::new(),
            block_stack: Vec::new(),
            lower,
            reserved_names,
            modules,
            preseed_imports,
            preseed_funcs,
        })
    }

    /// Span for end of script errors (no failing token site).
    fn eof_span(&self) -> SpanContext<'_> {
        let lines = self.input.lines().count().max(1);
        span_for_line(self.input, lines)
    }

    pub fn parse(mut self) -> ParseResult<Vec<Step>> {
        // Function scope tracking rides alongside lowering (issue #146).
        // `func_scopes` is a parse-local stack: the bottom is the top-level
        // scope, `{`/`}` toggle nested ones below, and braced statement
        // bodies push their own in `parse_block_elements_with_lower`. This
        // mirrors the runtime `push_scope`/`pop_scope` boundaries, so
        // duplicate and shadow errors fire at the definition line instead of
        // end of file. Each `LowerCtx` is built fresh per statement from
        // short borrows, so no `&self` borrow crosses a `&mut self` call.
        let func_scopes: RefCell<Vec<HashSet<String>>> = RefCell::new(vec![HashSet::new()]);
        // Import frames ride the same boundaries: the bottom is the top-level
        // scope, blocks and `FUNC` bodies push their own, and exit drops
        // them, so `IMPORT` applies from its line to the enclosing block end.
        let import_scopes: RefCell<Vec<Vec<String>>> = RefCell::new(vec![Vec::new()]);
        // Snippet re-parses seed their base frames with the enclosing
        // parse's visible state so lookup behaves identically.
        func_scopes.borrow_mut()[0].extend(self.preseed_funcs.iter().cloned());
        import_scopes.borrow_mut()[0].extend(self.preseed_imports.iter().cloned());
        while let Some(token) = self.tokens.pop_front() {
            let step_index = self.steps.len();
            if self.pending_io_block.is_some()
                && !matches!(
                    token,
                    RawToken::BlockStart { .. }
                        | RawToken::Command { .. }
                        | RawToken::Instruction { .. }
                        | RawToken::RunExec { .. }
                )
            {
                let pending = self.pending_io_block.take().unwrap();
                return Err(ParseError::structural(
                    "with_io",
                    format!(
                        "line {}: WITH_IO block must be followed by '{{'",
                        pending.line_no
                    ),
                    &pending.span,
                ));
            }
            match token {
                RawToken::Guard {
                    pair,
                    line_end,
                    span,
                } => {
                    let span = span.with_step(step_index);
                    let groups = parse_guard_line(&span, pair)?;
                    self.handle_guard_token(line_end, groups)?;
                }
                RawToken::BlockStart { line_no, span } => {
                    let span = span.with_step(step_index);
                    self.start_block(&span, line_no)?;
                    LowerCtx::new(
                        &self.lower,
                        &self.reserved_names,
                        &func_scopes,
                        &self.modules,
                        &import_scopes,
                    )
                    .enter_scope();
                }
                RawToken::BlockEnd { line_no, span } => {
                    let span = span.with_step(step_index);
                    self.end_block(&span, line_no)?;
                    LowerCtx::new(
                        &self.lower,
                        &self.reserved_names,
                        &func_scopes,
                        &self.modules,
                        &import_scopes,
                    )
                    .exit_scope();
                }
                RawToken::Command {
                    pair,
                    line_no,
                    span,
                } => {
                    let span = span.with_step(step_index);
                    let lctx = LowerCtx::new(
                        &self.lower,
                        &self.reserved_names,
                        &func_scopes,
                        &self.modules,
                        &import_scopes,
                    );
                    // IMPORT/EXPORT are lowering directives, not steps:
                    // IMPORT updates the import frames, EXPORT is reserved.
                    // Both emit zero runtime steps. Neither may be guarded:
                    // a guard here would leak onto the following statement.
                    if pair.as_rule() == Rule::import_statement {
                        if self.pending_guards.is_some() || self.pending_inline_guards.is_some() {
                            return Err(ParseError::structural(
                                KEYWORD_IMPORT,
                                "IMPORT cannot be guarded".to_string(),
                                &span,
                            ));
                        }
                        self.lower_import(&span, pair, &lctx)?;
                        continue;
                    }
                    if pair.as_rule() == Rule::export_statement {
                        return Err(ParseError::validation(
                            KEYWORD_EXPORT,
                            "`EXPORT` is reserved for future script-module support and cannot be used yet.".to_string(),
                            &span,
                        ));
                    }
                    let kind = parse_structural_command_with_lower(&span, pair, &lctx)?;
                    self.handle_command_token(&span, line_no, kind)?;
                }
                RawToken::Instruction {
                    pair,
                    line_no,
                    span,
                } => {
                    let span = span.with_step(step_index);
                    let lctx = LowerCtx::new(
                        &self.lower,
                        &self.reserved_names,
                        &func_scopes,
                        &self.modules,
                        &import_scopes,
                    );
                    let kind = self
                        .lower_instruction(&span, pair, &lctx)
                        .map_err(|e| e.with_span(&span))?;
                    self.handle_command_token(&span, line_no, kind)?;
                }
                RawToken::RunExec {
                    pair,
                    line_no,
                    span,
                } => {
                    let span = span.with_step(step_index);
                    let lctx = LowerCtx::new(
                        &self.lower,
                        &self.reserved_names,
                        &func_scopes,
                        &self.modules,
                        &import_scopes,
                    );
                    let kind = lower_run_exec_pair(&span, pair, &lctx)?;
                    self.handle_command_token(&span, line_no, kind)?;
                }
            }
        }

        if let Some(pending) = self.pending_io_block.take() {
            return Err(ParseError::structural(
                "with_io",
                format!(
                    "line {}: WITH_IO block must be followed by '{{'",
                    pending.line_no
                ),
                &pending.span,
            ));
        }

        if self.guard_stack.len() != 1 {
            let ctx = self.eof_span();
            return Err(ParseError::structural(
                "guard",
                "unclosed guard block at end of script".to_string(),
                &ctx,
            ));
        }
        if self.pending_guards.is_some() {
            let ctx = self.eof_span();
            return Err(ParseError::structural(
                "guard",
                "guard declared on final lines without a following command".to_string(),
                &ctx,
            ));
        }

        if let Some(frame) = self.io_scope_stack.last() {
            let ctx = span_for_line(self.input, frame.line_no);
            return Err(ParseError::structural(
                "with_io",
                format!(
                    "WITH_IO block starting on line {} was not closed",
                    frame.line_no
                ),
                &ctx,
            ));
        }

        // Validate `INHERIT_ENV` directives: only allowed in the prelude (before
        // any other commands) and at most one occurrence.
        {
            let ctx = self.eof_span();
            let mut seen_non_prelude = false;
            let mut inherit_count = 0usize;
            for step in &self.steps {
                match &step.kind {
                    StepKind::InheritEnv { .. } => {
                        if seen_non_prelude {
                            return Err(ParseError::structural(
                                "inherit_env",
                                "INHERIT_ENV must appear before any other commands".to_string(),
                                &ctx,
                            ));
                        }
                        if step.guard.is_some() || step.scope_enter > 0 || step.scope_exit > 0 {
                            return Err(ParseError::structural(
                                "inherit_env",
                                "INHERIT_ENV cannot be guarded or nested inside blocks".to_string(),
                                &ctx,
                            ));
                        }
                        inherit_count += 1;
                    }
                    kind => {
                        if contains_inherit_env(kind) {
                            return Err(ParseError::structural(
                                "inherit_env",
                                "INHERIT_ENV cannot be nested inside other commands".to_string(),
                                &ctx,
                            ));
                        }
                        seen_non_prelude = true;
                    }
                }
            }
            if inherit_count > 1 {
                return Err(ParseError::structural(
                    "inherit_env",
                    "only one INHERIT_ENV directive is allowed".to_string(),
                    &ctx,
                ));
            }
        }

        Ok(self.steps)
    }

    fn lower_instruction(
        &self,
        ctx: &SpanContext,
        pair: Pair<Rule>,
        lctx: &LowerCtx,
    ) -> ParseResult<StepKind> {
        lower_instruction_pair(ctx, pair, lctx)
    }

    /// Lower an `IMPORT` statement: update the import frames, emit nothing.
    /// Guards are rejected by the caller: with zero steps there is nothing
    /// to attach them to, so they would leak onto the next statement.
    fn lower_import(
        &self,
        ctx: &SpanContext,
        pair: Pair<Rule>,
        lctx: &LowerCtx,
    ) -> ParseResult<()> {
        lower_import_statement(ctx, pair, lctx)
    }

    fn handle_guard_token(&mut self, line_end: usize, expr: GuardExpr) -> ParseResult<()> {
        if let Some(RawToken::Command { line_no, .. }) = self.tokens.front()
            && *line_no == line_end
        {
            self.pending_inline_guards = Some(expr);
            self.pending_can_open_block = false;
            return Ok(());
        }
        self.stash_pending_guard(expr);
        self.pending_can_open_block = true;
        Ok(())
    }

    fn handle_command_token(
        &mut self,
        ctx: &SpanContext<'a>,
        line_no: usize,
        kind: StepKind,
    ) -> ParseResult<()> {
        let inline = self.pending_inline_guards.take();
        self.handle_command(ctx, line_no, kind, inline)
    }

    fn stash_pending_guard(&mut self, guard: GuardExpr) {
        self.pending_guards = Some(if let Some(existing) = self.pending_guards.take() {
            GuardExpr::all(vec![existing, guard])
        } else {
            guard
        });
    }

    fn start_guard_block_from_pending(
        &mut self,
        ctx: &SpanContext,
        line_no: usize,
    ) -> ParseResult<()> {
        let guards = self.pending_guards.take().ok_or_else(|| {
            ParseError::structural(
                "guard",
                format!("line {}: '{{' without a pending guard", line_no),
                ctx,
            )
        })?;
        if !self.pending_can_open_block {
            return Err(ParseError::structural(
                "guard",
                format!("line {}: '{{' must directly follow a guard", line_no),
                ctx,
            ));
        }
        self.pending_can_open_block = false;
        self.enter_guard_block(guards, line_no)
    }

    fn enter_guard_block(&mut self, guard: GuardExpr, line_no: usize) -> ParseResult<()> {
        let composed = if let Some(pending) = self.pending_guards.take() {
            GuardExpr::all(vec![pending, guard])
        } else {
            guard
        };
        let parent = self.guard_stack.last().cloned().unwrap_or(None);
        let next = and_guard_exprs(parent, Some(composed));
        self.guard_stack.push(next);
        self.scope_stack.push(ScopeFrame {
            line_no,
            had_command: false,
        });
        self.pending_scope_enters += 1;
        Ok(())
    }

    fn begin_io_block(
        &mut self,
        ctx: &SpanContext<'a>,
        line_no: usize,
        bindings: Vec<IoBinding>,
        guards: Option<GuardExpr>,
    ) -> ParseResult<()> {
        if self.pending_io_block.is_some() {
            return Err(ParseError::structural(
                "with_io",
                format!(
                    "line {}: previous WITH_IO block is still waiting for '{{'",
                    line_no
                ),
                ctx,
            ));
        }
        self.pending_io_block = Some(PendingIoBlock {
            line_no,
            span: ctx.clone(),
            bindings,
            guards,
        });
        Ok(())
    }

    fn start_block(&mut self, ctx: &SpanContext, line_no: usize) -> ParseResult<()> {
        if let Some(pending) = self.pending_io_block.take() {
            self.block_stack.push(BlockKind::Io);
            self.io_scope_stack.push(IoScopeFrame {
                line_no: pending.line_no,
                had_command: false,
                bindings: pending.bindings,
                guards: pending.guards,
                first_step: self.steps.len(),
            });
            Ok(())
        } else {
            self.start_guard_block_from_pending(ctx, line_no)?;
            self.block_stack.push(BlockKind::Guard);
            Ok(())
        }
    }

    fn end_block(&mut self, ctx: &SpanContext, line_no: usize) -> ParseResult<()> {
        let kind = self.block_stack.pop().ok_or_else(|| {
            ParseError::structural("block", format!("line {}: unexpected '}}'", line_no), ctx)
        })?;
        match kind {
            BlockKind::Guard => self.end_guard_block(ctx, line_no),
            BlockKind::Io => self.end_io_block(ctx, line_no),
        }
    }

    fn end_guard_block(&mut self, ctx: &SpanContext, line_no: usize) -> ParseResult<()> {
        if self.guard_stack.len() == 1 {
            return Err(ParseError::structural(
                "guard",
                format!("line {}: unexpected '}}'", line_no),
                ctx,
            ));
        }
        if self.pending_guards.is_some() {
            return Err(ParseError::structural(
                "guard",
                format!(
                    "line {}: guard declared immediately before '}}' without a command",
                    line_no
                ),
                ctx,
            ));
        }
        let frame = self.scope_stack.last().cloned().ok_or_else(|| {
            ParseError::structural(
                "guard",
                format!("line {}: scope stack underflow", line_no),
                ctx,
            )
        })?;
        if !frame.had_command {
            return Err(ParseError::structural(
                "guard",
                format!(
                    "line {}: guard block starting on line {} must contain at least one command",
                    line_no, frame.line_no
                ),
                ctx,
            ));
        }
        let step = self.steps.last_mut().ok_or_else(|| {
            ParseError::structural(
                "guard",
                format!("line {}: guard block closed without any commands", line_no),
                ctx,
            )
        })?;
        step.scope_exit += 1;
        self.scope_stack.pop();
        self.guard_stack.pop();
        Ok(())
    }

    fn end_io_block(&mut self, ctx: &SpanContext, line_no: usize) -> ParseResult<()> {
        let frame = self.io_scope_stack.pop().ok_or_else(|| {
            ParseError::structural("with_io", format!("line {}: unexpected '}}'", line_no), ctx)
        })?;
        if !frame.had_command {
            return Err(ParseError::structural(
                "with_io",
                format!(
                    "line {}: WITH_IO block starting on line {} must contain at least one command",
                    line_no, frame.line_no
                ),
                ctx,
            ));
        }
        // WITH_IO block bodies are lexical scopes like guard blocks: mark
        // scope boundaries so LET/ENV/WORKDIR/WORKSPACE revert on exit.
        // Pipe registrations live in ExecIo and are unaffected (they leak).
        if self.steps.len() > frame.first_step {
            self.steps[frame.first_step].scope_enter += 1;
            if let Some(last) = self.steps.last_mut() {
                last.scope_exit += 1;
            }
        }
        Ok(())
    }

    fn guard_context(&mut self, inline: Option<GuardExpr>) -> Option<GuardExpr> {
        let mut context = self.guard_stack.last().cloned().unwrap_or(None);
        if let Some(pending) = self.pending_guards.take() {
            context = and_guard_exprs(context, Some(pending));
            self.pending_can_open_block = false;
        }
        if let Some(inline_guard) = inline {
            context = and_guard_exprs(context, Some(inline_guard));
        }
        context
    }

    fn handle_command(
        &mut self,
        ctx: &SpanContext<'a>,
        line_no: usize,
        kind: StepKind,
        inline_guards: Option<GuardExpr>,
    ) -> ParseResult<()> {
        if let StepKind::WithIoBlock { bindings } = kind {
            let guards = self.guard_context(inline_guards);
            self.begin_io_block(ctx, line_no, bindings, guards)?;
            return Ok(());
        }

        let guards = self.guard_context(inline_guards);
        let guards = self.apply_io_guards(guards);
        let scope_enter = self.pending_scope_enters;
        self.pending_scope_enters = 0;
        for frame in self.scope_stack.iter_mut() {
            frame.had_command = true;
        }
        for frame in self.io_scope_stack.iter_mut() {
            frame.had_command = true;
        }
        let kind = self.apply_io_defaults(kind);
        self.steps.push(Step {
            guard: guards,
            kind,
            scope_enter,
            scope_exit: 0,
        });
        Ok(())
    }

    fn apply_io_defaults(&self, kind: StepKind) -> StepKind {
        let defaults = self.current_io_defaults();
        if defaults.is_empty() {
            return kind;
        }
        match kind {
            StepKind::WithIo { bindings, cmd } => StepKind::WithIo {
                bindings: merge_bindings(&defaults, &bindings),
                cmd,
            },
            other => StepKind::WithIo {
                bindings: defaults,
                cmd: Box::new(other),
            },
        }
    }

    fn current_io_defaults(&self) -> Vec<IoBinding> {
        if self.io_scope_stack.is_empty() {
            return Vec::new();
        }
        let mut set = IoBindingSet::default();
        for frame in &self.io_scope_stack {
            for binding in &frame.bindings {
                set.insert(binding.clone());
            }
        }
        set.into_vec()
    }

    fn apply_io_guards(&self, guard: Option<GuardExpr>) -> Option<GuardExpr> {
        self.io_scope_stack.iter().fold(guard, |acc, frame| {
            and_guard_exprs(acc, frame.guards.clone())
        })
    }
}

pub fn parse_script(
    input: &str,
    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
) -> ParseResult<Vec<Step>> {
    ScriptParser::new(input, lower)?.parse()
}

/// Parse a snippet with an enclosing parse's visible scope state, so
/// re-parsed inner commands (async bodies) resolve calls identically.
/// The snippet never defines, only reads: seeds affect lookup alone.
pub fn parse_script_with_preseed(
    input: &str,
    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
    reserved_names: HashSet<String>,
    modules: ModuleTable,
    preseed_funcs: HashSet<String>,
    preseed_imports: Vec<String>,
) -> ParseResult<Vec<Step>> {
    ScriptParser::new_with_preseed(
        input,
        lower,
        reserved_names,
        modules,
        preseed_funcs,
        preseed_imports,
    )?
    .parse()
}

/// Parse with a module provenance table so calls resolve statically:
/// qualified `MODULE::NAME` checks membership, bare `NAME` resolves through
/// `SCRIPT` definitions and `IMPORT`ed modules, and anything else fails at
/// parse time instead of at runtime.
pub fn parse_script_with_modules(
    input: &str,
    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
    reserved_names: HashSet<String>,
    modules: ModuleTable,
) -> ParseResult<Vec<Step>> {
    ScriptParser::new_with_modules(input, lower, reserved_names, modules)?.parse()
}

pub fn parse_guard_expr_str(input: &str) -> ParseResult<GuardExpr> {
    use pest::Parser;
    let pairs = lexer::LanguageParser::parse(Rule::guard_expr, input).map_err(parse_pest_error)?;
    let pair = pairs.into_iter().next().ok_or_else(|| {
        ParseError::structural("guard", "empty guard".to_string(), &span_for_line(input, 1))
    })?;
    let ctx = span_of(&pair, input);
    parse_guard_expr(&ctx, pair)
}

fn and_guard_exprs(left: Option<GuardExpr>, right: Option<GuardExpr>) -> Option<GuardExpr> {
    match (left, right) {
        (None, None) => None,
        (Some(expr), None) | (None, Some(expr)) => Some(expr),
        (Some(lhs), Some(rhs)) => Some(GuardExpr::all(vec![lhs, rhs])),
    }
}

fn merge_bindings(defaults: &[IoBinding], overrides: &[IoBinding]) -> Vec<IoBinding> {
    let mut set = IoBindingSet::default();
    for binding in defaults {
        set.insert(binding.clone());
    }
    for binding in overrides {
        set.insert(binding.clone());
    }
    set.into_vec()
}

fn contains_inherit_env(kind: &StepKind) -> bool {
    match kind {
        StepKind::InheritEnv { .. } => true,
        StepKind::WithIo { cmd, .. } => contains_inherit_env(cmd),
        StepKind::AssignCapture { cmd, .. } => contains_inherit_env(cmd),
        StepKind::While { body, .. } | StepKind::FuncDef { body, .. } => {
            body.iter().any(|s| contains_inherit_env(&s.kind))
        }
        StepKind::Timeout { body, .. } | StepKind::AssignAsync { body, .. } => {
            body.iter().any(|s| contains_inherit_env(&s.kind))
        }
        _ => false,
    }
}

/// True when bindings reroute stdout into a named pipe. A `LET`-capture owns
/// the step's stdout, so combining the two is a parse error.
fn has_stdout_pipe(bindings: &[IoBinding]) -> bool {
    bindings
        .iter()
        .any(|b| b.stream == IoStream::Stdout && b.pipe.is_some())
}

/// Reject async machinery inside a capture body: background tasks are
/// captured via `LET $o: STRING = AWAIT $t`, never inline.
fn reject_async_in_capture(ctx: &SpanContext, kind: &StepKind) -> ParseResult<()> {
    let bad = match kind {
        StepKind::AsyncBlock { .. }
        | StepKind::AssignAsync { .. }
        | StepKind::Await { .. }
        | StepKind::AwaitCapture { .. }
        | StepKind::Cancel { .. } => true,
        StepKind::WithIo { cmd, .. } => reject_async_in_capture(ctx, cmd).is_err(),
        StepKind::Timeout { body, .. } => body
            .iter()
            .any(|s| reject_async_in_capture(ctx, &s.kind).is_err()),
        StepKind::While { body, .. } | StepKind::FuncDef { body, .. } => body
            .iter()
            .any(|s| reject_async_in_capture(ctx, &s.kind).is_err()),
        _ => false,
    };
    if bad {
        return Err(ParseError::structural("let", "LET capture cannot run ASYNC/AWAIT/CANCEL inline; use LET $t: HANDLE = ASYNC ... then LET $o: STRING = AWAIT $t".to_string(), ctx));
    }
    Ok(())
}

/// Reject `WITH_IO [stdout=$var]` anywhere inside a capture body: the
/// capture sink owns stdout.
fn reject_pipe_stdout_in_capture(ctx: &SpanContext, kind: &StepKind) -> ParseResult<()> {
    match kind {
        StepKind::WithIo { bindings, cmd } => {
            if has_stdout_pipe(bindings) {
                return Err(ParseError::structural(
                    "let",
                    "LET capture cannot use WITH_IO [stdout=$var]; the capture sink owns stdout"
                        .to_string(),
                    ctx,
                ));
            }
            reject_pipe_stdout_in_capture(ctx, cmd)
        }
        StepKind::Timeout { body, .. } => {
            for step in body {
                reject_pipe_stdout_in_capture(ctx, &step.kind)?;
            }
            Ok(())
        }
        StepKind::While { body, .. } | StepKind::FuncDef { body, .. } => {
            for step in body {
                reject_pipe_stdout_in_capture(ctx, &step.kind)?;
            }
            Ok(())
        }
        _ => Ok(()),
    }
}

/// Re-parse raw RHS text as an expression (fallback when the `LET` RHS lead
/// token is not a known command). Requires the expression to consume the
/// full text so `LET $x: STRING = FOO bar` stays an error instead of binding `FOO`.
fn parse_expr_str(ctx: &SpanContext, lctx: &LowerCtx, text: &str) -> ParseResult<Expr> {
    use pest::Parser;
    let mut pairs = lexer::LanguageParser::parse(Rule::expr, text).map_err(parse_pest_error)?;
    let pair = pairs.next().ok_or_else(|| {
        ParseError::validation("LET", "LET requires an expression".to_string(), ctx)
    })?;
    if pair.as_span().end() != text.len() {
        return Err(ParseError::structural(
            "expr",
            format!("invalid LET expression {text:?}"),
            ctx,
        ));
    }
    parse_expr(ctx, lctx, pair)
}

fn parse_structural_command_with_lower(
    ctx: &SpanContext,
    pair: Pair<Rule>,
    lctx: &LowerCtx,
) -> ParseResult<StepKind> {
    let span = refine_span(ctx, &pair);
    let kind = match pair.as_rule() {
        Rule::inherit_env_command => {
            let mut keys = Vec::new();
            for inner in pair.into_inner() {
                if inner.as_rule() == Rule::inherit_list {
                    for key in inner.into_inner() {
                        if key.as_rule() == Rule::env_key {
                            keys.push(key.as_str().trim().to_string());
                        }
                    }
                } else if inner.as_rule() == Rule::env_key {
                    keys.push(inner.as_str().trim().to_string());
                }
            }
            StepKind::InheritEnv { keys }
        }
        Rule::with_io_command => {
            let mut bindings = Vec::new();
            let mut cmd = None;
            for inner in pair.into_inner() {
                match inner.as_rule() {
                    Rule::io_flags => {
                        for flag in inner.into_inner() {
                            if flag.as_rule() == Rule::io_binding {
                                bindings.push(parse_io_binding(ctx, flag)?);
                            }
                        }
                    }
                    Rule::with_io_command => {
                        cmd = Some(Box::new(parse_structural_command_with_lower(
                            ctx, inner, lctx,
                        )?));
                    }
                    Rule::inherit_env_command => {
                        cmd = Some(Box::new(parse_structural_command_with_lower(
                            ctx, inner, lctx,
                        )?));
                    }
                    Rule::async_statement | Rule::async_statement_block => {
                        cmd = Some(Box::new(parse_structural_command_with_lower(
                            ctx, inner, lctx,
                        )?));
                    }
                    Rule::timeout_statement | Rule::cancel_statement => {
                        cmd = Some(Box::new(parse_structural_command_with_lower(
                            ctx, inner, lctx,
                        )?));
                    }
                    Rule::call_statement | Rule::while_statement => {
                        cmd = Some(Box::new(parse_structural_command_with_lower(
                            ctx, inner, lctx,
                        )?));
                    }
                    Rule::func_def
                    | Rule::return_statement
                    | Rule::break_statement
                    | Rule::continue_statement => {
                        return Err(ParseError::structural(
                            "parser",
                            format!(
                                "WITH_IO cannot wrap {:?}; place it around a command or block instead",
                                inner.as_rule()
                            ),
                            &span,
                        ));
                    }
                    Rule::instruction | Rule::instruction_inner => {
                        cmd = Some(Box::new(lower_instruction_pair(ctx, inner, lctx)?));
                    }
                    Rule::run_exec_statement | Rule::run_exec_inner => {
                        cmd = Some(Box::new(lower_run_exec_pair(ctx, inner, lctx)?));
                    }
                    _ => {}
                }
            }
            if let Some(cmd) = cmd {
                StepKind::WithIo { bindings, cmd }
            } else {
                StepKind::WithIoBlock { bindings }
            }
        }
        Rule::for_statement => parse_for_statement_from_pair(ctx, pair, lctx)?,
        Rule::while_statement => parse_while_statement_from_pair(ctx, pair, lctx)?,
        Rule::func_def => parse_func_def_from_pair(ctx, pair, lctx)?,
        Rule::call_statement => parse_call_statement_from_pair(ctx, lctx, pair)?,
        Rule::return_statement => parse_return_statement_from_pair(ctx, lctx, pair)?,
        Rule::break_statement => StepKind::Break,
        Rule::continue_statement => StepKind::Continue,
        Rule::let_statement => parse_let_statement_from_pair(ctx, lctx, pair)?,
        Rule::mutate_statement => parse_mutate_statement_from_pair(ctx, lctx, pair)?,
        Rule::let_async_statement => parse_let_async_statement_from_pair(ctx, pair, lctx)?,
        Rule::let_capture_statement => parse_let_capture_statement_from_pair(ctx, pair, lctx)?,
        Rule::await_statement => parse_await_statement_from_pair(ctx, pair)?,
        Rule::cancel_statement => parse_cancel_statement_from_pair(ctx, pair)?,
        Rule::if_statement => parse_if_statement_from_pair(ctx, pair, lctx)?,
        Rule::async_statement => parse_async_statement_from_pair(ctx, pair, lctx)?,
        Rule::async_statement_block => parse_async_statement_block_from_pair(ctx, pair, lctx)?,
        Rule::timeout_statement => parse_timeout_statement_from_pair(ctx, pair, lctx)?,
        Rule::command_inner => {
            // command_inner = { inherit_env_command | instruction }
            // Unwrap to the inner rule
            let inner = pair.into_inner().next().ok_or_else(|| {
                ParseError::structural("parser", "empty command_inner".to_string(), &span)
            })?;
            parse_structural_command_with_lower(ctx, inner, lctx)?
        }
        Rule::instruction | Rule::instruction_inner => lower_instruction_pair(ctx, pair, lctx)?,
        Rule::run_exec_statement | Rule::run_exec_inner => lower_run_exec_pair(ctx, pair, lctx)?,
        _ => {
            return Err(ParseError::structural(
                "parser",
                format!("unexpected structural command rule: {:?}", pair.as_rule()),
                &span,
            ));
        }
    };
    Ok(kind)
}

fn extract_instruction(
    ctx: &SpanContext,
    pair: Pair<Rule>,
    lctx: &LowerCtx,
) -> ParseResult<(String, Vec<InsToken>)> {
    let span = refine_span(ctx, &pair);
    let mut name = None;
    let mut args = Vec::new();
    for inner in pair.into_inner() {
        match inner.as_rule() {
            Rule::command_name => {
                name = Some(inner.as_str().to_string());
            }
            Rule::argument => {
                args.extend(
                    parse_argument(ctx, lctx, inner)?
                        .into_iter()
                        .map(InsToken::Pos),
                );
            }
            Rule::assignment => {
                let (key, value) = parse_assignment(ctx, lctx, inner)?;
                args.push(InsToken::Assign(key, value));
            }
            _ => {}
        }
    }
    let name = name.ok_or_else(|| {
        ParseError::structural(
            "instruction",
            "instruction missing command name".to_string(),
            &span,
        )
    })?;
    Ok((name, args))
}

/// One lowered instruction token: a positional argument, or a pre-split
/// `KEY=value` assignment from the unified grammar rule. Assignments reach
/// ENV/EXPAND lowerings intact; every other command sees them collapsed to
/// canonical `key=value` text (see `lower_instruction_pair`).
enum InsToken {
    Pos(Arg),
    Assign(String, Arg),
}

/// Lower one generic instruction pair: ENV/EXPAND build `StepKind` directly
/// from pre-split assignments (never via the injected `lower`, mirroring how
/// LET/FOR/IF bypass it); all other commands flow through `lower` with
/// assignments in canonical text form.
fn lower_instruction_pair(
    ctx: &SpanContext,
    pair: Pair<Rule>,
    lctx: &LowerCtx,
) -> ParseResult<StepKind> {
    let span = refine_span(ctx, &pair);
    let (name, tokens) = extract_instruction(ctx, pair, lctx)?;
    if name == "ENV" {
        return lower_env_command(ctx, tokens);
    }
    if name == "EXPAND" {
        return lower_expand_command(ctx, tokens);
    }
    let args = tokens
        .into_iter()
        .map(|token| match token {
            InsToken::Pos(arg) => arg,
            InsToken::Assign(key, value) => crate::commands::canonical_assignment_arg(&key, &value),
        })
        .collect();
    (lctx.lower)(&name, args).map_err(|e| e.with_span(&span))
}

/// Lower a `run_exec` grammar pair: the PEG engine has already validated the
/// full `RUN [...]` span, so extract the inner `list_literal` and route the
/// structured `Expr::List` through the injected `lower` as `RUN` with one
/// typed argument (production `lower_command` maps it to `StepKind::RunExec`;
/// the grammar-test mock wraps it in `StepKind::Run`).
fn lower_run_exec_pair(
    ctx: &SpanContext,
    pair: Pair<Rule>,
    lctx: &LowerCtx,
) -> ParseResult<StepKind> {
    let span = refine_span(ctx, &pair);
    let mut list = None;
    for inner in pair.into_inner() {
        if inner.as_rule() == Rule::run_exec_list {
            list = Some(parse_run_exec_list(ctx, lctx, inner)?);
        }
    }
    let list = list.ok_or_else(|| {
        ParseError::structural(
            "run_exec",
            "RUN exec form missing list literal".to_string(),
            &span,
        )
    })?;
    (lctx.lower)("RUN", vec![Arg::Expr(list)]).map_err(|e| e.with_span(&span))
}

/// Lower a `run_exec_list` pair: like `parse_list_literal` but elements are
/// atoms only (see `run_exec_arg` in the grammar), so shell bracket content
/// never parses here. Numeric atoms lower exactly like expression atoms
/// (including the `i64::MIN` boundary rejection).
fn parse_run_exec_list(ctx: &SpanContext, lctx: &LowerCtx, pair: Pair<Rule>) -> ParseResult<Expr> {
    let mut items = Vec::new();
    for inner in pair.into_inner() {
        if inner.as_rule() == Rule::run_exec_arg {
            let item = parse_run_exec_arg(ctx, lctx, inner)?;
            reject_boundary(ctx, &item)?;
            items.push(item);
        }
    }
    Ok(Expr::List(items))
}

fn parse_run_exec_arg(ctx: &SpanContext, lctx: &LowerCtx, pair: Pair<Rule>) -> ParseResult<Expr> {
    let span = refine_span(ctx, &pair);
    let inner = pair.into_inner().next().ok_or_else(|| {
        ParseError::structural("run_exec", "RUN exec argument is empty".to_string(), &span)
    })?;
    match inner.as_rule() {
        Rule::parenthesized_expr => parse_expr_inner(ctx, lctx, inner.into_inner().next().unwrap()),
        Rule::func_call => parse_func_call(ctx, lctx, inner),
        Rule::key_path => parse_key_path(ctx, inner),
        Rule::variable => {
            let name = inner.as_str();
            let name = name.strip_prefix('$').unwrap_or(name).to_string();
            Ok(Expr::Var(name))
        }
        Rule::env_read => parse_env_read(ctx, inner).map(Expr::Env),
        Rule::list_literal => parse_list_literal(ctx, lctx, inner),
        Rule::map_literal => parse_map_literal(ctx, lctx, inner),
        Rule::block => Ok(Expr::Block(parse_block_elements_with_lower(
            ctx, inner, lctx,
        )?)),
        Rule::string_literal | Rule::quoted_string => {
            let s = parse_quoted_string(inner)?;
            Ok(Expr::Literal(Value::string(s)))
        }
        Rule::numeric_literal => parse_numeric_literal(ctx, inner),
        Rule::bare_word => {
            let s = inner.as_str().to_string();
            match s.as_str() {
                "true" => Ok(Expr::Literal(Value::bool(true))),
                "false" => Ok(Expr::Literal(Value::bool(false))),
                _ => Ok(Expr::Literal(Value::string(s))),
            }
        }
        _ => Err(ParseError::structural(
            "run_exec",
            format!("unexpected RUN exec argument rule: {:?}", inner.as_rule()),
            &span,
        )),
    }
}

/// Split one `assignment` pair into its key and lowered value.
fn parse_assignment(
    ctx: &SpanContext,
    lctx: &LowerCtx,
    pair: Pair<Rule>,
) -> ParseResult<(String, Arg)> {
    let span = refine_span(ctx, &pair);
    let mut key = None;
    let mut value = None;
    for inner in pair.into_inner() {
        match inner.as_rule() {
            Rule::assign_key => {
                key = Some(inner.as_str().to_string());
            }
            Rule::assign_value => {
                value = Some(lower_command_value(ctx, lctx, inner)?);
            }
            _ => {
                return Err(ParseError::structural(
                    "assignment",
                    format!("unexpected assignment rule: {:?}", inner.as_rule()),
                    &span,
                ));
            }
        }
    }
    Ok((
        key.ok_or_else(|| {
            ParseError::structural("assignment", "assignment missing key".to_string(), &span)
        })?,
        value.unwrap_or(Arg::String(String::new(), false)),
    ))
}

/// Single unified value lowering: every command's free-text value flows through
/// here on raw pest spans. Quoted bytes stay exact, lone `$var`/`$a.b`/`F()`
/// stay typed `Arg::Expr`, and anything else becomes literal text with only
/// `{{ }}` as the interpolation trigger. No heuristic rewriting, ever.
fn lower_command_value(ctx: &SpanContext, lctx: &LowerCtx, pair: Pair<Rule>) -> ParseResult<Arg> {
    let span = refine_span(ctx, &pair);
    let inner = pair.into_inner().next().ok_or_else(|| {
        ParseError::structural("assignment", "assignment value is empty".to_string(), &span)
    })?;
    match inner.as_rule() {
        Rule::quoted_string => Ok(Arg::String(parse_quoted_string(inner)?, true)),
        Rule::assign_expr => {
            let shape = inner.into_inner().next().ok_or_else(|| {
                ParseError::structural(
                    "assignment",
                    "assignment expression is empty".to_string(),
                    &span,
                )
            })?;
            match shape.as_rule() {
                Rule::variable => Ok(Arg::Expr(Expr::Var(parse_dollar_ident(shape)))),
                Rule::key_path => Ok(Arg::Expr(parse_key_path(ctx, shape)?)),
                Rule::env_read => Ok(Arg::Expr(Expr::Env(parse_env_read(ctx, shape)?))),
                Rule::func_call => Ok(Arg::Expr(parse_func_call(ctx, lctx, shape)?)),
                other => Err(ParseError::structural(
                    "assignment",
                    format!("unexpected assignment expression shape: {:?}", other),
                    &span,
                )),
            }
        }
        Rule::raw_fragments => lower_raw_fragments(ctx, inner),
        other => Err(ParseError::structural(
            "assignment",
            format!("unexpected assignment value rule: {:?}", other),
            &span,
        )),
    }
}

/// Assemble a bounded raw span into one literal `Arg::String`: `{{ }}` template
/// chunks pass through verbatim for `expand_string`, quoted chunks unquote
/// once with exact bytes, and unquoted runs collapse whitespace to single
/// spaces (trailing/leading edges trimmed). Pure text needs no `Parts` — every
/// fragment resolves through the same `expand_string` pass.
fn lower_raw_fragments(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<Arg> {
    let span = refine_span(ctx, &pair);
    let mut body = String::new();
    for fragment in pair.into_inner() {
        match fragment.as_rule() {
            Rule::quoted_string => body.push_str(&parse_quoted_string(fragment)?),
            Rule::templated_arg => body.push_str(fragment.as_str()),
            Rule::raw_text => body.push_str(&collapse_ws(fragment.as_str())),
            other => {
                return Err(ParseError::structural(
                    "assignment",
                    format!("unexpected raw value fragment: {:?}", other),
                    &span,
                ));
            }
        }
    }
    Ok(Arg::String(body.trim().to_string(), false))
}

/// Collapse every whitespace run to a single space, preserving edge positions
/// (callers trim the assembled value).
fn collapse_ws(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut in_run = false;
    for c in s.chars() {
        if c.is_whitespace() {
            if !in_run {
                out.push(' ');
                in_run = true;
            }
        } else {
            out.push(c);
            in_run = false;
        }
    }
    out
}

/// Parser-direct `ENV` lowering: exactly one assignment. A lone positional
/// holding `=` is the exotic-key fringe (keys the grammar cannot classify);
/// anything else is a precise error instead of a silent drop.
fn lower_env_command(ctx: &SpanContext, tokens: Vec<InsToken>) -> ParseResult<StepKind> {
    if tokens.is_empty() {
        return Err(ParseError::validation(
            "ENV",
            "ENV requires KEY=value".to_string(),
            ctx,
        ));
    }
    match tokens.as_slice() {
        [InsToken::Assign(key, value)] => {
            // Same KEY=value check the ENV lower applies on the
            // `lower_command` path, over the joined assignment form.
            if crate::command::split_assignment(&format!("{key}={}", value.render()))
                .map_err(|e| ParseError::validation("ENV", e.to_string(), ctx))?
                .is_none()
            {
                return Err(ParseError::validation(
                    "ENV",
                    "ENV requires KEY=value format".to_string(),
                    ctx,
                ));
            }
            Ok(StepKind::Env {
                key: key.clone(),
                value: value.clone(),
            })
        }
        [InsToken::Pos(Arg::String(text, _))] => match crate::command::split_assignment(text)
            .map_err(|e| ParseError::validation("ENV", e.to_string(), ctx))?
        {
            Some((key, value)) => Ok(StepKind::Env { key, value }),
            None => Err(ParseError::validation(
                "ENV",
                "ENV requires KEY=value format".to_string(),
                ctx,
            )),
        },
        _ => Err(ParseError::validation(
            "ENV",
            "ENV requires KEY=value format".to_string(),
            ctx,
        )),
    }
}

/// Parser-direct `EXPAND` lowering: positional tokens are the optional path,
/// assignments are overrides. Split quoted values can never masquerade as
/// extra paths — tokenize time already proved they are one value.
fn lower_expand_command(ctx: &SpanContext, tokens: Vec<InsToken>) -> ParseResult<StepKind> {
    let mut path = None;
    let mut overrides = Vec::new();
    for token in tokens {
        match token {
            InsToken::Assign(key, value) => {
                if key.is_empty() {
                    return Err(ParseError::validation(
                        "EXPAND",
                        "EXPAND requires KEY=value format for overrides".to_string(),
                        ctx,
                    ));
                }
                overrides.push((key, value));
            }
            InsToken::Pos(arg) => match &arg {
                Arg::String(text, quoted) if !quoted && text.contains('=') => {
                    let Some((key, value)) = crate::command::split_assignment(text)
                        .map_err(|e| ParseError::validation("EXPAND", e.to_string(), ctx))?
                    else {
                        return Err(ParseError::validation(
                            "EXPAND",
                            "EXPAND requires KEY=value format for overrides".to_string(),
                            ctx,
                        ));
                    };
                    overrides.push((key, value));
                }
                _ => {
                    if path.is_none() {
                        // Path-typed positional, checked like every other
                        // `lower_command` path arg (literals always pass;
                        // resolution stays runtime).
                        ArgType::Path
                            .check_arg(&arg)
                            .map_err(|e| ParseError::validation("EXPAND", e.to_string(), ctx))?;
                        path = Some(arg);
                    } else {
                        return Err(ParseError::validation(
                            "EXPAND",
                            "EXPAND accepts at most one path".to_string(),
                            ctx,
                        ));
                    }
                }
            },
        }
    }
    Ok(StepKind::Expand { path, overrides })
}

fn parse_type_tag(pair: Pair<Rule>) -> String {
    // The open `type_tag` rule accepts any uppercase identifier; tags are
    // plain names here and resolve against the descriptor table at runtime.
    pair.as_str().trim().to_string()
}

fn check_func_ident(ctx: &SpanContext, name: &str) -> ParseResult<()> {
    let ok = name
        .chars()
        .next()
        .map(|c| c.is_ascii_uppercase())
        .unwrap_or(false)
        && name
            .chars()
            .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_');
    if !ok {
        return Err(ParseError::validation(
            "FUNC",
            format!(
                "function names must be UPPERCASE (ASCII_ALPHA_UPPER, digits, _), got `{name}`"
            ),
            ctx,
        ));
    }
    Ok(())
}

fn parse_while_statement_from_pair(
    ctx: &SpanContext,
    pair: Pair<Rule>,
    lctx: &LowerCtx,
) -> ParseResult<StepKind> {
    let span = refine_span(ctx, &pair);
    let mut cond = None;
    let mut body = None;
    for inner in pair.into_inner() {
        match inner.as_rule() {
            Rule::expr => {
                if cond.is_none() {
                    cond = Some(parse_expr(ctx, lctx, inner)?);
                }
            }
            Rule::block => {
                body = Some(parse_block_elements_with_lower(ctx, inner, lctx)?);
            }
            _ => {}
        }
    }
    Ok(StepKind::While {
        cond: Box::new(cond.ok_or_else(|| {
            ParseError::validation("WHILE", "WHILE requires a condition".to_string(), &span)
        })?),
        body: body.ok_or_else(|| {
            ParseError::validation("WHILE", "WHILE requires a block".to_string(), &span)
        })?,
    })
}

fn parse_func_def_from_pair(
    ctx: &SpanContext,
    pair: Pair<Rule>,
    lctx: &LowerCtx,
) -> ParseResult<StepKind> {
    let span = refine_span(ctx, &pair);
    // Declare before lowering the body so recursive self-calls resolve:
    // the name is visible from its definition line, in execution order,
    // exactly like `LET`. (Mutual recursion stays unsupported: the second
    // name does not exist while the first body lowers.)
    let def_name = pair
        .clone()
        .into_inner()
        .find(|inner| inner.as_rule() == Rule::func_ident)
        .map(|inner| inner.as_str().to_string())
        .ok_or_else(|| ParseError::validation("FUNC", "FUNC requires a name".to_string(), &span))?;
    check_func_ident(ctx, &def_name)?;
    // Same-scope duplicates and reserved-name shadows fail here, at the
    // definition line: the post-parse AST keeps no spans, so a later walk
    // could only point at end of file. Nested shadowing of an outer DSL
    // name stays allowed and reverts on scope exit at runtime. Reserved
    // covers the flat host set plus every module's base names: a `FUNC`
    // defines `SCRIPT::NAME`, which would collide on bare resolution.
    if lctx.reserved_names.contains(&def_name) || lctx.module_base_names().contains(&def_name) {
        return Err(ParseError::validation(
            "FUNC",
            format!("FUNC {def_name} cannot shadow reserved function `{def_name}`"),
            &span,
        ));
    }
    if !lctx.declare_func(&def_name) {
        return Err(ParseError::validation(
            "FUNC",
            format!("duplicate function `{def_name}` in same scope"),
            &span,
        ));
    }
    let mut name: Option<String> = None;
    let mut param_names: Vec<String> = Vec::new();
    let mut param_types: Vec<String> = Vec::new();
    let mut body = None;
    for inner in pair.into_inner() {
        match inner.as_rule() {
            Rule::func_ident => {
                if name.is_none() {
                    name = Some(inner.as_str().to_string());
                }
            }
            Rule::func_param => {
                let mut pname = None;
                let mut ptype = None;
                for part in inner.into_inner() {
                    match part.as_rule() {
                        Rule::dollar_ident => {
                            pname = Some(parse_dollar_ident(part));
                        }
                        Rule::type_tag => {
                            ptype = Some(parse_type_tag(part));
                        }
                        _ => {}
                    }
                }
                param_names.push(pname.ok_or_else(|| {
                    ParseError::validation(
                        "FUNC",
                        "FUNC parameter requires a $variable".to_string(),
                        &span,
                    )
                })?);
                param_types.push(ptype.ok_or_else(|| {
                    ParseError::validation(
                        "FUNC",
                        "FUNC parameters require explicit types: FUNC NAME($p: TYPE, ...)"
                            .to_string(),
                        &span,
                    )
                })?);
            }
            Rule::block => {
                body = Some(parse_block_elements_with_lower(ctx, inner, lctx)?);
            }
            _ => {}
        }
    }
    let name = name
        .ok_or_else(|| ParseError::validation("FUNC", "FUNC requires a name".to_string(), &span))?;
    check_func_ident(ctx, &name)?;
    if param_names.len() != param_types.len() {
        return Err(ParseError::validation(
            "FUNC",
            format!("FUNC {name} has mismatched parameter names and types"),
            &span,
        ));
    }
    let mut seen = std::collections::HashSet::new();
    for pname in &param_names {
        if !seen.insert(pname.clone()) {
            return Err(ParseError::validation(
                "FUNC",
                format!("FUNC {name} declares duplicate parameter ${pname}"),
                &span,
            ));
        }
    }
    Ok(StepKind::FuncDef {
        name,
        params: param_names.into_iter().zip(param_types).collect(),
        body: body.ok_or_else(|| {
            ParseError::validation("FUNC", "FUNC requires a block".to_string(), &span)
        })?,
    })
}

fn parse_call_statement_from_pair(
    ctx: &SpanContext,
    lctx: &LowerCtx,
    pair: Pair<Rule>,
) -> ParseResult<StepKind> {
    let span = refine_span(ctx, &pair);
    let mut name: Option<String> = None;
    let mut args = Vec::new();
    // The head arrives wrapped in the atomic `call_head_paren` token (which
    // is what forbids whitespace before `(`). Atomic tokens produce no
    // inner pairs, so the name comes from the token text minus its `(`.
    for inner in pair.into_inner() {
        match inner.as_rule() {
            Rule::call_head_paren => {
                if name.is_none() {
                    let text = inner.as_str();
                    name = Some(text.strip_suffix('(').unwrap_or(text).to_string());
                }
            }
            Rule::func_call_head => {
                if name.is_none() {
                    name = Some(inner.as_str().to_string());
                }
            }
            Rule::expr => {
                args.push(parse_expr(ctx, lctx, inner)?);
            }
            _ => {}
        }
    }
    let name = name.ok_or_else(|| {
        ParseError::validation(
            "FUNC",
            "function call requires a function name".to_string(),
            &span,
        )
    })?;
    // Bare heads keep the legacy UPPERCASE check; qualified heads validate
    // per part inside resolution. Either way the emitted call is qualified.
    if !name.contains(MODULE_SEPARATOR) {
        check_func_ident(ctx, &name)?;
    }
    let qualified = lctx.resolve_call(&span, &name)?;
    Ok(StepKind::Call {
        name: qualified,
        args,
    })
}

fn parse_return_statement_from_pair(
    ctx: &SpanContext,
    lctx: &LowerCtx,
    pair: Pair<Rule>,
) -> ParseResult<StepKind> {
    use crate::ast::Value;
    for inner in pair.into_inner() {
        if inner.as_rule() == Rule::expr {
            return Ok(StepKind::Return {
                expr: Box::new(parse_expr(ctx, lctx, inner)?),
            });
        }
    }
    Ok(StepKind::Return {
        expr: Box::new(Expr::Literal(Value::string(String::new()))),
    })
}

fn parse_for_statement_from_pair(
    ctx: &SpanContext,
    pair: Pair<Rule>,
    lctx: &LowerCtx,
) -> ParseResult<StepKind> {
    let span = refine_span(ctx, &pair);
    let mut idents: Vec<String> = Vec::new();
    let mut types: Vec<String> = Vec::new();
    let mut type_spans: Vec<SpanContext> = Vec::new();
    let mut in_expr = None;
    let mut body_steps = Vec::new();
    for inner in pair.into_inner() {
        match inner.as_rule() {
            Rule::dollar_ident => {
                idents.push(parse_dollar_ident(inner));
            }
            Rule::type_tag => {
                type_spans.push(refine_span(ctx, &inner));
                types.push(parse_type_tag(inner));
            }
            Rule::expr => {
                in_expr = Some(parse_expr(ctx, lctx, inner)?);
            }
            Rule::block => {
                body_steps = parse_block_elements_with_lower(ctx, inner, lctx)?;
            }
            _ => {}
        }
    }
    if idents.len() != types.len() {
        return Err(ParseError::validation(
            "FOR",
            format!(
                "FOR requires explicit types: FOR $item: TYPE IN <expr> (got {} vars, {} types)",
                idents.len(),
                types.len()
            ),
            &span,
        ));
    }
    let (key_var, key_type, var, var_type) = match idents.len() {
        1 => (
            None,
            None,
            idents.into_iter().next().unwrap(),
            types.into_iter().next().unwrap(),
        ),
        2 => {
            let mut iv = idents.into_iter();
            let mut tv = types.into_iter();
            (
                Some(iv.next().unwrap()),
                Some(tv.next().unwrap()),
                iv.next().unwrap(),
                tv.next().unwrap(),
            )
        }
        _ => {
            return Err(ParseError::validation(
                "FOR",
                "FOR requires one or two variables".to_string(),
                &span,
            ));
        }
    };
    if let Some(kt) = &key_type
        && kt != "STRING"
        && kt != "INT"
    {
        // Pinpoint the offending key type tag rather than the statement.
        let at = type_spans.first().unwrap_or(&span);
        return Err(ParseError::validation(
            "FOR",
            format!("FOR key variable must be INT or STRING, got {kt}"),
            at,
        ));
    }
    Ok(StepKind::For {
        key_var,
        key_type,
        var,
        var_type,
        in_expr: in_expr.ok_or_else(|| {
            ParseError::validation(
                "FOR",
                "FOR requires an iterable expression".to_string(),
                &span,
            )
        })?,
        body: body_steps,
    })
}

fn parse_let_statement_from_pair(
    ctx: &SpanContext,
    lctx: &LowerCtx,
    pair: Pair<Rule>,
) -> ParseResult<StepKind> {
    let span = refine_span(ctx, &pair);
    let mut var = None;
    let mut decl_type = None;
    let mut expr = None;
    for inner in pair.into_inner() {
        match inner.as_rule() {
            Rule::dollar_ident => {
                var = Some(parse_dollar_ident(inner));
            }
            Rule::type_tag => {
                decl_type = Some(parse_type_tag(inner));
            }
            Rule::expr => {
                expr = Some(parse_expr(ctx, lctx, inner)?);
            }
            _ => {}
        }
    }
    let var = var.ok_or_else(|| {
        ParseError::validation("LET", "LET requires a variable".to_string(), &span)
    })?;
    let decl_type = decl_type.ok_or_else(|| {
        ParseError::validation(
            "LET",
            "LET requires explicit type: LET $var: TYPE = <expr>".to_string(),
            &span,
        )
    })?;
    // Bare `LET $p: PIPE` (no initializer) mints a fresh anonymous pipe.
    // Every other type still requires `= <expr>`.
    let expr = match expr {
        Some(e) => e,
        None if decl_type == "PIPE" => Expr::FreshPipe,
        None => {
            return Err(ParseError::validation(
                "LET",
                "LET requires an expression: LET $var: TYPE = <expr> (only LET $p: PIPE omits the initializer)".to_string(),
                &span,
            ));
        }
    };
    Ok(StepKind::Assign {
        var,
        decl_type,
        expr,
    })
}

fn parse_mutate_statement_from_pair(
    ctx: &SpanContext,
    lctx: &LowerCtx,
    pair: Pair<Rule>,
) -> ParseResult<StepKind> {
    let span = refine_span(ctx, &pair);
    let mut var = None;
    let mut expr = None;
    for inner in pair.into_inner() {
        match inner.as_rule() {
            Rule::dollar_ident => {
                var = Some(parse_dollar_ident(inner));
            }
            Rule::expr => {
                expr = Some(parse_expr(ctx, lctx, inner)?);
            }
            _ => {}
        }
    }
    Ok(StepKind::Set {
        var: var.ok_or_else(|| {
            ParseError::validation(
                "mutate",
                "mutation requires a variable: $var = <expr>".to_string(),
                &span,
            )
        })?,
        expr: expr.ok_or_else(|| {
            ParseError::validation(
                "mutate",
                "mutation requires an expression: $var = <expr>".to_string(),
                &span,
            )
        })?,
    })
}

fn parse_let_async_statement_from_pair(
    ctx: &SpanContext,
    pair: Pair<Rule>,
    lctx: &LowerCtx,
) -> ParseResult<StepKind> {
    let span = refine_span(ctx, &pair);
    let mut var = None;
    let mut decl_type: Option<String> = None;
    let mut body = None;
    for inner in pair.into_inner() {
        match inner.as_rule() {
            Rule::dollar_ident => {
                var = Some(parse_dollar_ident(inner));
            }
            Rule::type_tag => {
                decl_type = Some(parse_type_tag(inner));
            }
            Rule::block => {
                body = Some(parse_block_elements_with_lower(ctx, inner, lctx)?);
            }
            Rule::command_inner => {
                // command_inner = { inherit_env_command | async_statement | async_statement_block | instruction }
                // Unwrap to the inner rule
                let inner = inner.into_inner().next().ok_or_else(|| {
                    ParseError::structural("let", "empty command_inner".to_string(), &span)
                })?;
                let step_kind = parse_structural_command_with_lower(ctx, inner, lctx)?;
                body = Some(vec![Step {
                    guard: None,
                    kind: step_kind,
                    scope_enter: 0,
                    scope_exit: 0,
                }]);
            }
            Rule::with_io_command => {
                // LET $var: TYPE = WITH_IO [flags] ... — two shapes share this rule
                // (`let_async_statement` precedes `let_capture_statement` in
                // the grammar, so every WITH_IO-led LET lands here):
                // - wrapping ASYNC binds a pipe-wired background task. The
                //   bindings apply inside the task thread — the same shape as
                //   a braced body holding one WITH_IO step, which the
                //   AssignAsync runtime path supports.
                // - wrapping a synchronous command captures its stdout into
                //   the variable (same semantics as LET $x: STRING = <command>).
                let kind = parse_structural_command_with_lower(ctx, inner, lctx)?;
                let StepKind::WithIo { bindings, cmd } = kind else {
                    return Err(ParseError::validation("LET", "LET $var: TYPE = WITH_IO requires an ASYNC command (e.g. LET $t = WITH_IO [stdin=$p] ASYNC WRITE \"f\")".to_string(), &span));
                };
                match *cmd {
                    StepKind::AsyncBlock { body: async_body } => {
                        if async_body.len() != 1 {
                            return Err(ParseError::structural("let", "LET $var: TYPE = WITH_IO [..] ASYNC accepts a single command; use LET $var: HANDLE = ASYNC {{ ... }} with WITH_IO inside the block for multi-step tasks".to_string(), &span));
                        }
                        let step = async_body.into_iter().next().ok_or_else(|| {
                            ParseError::validation(
                                "LET",
                                "LET $var: HANDLE = ASYNC requires a body".to_string(),
                                &span,
                            )
                        })?;
                        body = Some(vec![Step {
                            guard: step.guard,
                            kind: StepKind::WithIo {
                                bindings,
                                cmd: Box::new(step.kind),
                            },
                            scope_enter: step.scope_enter,
                            scope_exit: step.scope_exit,
                        }]);
                    }
                    sync_cmd => {
                        if has_stdout_pipe(&bindings) {
                            return Err(ParseError::structural("let", "LET capture cannot use WITH_IO [stdout=$var]; the capture sink owns stdout".to_string(), &span));
                        }
                        reject_async_in_capture(ctx, &sync_cmd)?;
                        let name = var.clone().ok_or_else(|| {
                            ParseError::validation(
                                "LET",
                                "LET $var: TYPE = WITH_IO requires a variable".to_string(),
                                &span,
                            )
                        })?;
                        let dtype = decl_type.ok_or_else(|| {
                            ParseError::validation(
                                "LET",
                                "LET requires explicit type: LET $var: TYPE = ...".to_string(),
                                &span,
                            )
                        })?;
                        return Ok(StepKind::AssignCapture {
                            var: name,
                            decl_type: dtype,
                            cmd: Box::new(StepKind::WithIo {
                                bindings,
                                cmd: Box::new(sync_cmd),
                            }),
                        });
                    }
                }
            }
            _ => {}
        }
    }
    Ok(StepKind::AssignAsync {
        var: var.ok_or_else(|| {
            ParseError::validation(
                "LET",
                "LET $var: HANDLE = ASYNC requires a variable".to_string(),
                &span,
            )
        })?,
        decl_type: decl_type.ok_or_else(|| {
            ParseError::validation(
                "LET",
                "LET requires explicit type: LET $var: TYPE = ...".to_string(),
                &span,
            )
        })?,
        body: body.ok_or_else(|| {
            ParseError::validation(
                "LET",
                "LET $var: HANDLE = ASYNC requires a body".to_string(),
                &span,
            )
        })?,
    })
}

/// Lower `LET $var: STRING = <sync command>` / `LET $out: STRING = AWAIT $task`.
///
/// Shadow-safe by construction: the grammar only routes UPPERCASE-led
/// `instruction` lines here (`let_async_statement` claims ASYNC-led and
/// WITH_IO-led lines first; lowercase/digit/sigil RHSs never match). Rust
/// then branches on the lead token: known commands lower to capture,
/// unknown leads re-parse as plain expressions.
fn parse_let_capture_statement_from_pair(
    ctx: &SpanContext,
    pair: Pair<Rule>,
    lctx: &LowerCtx,
) -> ParseResult<StepKind> {
    let span = refine_span(ctx, &pair);
    use pest::Parser;
    let mut var = None;
    let mut decl_type: Option<String> = None;
    let mut await_pair = None;
    let mut timeout_pair = None;
    let mut instruction_pair = None;
    for inner in pair.into_inner() {
        match inner.as_rule() {
            Rule::dollar_ident => {
                var = Some(parse_dollar_ident(inner));
            }
            Rule::type_tag => {
                decl_type = Some(parse_type_tag(inner));
            }
            Rule::await_statement => {
                await_pair = Some(inner);
            }
            Rule::timeout_statement => {
                timeout_pair = Some(inner);
            }
            Rule::instruction => {
                instruction_pair = Some(inner);
            }
            _ => {}
        }
    }
    let var = var.ok_or_else(|| {
        ParseError::validation("LET", "LET requires a variable".to_string(), &span)
    })?;
    let dtype: String = decl_type.ok_or_else(|| {
        ParseError::validation(
            "LET",
            "LET requires explicit type: LET $var: TYPE = ...".to_string(),
            &span,
        )
    })?;
    if let Some(awaited) = await_pair {
        let mut task_var = None;
        for inner in awaited.into_inner() {
            if inner.as_rule() == Rule::ident {
                task_var = Some(inner.as_str().to_string());
            }
        }
        return Ok(StepKind::AwaitCapture {
            out_var: var,
            out_type: dtype,
            task_var: task_var.ok_or_else(|| {
                ParseError::validation(
                    "LET",
                    "LET $out = AWAIT requires a task variable".to_string(),
                    &span,
                )
            })?,
        });
    }
    if let Some(timeouted) = timeout_pair {
        let kind = parse_structural_command_with_lower(ctx, timeouted, lctx)?;
        reject_async_in_capture(ctx, &kind)?;
        reject_pipe_stdout_in_capture(ctx, &kind)?;
        return Ok(StepKind::AssignCapture {
            var,
            decl_type: dtype,
            cmd: Box::new(kind),
        });
    }
    if let Some(ins) = instruction_pair {
        let text = ins.as_str().to_string();
        let mut lead = None;
        for token in ins.into_inner() {
            if token.as_rule() == Rule::command_name {
                lead = Some(token.as_str().to_string());
                break;
            }
        }
        let lead = lead.ok_or_else(|| {
            ParseError::validation("LET", "LET capture requires a command".to_string(), &span)
        })?;
        if crate::commands::is_known_command(&lead) {
            let kind = lower_instruction_pair(
                ctx,
                lexer::LanguageParser::parse(Rule::instruction, &text)
                    .map_err(parse_pest_error)?
                    .next()
                    .ok_or_else(|| {
                        ParseError::validation(
                            "LET",
                            "LET capture requires a command".to_string(),
                            &span,
                        )
                    })?,
                lctx,
            )?;
            reject_async_in_capture(ctx, &kind)?;
            reject_pipe_stdout_in_capture(ctx, &kind)?;
            return Ok(StepKind::AssignCapture {
                var,
                decl_type: dtype,
                cmd: Box::new(kind),
            });
        }
        let expr = parse_expr_str(&span, lctx, &text)?;
        return Ok(StepKind::Assign {
            var,
            decl_type: dtype,
            expr,
        });
    }
    Err(ParseError::structural(
        "let",
        "LET requires a value".to_string(),
        &span,
    ))
}

fn parse_await_statement_from_pair(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<StepKind> {
    let span = refine_span(ctx, &pair);
    let mut var = None;
    for inner in pair.into_inner() {
        if inner.as_rule() == Rule::ident {
            var = Some(inner.as_str().to_string());
        }
    }
    Ok(StepKind::Await {
        var: var.ok_or_else(|| {
            ParseError::validation("AWAIT", "AWAIT requires a variable".to_string(), &span)
        })?,
    })
}

fn parse_cancel_statement_from_pair(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<StepKind> {
    let span = refine_span(ctx, &pair);
    let mut var = None;
    for inner in pair.into_inner() {
        if inner.as_rule() == Rule::ident {
            var = Some(inner.as_str().to_string());
        }
    }
    Ok(StepKind::Cancel {
        var: var.ok_or_else(|| {
            ParseError::validation("CANCEL", "CANCEL requires a variable".to_string(), &span)
        })?,
    })
}

/// Build a TIMEOUT duration [`Arg`] from the widened `timeout_duration`
/// alternatives. Static literals type-check now via the declared Duration
/// arg type; dynamics (`$var`, templates) resolve at runtime.
fn parse_timeout_duration_arg(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<Arg> {
    let span = refine_span(ctx, &pair);
    for inner in pair.into_inner() {
        let arg = match inner.as_rule() {
            Rule::timeout_literal => Arg::String(inner.as_str().to_string(), false),
            Rule::dollar_ident => Arg::Expr(Expr::Var(parse_dollar_ident(inner))),
            Rule::quoted_string => Arg::String(
                crate::command::strip_surrounding_quotes(inner.as_str()).to_string(),
                true,
            ),
            Rule::templated_arg => Arg::String(inner.as_str().to_string(), false),
            _ => continue,
        };
        ArgType::Duration
            .check_arg(&arg)
            .map_err(|e| ParseError::validation("TIMEOUT", e.to_string(), &span))?;
        return Ok(arg);
    }
    Err(ParseError::validation(
        "TIMEOUT",
        "TIMEOUT requires a duration".to_string(),
        &span,
    ))
}

fn parse_timeout_statement_from_pair(
    ctx: &SpanContext,
    pair: Pair<Rule>,
    lctx: &LowerCtx,
) -> ParseResult<StepKind> {
    let span = refine_span(ctx, &pair);
    let mut duration: Option<Arg> = None;
    let mut body: Option<Vec<Step>> = None;
    for inner in pair.into_inner() {
        match inner.as_rule() {
            Rule::timeout_duration => {
                duration = Some(parse_timeout_duration_arg(ctx, inner)?);
            }
            Rule::block => {
                body = Some(parse_block_elements_with_lower(ctx, inner, lctx)?);
            }
            Rule::await_statement => {
                let kind = parse_await_statement_from_pair(ctx, inner)?;
                body = Some(vec![Step {
                    guard: None,
                    kind,
                    scope_enter: 0,
                    scope_exit: 0,
                }]);
            }
            Rule::cancel_statement => {
                let kind = parse_cancel_statement_from_pair(ctx, inner)?;
                body = Some(vec![Step {
                    guard: None,
                    kind,
                    scope_enter: 0,
                    scope_exit: 0,
                }]);
            }
            Rule::with_io_command
            | Rule::inherit_env_command
            | Rule::async_statement
            | Rule::async_statement_block
            | Rule::call_statement
            | Rule::while_statement
            | Rule::func_def
            | Rule::return_statement
            | Rule::break_statement
            | Rule::continue_statement
            | Rule::timeout_statement => {
                let kind = parse_structural_command_with_lower(ctx, inner, lctx)?;
                body = Some(vec![Step {
                    guard: None,
                    kind,
                    scope_enter: 0,
                    scope_exit: 0,
                }]);
            }
            Rule::instruction | Rule::instruction_inner => {
                let kind = lower_instruction_pair(ctx, inner, lctx)?;
                body = Some(vec![Step {
                    guard: None,
                    kind,
                    scope_enter: 0,
                    scope_exit: 0,
                }]);
            }
            Rule::run_exec_statement | Rule::run_exec_inner => {
                let kind = lower_run_exec_pair(ctx, inner, lctx)?;
                body = Some(vec![Step {
                    guard: None,
                    kind,
                    scope_enter: 0,
                    scope_exit: 0,
                }]);
            }
            _ => {}
        }
    }
    Ok(StepKind::Timeout {
        duration: duration.ok_or_else(|| {
            ParseError::validation("TIMEOUT", "TIMEOUT requires a duration".to_string(), &span)
        })?,
        body: body.ok_or_else(|| {
            ParseError::validation(
                "TIMEOUT",
                "TIMEOUT requires a command or block".to_string(),
                &span,
            )
        })?,
    })
}

fn parse_if_statement_from_pair(
    ctx: &SpanContext,
    pair: Pair<Rule>,
    lctx: &LowerCtx,
) -> ParseResult<StepKind> {
    let span = refine_span(ctx, &pair);
    let mut cond = None;
    let mut then_body = Vec::new();
    let mut else_ifs = Vec::new();
    let mut else_body = None;

    for inner in pair.into_inner() {
        match inner.as_rule() {
            Rule::expr => {
                if cond.is_none() {
                    cond = Some(parse_expr(ctx, lctx, inner)?);
                }
            }
            Rule::block => {
                if then_body.is_empty() {
                    then_body = parse_block_elements_with_lower(ctx, inner, lctx)?;
                }
            }
            Rule::else_if_clause => {
                let (eif_cond, eif_body) = parse_else_if_clause(ctx, inner, lctx)?;
                else_ifs.push((eif_cond, eif_body));
            }
            Rule::else_clause => {
                else_body = Some(parse_else_clause(ctx, inner, lctx)?);
            }
            _ => {}
        }
    }
    Ok(StepKind::If {
        cond: Box::new(cond.ok_or_else(|| {
            ParseError::structural("if", "IF requires a condition".to_string(), &span)
        })?),
        then_body,
        else_ifs,
        else_body,
    })
}

fn parse_else_if_clause(
    ctx: &SpanContext,
    pair: Pair<Rule>,
    lctx: &LowerCtx,
) -> ParseResult<(Box<Expr>, Vec<Step>)> {
    let span = refine_span(ctx, &pair);
    let mut cond = None;
    let mut body = Vec::new();
    for inner in pair.into_inner() {
        match inner.as_rule() {
            Rule::expr => cond = Some(parse_expr(ctx, lctx, inner)?),
            Rule::block => body = parse_block_elements_with_lower(ctx, inner, lctx)?,
            _ => {}
        }
    }
    Ok((
        Box::new(cond.ok_or_else(|| {
            ParseError::structural("if", "ELSE IF requires a condition".to_string(), &span)
        })?),
        body,
    ))
}

fn parse_else_clause(
    ctx: &SpanContext,
    pair: Pair<Rule>,
    lctx: &LowerCtx,
) -> ParseResult<Vec<Step>> {
    for inner in pair.into_inner() {
        if let Rule::block = inner.as_rule() {
            return parse_block_elements_with_lower(ctx, inner, lctx);
        }
    }
    Ok(Vec::new())
}

fn parse_async_statement_from_pair(
    ctx: &SpanContext,
    pair: Pair<Rule>,
    lctx: &LowerCtx,
) -> ParseResult<StepKind> {
    let span = refine_span(ctx, &pair);
    let mut inner_cmd = None;
    let mut block_body = None;
    for inner in pair.into_inner() {
        match inner.as_rule() {
            Rule::command => {
                // command is _{} = silent, so its children aren't visible as pairs
                // when nested inside compound-atomic async_statement.
                // Parse the command text directly, seeding the snippet with
                // this point's visible scope so calls resolve identically.
                let cmd_text = inner.as_str();
                let (preseed_funcs, preseed_imports) = lctx.visible_snapshot();
                let steps = parse_script_with_preseed(
                    cmd_text,
                    |name, args| (lctx.lower)(name, args),
                    lctx.reserved_names.clone(),
                    lctx.modules.clone(),
                    preseed_funcs,
                    preseed_imports,
                )?;
                if steps.len() == 1 {
                    inner_cmd = Some(steps.into_iter().next().unwrap().kind);
                } else {
                    return Err(ParseError::structural(
                        "async",
                        "unexpected multiple steps in async inner command".to_string(),
                        &span,
                    ));
                }
            }
            Rule::command_inner => {
                // command_inner = { inherit_env_command | async_statement | async_statement_block | instruction }
                let child = inner.into_inner().next().ok_or_else(|| {
                    ParseError::structural("async", "empty command_inner".to_string(), &span)
                })?;
                match child.as_rule() {
                    Rule::inherit_env_command => {
                        inner_cmd = Some(parse_structural_command_with_lower(ctx, child, lctx)?);
                    }
                    Rule::async_statement | Rule::async_statement_block => {
                        inner_cmd = Some(parse_structural_command_with_lower(ctx, child, lctx)?);
                    }
                    Rule::timeout_statement | Rule::cancel_statement => {
                        inner_cmd = Some(parse_structural_command_with_lower(ctx, child, lctx)?);
                    }
                    Rule::call_statement | Rule::while_statement => {
                        inner_cmd = Some(parse_structural_command_with_lower(ctx, child, lctx)?);
                    }
                    Rule::func_def
                    | Rule::return_statement
                    | Rule::break_statement
                    | Rule::continue_statement => {
                        return Err(ParseError::structural(
                            "async",
                            format!(
                                "{:?} cannot run as a lone ASYNC command; use ASYNC {{ ... }} block form if needed",
                                child.as_rule()
                            ),
                            &span,
                        ));
                    }
                    Rule::instruction => {
                        inner_cmd = Some(lower_instruction_pair(ctx, child, lctx)?);
                    }
                    Rule::run_exec_statement | Rule::run_exec_inner => {
                        inner_cmd = Some(lower_run_exec_pair(ctx, child, lctx)?);
                    }
                    other => {
                        return Err(ParseError::structural(
                            "async",
                            format!("unexpected command_inner child: {:?}", other),
                            &span,
                        ));
                    }
                }
            }
            Rule::instruction | Rule::instruction_inner => {
                inner_cmd = Some(lower_instruction_pair(ctx, inner, lctx)?);
            }
            Rule::run_exec_statement | Rule::run_exec_inner => {
                inner_cmd = Some(lower_run_exec_pair(ctx, inner, lctx)?);
            }
            Rule::block => {
                block_body = Some(parse_block_elements_with_lower(ctx, inner, lctx)?);
            }
            _ => {}
        }
    }
    if let Some(body) = block_body {
        for step in &body {
            if matches!(&step.kind, StepKind::WithIo { .. }) {
                return Err(ParseError::structural("async", "WITH_IO cannot be placed inside ASYNC. Place WITH_IO outside ASYNC instead (e.g. WITH_IO [...] ASYNC RUN ...)".to_string(), &span));
            }
        }
        Ok(StepKind::AsyncBlock { body })
    } else if let Some(cmd) = inner_cmd {
        if matches!(&cmd, StepKind::WithIo { .. }) {
            return Err(ParseError::structural("async", "WITH_IO cannot be placed inside ASYNC. Place WITH_IO outside ASYNC instead (e.g. WITH_IO [...] ASYNC RUN ...)".to_string(), &span));
        }
        Ok(StepKind::AsyncBlock {
            body: vec![Step {
                guard: None,
                kind: cmd,
                scope_enter: 0,
                scope_exit: 0,
            }],
        })
    } else {
        Err(ParseError::structural(
            "async",
            "ASYNC requires either a command or a block".to_string(),
            &span,
        ))
    }
}

fn parse_async_statement_block_from_pair(
    ctx: &SpanContext,
    pair: Pair<Rule>,
    lctx: &LowerCtx,
) -> ParseResult<StepKind> {
    let span = refine_span(ctx, &pair);
    let mut block_body = None;
    for inner in pair.into_inner() {
        if inner.as_rule() == Rule::block {
            block_body = Some(parse_block_elements_with_lower(ctx, inner, lctx)?);
        }
    }
    let body = block_body.ok_or_else(|| {
        ParseError::structural(
            "async",
            "async_statement_block requires a block".to_string(),
            &span,
        )
    })?;
    for step in &body {
        if matches!(&step.kind, StepKind::WithIo { .. }) {
            return Err(ParseError::structural("async", "WITH_IO cannot be placed inside ASYNC. Place WITH_IO outside ASYNC instead (e.g. WITH_IO [...] ASYNC RUN ...)".to_string(), &span));
        }
    }
    Ok(StepKind::AsyncBlock { body })
}

/// Lower an `IMPORT` statement: update the import frames, emit nothing.
fn lower_import_statement(ctx: &SpanContext, pair: Pair<Rule>, lctx: &LowerCtx) -> ParseResult<()> {
    let mut modules = Vec::new();
    for inner in pair.into_inner() {
        match inner.as_rule() {
            Rule::import_list => {
                for module in inner.into_inner() {
                    if module.as_rule() == Rule::import_module {
                        modules.push(module.as_str().to_string());
                    }
                }
            }
            Rule::import_module => modules.push(inner.as_str().to_string()),
            _ => {}
        }
    }
    lctx.import_modules(ctx, &modules)
}

fn parse_block_elements_with_lower(
    ctx: &SpanContext,
    block_pair: Pair<Rule>,
    lctx: &LowerCtx,
) -> ParseResult<Vec<Step>> {
    // One function scope per braced body, mirroring the runtime
    // `push_scope`/`pop_scope` boundary: same-block `FUNC` redefinition
    // errors, nested shadowing stays allowed.
    lctx.enter_scope();
    let mut steps = Vec::new();
    for elem in block_pair.into_inner() {
        match elem.as_rule() {
            Rule::for_statement
            | Rule::while_statement
            | Rule::func_def
            | Rule::call_statement
            | Rule::return_statement
            | Rule::break_statement
            | Rule::continue_statement
            | Rule::let_statement
            | Rule::mutate_statement
            | Rule::let_async_statement
            | Rule::let_capture_statement
            | Rule::await_statement
            | Rule::cancel_statement
            | Rule::if_statement
            | Rule::async_statement
            | Rule::timeout_statement
            | Rule::async_statement_block => {
                let step_kind = parse_structural_command_with_lower(ctx, elem, lctx)?;
                steps.push(Step {
                    guard: None,
                    kind: step_kind,
                    scope_enter: 0,
                    scope_exit: 0,
                });
            }
            Rule::guard_block => {
                let mut guard_pair = None;
                let mut inner_block = None;
                for inner in elem.into_inner() {
                    match inner.as_rule() {
                        Rule::guard_line => guard_pair = Some(inner),
                        Rule::block => inner_block = Some(inner),
                        _ => {}
                    }
                }
                if let (Some(gp), Some(bp)) = (guard_pair, inner_block) {
                    let guard_expr = parse_guard_line(ctx, gp)?;
                    let mut inner_steps = parse_block_elements_with_lower(ctx, bp, lctx)?;
                    for step in &mut inner_steps {
                        step.guard = Some(guard_expr.clone());
                    }
                    steps.extend(inner_steps);
                }
            }
            Rule::instruction | Rule::instruction_inner => {
                let kind = lower_instruction_pair(ctx, elem, lctx)?;
                steps.push(Step {
                    guard: None,
                    kind,
                    scope_enter: 0,
                    scope_exit: 0,
                });
            }
            Rule::run_exec_statement | Rule::run_exec_inner => {
                let kind = lower_run_exec_pair(ctx, elem, lctx)?;
                steps.push(Step {
                    guard: None,
                    kind,
                    scope_enter: 0,
                    scope_exit: 0,
                });
            }
            Rule::with_io_command => {
                let step_kind = parse_structural_command_with_lower(ctx, elem, lctx)?;
                steps.push(Step {
                    guard: None,
                    kind: step_kind,
                    scope_enter: 0,
                    scope_exit: 0,
                });
            }
            Rule::import_statement => {
                // Lowering directive: updates import frames, emits no step.
                // A guard block wrapping only IMPORTs yields no steps, so
                // its guard binds nothing; IMPORT itself stays static.
                lower_import_statement(ctx, elem, lctx)?;
            }
            Rule::export_statement => {
                return Err(ParseError::validation(
                    KEYWORD_EXPORT,
                    "`EXPORT` is reserved for future script-module support and cannot be used yet."
                        .to_string(),
                    ctx,
                ));
            }
            _ => {} // blank, hash_comment, semicolon, block_start, block_end, etc.
        }
    }
    lctx.exit_scope();
    Ok(steps)
}

fn parse_argument(ctx: &SpanContext, lctx: &LowerCtx, pair: Pair<Rule>) -> ParseResult<Vec<Arg>> {
    let inners: Vec<_> = pair.into_inner().collect();
    // An `expr` fragment can swallow its trailing separator through inner
    // `gap` rules, gluing following text into one argument pair
    // (`ECHO $x hello` lexes as `[expr("$x "), unquoted("hello")]`). Split
    // groups there so expressions survive as typed `Arg::Expr`; every other
    // fragment kind is whitespace-tight by construction.
    let mut groups: Vec<Vec<Pair<Rule>>> = vec![Vec::new()];
    for fragment in inners {
        let glued = fragment.as_rule() == Rule::expr
            && fragment.as_str().ends_with(|c: char| c.is_whitespace());
        groups
            .last_mut()
            .expect("argument always holds a group")
            .push(fragment);
        if glued {
            groups.push(Vec::new());
        }
    }
    let mut args = Vec::new();
    for group in groups {
        if group.is_empty() {
            continue;
        }
        // Single expression — preserve as Arg::Expr for runtime evaluation
        if group.len() == 1 && group[0].as_rule() == Rule::expr {
            args.push(Arg::Expr(parse_expr(
                ctx,
                lctx,
                group.into_iter().next().expect("group holds one pair"),
            )?));
            continue;
        }
        // Single quoted string: preserve quote status and process escapes
        if group.len() == 1 && group[0].as_rule() == Rule::string_literal {
            args.push(Arg::String(parse_fragments(&group)?, true));
            continue;
        }
        args.push(Arg::String(parse_fragments(&group)?, false));
    }
    Ok(args)
}

fn parse_quoted_string(pair: Pair<Rule>) -> ParseResult<String> {
    let s = pair.as_str();
    let content = &s[1..s.len() - 1];
    // Pass contents verbatim — all escape processing deferred to runtime expand_string
    Ok(content.to_string())
}

/// Concatenate fragment pairs (string_literal, templated_arg, unquoted_arg, expr)
/// into a single String. Adjacent fragments without whitespace are joined directly;
/// fragments separated by whitespace get a space inserted.
fn parse_fragments(parts: &[Pair<Rule>]) -> ParseResult<String> {
    // Single quoted string: unquote unconditionally
    if parts.len() == 1 && parts[0].as_rule() == Rule::string_literal {
        let s = parts[0].as_str();
        return Ok(s[1..s.len() - 1].to_string());
    }

    let mut body = String::new();
    let mut last_end = None;
    for part in parts {
        let span = part.as_span();
        if let Some(end) = last_end
            && span.start() > end
        {
            body.push(' ');
        }
        match part.as_rule() {
            Rule::string_literal => {
                let s = part.as_str();
                let unquoted = &s[1..s.len() - 1];
                body.push_str(unquoted);
            }
            Rule::templated_arg | Rule::unquoted_arg => {
                body.push_str(part.as_str());
            }
            Rule::expr => body.push_str(part.as_str()),
            _ => {}
        }
        last_end = Some(span.end());
    }
    Ok(body)
}

fn parse_guard_line(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<GuardExpr> {
    let span = refine_span(ctx, &pair);
    for inner in pair.into_inner() {
        if inner.as_rule() == Rule::guard_expr {
            return parse_guard_expr(ctx, inner);
        }
    }
    Err(ParseError::structural(
        "guard",
        "guard line missing expression".to_string(),
        &span,
    ))
}

fn parse_io_binding(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<IoBinding> {
    let span = refine_span(ctx, &pair);
    let mut stream = None;
    let mut pipe = None;
    for inner in pair.into_inner() {
        match inner.as_rule() {
            Rule::io_stream => stream = Some(parse_io_stream(inner.as_str())),
            Rule::pipe_binding => pipe = Some(parse_pipe_binding(ctx, inner)?),
            _ => {}
        }
    }
    let stream = stream.ok_or_else(|| {
        ParseError::structural("with_io", "missing IO stream in WITH_IO".to_string(), &span)
    })?;
    Ok(IoBinding { stream, pipe })
}

fn parse_io_stream(text: &str) -> IoStream {
    match text {
        "stdin" => IoStream::Stdin,
        "stdout" => IoStream::Stdout,
        "stderr" => IoStream::Stderr,
        _ => unreachable!("parser produced invalid io_stream token"),
    }
}

fn parse_pipe_binding(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<PipeTarget> {
    let span = refine_span(ctx, &pair);
    for inner in pair.into_inner() {
        if inner.as_rule() == Rule::dollar_ident {
            return Ok(PipeTarget::Var(parse_dollar_ident(inner)));
        }
    }
    Err(ParseError::structural(
        "with_io",
        "missing pipe identifier in WITH_IO binding".to_string(),
        &span,
    ))
}

fn parse_guard_expr(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<GuardExpr> {
    let span = refine_span(ctx, &pair);
    match pair.as_rule() {
        Rule::guard_expr => {
            let next = pair.into_inner().next().ok_or_else(|| {
                ParseError::structural("guard", "guard expression missing body".to_string(), &span)
            })?;
            parse_guard_expr(ctx, next)
        }
        Rule::guard_seq => parse_guard_seq(ctx, pair),
        Rule::guard_factor => parse_guard_factor(ctx, pair),
        Rule::guard_not => {
            // guard_not is silent, so its inner pairs are the actual content
            Err(ParseError::structural(
                "guard",
                "guard_not should not create a pair".to_string(),
                &span,
            ))
        }
        Rule::guard_primary => parse_guard_primary(ctx, pair),
        Rule::guard_group => parse_guard_group(ctx, pair),
        Rule::guard_any_call => parse_guard_any_call(ctx, pair),
        Rule::guard_all_call => parse_guard_all_call(ctx, pair),
        Rule::not_call => parse_not_call(ctx, pair),
        Rule::guard_term => parse_guard_term(ctx, pair),
        _ => Err(ParseError::structural(
            "guard",
            format!("unexpected guard expression rule: {:?}", pair.as_rule()),
            &span,
        )),
    }
}

fn parse_guard_seq(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<GuardExpr> {
    let span = refine_span(ctx, &pair);
    let mut exprs = Vec::new();
    for inner in pair.into_inner() {
        if inner.as_rule() == Rule::guard_factor {
            exprs.push(parse_guard_factor(ctx, inner)?);
        }
    }
    match exprs.len() {
        0 => Err(ParseError::structural(
            "guard",
            "guard list requires at least one entry".to_string(),
            &span,
        )),
        1 => Ok(exprs.pop().unwrap()),
        _ => Ok(GuardExpr::all(exprs)),
    }
}

fn parse_guard_factor(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<GuardExpr> {
    let span = refine_span(ctx, &pair);
    let inner = pair.into_inner().next().ok_or_else(|| {
        ParseError::structural(
            "guard",
            "guard factor missing expression".to_string(),
            &span,
        )
    })?;
    parse_guard_expr(ctx, inner)
}

fn parse_not_call(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<GuardExpr> {
    let span = refine_span(ctx, &pair);
    for inner in pair.into_inner() {
        if inner.as_rule() == Rule::guard_expr {
            return parse_guard_expr(ctx, inner).map(|e| GuardExpr::Not(Box::new(e)));
        }
    }
    Err(ParseError::structural(
        "guard",
        "not() missing expression".to_string(),
        &span,
    ))
}

fn parse_guard_primary(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<GuardExpr> {
    let span = refine_span(ctx, &pair);
    match pair.as_rule() {
        Rule::guard_primary => {
            let inner = pair.into_inner().next().ok_or_else(|| {
                ParseError::structural("guard", "guard primary missing body".to_string(), &span)
            })?;
            parse_guard_primary(ctx, inner)
        }
        Rule::guard_group => parse_guard_group(ctx, pair),
        Rule::guard_any_call => parse_guard_any_call(ctx, pair),
        Rule::guard_all_call => parse_guard_all_call(ctx, pair),
        Rule::not_call => parse_not_call(ctx, pair),
        Rule::guard_term => parse_guard_term(ctx, pair),
        _ => Err(ParseError::structural(
            "guard",
            format!("unexpected guard primary rule: {:?}", pair.as_rule()),
            &span,
        )),
    }
}

fn parse_guard_group(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<GuardExpr> {
    let span = refine_span(ctx, &pair);
    for inner in pair.into_inner() {
        if inner.as_rule() == Rule::guard_expr {
            return parse_guard_expr(ctx, inner);
        }
    }
    Err(ParseError::structural(
        "guard",
        "grouped guard missing expression".to_string(),
        &span,
    ))
}

fn parse_guard_any_call(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<GuardExpr> {
    let span = refine_span(ctx, &pair);
    let mut args = Vec::new();
    for inner in pair.into_inner() {
        if inner.as_rule() == Rule::guard_expr_list {
            args = parse_guard_expr_list(ctx, inner)?;
        }
    }
    if args.len() < 2 {
        return Err(ParseError::structural(
            "guard",
            "any(...) requires at least two guard expressions".to_string(),
            &span,
        ));
    }
    Ok(GuardExpr::or(args))
}

fn parse_guard_all_call(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<GuardExpr> {
    let span = refine_span(ctx, &pair);
    let mut args = Vec::new();
    for inner in pair.into_inner() {
        if inner.as_rule() == Rule::guard_expr_list {
            args = parse_guard_expr_list(ctx, inner)?;
        }
    }
    if args.is_empty() {
        return Err(ParseError::structural(
            "guard",
            "all(...) requires at least one guard expression".to_string(),
            &span,
        ));
    }
    Ok(GuardExpr::all(args))
}

fn parse_guard_expr_list(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<Vec<GuardExpr>> {
    let mut exprs = Vec::new();
    for inner in pair.into_inner() {
        if inner.as_rule() == Rule::guard_expr {
            push_guard_or_args_from_expr(ctx, inner, &mut exprs)?;
        }
    }
    Ok(exprs)
}

fn push_guard_or_args_from_expr(
    ctx: &SpanContext,
    expr_pair: Pair<Rule>,
    exprs: &mut Vec<GuardExpr>,
) -> ParseResult<()> {
    if let Some(seq_pair) = expr_pair
        .clone()
        .into_inner()
        .find(|inner| inner.as_rule() == Rule::guard_seq)
    {
        let factors: Vec<Pair<Rule>> = seq_pair
            .into_inner()
            .filter(|inner| inner.as_rule() == Rule::guard_factor)
            .collect();
        if factors.len() > 1 {
            for factor in factors {
                exprs.push(parse_guard_factor(ctx, factor)?);
            }
            return Ok(());
        }
    }
    exprs.push(parse_guard_expr(ctx, expr_pair)?);
    Ok(())
}

fn parse_guard_term(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<GuardExpr> {
    let span = refine_span(ctx, &pair);
    for inner in pair.into_inner() {
        match inner.as_rule() {
            Rule::eq_guard => {
                return Ok(GuardExpr::Predicate(parse_func_guard(inner)?));
            }
            Rule::neq_guard => {
                let guard = parse_func_guard(inner)?;
                return Ok(GuardExpr::Not(Box::new(GuardExpr::Predicate(guard))));
            }
            Rule::bool_guard => {
                let val = inner
                    .into_inner()
                    .find(|p| p.as_rule() == Rule::bool_value)
                    .expect("grammar invariant violated: bool_guard missing bool_value")
                    .as_str()
                    .to_string();
                return Ok(GuardExpr::Predicate(Guard::StaticBool { value: val }));
            }
            Rule::env_guard => {
                return Ok(GuardExpr::Predicate(parse_env_guard(inner)?));
            }
            Rule::bare_guard_ident => {
                let tag = inner.as_str();
                if let Ok(g) = parse_platform_tag(ctx, tag) {
                    return Ok(GuardExpr::Predicate(g));
                }
                return Ok(GuardExpr::Predicate(Guard::EnvExists {
                    key: tag.to_string(),
                }));
            }
            _ => {}
        }
    }
    Err(ParseError::structural(
        "guard",
        "missing guard predicate".to_string(),
        &span,
    ))
}

fn parse_func_guard(pair: Pair<Rule>) -> ParseResult<Guard> {
    let mut key = String::new();
    let mut value = String::new();
    let mut saw_env_prefix = false;
    for inner in pair.into_inner() {
        match inner.as_rule() {
            Rule::env_prefix => saw_env_prefix = true,
            Rule::env_key if saw_env_prefix => {
                key = inner.as_str().trim().to_string();
            }
            Rule::bare_guard_value | Rule::quoted_string => {
                value = unquote(inner.as_str().trim()).to_string();
            }
            _ => {}
        }
    }
    Ok(Guard::EnvEquals { key, value })
}

fn unquote(s: &str) -> &str {
    s.strip_prefix('"')
        .and_then(|s| s.strip_suffix('"'))
        .or_else(|| s.strip_prefix('\'').and_then(|s| s.strip_suffix('\'')))
        .unwrap_or(s)
}

fn parse_env_guard(pair: Pair<Rule>) -> ParseResult<Guard> {
    let mut key = String::new();
    for inner in pair.into_inner() {
        if inner.as_rule() == Rule::env_key {
            key = inner.as_str().trim().to_string();
        }
    }
    Ok(Guard::EnvExists { key })
}

fn parse_platform_tag(ctx: &SpanContext, tag: &str) -> ParseResult<Guard> {
    let target = match tag.to_ascii_lowercase().as_str() {
        "unix" => PlatformGuard::Unix,
        "windows" => PlatformGuard::Windows,
        "mac" | "macos" => PlatformGuard::Macos,
        "linux" => PlatformGuard::Linux,
        _ => {
            return Err(ParseError::structural(
                "platform",
                format!("unknown platform '{}'", tag),
                ctx,
            ));
        }
    };
    Ok(Guard::Platform { target })
}

fn parse_dollar_ident(pair: Pair<Rule>) -> String {
    // Strip the leading '$' from the identifier
    let s = pair.as_str();
    s.strip_prefix('$').unwrap_or(s).to_string()
}

use crate::ast::{ArithOp, CompareOp, LogicalOp, MathOp, Value};

fn parse_expr(ctx: &SpanContext, lctx: &LowerCtx, pair: Pair<Rule>) -> ParseResult<Expr> {
    let span = refine_span(ctx, &pair);
    let expr = parse_expr_inner(ctx, lctx, pair)?;
    if matches!(expr, Expr::UnsignedIntBoundary(_)) {
        return Err(ParseError::structural(
            "expr",
            "integer overflow: 9223372036854775808 exceeds i64::MAX".to_string(),
            &span,
        ));
    }
    Ok(expr)
}

fn parse_expr_inner(ctx: &SpanContext, lctx: &LowerCtx, pair: Pair<Rule>) -> ParseResult<Expr> {
    let span = refine_span(ctx, &pair);
    let inner = pair.into_inner().next().unwrap();
    match inner.as_rule() {
        Rule::expr_logical_or => parse_expr_logical_or(ctx, lctx, inner),
        _ => Err(ParseError::structural(
            "expr",
            format!("unexpected expr rule: {:?}", inner.as_rule()),
            &span,
        )),
    }
}

fn parse_expr_logical_or(
    ctx: &SpanContext,
    lctx: &LowerCtx,
    pair: Pair<Rule>,
) -> ParseResult<Expr> {
    let span = refine_span(ctx, &pair);
    let mut inner = pair.into_inner();
    let mut left = parse_expr_logical_and(ctx, lctx, inner.next().unwrap())?;
    while let Some(op_pair) = inner.next() {
        let op = match op_pair.as_rule() {
            Rule::or_op => LogicalOp::Or,
            _ => {
                return Err(ParseError::structural(
                    "expr",
                    format!("unexpected operator in logical-or: {:?}", op_pair.as_rule()),
                    &span,
                ));
            }
        };
        let right = parse_expr_logical_and(ctx, lctx, inner.next().unwrap())?;
        left = Expr::Logical {
            op,
            left: Box::new(left),
            right: Box::new(right),
        };
    }
    Ok(left)
}

fn parse_expr_logical_and(
    ctx: &SpanContext,
    lctx: &LowerCtx,
    pair: Pair<Rule>,
) -> ParseResult<Expr> {
    let span = refine_span(ctx, &pair);
    let mut inner = pair.into_inner();
    let mut left = parse_expr_comparison(ctx, lctx, inner.next().unwrap())?;
    while let Some(op_pair) = inner.next() {
        let op = match op_pair.as_rule() {
            Rule::and_op => LogicalOp::And,
            _ => {
                return Err(ParseError::structural(
                    "expr",
                    format!(
                        "unexpected operator in logical-and: {:?}",
                        op_pair.as_rule()
                    ),
                    &span,
                ));
            }
        };
        let right = parse_expr_comparison(ctx, lctx, inner.next().unwrap())?;
        reject_boundary(ctx, &left)?;
        reject_boundary(ctx, &right)?;
        left = Expr::Logical {
            op,
            left: Box::new(left),
            right: Box::new(right),
        };
    }
    Ok(left)
}

fn parse_expr_comparison(
    ctx: &SpanContext,
    lctx: &LowerCtx,
    pair: Pair<Rule>,
) -> ParseResult<Expr> {
    let span = refine_span(ctx, &pair);
    let mut inner = pair.into_inner();
    let left = parse_expr_ordering(ctx, lctx, inner.next().unwrap())?;
    if let Some(op_pair) = inner.next() {
        let op = match op_pair.as_rule() {
            Rule::eq_op => CompareOp::Eq,
            Rule::neq_op => CompareOp::Ne,
            _ => {
                return Err(ParseError::structural(
                    "expr",
                    format!("unexpected comparison operator: {:?}", op_pair.as_rule()),
                    &span,
                ));
            }
        };
        let right = parse_expr_ordering(ctx, lctx, inner.next().unwrap())?;
        return make_compare(ctx, op, left, right);
    }
    Ok(left)
}

fn parse_expr_ordering(ctx: &SpanContext, lctx: &LowerCtx, pair: Pair<Rule>) -> ParseResult<Expr> {
    let span = refine_span(ctx, &pair);
    let mut inner = pair.into_inner();
    let left = parse_expr_add_sub(ctx, lctx, inner.next().unwrap())?;
    if let Some(op_pair) = inner.next() {
        let op = match op_pair.as_rule() {
            Rule::lt_op => CompareOp::Lt,
            Rule::le_op => CompareOp::Le,
            Rule::gt_op => CompareOp::Gt,
            Rule::ge_op => CompareOp::Ge,
            _ => {
                return Err(ParseError::structural(
                    "expr",
                    format!("unexpected ordering operator: {:?}", op_pair.as_rule()),
                    &span,
                ));
            }
        };
        let right = parse_expr_add_sub(ctx, lctx, inner.next().unwrap())?;
        return make_compare(ctx, op, left, right);
    }
    Ok(left)
}

fn parse_expr_add_sub(ctx: &SpanContext, lctx: &LowerCtx, pair: Pair<Rule>) -> ParseResult<Expr> {
    let span = refine_span(ctx, &pair);
    let mut inner = pair.into_inner();
    let mut left = parse_expr_mul_div(ctx, lctx, inner.next().unwrap())?;
    while let Some(op_pair) = inner.next() {
        let op = match op_pair.as_rule() {
            Rule::plus_op => ArithOp::Add,
            Rule::minus_op => ArithOp::Sub,
            _ => {
                return Err(ParseError::structural(
                    "expr",
                    format!("unexpected additive operator: {:?}", op_pair.as_rule()),
                    &span,
                ));
            }
        };
        let right = parse_expr_mul_div(ctx, lctx, inner.next().unwrap())?;
        left = make_arith(ctx, op, left, right)?;
    }
    Ok(left)
}

fn parse_expr_mul_div(ctx: &SpanContext, lctx: &LowerCtx, pair: Pair<Rule>) -> ParseResult<Expr> {
    let span = refine_span(ctx, &pair);
    let mut inner = pair.into_inner();
    let mut left = parse_expr_unary(ctx, lctx, inner.next().unwrap())?;
    while let Some(op_pair) = inner.next() {
        let op = match op_pair.as_rule() {
            Rule::star_op => ArithOp::Mul,
            Rule::slash_op => ArithOp::Div,
            _ => {
                return Err(ParseError::structural(
                    "expr",
                    format!(
                        "unexpected multiplicative operator: {:?}",
                        op_pair.as_rule()
                    ),
                    &span,
                ));
            }
        };
        let right = parse_expr_unary(ctx, lctx, inner.next().unwrap())?;
        left = make_arith(ctx, op, left, right)?;
    }
    Ok(left)
}

fn parse_expr_unary(ctx: &SpanContext, lctx: &LowerCtx, pair: Pair<Rule>) -> ParseResult<Expr> {
    let span = refine_span(ctx, &pair);
    let mut prefixes = Vec::new();
    let mut atom = None;
    for inner in pair.into_inner() {
        match inner.as_rule() {
            Rule::not_op => prefixes.push(false),
            Rule::neg_op => prefixes.push(true),
            Rule::expr_atom => atom = Some(parse_expr_atom(ctx, lctx, inner)?),
            _ => {
                return Err(ParseError::structural(
                    "expr",
                    format!("unexpected unary operand rule: {:?}", inner.as_rule()),
                    &span,
                ));
            }
        }
    }
    let mut expr = atom.ok_or_else(|| {
        ParseError::structural(
            "expr",
            "'!'/'-' requires an expression operand".to_string(),
            &span,
        )
    })?;
    // Innermost prefix is closest to the atom: apply in reverse order.
    for is_neg in prefixes.into_iter().rev() {
        if is_neg {
            expr = apply_unary_neg(ctx, expr)?;
        } else {
            reject_boundary(ctx, &expr)?;
            expr = Expr::Not(Box::new(expr));
        }
    }
    Ok(expr)
}

/// Reject a staged `UnsignedIntBoundary` in any position where unary `-`
/// cannot consume it (every composite constructor calls this on children).
fn reject_boundary(ctx: &SpanContext, expr: &Expr) -> ParseResult<()> {
    if matches!(expr, Expr::UnsignedIntBoundary(_)) {
        return Err(ParseError::structural(
            "expr",
            "integer overflow: 9223372036854775808 exceeds i64::MAX".to_string(),
            ctx,
        ));
    }
    Ok(())
}

/// Apply unary `-`: fold literals, consume the `i64::MIN` boundary, else
/// compile to RPN `Neg` (or AST `0 - x` fallback for non-math operands).
fn apply_unary_neg(ctx: &SpanContext, expr: Expr) -> ParseResult<Expr> {
    match expr {
        Expr::Literal(v) => match (v.as_i64(), v.as_f64()) {
            (Some(n), _) => match n.checked_neg() {
                Some(neg) => Ok(Expr::Literal(Value::int(neg))),
                None => Ok(Expr::CompiledMath(vec![MathOp::PushConst(v), MathOp::Neg])),
            },
            (None, Some(f)) => Ok(Expr::Literal(Value::float(-f))),
            (None, None) => {
                let other = Expr::Literal(v);
                if let Some(mut ops) = expr_to_rpn(&other) {
                    ops.push(MathOp::Neg);
                    Ok(Expr::CompiledMath(ops))
                } else {
                    // Non-math operand (list/map/logical): `0 - x` evaluates via
                    // the shared arithmetic helper to a runtime Type Error.
                    Ok(Expr::Arithmetic {
                        op: ArithOp::Sub,
                        left: Box::new(Expr::Literal(Value::int(0))),
                        right: Box::new(other),
                    })
                }
            }
        },
        Expr::UnsignedIntBoundary(n) => {
            if n == i64::MAX as u64 + 1 {
                Ok(Expr::Literal(Value::int(i64::MIN)))
            } else {
                Err(ParseError::structural(
                    "expr",
                    format!("integer overflow: {} exceeds i64::MAX", n),
                    ctx,
                ))
            }
        }
        other => {
            if let Some(mut ops) = expr_to_rpn(&other) {
                ops.push(MathOp::Neg);
                Ok(Expr::CompiledMath(ops))
            } else {
                // Non-math operand (list/map/logical): `0 - x` evaluates via
                // the shared arithmetic helper to a runtime Type Error.
                Ok(Expr::Arithmetic {
                    op: ArithOp::Sub,
                    left: Box::new(Expr::Literal(Value::int(0))),
                    right: Box::new(other),
                })
            }
        }
    }
}

/// Try parse-time constant folding for binary arithmetic/comparison.
/// Returns `Some(literal)` on success, `None` when not both literals or
/// when the op would error at runtime (div-zero/overflow/non-finite:
/// leave for the RPN evaluator so the error surfaces at runtime).
fn try_fold_arith(op: ArithOp, left: &Expr, right: &Expr) -> Option<Expr> {
    let (Expr::Literal(lv), Expr::Literal(rv)) = (left, right) else {
        return None;
    };
    fold_arith_values(op, lv, rv).map(Expr::Literal)
}

fn fold_arith_values(op: ArithOp, left: &Value, right: &Value) -> Option<Value> {
    match (left.as_i64(), right.as_i64()) {
        (Some(a), Some(b)) => {
            let v = match op {
                ArithOp::Add => a.checked_add(b)?,
                ArithOp::Sub => a.checked_sub(b)?,
                ArithOp::Mul => a.checked_mul(b)?,
                ArithOp::Div => a.checked_div(b)?,
            };
            Some(Value::int(v))
        }
        _ => {
            let (af, bf) = (as_f64(left)?, as_f64(right)?);
            fold_float(op, af, bf)
        }
    }
}

fn fold_float(op: ArithOp, a: f64, b: f64) -> Option<Value> {
    if !a.is_finite() || !b.is_finite() {
        return None;
    }
    let v = match op {
        ArithOp::Add => a + b,
        ArithOp::Sub => a - b,
        ArithOp::Mul => a * b,
        ArithOp::Div => {
            if b == 0.0 {
                return None;
            }
            a / b
        }
    };
    if v.is_finite() {
        Some(Value::float(v))
    } else {
        None
    }
}

fn try_fold_compare(op: CompareOp, left: &Expr, right: &Expr) -> Option<Expr> {
    let (Expr::Literal(lv), Expr::Literal(rv)) = (left, right) else {
        return None;
    };
    match (lv.as_i64(), rv.as_i64()) {
        (Some(a), Some(b)) => {
            let r = match op {
                CompareOp::Eq => a == b,
                CompareOp::Ne => a != b,
                CompareOp::Lt => a < b,
                CompareOp::Le => a <= b,
                CompareOp::Gt => a > b,
                CompareOp::Ge => a >= b,
            };
            Some(Expr::Literal(Value::bool(r)))
        }
        _ => {
            if let (Some(a), Some(b)) = (lv.as_bool(), rv.as_bool()) {
                return match op {
                    CompareOp::Eq => Some(Expr::Literal(Value::bool(a == b))),
                    CompareOp::Ne => Some(Expr::Literal(Value::bool(a != b))),
                    _ => None,
                };
            }
            let (af, bf) = (as_f64(lv)?, as_f64(rv)?);
            let r = match op {
                CompareOp::Eq => af == bf,
                CompareOp::Ne => af != bf,
                CompareOp::Lt => af < bf,
                CompareOp::Le => af <= bf,
                CompareOp::Gt => af > bf,
                CompareOp::Ge => af >= bf,
            };
            Some(Expr::Literal(Value::bool(r)))
        }
    }
}

fn as_f64(v: &Value) -> Option<f64> {
    if let Some(n) = v.as_i64() {
        return Some(n as f64);
    }
    match v.as_f64() {
        Some(f) if f.is_finite() => Some(f),
        _ => None,
    }
}

fn make_arith(ctx: &SpanContext, op: ArithOp, left: Expr, right: Expr) -> ParseResult<Expr> {
    reject_boundary(ctx, &left)?;
    reject_boundary(ctx, &right)?;
    if let Some(folded) = try_fold_arith(op, &left, &right) {
        return Ok(folded);
    }
    if let (Some(mut lops), Some(mut rops)) = (expr_to_rpn(&left), expr_to_rpn(&right)) {
        lops.append(&mut rops);
        lops.push(match op {
            ArithOp::Add => MathOp::Add,
            ArithOp::Sub => MathOp::Sub,
            ArithOp::Mul => MathOp::Mul,
            ArithOp::Div => MathOp::Div,
        });
        return Ok(Expr::CompiledMath(lops));
    }
    Ok(Expr::Arithmetic {
        op,
        left: Box::new(left),
        right: Box::new(right),
    })
}

fn make_compare(ctx: &SpanContext, op: CompareOp, left: Expr, right: Expr) -> ParseResult<Expr> {
    reject_boundary(ctx, &left)?;
    reject_boundary(ctx, &right)?;
    if let Some(folded) = try_fold_compare(op, &left, &right) {
        return Ok(folded);
    }
    if let (Some(mut lops), Some(mut rops)) = (expr_to_rpn(&left), expr_to_rpn(&right)) {
        lops.append(&mut rops);
        lops.push(match op {
            CompareOp::Eq => MathOp::Eq,
            CompareOp::Ne => MathOp::Ne,
            CompareOp::Lt => MathOp::Lt,
            CompareOp::Le => MathOp::Le,
            CompareOp::Gt => MathOp::Gt,
            CompareOp::Ge => MathOp::Ge,
        });
        return Ok(Expr::CompiledMath(lops));
    }
    Ok(Expr::Compare {
        op,
        left: Box::new(left),
        right: Box::new(right),
    })
}

/// Convert an operand subtree to flat RPN. Returns `None` for shapes with
/// no RPN encoding (`Not`/`Logical`/`List`/`Map`/`FreshPipe`/stray boundary): callers
/// fall back to AST nodes evaluated recursively.
fn expr_to_rpn(expr: &Expr) -> Option<Vec<MathOp>> {
    match expr {
        Expr::Literal(v) => Some(vec![MathOp::PushConst(v.clone())]),
        Expr::Var(name) => Some(vec![MathOp::LoadVar(name.clone())]),
        Expr::Env(key) => Some(vec![MathOp::LoadEnv(key.clone())]),
        Expr::KeyPath { base, keys } => Some(vec![MathOp::LoadKeyPath {
            base: base.clone(),
            keys: keys.clone(),
        }]),
        Expr::Call { name, args } => {
            let mut ops = Vec::new();
            for arg in args {
                ops.extend(expr_to_rpn(arg)?);
            }
            ops.push(MathOp::Call {
                name: name.clone(),
                arity: args.len(),
            });
            Some(ops)
        }
        Expr::Inspect(var) => Some(vec![MathOp::Inspect(var.clone())]),
        Expr::Arithmetic { op, left, right } => {
            let mut ops = expr_to_rpn(left)?;
            ops.extend(expr_to_rpn(right)?);
            ops.push(match op {
                ArithOp::Add => MathOp::Add,
                ArithOp::Sub => MathOp::Sub,
                ArithOp::Mul => MathOp::Mul,
                ArithOp::Div => MathOp::Div,
            });
            Some(ops)
        }
        Expr::Compare { op, left, right } => {
            let mut ops = expr_to_rpn(left)?;
            ops.extend(expr_to_rpn(right)?);
            ops.push(match op {
                CompareOp::Eq => MathOp::Eq,
                CompareOp::Ne => MathOp::Ne,
                CompareOp::Lt => MathOp::Lt,
                CompareOp::Le => MathOp::Le,
                CompareOp::Gt => MathOp::Gt,
                CompareOp::Ge => MathOp::Ge,
            });
            Some(ops)
        }
        Expr::CompiledMath(ops) => Some(ops.clone()),
        Expr::FreshPipe => None,
        Expr::Not(_) | Expr::Logical { .. } | Expr::List(_) | Expr::Map(_) | Expr::Block(_) => None,
        Expr::UnsignedIntBoundary(_) => None,
    }
}

fn parse_expr_atom(ctx: &SpanContext, lctx: &LowerCtx, pair: Pair<Rule>) -> ParseResult<Expr> {
    let span = refine_span(ctx, &pair);
    let inner = pair.into_inner().next().unwrap();
    match inner.as_rule() {
        Rule::parenthesized_expr => parse_expr_inner(ctx, lctx, inner.into_inner().next().unwrap()),
        Rule::func_call => parse_func_call(ctx, lctx, inner),
        Rule::key_path => parse_key_path(ctx, inner),
        Rule::variable => {
            let name = inner.as_str();
            let name = name.strip_prefix('$').unwrap_or(name).to_string();
            Ok(Expr::Var(name))
        }
        Rule::env_read => parse_env_read(ctx, inner).map(Expr::Env),
        Rule::list_literal => parse_list_literal(ctx, lctx, inner),
        Rule::map_literal => parse_map_literal(ctx, lctx, inner),
        Rule::block => Ok(Expr::Block(parse_block_elements_with_lower(
            ctx, inner, lctx,
        )?)),
        Rule::string_literal | Rule::quoted_string => {
            let s = parse_quoted_string(inner)?;
            Ok(Expr::Literal(Value::string(s)))
        }
        Rule::numeric_literal => parse_numeric_literal(ctx, inner),
        Rule::bare_word => {
            let s = inner.as_str().to_string();
            match s.as_str() {
                "true" => Ok(Expr::Literal(Value::bool(true))),
                "false" => Ok(Expr::Literal(Value::bool(false))),
                _ => Ok(Expr::Literal(Value::string(s))),
            }
        }
        _ => Err(ParseError::structural(
            "expr",
            format!("unexpected expression atom rule: {:?}", inner.as_rule()),
            &span,
        )),
    }
}

/// Lower an unsigned `numeric_literal` token. Floats (containing `.`) parse
/// as `f64` (non-finite/overflow bails); integers parse as `u64` so the
/// unsigned half of `i64::MIN` (`9223372036854775808`) stages as
/// `UnsignedIntBoundary` for unary `-` to consume. Larger values bail.
fn parse_numeric_literal(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<Expr> {
    let span = refine_span(ctx, &pair);
    let text = pair.as_str();
    if text.contains('.') {
        let parsed: f64 = text.parse().map_err(|_| {
            ParseError::structural("expr", format!("invalid float literal {text:?}"), &span)
        })?;
        if !parsed.is_finite() {
            return Err(ParseError::structural(
                "expr",
                format!("invalid float literal {text:?}"),
                &span,
            ));
        }
        return Ok(Expr::Literal(Value::float(parsed)));
    }
    let digits: u64 = text.parse().map_err(|_| {
        ParseError::structural(
            "expr",
            format!("integer overflow: {text:?} exceeds i64::MAX"),
            &span,
        )
    })?;
    if digits <= i64::MAX as u64 {
        Ok(Expr::Literal(Value::int(digits as i64)))
    } else if digits == i64::MAX as u64 + 1 {
        Ok(Expr::UnsignedIntBoundary(digits))
    } else {
        Err(ParseError::structural(
            "expr",
            format!("integer overflow: {text:?} exceeds i64::MAX"),
            &span,
        ))
    }
}

fn parse_env_read(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<String> {
    let span = refine_span(ctx, &pair);
    for inner in pair.into_inner() {
        if inner.as_rule() == Rule::env_read_key {
            return Ok(inner.as_str().trim().to_string());
        }
    }
    Err(ParseError::structural(
        "expr",
        "env read requires a key: env:KEY".to_string(),
        &span,
    ))
}

fn parse_key_path(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<Expr> {
    let span = refine_span(ctx, &pair);
    let mut base = None;
    let mut keys = Vec::new();
    for inner in pair.into_inner() {
        match inner.as_rule() {
            Rule::ident => {
                if base.is_none() {
                    base = Some(inner.as_str().to_string());
                }
            }
            Rule::key_path_segment => {
                keys.push(inner.as_str().to_string());
            }
            _ => {}
        }
    }
    Ok(Expr::KeyPath {
        base: base.ok_or_else(|| {
            ParseError::structural(
                "expr",
                "key path requires a base identifier".to_string(),
                &span,
            )
        })?,
        keys,
    })
}

fn parse_func_call(ctx: &SpanContext, lctx: &LowerCtx, pair: Pair<Rule>) -> ParseResult<Expr> {
    let span = refine_span(ctx, &pair);
    let mut name = None;
    let mut args = Vec::new();
    for inner in pair.into_inner() {
        match inner.as_rule() {
            Rule::qualified_func_name => {
                name = Some(inner.as_str().to_string());
            }
            Rule::expr => {
                let arg = parse_expr_inner(ctx, lctx, inner)?;
                reject_boundary(ctx, &arg)?;
                args.push(arg);
            }
            _ => {}
        }
    }
    let name = name.ok_or_else(|| {
        ParseError::structural("expr", "function call requires a name".to_string(), &span)
    })?;
    // `INSPECT` lowers to its own node carrying the variable unevaluated:
    // pre-evaluating to a `Value` would lose the binding name. Anything else
    // resolves statically to `MODULE::NAME` against SCRIPT definitions and
    // `IMPORT`ed modules; the runtime registry is keyed the same way.
    if name == KEYWORD_INSPECT {
        let [arg] = args.as_slice() else {
            return Err(ParseError::structural(
                "expr",
                "INSPECT requires exactly one argument: INSPECT($var)".to_string(),
                &span,
            ));
        };
        if let Expr::Var(var) = arg {
            return Ok(Expr::Inspect(var.clone()));
        }
        return Err(ParseError::structural(
            "expr",
            format!("INSPECT requires a $variable argument, found {arg:?}"),
            &span,
        ));
    }
    let qualified = lctx.resolve_call(&span, &name)?;
    Ok(Expr::Call {
        name: qualified,
        args,
    })
}

fn parse_list_literal(ctx: &SpanContext, lctx: &LowerCtx, pair: Pair<Rule>) -> ParseResult<Expr> {
    let mut items = Vec::new();
    for inner in pair.into_inner() {
        if inner.as_rule() == Rule::expr {
            let item = parse_expr_inner(ctx, lctx, inner)?;
            reject_boundary(ctx, &item)?;
            items.push(item);
        }
    }
    Ok(Expr::List(items))
}

fn parse_map_literal(ctx: &SpanContext, lctx: &LowerCtx, pair: Pair<Rule>) -> ParseResult<Expr> {
    let span = refine_span(ctx, &pair);
    let mut entries = Vec::new();
    for inner in pair.into_inner() {
        if inner.as_rule() == Rule::map_entry {
            let mut key = String::new();
            let mut value = None;
            for entry_inner in inner.into_inner() {
                match entry_inner.as_rule() {
                    Rule::quoted_string => {
                        key = parse_quoted_string(entry_inner)?;
                    }
                    Rule::bare_word => {
                        key = entry_inner.as_str().to_string();
                    }
                    Rule::expr => {
                        let val = parse_expr_inner(ctx, lctx, entry_inner)?;
                        reject_boundary(ctx, &val)?;
                        value = Some(val);
                    }
                    _ => {}
                }
            }
            let val = value.ok_or_else(|| {
                ParseError::structural("expr", "map entry missing value".to_string(), &span)
            })?;
            entries.push((key, val));
        }
    }
    Ok(Expr::Map(entries))
}