zshrs 0.11.0

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

use super::lex::{
    lextok, set_tok, AMPER, AMPERBANG, AMPOUTANG, BANG_TOK, BARAMP, BAR_TOK, CASE, COPROC, DAMPER,
    DBAR, DINANG, DINANGDASH, DINBRACK, DINPAR, DOLOOP, DONE, DOUTANG, DOUTANGAMP, DOUTANGAMPBANG,
    DOUTANGBANG, DOUTBRACK, DOUTPAR, DSEMI, ELIF, ELSE, ENDINPUT, ENVARRAY, ENVSTRING, ESAC, FI,
    FOR, FOREACH, FUNC, IF, INANGAMP, INANG_TOK, INBRACE_TOK, INOUTANG, INOUTPAR, INPAR_TOK,
    IS_REDIROP, LEXERR, NEWLIN, NOCORRECT, NULLTOK, OUTANGAMP, OUTANGAMPBANG, OUTANGBANG,
    OUTANG_TOK, OUTBRACE_TOK, OUTPAR_TOK, REPEAT, SELECT, SEMI, SEMIAMP, SEMIBAR, SEPER,
    STRING_LEX, THEN, TIME, TRINANG, TYPESET, UNTIL, WHILE, ZEND,
};
use super::zsh_h::{
    eprog, estate, isset, redir, unset, wc_code, wordcode, Bang, Dash, Equals, Inang, Inpar,
    Outang, Outpar, Stringg, Tilde, ALIASFUNCDEF, COND_AND, COND_MOD, COND_MODI, COND_NOT, COND_NT,
    COND_OR, COND_REGEX, COND_STRDEQ, COND_STREQ, COND_STRGTR, COND_STRLT, COND_STRNEQ,
    CSHJUNKIELOOPS,
    EC_DUP, EC_NODUP, EF_HEAP, EF_REAL, EXECOPT, IGNOREBRACES, IS_DASH, MULTIFUNCDEF, OPT_ISSET,
    PM_UNDEFINED, POSIXBUILTINS, REDIRF_FROM_HEREDOC, REDIR_APP, REDIR_APPNOW,
    REDIR_FROM_HEREDOC_MASK, REDIR_VARID_MASK, REDIR_ERRAPP,
    REDIR_ERRAPPNOW, REDIR_ERRWRITE, REDIR_ERRWRITENOW, REDIR_HEREDOC, REDIR_HEREDOCDASH,
    REDIR_HERESTR, REDIR_INPIPE, REDIR_MERGEIN, REDIR_MERGEOUT, REDIR_OUTPIPE, REDIR_READ,
    REDIR_READWRITE, REDIR_WRITE, REDIR_WRITENOW, SHORTLOOPS, SHORTREPEAT, WCB_COND, WCB_SIMPLE,
    WC_REDIR, WC_REDIR_FROM_HEREDOC, WC_REDIR_TYPE, WC_REDIR_VARID, WC_SUBLIST_COPROC,
    WC_SUBLIST_NOT,
};
use crate::ported::utils::{zerr, zwarnnam};
use serde::{Deserialize, Serialize};
use std::fs::File;
use std::io::{Read, Seek, SeekFrom, Write};
use std::sync::atomic::{AtomicUsize, Ordering};

/// Port of C `struct eccstr` (zsh.h:836) — the long-string dedup BST
/// node. The dedup-walk and cmp logic in `ecstrcode` is faithful to
/// parse.c:447-453 including the conditional cmp chain
/// (nfunc → hashval → strcmp), so corpus inputs where C's tree-walk
/// finds-or-misses match get the same outcome on the Rust side.
struct EccstrNode {
    left: Option<Box<EccstrNode>>,
    right: Option<Box<EccstrNode>>,
    /// C-byte form of the string (single byte per char ≤ 0xff).
    /// Owned because Rust doesn't have C zsh's "stable pointers into
    /// the lexer's tokstr arena" — every tokstr lives as a fresh
    /// Rust String allocation.
    str: Vec<u8>,
    /// Wordcode-encoded offset: `(byte_offset << 2) | token_bit`.
    /// Same shape as `Eccstr::offs` (parse.c:459).
    offs: u32,
    /// `nfunc` snapshot at insert time. Per-function namespace key
    /// — top-level scripts use 0; each funcdef bumps it.
    nfunc: i32,
    /// Hash of `str` computed via zsh's `hasher` (hashtable.c:86).
    hashval: u32,
}

// Wordcode-buffer thread-locals — direct port of `Src/parse.c:269-285`
// file-statics. Per-evaluator (bucket-1 in PORT_PLAN.md): each worker
// thread parsing a separate program needs its own wordcode buffer.
//
// ECBUF: the wordcode array being built. C `Wordcode ecbuf`
// (parse.c:275).
// ECLEN: allocated entries in ECBUF (parse.c:269).
// ECUSED: entries actually used so far (parse.c:271).
// ECNPATS: count of patterns referenced by ECBUF (parse.c:273).
// ECSOFFS / ECSSUB: byte offsets into the deferred string region
// (parse.c:279). ECSSUB subtracts substring overlap.
// ECNFUNC: count of functions defined so far (parse.c:285).
// ECSTRS_INDEX: dedup index for long strings — C uses a binary tree
// of `struct eccstr` (zsh.h:836); the canonical Eccstr port exists
// at zsh_h::eccstr but stays unused at runtime here. The HashMap
// preserves the API contract (lookup by (nfunc, str) → offs) with
// simpler ownership semantics.
thread_local! {
    pub static ECBUF: std::cell::RefCell<Vec<u32>> = std::cell::RefCell::new(Vec::new());
    static ECLEN: std::cell::Cell<i32> = const { std::cell::Cell::new(0) };
    static ECUSED: std::cell::Cell<i32> = const { std::cell::Cell::new(0) };
    static ECNPATS: std::cell::Cell<i32> = const { std::cell::Cell::new(0) };
    static ECSOFFS: std::cell::Cell<i32> = const { std::cell::Cell::new(0) };
    static ECSSUB: std::cell::Cell<i32> = const { std::cell::Cell::new(0) };
    static ECNFUNC: std::cell::Cell<i32> = const { std::cell::Cell::new(0) };
    static ECSTRS_INDEX: std::cell::RefCell<std::collections::HashMap<(i32, String), u32>>
        = std::cell::RefCell::new(std::collections::HashMap::new());
    /// C zsh's `eccstr` BST (parse.c:447). Port of `Eccstr ecstrs` —
    /// a hashval-ordered binary search tree of long-strings for
    /// dedup. Same cmp logic as C: nfunc, then hashval, then strcmp.
    /// HashMap above is a fast-path lookup; this tree is the
    /// C-fidelity walker that mirrors C's exact dedup-hit pattern
    /// (including its quirks for hash-colliding content).
    static ECSTRS_TREE: std::cell::RefCell<Option<Box<EccstrNode>>>
        = const { std::cell::RefCell::new(None) };
    /// Reverse index for `ecgetstr`: offs → owned string. Populated
    /// at ecstrcode time so the consumer can recover the string from
    /// the wordcode offs without walking the encode-time HashMap.
    /// Stores the METAFIED BYTE form of each long-string, exactly
    /// matching what C's strs region holds. `String` would not work
    /// here because Rust strings carry UTF-8-encoded chars (e.g.
    /// the Dash marker `\u{9b}` UTF-8-encodes to two bytes
    /// `\xc2 \x9b`) while C stores zsh markers as single bytes
    /// (raw `\x9b`). Storing Vec<u8> lets us write byte-for-byte
    /// what C writes after metafy.
    pub static ECSTRS_REVERSE: std::cell::RefCell<std::collections::HashMap<u32, Vec<u8>>>
        = std::cell::RefCell::new(std::collections::HashMap::new());
}

// Direct port of `Src/parse.c:287-289` grow-policy constants.
const EC_INIT_SIZE: i32 = 256;
const EC_DOUBLE_THRESHOLD: i32 = 32768;
const EC_INCREMENT: i32 = 1024;

// Parser recursion + iteration safety counters as file-scope
// thread_locals (Rust-only — no C analog; C uses OS stack overflow).
thread_local! {
    pub static PARSER_RECURSION_DEPTH: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
    pub static PARSER_GLOBAL_ITERATIONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

// =============================================================================
// Wordcode read helpers — used by text.rs's `gettext2` and exec dispatch
// to walk a compiled Eprog without re-running the parser. These are the
// only `Src/parse.c` functions ported so far in this file; the recursive-
// descent parser (par_event / par_list / par_cmd / par_*) follows
// below as free fns at module scope.
// =============================================================================

/// Port of `ecgetstr(Estate s, int dup, int *tokflag)` from `Src/parse.c:2855`.
/// `s->pc` advances through the wordcode buffer; `s->strs` indexes the
/// string pool. Returns the interned string (or a 1-3-char literal
/// inlined directly into the wordcode word).
pub fn ecgetstr(s: &mut estate, dup: i32, tokflag: Option<&mut i32>) -> String {
    let prog = &s.prog.prog;
    if s.pc >= prog.len() {
        return String::new();
    }
    let c = prog[s.pc]; // c:2858 `wordcode c = *s->pc++;`
    s.pc += 1;
    if let Some(tf) = tokflag {
        *tf = i32::from((c & 1) != 0); // c:2880 `*tokflag = (c & 1);`
    }
    if c == 6 || c == 7 {
        // c:2861 `if (c == 6 || c == 7) r = "";`
        return String::new();
    }
    let r: String = if (c & 2) != 0 {
        // c:2862 `else if (c & 2)`
        // c:2863-2866 — 3-byte inline string packed into the wordcode word.
        let b0 = ((c >> 3) & 0xff) as u8;
        let b1 = ((c >> 11) & 0xff) as u8;
        let b2 = ((c >> 19) & 0xff) as u8;
        let mut v = vec![b0, b1, b2];
        v.retain(|&x| x != 0);
        String::from_utf8_lossy(&v).into_owned()
    } else {
        // c:2877 `else r = s->strs + (c >> 2);`
        let off = (c >> 2) as usize + s.strs_offset;
        let strs_bytes = s.strs.as_deref().unwrap_or("").as_bytes();
        if off >= strs_bytes.len() {
            String::new()
        } else {
            let tail = &strs_bytes[off..];
            let end = tail.iter().position(|&b| b == 0).unwrap_or(tail.len());
            String::from_utf8_lossy(&tail[..end]).into_owned()
        }
    };
    // c:2891 `return ((dup == EC_DUP || (dup && (c & 1))) ? dupstring(r) : r);`
    // Rust owns the String already; `dup` flag has no observable effect.
    let _ = (dup, EC_DUP, EC_NODUP);
    r
}

/// Port of `ecgetredirs(Estate s)` from `Src/parse.c:2959`.
///
/// `strs` must be the same tail `ecgetstr` uses (`s->strs` / `estate.strs` from offset).
/// WARNING: param names don't match C — Rust=(prog, strs, pc) vs C=(s)
pub fn ecgetredirs(s: &mut estate) -> Vec<redir> {
    let mut ret: Vec<redir> = Vec::new(); // c:2959 `LinkList ret = newlinklist();`
    let prog_len = s.prog.prog.len();
    if s.pc >= prog_len {
        return ret;
    }
    let mut code = s.prog.prog[s.pc]; // c:2962 `wordcode code = *s->pc++;`
    s.pc += 1;

    loop {
        if wc_code(code) != WC_REDIR {
            // c:2988-2989 `s->pc--` then break from while
            s.pc = s.pc.saturating_sub(1);
            break;
        }

        let typ = WC_REDIR_TYPE(code); // c:2967 `r->type = WC_REDIR_TYPE(code);`
        if s.pc >= prog_len {
            break;
        }
        let fd1_w = s.prog.prog[s.pc]; // c:2968 `r->fd1 = *s->pc++;`
        s.pc += 1;

        let name = ecgetstr(s, EC_DUP, None); // c:2969 `r->name = ecgetstr(...)`

        let (flags, here_terminator, munged_here_terminator) = if WC_REDIR_FROM_HEREDOC(code) != 0 {
            // c:2970-2973
            let term = ecgetstr(s, EC_DUP, None);
            let munged = ecgetstr(s, EC_DUP, None);
            (REDIRF_FROM_HEREDOC, Some(term), Some(munged))
        } else {
            // c:2974-2977
            (0, None, None)
        };

        let varid = if WC_REDIR_VARID(code) != 0 {
            // c:2979-2980
            Some(ecgetstr(s, EC_DUP, None))
        } else {
            None // c:2981-2982
        };

        ret.push(redir {
            // c:2965-2982 fields + c:2984 `addlinknode`
            typ,
            flags,
            fd1: fd1_w as i32,
            fd2: 0,
            name: Some(name),
            varid,
            here_terminator,
            munged_here_terminator,
        });

        if s.pc >= prog_len {
            break;
        }
        code = s.prog.prog[s.pc]; // c:2986 `code = *s->pc++;`
        s.pc += 1;
    }

    ret // c:2990 `return ret`
}

// === AST tree relocated to src/extensions/zsh_ast.rs ===
//
// zsh C does NOT have an AST tree — it emits wordcode directly via
// par_event/par_list/par_sublist/par_pipe/par_cmd/par_simple/etc.
// (Src/parse.c:485-3000) into a flat `Wordcode ecbuf[]`. The Zsh*/
// Shell* AST node types lived in this file as a Rust-only IR that
// stands in for that wordcode.
//
// P9e (PORT_PLAN.md): the types moved to src/extensions/zsh_ast.rs
// to make their Rust-only-extension nature explicit. The full P9c +
// P9d rewrite (par_* emitting wordcode + exec.rs reading wordcode)
// retires them entirely — until then, callers reach them via this
// re-export.
pub use crate::heredoc_ast::HereDoc;
pub use crate::zsh_ast::{
    CaseArm, CaseTerm, CaseTerminator, CompoundCommand, ForList, HereDocInfo, ListFlags, ListOp,
    Redirect, RedirectOp, ShellCommand, ShellWord, SimpleCommand, SublistFlags, SublistOp,
    VarModifier, ZshAssign, ZshAssignValue, ZshCase, ZshCommand, ZshCond, ZshFor, ZshFuncDef,
    ZshIf, ZshList, ZshParamFlag, ZshPipe, ZshProgram, ZshRedir, ZshRepeat, ZshSimple, ZshSublist,
    ZshTry, ZshWhile,
};
use crate::ported::lex::{
    heredocs_clear, heredocs_clone, heredocs_is_empty, heredocs_len, heredocs_push, heredocs_set,
    heredocs_take, incasepat, incmdpos, incond, infor, input_slice, inredir, inrepeat, intypeset,
    isnewlin, lex_init, lineno, noaliases, nocorrect, pos, set_incasepat, set_incmdpos, set_incond,
    set_infor, set_inredir, set_inrepeat, set_intypeset, set_isnewlin, set_noaliases,
    set_nocorrect, set_pos, set_tokfd, set_toklineno, set_tokstr, tok, tokfd, toklineno, tokstr,
    tokstr_eq, tokstr_is_none, tokstr_is_some, tokstr_take, zshlex,
};
use crate::prompt::{cmdpop, cmdpush};
use crate::zsh_h::{
    wc_bdata, CS_ARRAY, CS_CASE, CS_CMDAND, CS_CMDOR, CS_COND, CS_CURSH, CS_ELIF, CS_ELSE,
    CS_ERRPIPE, CS_FOR, CS_FOREACH, CS_FUNCDEF, CS_IF, CS_IFTHEN, CS_PIPE, CS_REPEAT, CS_SELECT,
    CS_SUBSH, CS_UNTIL, CS_WHILE, EF_RUN, WCB_ARITH, WCB_ASSIGN, WCB_CASE, WCB_CURSH, WCB_END,
    WCB_FOR, WCB_FUNCDEF, WCB_IF, WCB_LIST, WCB_PIPE, WCB_REDIR, WCB_REPEAT, WCB_SELECT,
    WCB_SUBLIST, WCB_SUBSH, WCB_TIMED, WCB_TRY, WCB_TYPESET, WCB_WHILE, WC_ASSIGN_ARRAY, WC_ASSIGN_INC,
    WC_ASSIGN_NEW, WC_ASSIGN_SCALAR, WC_CASE_AND, WC_CASE_HEAD, WC_CASE_OR, WC_CASE_TESTAND,
    WC_FOR_COND, WC_FOR_LIST, WC_FOR_PPARAM, WC_IF_HEAD, WC_IF_IF, WC_PIPE_END, WC_PIPE_LINENO,
    WC_PIPE_MID, WC_REDIR_WORDS, WC_SELECT_LIST, WC_SELECT_PPARAM, WC_SUBLIST_AND, WC_SUBLIST_END,
    WC_SUBLIST_FLAGS, WC_SUBLIST_OR, WC_SUBLIST_SIMPLE, WC_SUBLIST_TYPE, WC_TIMED_EMPTY,
    WC_TIMED_PIPE, WC_WHILE_UNTIL, WC_WHILE_WHILE, Z_ASYNC, Z_DISOWN, Z_END, Z_SIMPLE, Z_SYNC,
};
// === end AST relocation ===

// Parser state lives in file-scope thread_locals:
//   - LEX_* (lexer side, matching Src/lex.c file-statics)
//   - ECBUF / ECLEN / ECUSED / ECNPATS / ECSOFFS / ECSSUB / ECNFUNC /
//     ECSTRS_INDEX / ECSTRS_REVERSE (wordcode-emission state, matching
//     Src/parse.c file-statics)
//   - PARSER_RECURSION_DEPTH / PARSER_GLOBAL_ITERATIONS (Rust-only
//     safety counters; no C analog — C relies on OS stack overflow).
//
// Callers use the free-fn entry points directly:
//   crate::ported::parse::parse_init(input);
//   let prog = crate::ported::parse::parse();

const MAX_RECURSION_DEPTH: usize = 500;

/// Direct port of `struct parse_stack` at `Src/zsh.h:3099-3109`.
/// Used by `parse_context_save` / `parse_context_restore`
/// (parse.c:295-355) to snapshot per-parse-call state so a nested
/// parse (e.g. inside command substitution) doesn't clobber the
/// outer parse.
///
/// A second port of `struct parse_stack` exists at
/// `crate::ported::zsh_h::parse_stack` (zsh.h:1066) using canonical
/// Wordcode / Eccstr / `struct heredocs` types — that port is unused
/// today and will become authoritative when Phase 9b (PORT_PLAN.md)
/// wires wordcode emission. This local version uses the working-set
/// shapes (Vec<HereDoc>, stubbed wordcode fields) suited to zshrs's
/// pre-wordcode AST architecture; the consolidation happens in P9b.
#[allow(non_camel_case_types)]
#[derive(Debug, Default, Clone)]
pub struct parse_stack {
    // ── Direct port of struct parse_stack at zsh.h:3099-3109 ──
    /// Pending heredocs awaiting body collection. C: `struct heredocs
    /// *hdocs` (zsh.h:3100). zshrs uses Vec<HereDoc> until Phase 9b
    /// (PORT_PLAN.md) reinstates C's linked-list shape.
    pub hdocs: Vec<HereDoc>,
    /// C: `int incmdpos` (zsh.h:3102).
    pub incmdpos: bool,
    /// C: `int aliasspaceflag` (zsh.h:3103).
    pub aliasspaceflag: i32,
    /// C: `int incond` (zsh.h:3104).
    pub incond: i32,
    /// C: `int inredir` (zsh.h:3105).
    pub inredir: bool,
    /// C: `int incasepat` (zsh.h:3106).
    pub incasepat: i32,
    /// C: `int isnewlin` (zsh.h:3107).
    pub isnewlin: i32,
    /// C: `int infor` (zsh.h:3108).
    pub infor: i32,
    /// C: `int inrepeat_` (zsh.h:3109).
    pub inrepeat_: i32,
    /// C: `int intypeset` (zsh.h:3110).
    pub intypeset: bool,
    // ── Wordcode-buffer state — STUB until Phase 9b ──
    // C `Wordcode ecbuf` (zsh.h:3112) + `Eccstr ecstrs` (zsh.h:3113) +
    // `int eclen/ecused/ecnpats/ecsoffs/ecssub/ecnfunc` (zsh.h:3112-3114).
    // zshrs hasn't emitted wordcode yet — these fields exist to
    // preserve the C shape but read/write nothing until P9b lands.
    pub eclen: i32,
    pub ecused: i32,
    pub ecnpats: i32,
    pub ecbuf: Option<Vec<u32>>,
    pub ecstrs: Option<Vec<u8>>,
    pub ecsoffs: i32,
    pub ecssub: i32,
    pub ecnfunc: i32,
    // P8: Rust-only safety counters (recursion_depth, global_iterations)
    // migrated to PARSER_RECURSION_DEPTH + PARSER_GLOBAL_ITERATIONS
    // thread_locals. parse_stack no longer carries them — matches C
    // exactly (C's struct parse_stack has no analog).
}

// Old uppercase Rust-only `ParseStack` is gone. Compat alias so
// existing call sites (context.rs) keep resolving until the
// rename ripples through.
#[allow(non_camel_case_types)]
pub type ParseStack = parse_stack;

/// Walk every ZshRedir in the program and, for any with a `heredoc_idx`,
/// pull the body+terminator out of `bodies` and stuff into `heredoc`.
/// `bodies[i]` corresponds to the i-th heredoc registered by the lexer
/// during scanning (in source order).
fn fill_heredoc_bodies(prog: &mut ZshProgram, bodies: &[HereDocInfo]) {
    for list in &mut prog.lists {
        fill_in_sublist(&mut list.sublist, bodies);
    }
}

fn fill_in_sublist(sub: &mut ZshSublist, bodies: &[HereDocInfo]) {
    fill_in_pipe(&mut sub.pipe, bodies);
    if let Some(next) = &mut sub.next {
        fill_in_sublist(&mut next.1, bodies);
    }
}

fn fill_in_pipe(pipe: &mut ZshPipe, bodies: &[HereDocInfo]) {
    fill_in_command(&mut pipe.cmd, bodies);
    if let Some(next) = &mut pipe.next {
        fill_in_pipe(next, bodies);
    }
}

fn fill_in_command(cmd: &mut ZshCommand, bodies: &[HereDocInfo]) {
    match cmd {
        ZshCommand::Simple(s) => {
            for r in &mut s.redirs {
                resolve_redir(r, bodies);
            }
        }
        ZshCommand::Subsh(p) | ZshCommand::Cursh(p) => fill_heredoc_bodies(p, bodies),
        ZshCommand::FuncDef(f) => fill_heredoc_bodies(&mut f.body, bodies),
        ZshCommand::If(i) => {
            fill_heredoc_bodies(&mut i.cond, bodies);
            fill_heredoc_bodies(&mut i.then, bodies);
            for (c, b) in &mut i.elif {
                fill_heredoc_bodies(c, bodies);
                fill_heredoc_bodies(b, bodies);
            }
            if let Some(e) = &mut i.else_ {
                fill_heredoc_bodies(e, bodies);
            }
        }
        ZshCommand::While(w) | ZshCommand::Until(w) => {
            fill_heredoc_bodies(&mut w.cond, bodies);
            fill_heredoc_bodies(&mut w.body, bodies);
        }
        ZshCommand::For(f) => fill_heredoc_bodies(&mut f.body, bodies),
        ZshCommand::Case(c) => {
            for arm in &mut c.arms {
                fill_heredoc_bodies(&mut arm.body, bodies);
            }
        }
        ZshCommand::Repeat(r) => fill_heredoc_bodies(&mut r.body, bodies),
        ZshCommand::Time(Some(sublist)) => fill_in_sublist(sublist, bodies),
        ZshCommand::Try(t) => {
            fill_heredoc_bodies(&mut t.try_block, bodies);
            fill_heredoc_bodies(&mut t.always, bodies);
        }
        ZshCommand::Redirected(inner, redirs) => {
            for r in redirs {
                resolve_redir(r, bodies);
            }
            fill_in_command(inner, bodies);
        }
        ZshCommand::Time(None) | ZshCommand::Cond(_) | ZshCommand::Arith(_) => {}
    }
}

fn resolve_redir(r: &mut ZshRedir, bodies: &[HereDocInfo]) {
    if let Some(idx) = r.heredoc_idx {
        if let Some(info) = bodies.get(idx) {
            r.heredoc = Some(info.clone());
        }
    }
}

/// If `list` is a Simple containing one word that ends in the
/// `<Inpar><Outpar>` token pair (the lexer-port encoding of `()`),
/// return the bare name. Used by `parse_program_until` to detect
/// `name() {body}` style function definitions where the lexer
/// hasn't split the `()` from the name.
/// Detect the `name() …` shape inside a Simple. Returns the function
/// name and (when the body was already inlined into the same Simple,
/// e.g. `foo() echo hi`) the rest of the words as the body's argv.
/// Returns None for non-funcdef shapes.
fn simple_name_with_inoutpar(list: &ZshList) -> Option<(Vec<String>, Vec<String>)> {
    if list.flags.async_ || list.sublist.next.is_some() {
        return None;
    }
    let pipe = &list.sublist.pipe;
    if pipe.next.is_some() {
        return None;
    }
    let simple = match &pipe.cmd {
        ZshCommand::Simple(s) => s,
        _ => return None,
    };
    if simple.words.is_empty() || !simple.assigns.is_empty() {
        return None;
    }
    let suffix = "\u{88}\u{8a}"; // Inpar + Outpar
                                 // Find the FIRST word ending in `()`. zsh accepts the
                                 // multi-name shorthand `fna fnb fnc() { body }` (parse.c:
                                 // par_funcdef wordlist) — words[0..i-1] are extra names,
                                 // words[i] is `lastname()`. Words after are the body argv
                                 // (one-line shorthand, `name() cmd args`).
    let par_idx = simple.words.iter().position(|w| w.ends_with(suffix))?;
    let mut names: Vec<String> = Vec::with_capacity(par_idx + 1);
    for w in &simple.words[..par_idx] {
        // Earlier names must be bare identifiers, NOT contain
        // tokens that imply they're not function names (no `()`,
        // no quotes, no expansions). zsh's lexer enforces this
        // at the wordlist level; we approximate by requiring the
        // word be an identifier-shaped token after untokenize.
        let bare = super::lex::untokenize(w);
        let valid = !bare.is_empty()
            && bare
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.' || c == '$');
        if !valid {
            return None;
        }
        names.push(bare);
    }
    let last = &simple.words[par_idx];
    let bare = &last[..last.len() - suffix.len()];
    if bare.is_empty() {
        return None;
    }
    names.push(super::lex::untokenize(bare));
    let rest = simple.words[par_idx + 1..].to_vec();
    Some((names, rest))
}

/// Initialize parser state for a fresh parse of `input`.
/// Free-fn entry point — resets parser thread_locals and loads input.
pub fn parse_init(input: &str) {
    // P8: reset Rust-only safety counters at parser construction.
    PARSER_GLOBAL_ITERATIONS.set(0);
    PARSER_RECURSION_DEPTH.set(0);
    // Seed the option defaults the parser/lexer inspect. Real zsh
    // installs these via `install_emulation_defaults` (options.c:172)
    // at shell startup; zshrs's parse-only test entry path bypasses
    // init_main, so we mirror the `zsh` emulation defaults here.
    // Only seeds when unset so a script that explicitly disabled an
    // option stays so.
    for (name, default) in [
        ("shortloops", true),
        ("shortrepeat", false),
        ("multifuncdef", true),
        ("aliasfuncdef", false),
        ("ignorebraces", false),
        ("cshjunkieloops", false),
        ("posixbuiltins", false),
        ("execopt", true),
        ("kshautoload", false),
        ("aliases", true),
    ] {
        if crate::ported::options::opt_state_get(name).is_none() {
            crate::ported::options::opt_state_set(name, default);
        }
    }
    lex_init(input);
}

/// C zsh's parser has no iteration cap — it trusts itself. The
/// Rust-only `check_limit` was a paranoia counter that fired
/// spuriously under nested cmdsubst (parse_context_save resets the
/// counter to 0 mid-parse, then the outer frame's tear-down decrement
/// underflowed). Now a no-op for C fidelity; mirrors the Phase 1
/// removal in lex.rs.
#[inline]
fn check_limit() -> bool {
    false
}

/// Same story as `check_limit` — C has no recursion cap, and the
/// Rust counter underflowed across nested-context boundaries. Stub.
#[inline]
fn check_recursion() -> bool {
    false
}

/// Direct port of `parse_context_save(struct parse_stack *ps, int toplevel)` at `Src/parse.c:295`.
/// Snapshots the lexer-side file-statics (which currently live on
/// `lexer` until Phase 7 dissolution makes them file-scope
/// thread_local!s) plus the pending heredoc list, plus the
/// wordcode-buffer state (STUB until Phase 9b). Saves Rust-only
/// recursion counters too so nested parses get fresh limits.
/// WARNING: param names don't match C — Rust=(ps) vs C=(ps, toplevel)
pub fn parse_context_save(ps: &mut parse_stack) {
    // parse.c:299 — `ps->hdocs = hdocs; hdocs = NULL;`
    ps.hdocs = heredocs_take();
    // parse.c:302-310 — save lexer-side state.
    ps.incmdpos = incmdpos();
    // parse.c:303 — aliasspaceflag — not yet a LEX_* thread_local.
    // STUB; Phase 7 wires it. Same for the few below marked STUB.
    ps.aliasspaceflag = 0;
    ps.incond = incond();
    ps.inredir = inredir();
    ps.incasepat = incasepat();
    ps.isnewlin = isnewlin();
    ps.infor = infor();
    ps.inrepeat_ = inrepeat();
    ps.intypeset = intypeset();
    // parse.c:312-317 — wordcode buffer state. STUB until Phase 9b
    // (zshrs has no ecbuf yet).
    ps.eclen = 0;
    ps.ecused = 0;
    ps.ecnpats = 0;
    ps.ecbuf = None;
    ps.ecstrs = None;
    ps.ecsoffs = 0;
    ps.ecssub = 0;
    ps.ecnfunc = 0;
    // P8: counters are file-scope thread_locals; reset them on save
    // (matches the C parse_context_save clear-buffer semantics).
    // Nested parses get a fresh limit; outer parse's count is lost
    // — acceptable since the counters are safety nets, not state.
    PARSER_RECURSION_DEPTH.set(0);
    PARSER_GLOBAL_ITERATIONS.set(0);
    set_incmdpos(true);
    set_incond(0);
    set_inredir(false);
    set_incasepat(0);
    set_infor(0);
    set_inrepeat(0);
    set_intypeset(false);
}

/// Direct port of `parse_context_restore(const struct parse_stack *ps, int toplevel)` at `Src/parse.c:326`.
/// Inverse of `parse_context_save`. Restores lexer-side state +
/// pending heredocs + Rust-only counters from `ps`, then clears
/// `errflag & ERRFLAG_ERROR` per parse.c:354.
/// WARNING: param names don't match C — Rust=(ps) vs C=(ps, toplevel)
pub fn parse_context_restore(ps: &parse_stack) {
    // parse.c:330-331 — free any in-progress wordcode buffer.
    // zshrs has no wordcode yet (STUB until Phase 9b); the AST
    // nodes are owned by their parent so dropping the parser
    // frees them.

    // parse.c:333-352 — restore saved state.
    heredocs_set(ps.hdocs.clone());
    set_incmdpos(ps.incmdpos);
    // aliasspaceflag STUB until Phase 7.
    set_incond(ps.incond);
    set_inredir(ps.inredir);
    set_incasepat(ps.incasepat);
    set_isnewlin(ps.isnewlin);
    set_infor(ps.infor);
    set_inrepeat(ps.inrepeat_);
    set_intypeset(ps.intypeset);
    // ecbuf/eclen/ecused/ecnpats/ecstrs/ecsoffs/ecssub/ecnfunc
    // STUB until Phase 9b.
    // P8: counters not restored — see parse_context_save comment.

    // parse.c:354 — `errflag &= ~ERRFLAG_ERROR;` — clear the
    // error flag so the outer parse sees a clean state.
    crate::ported::utils::errflag.fetch_and(
        !crate::ported::utils::ERRFLAG_ERROR,
        std::sync::atomic::Ordering::Relaxed,
    );
}

/// Initialize parser status. Direct port of zsh/Src/parse.c:491
/// `init_parse_status`. Clears the per-parse-call lexer flags
/// so a fresh parse starts from cmd-position with no nesting
/// state inherited from a prior parse.
pub fn init_parse_status() {
    // parse.c:500-502 — `incasepat = incond = inredir = infor =
    // intypeset = 0; inrepeat_ = 0; incmdpos = 1;`
    set_incasepat(0);
    set_incond(0);
    set_inredir(false);
    set_infor(0);
    set_intypeset(false);
    set_incmdpos(true);
}

/// Initialize parser for a fresh parse. Direct port of
/// zsh/Src/parse.c:509 `init_parse`. C source allocates a
/// fresh wordcode buffer (ecbuf) sized EC_INIT_SIZE, resets the
/// per-parse-call counters, and calls init_parse_status. zshrs
/// has no flat wordcode buffer (AST is built inline) so this
/// function reduces to init_parse_status + recursion_depth/
/// global_iterations clear.
pub fn init_parse() {
    // parse.c:513-520 — `ecbuf = (Wordcode) zalloc(EC_INIT_SIZE *
    // sizeof(wordcode)); eclen = EC_INIT_SIZE; ecused = 0;
    // ecnpats = 0; ecstrs = NULL; ecsoffs = ecnfunc = 0;
    // ecssub = 0;`. P9b — initialize the per-evaluator wordcode
    // buffer for this parse call. zshrs uses thread-local
    // statics declared at file scope (parse.rs:25-50).
    ECBUF.with_borrow_mut(|buf| {
        buf.clear();
        buf.resize(EC_INIT_SIZE as usize, 0);
    });
    ECLEN.set(EC_INIT_SIZE);
    ECUSED.set(0);
    ECNPATS.set(0);
    ECSOFFS.set(0);
    ECSSUB.set(0);
    ECNFUNC.set(0);
    ECSTRS_INDEX.with_borrow_mut(|m| m.clear());
    ECSTRS_REVERSE.with_borrow_mut(|m| m.clear());
    ECSTRS_TREE.with_borrow_mut(|t| *t = None);

    PARSER_RECURSION_DEPTH.set(0);
    PARSER_GLOBAL_ITERATIONS.set(0);
    // parse.c:522 — `init_parse_status();`
    init_parse_status();
}

/// Port of `int empty_eprog(Eprog p)` from `Src/parse.c:584`. C
/// body: `return (!p || !p->prog || *p->prog == WCB_END());` —
/// the eprog is empty when its prog buffer is missing or the
/// first wordcode is the WC_END marker. Used by signal handlers
/// (`Src/signals.c:712`) to short-circuit a trap that resolves to
/// an empty program.
pub fn empty_eprog(p: &crate::ported::zsh_h::eprog) -> bool {
    p.prog.is_empty() || p.prog[0] == crate::ported::zsh_h::WCB_END()
}

/// Clear pending here-document list. Direct port of
/// zsh/Src/parse.c:591 `clear_hdocs`. The C version walks
/// the global `hdocs` linked list and frees each node. zshrs
/// stores pending heredocs on the lexer's `heredocs` Vec —
/// truncating it has the same effect.
pub fn clear_hdocs() {
    heredocs_clear();
}

/// Top-level parse-event entry. Direct port of zsh/Src/parse.c:
/// 612-631 `parse_event`. Reads one event from the lexer (a
/// sublist optionally followed by SEPER/AMPER/AMPERBANG) and
/// returns the resulting ZshProgram.
///
/// `endtok` is the token that terminates the event — usually
/// ENDINPUT, but for command-style substitutions the closing
/// `)` (zsh's CMD_SUBST_CLOSE).
///
/// zshrs port note: zsh's parse_event returns an `Eprog` (heap-
/// allocated wordcode program). zshrs returns a `ZshProgram`
/// (AST root). Same role at the parse-output boundary.
pub fn parse_event(endtok: lextok) -> Option<ZshProgram> {
    // parse.c:616-619 — reset state and prime the lexer.
    set_tok(ENDINPUT);
    set_incmdpos(true);
    zshlex();
    // parse.c:620 — `init_parse();`
    init_parse();

    // parse.c:622-625 — drive par_event; on failure clear hdocs.
    if !par_event(endtok) {
        clear_hdocs();
        return None;
    }
    // parse.c:626-628 — if endtok != ENDINPUT, this is a sub-
    // parse for a substitution that doesn't need its own eprog.
    // zshrs returns an empty program in that case (caller
    // discards).
    if endtok != ENDINPUT {
        return Some(ZshProgram { lists: Vec::new() });
    }
    // parse.c:630 — `bld_eprog(1);` — build the final eprog.
    // zshrs has already built the AST via parse_program_until,
    // but parse_event uses par_event directly so we need to
    // collect what par_event accumulated.
    Some(parse_program_until(None))
}

/// Parse one event (sublist with optional separator). Direct
/// port of zsh/Src/parse.c:635 `par_event`. Returns true if
/// an event was successfully parsed, false on EOF / endtok.
///
/// zshrs port note: the C version emits wordcodes via ecadd/
/// set_list_code; zshrs's parser builds AST nodes via
/// par_sublist + par_list. Same flow, different output.
pub fn par_event(endtok: lextok) -> bool {
    // parse.c:639-643 — skip leading SEPERs.
    while tok() == SEPER {
        // parse.c:640-641 — at top-level (endtok == ENDINPUT),
        // a SEPER on a fresh line ends the event.
        if isnewlin() > 0 && endtok == ENDINPUT {
            return false;
        }
        zshlex();
    }
    // parse.c:644-647 — terminate on EOF or matching close-token.
    if tok() == ENDINPUT {
        return false;
    }
    if tok() == endtok {
        return true;
    }
    // parse.c:649-... — drive par_sublist + handle terminator.
    // zshrs's par_sublist already builds the AST node directly.
    match par_sublist() {
        Some(_) => {
            // parse.c:651-693 — terminator handling. zshrs's
            // par_list wraps this; for parse_event we just
            // confirm the sublist parsed.
            true
        }
        None => false,
    }
}

/// Parse one list — non-recursing variant. Direct port of
/// zsh/Src/parse.c:808 `par_list1`. Like par_list but
/// doesn't recurse on the trailing-separator path; used by
/// callers that only want one statement (e.g. each arm of a
/// case body).
pub fn par_list1() -> Option<ZshSublist> {
    // parse.c:810-816 — body is a single par_sublist call wrapped
    // in the eu/ecused tracking that zshrs doesn't need (no
    // wordcode buffer).
    par_sublist()
}

/// Wire a here-document body onto the redirection token that
/// requested it. Direct port of zsh/Src/parse.c:2347
/// `setheredoc`. Called when a heredoc terminator has been
/// matched and the body is ready to be attached to the redir.
///
/// zshrs port note: zsh's setheredoc patches the wordcode
/// in-place via `pc[1] = ecstrcode(doc); pc[2] = ecstrcode(term);`.
/// zshrs threads heredoc bodies through `HereDocInfo` structs
/// that resolve_redir applies during the post-parse fill_in pass.
/// This method is the AST-side equivalent: writes back to the
/// matching redir node by index.
pub fn setheredoc(_pc: usize, _redir_type: i32, _doc: &str, _term: &str, _munged_term: &str) {
    // zshrs's heredoc resolution happens in fill_in_command /
    // resolve_redir at parse top. This stub exists for API
    // parity with the C signature; live wiring happens via
    // heredocs which the post-parse pass consumes.
}

/// Parse a wordlist for `for ... in WORDS;`. Direct port of
/// zsh/Src/parse.c:2362 `par_wordlist`. Reads STRING tokens
/// until the next SEPER / SEMI / NEWLIN.
pub fn par_wordlist() -> Vec<String> {
    let mut out = Vec::new();
    // parse.c:2362-2378 — collect STRINGs into the wordlist.
    while tok() == STRING_LEX {
        if let Some(text) = tokstr() {
            out.push(text);
        }
        zshlex();
    }
    out
}

/// Parse a newline-separated wordlist. Direct port of
/// zsh/Src/parse.c:2379 `par_nl_wordlist`. Like
/// par_wordlist but tolerates leading/trailing newlines.
pub fn par_nl_wordlist() -> Vec<String> {
    // parse.c:2380-2381 — skip leading newlines.
    while tok() == NEWLIN {
        zshlex();
    }
    let out = par_wordlist();
    // parse.c:2395-2397 — skip trailing newlines.
    while tok() == NEWLIN {
        zshlex();
    }
    out
}

/// Read an integer from the next cond token. NOT a direct C port —
/// the C `get_cond_num(char *tst)` (parse.c:2643) is the
/// string-lookup helper ported below. This Rust-only helper exists
/// to support the AST cond-walker (`par_cond_*` analogs) when it
/// needs a numeric literal from the current lex position.
pub fn read_cond_num() -> Option<i64> {
    if tok() != STRING_LEX {
        return None;
    }
    let text = tokstr()?;
    let parsed = text.parse::<i64>().ok()?;
    zshlex();
    Some(parsed)
}

/// Port of `get_cond_num(char *tst)` from `Src/parse.c:2643`. Returns
/// the index of `tst` in `{"nt","ot","ef","eq","ne","lt","gt","le","ge"}`
/// or `-1` if not a recognized binary cond operator.
pub fn get_cond_num(tst: &str) -> i32 {
    // c:2643
    const CONDSTRS: [&str; 9] = [
        "nt", "ot", "ef", "eq", "ne", "lt", "gt", "le", "ge", // c:2647
    ];
    for (i, &c) in CONDSTRS.iter().enumerate() {
        if c == tst {
            return i as i32; // c:2654
        }
    }
    -1 // c:2656
}

/// Emit a parser-level error. Direct port of zsh/Src/parse.c
/// 2733-2766 `yyerror`. C version fills a per-event error buffer
/// and sets errflag. zshrs pushes onto errors which the
/// caller drains via parse()'s Result return.
pub fn yyerror(msg: &str) {
    // parse.c:2735-2765 — zsh's yyerror collects the offending
    // token's literal text + line number. zshrs already does
    // this via error() with the lexer's toklineno.
    error(msg);
}

// ============================================================
// Wordcode emission stubs (parse.c private helpers)
//
// The following functions are direct counterparts of zsh's
// private wordcode-emission helpers in parse.c. zsh uses these
// to write u32 opcodes into a flat `ecbuf` array; zshrs builds
// an AST tree and never emits wordcode at the parse layer.
// The implementations are documented stubs that preserve the
// function signatures + cite the C source. Real wordcode would
// be emitted later by compile_zsh.rs walking the AST.
//
// Listed for port-surface completeness so every parse.c symbol
// has a Rust counterpart even when the algorithm is moot in the
// AST architecture.
// ============================================================

/// Patch a list-placeholder wordcode with its actual opcode +
/// jump distance. Direct port of zsh/Src/parse.c:738
/// `set_list_code`. zsh emits an `ecadd(0)` placeholder before
/// par_sublist runs, then comes back through set_list_code to
/// rewrite the slot with WCB_LIST(type, distance) once the
/// sublist's final length is known.
///
/// Port of `set_list_code(int p, int type, int cmplx)` from
/// `Src/parse.c:738`. Patches the WCB_LIST header at `p` based on
/// whether the sublist body is simple (single command, no
/// pipeline) and Z_SYNC/Z_END — emits the Z_SIMPLE-optimized
/// header when possible, otherwise the plain WCB_LIST(type, 0).
pub fn set_list_code(p: usize, type_code: i32, cmplx: bool) {
    let _ = wc_bdata;
    // c:740 — `if (!cmplx && (type == Z_SYNC || type == (Z_SYNC | Z_END))
    // && WC_SUBLIST_TYPE(ecbuf[p+1]) == WC_SUBLIST_END)`
    let sublist_code = ECBUF.with_borrow(|b| b.get(p + 1).copied().unwrap_or(0));
    let z = type_code;
    let qualifies = !cmplx
        && (z == Z_SYNC || z == (Z_SYNC | Z_END))
        && WC_SUBLIST_TYPE(sublist_code) == WC_SUBLIST_END;
    if qualifies {
        // c:742 — `int ispipe = !(WC_SUBLIST_FLAGS(ecbuf[p+1])
        // & WC_SUBLIST_SIMPLE);`
        let ispipe = (WC_SUBLIST_FLAGS(sublist_code) & WC_SUBLIST_SIMPLE) == 0;
        // c:743 — `ecbuf[p] = WCB_LIST((type|Z_SIMPLE), ecused-2-p);`
        let used = ECUSED.get() as usize;
        let off = used.saturating_sub(2 + p);
        ECBUF.with_borrow_mut(|b| {
            if p < b.len() {
                b[p] = WCB_LIST((z | Z_SIMPLE) as wordcode, off as wordcode);
            }
        });
        // c:744 — `ecdel(p+1);`
        ecdel(p + 1);
        // c:745-746 — `if (ispipe) ecbuf[p+1] = WC_PIPE_LINENO(ecbuf[p+1]);`
        if ispipe {
            ECBUF.with_borrow_mut(|b| {
                if p + 1 < b.len() {
                    b[p + 1] = WC_PIPE_LINENO(b[p + 1]);
                }
            });
        }
    } else {
        // c:748 — `ecbuf[p] = WCB_LIST(type, 0);`
        ECBUF.with_borrow_mut(|b| {
            if p < b.len() {
                b[p] = WCB_LIST(z as wordcode, 0);
            }
        });
    }
}

/// Port of `set_sublist_code(int p, int type, int flags, int skip, int cmplx)`
/// from `Src/parse.c:755`. Patches the WCB_SUBLIST header at `p`.
/// When the sublist is non-complex (single command, no pipeline),
/// sets WC_SUBLIST_SIMPLE and rewrites the following slot to
/// `WC_PIPE_LINENO`.
pub fn set_sublist_code(p: usize, type_code: i32, flags: i32, skip: i32, cmplx: bool) {
    if cmplx {
        // c:758 — `ecbuf[p] = WCB_SUBLIST(type, flags, skip);`
        ECBUF.with_borrow_mut(|b| {
            if p < b.len() {
                b[p] = WCB_SUBLIST(type_code as wordcode, flags as wordcode, skip as wordcode);
            }
        });
    } else {
        // c:760 — `ecbuf[p] = WCB_SUBLIST(type, flags|WC_SUBLIST_SIMPLE, skip);`
        ECBUF.with_borrow_mut(|b| {
            if p < b.len() {
                b[p] = WCB_SUBLIST(
                    type_code as wordcode,
                    (flags as wordcode) | WC_SUBLIST_SIMPLE,
                    skip as wordcode,
                );
            }
        });
        // c:761 — `ecbuf[p+1] = WC_PIPE_LINENO(ecbuf[p+1]);`
        ECBUF.with_borrow_mut(|b| {
            if p + 1 < b.len() {
                b[p + 1] = WC_PIPE_LINENO(b[p + 1]);
            }
        });
    }
}

/// Direct port of `ecadd(wordcode c)` at `Src/parse.c:397`. Append `c` to
/// the wordcode buffer with grow-on-demand, return the new index.
pub fn ecadd(c: u32) -> usize {
    // parse.c:399-405 — `if ((eclen - ecused) < 1) grow`.
    if (ECLEN.get() - ECUSED.get()) < 1 {
        let cur = ECLEN.get();
        let a = if cur < EC_DOUBLE_THRESHOLD {
            cur
        } else {
            EC_INCREMENT
        };
        ECBUF.with_borrow_mut(|buf| {
            buf.resize((cur + a) as usize, 0);
        });
        ECLEN.set(cur + a);
    }
    let idx = ECUSED.get();
    ECBUF.with_borrow_mut(|buf| {
        if (idx as usize) >= buf.len() {
            buf.resize((idx + 1) as usize, 0);
        }
        buf[idx as usize] = c;
    });
    ECUSED.set(idx + 1);
    idx as usize
}

/// Direct port of `ecdel(int p)` at `Src/parse.c:413`. Remove the
/// wordcode at position `p`, shift later entries left by one,
/// decrement ecused, adjust pending heredoc pointers.
pub fn ecdel(p: usize) {
    // parse.c:415-418 — memmove + decrement ecused.
    let n = ECUSED.get() as usize - p - 1;
    if n > 0 {
        ECBUF.with_borrow_mut(|buf| {
            for i in 0..n {
                buf[p + i] = buf[p + i + 1];
            }
        });
    }
    ECUSED.set(ECUSED.get() - 1);
    // parse.c:420 — `ecadjusthere(p, -1)`.
    ecadjusthere(p, -1);
}

/// Direct port of `ecstrcode(char *s)` at `Src/parse.c:426`. Encode a
/// string into a single wordcode (short strings ≤4 bytes packed
/// inline; longer strings get an offset into the deduped registry).
///
/// The long-string path stores the METAFIED bytes (matches what C's
/// strs region contains): collapse Rust UTF-8 chars in 0x80..=0xff
/// to single bytes, then apply zsh metafy (high bytes ≥ 0x83 →
/// `Meta=0x83 + byte^0x20`). Length tracking (ECSOFFS) uses the
/// metafied byte count — same as C `strlen(s) + 1` where C's `s`
/// is already metafied at this point.
pub fn ecstrcode(s: &str) -> u32 {
    // Convert Rust UTF-8 → C-byte form inline: chars ≤ 0xff collapse
    // to single bytes (so zsh markers like Dash = `\u{9b}` are 1 byte
    // instead of `\xc2 \x9b` UTF-8). Chars > 0xff fall back to their
    // UTF-8 bytes — matches how C tokstr would hold them (it sees
    // multi-byte UTF-8 source as raw byte sequences).
    let mut c_bytes: Vec<u8> = Vec::with_capacity(s.len());
    for ch in s.chars() {
        let cu = ch as u32;
        if cu <= 0xff {
            c_bytes.push(cu as u8);
        } else {
            let mut tmp = [0u8; 4];
            c_bytes.extend_from_slice(ch.encode_utf8(&mut tmp).as_bytes());
        }
    }
    let t = c_bytes.iter().any(|&b| (0x83..=0x9f).contains(&b));
    let l = c_bytes.len() + 1; // include NUL terminator
    if l <= 4 {
        // parse.c:436-445 — short-string inline pack. Uses raw C-bytes
        // (NOT metafied — the inline packing stores 1 byte per slot).
        let mut c: u32 = if t { 3 } else { 2 };
        match l {
            4 => {
                c |= (c_bytes[2] as u32) << 19;
                c |= (c_bytes[1] as u32) << 11;
                c |= (c_bytes[0] as u32) << 3;
            }
            3 => {
                c |= (c_bytes[1] as u32) << 11;
                c |= (c_bytes[0] as u32) << 3;
            }
            2 => {
                c |= (c_bytes[0] as u32) << 3;
            }
            1 => {
                // parse.c:443 — empty string special case.
                c = if t { 7 } else { 6 };
            }
            _ => {}
        }
        c
    } else {
        // parse.c:447-466 — long string. Port of C's eccstr BST walk
        // exactly: walk the tree comparing nfunc, then hashval, then
        // strcmp on bytes. Return offs on full match; insert new
        // leaf otherwise. Matches C's exact dedup-hit pattern
        // (which is content-dependent — hash collisions and the
        // lazy short-circuit cmp chain make the tree shape determine
        // whether matching nodes are reachable).
        // hasher is byte-by-byte polynomial (hashtable.c:86); pass
        // c_bytes via from_utf8_unchecked so non-UTF-8 zsh marker
        // bytes feed straight in. SAFETY: hasher only iterates
        // `.bytes()` — no UTF-8 validity assumed.
        let val = crate::ported::hashtable::hasher(unsafe {
            std::str::from_utf8_unchecked(&c_bytes)
        });
        let nfunc = ECNFUNC.get();
        let found_offs = ECSTRS_TREE.with_borrow_mut(|root| {
            // Walk the tree. At each node, if all 3 cmps == 0,
            // return the node's offs. Otherwise descend left/right
            // by the first non-zero cmp's sign.
            let mut cur: &mut Option<Box<EccstrNode>> = root;
            loop {
                let p = match cur.as_mut() {
                    Some(p) => p,
                    None => break None,
                };
                // c:448 — `cmp = p->nfunc - ecnfunc`
                let mut cmp = (p.nfunc as i64) - (nfunc as i64);
                if cmp == 0 {
                    // c:448 — `&& !(cmp = (long)p->hashval - (long)val)`
                    cmp = (p.hashval as i64) - (val as i64);
                    if cmp == 0 {
                        // c:448 — `&& !(cmp = strcmp(p->str, s))`
                        cmp = match p.str.as_slice().cmp(c_bytes.as_slice()) {
                            std::cmp::Ordering::Less => -1,
                            std::cmp::Ordering::Equal => 0,
                            std::cmp::Ordering::Greater => 1,
                        };
                        if cmp == 0 {
                            // c:450 — `return p->offs;`
                            break Some(p.offs);
                        }
                    }
                }
                // c:452 — `pp = (cmp < 0 ? &p->left : &p->right);`
                cur = if cmp < 0 { &mut p.left } else { &mut p.right };
            }
        });
        if let Some(offs) = found_offs {
            return offs;
        }
        let offs =
            (((ECSOFFS.get() - ECSSUB.get()) as u32) << 2) | if t { 1 } else { 0 };
        // c:457-465 — insert new node at the NULL slot the walk
        // terminated at. Encode the walk path as a Vec<bool> of
        // left/right turns (true = right), then re-descend to
        // insert. Borrow-checker friendly: a single mutable walk
        // that either finds an existing node (descend) or fills
        // the empty slot (return).
        let stored = c_bytes.clone();
        let stored_len = stored.len();
        let new_node = Box::new(EccstrNode {
            left: None,
            right: None,
            str: stored.clone(),
            offs,
            nfunc,
            hashval: val,
        });
        ECSTRS_TREE.with_borrow_mut(|root| {
            // Build the path first (immutable-walk; safe because we
            // only ever go further down).
            let mut path: Vec<bool> = Vec::new();
            {
                let mut cur: &Option<Box<EccstrNode>> = root;
                while let Some(p) = cur.as_ref() {
                    let mut cmp = (p.nfunc as i64) - (nfunc as i64);
                    if cmp == 0 {
                        cmp = (p.hashval as i64) - (val as i64);
                        if cmp == 0 {
                            cmp = match p.str.as_slice().cmp(c_bytes.as_slice()) {
                                std::cmp::Ordering::Less => -1,
                                std::cmp::Ordering::Equal => 0,
                                std::cmp::Ordering::Greater => 1,
                            };
                        }
                    }
                    let go_right = cmp >= 0;
                    path.push(go_right);
                    cur = if go_right { &p.right } else { &p.left };
                }
            }
            // Descend mutably along the recorded path and assign at
            // the NULL leaf.
            let mut cur: &mut Option<Box<EccstrNode>> = root;
            for turn in path {
                let p = cur.as_mut().expect("path matches walk");
                cur = if turn { &mut p.right } else { &mut p.left };
            }
            *cur = Some(new_node);
        });
        // Also keep the existing reverse index (offs → bytes) for
        // ecgetstr_wordcode and copy_ecstr — they read flat by offs.
        ECSTRS_REVERSE.with_borrow_mut(|m| {
            m.insert(offs, stored);
        });
        let _ = l;
        ECSOFFS.set(ECSOFFS.get() + (stored_len + 1) as i32);
        offs
    }
}

/// P9b decoder (wordcode-pipeline variant): direct port of
/// `ecgetstr(Estate s, int dup, int *tokflag)` from
/// `Src/parse.c:2855-2890`. Reads a wordcode at `pc`, decodes the
/// encoded string back to owned String. Returns (string,
/// pc_after_consumed). Distinct from the existing `ecgetstr` (which
/// takes a separate strs buffer for text.rs) — this variant uses
/// the live ECSTRS_REVERSE HashMap populated at ecstrcode time.
pub fn ecgetstr_wordcode(buf: &[u32], pc: usize) -> (String, usize) {
    if pc >= buf.len() {
        return (String::new(), pc);
    }
    let c = buf[pc];
    let next = pc + 1;
    // parse.c:2862-2863 — empty-string sentinels.
    if c == 6 || c == 7 {
        return (String::new(), next);
    }
    // parse.c:2864-2871 — inline-packed short string.
    if (c & 2) != 0 {
        let b0 = ((c >> 3) & 0xff) as u8;
        let b1 = ((c >> 11) & 0xff) as u8;
        let b2 = ((c >> 19) & 0xff) as u8;
        let mut bytes: Vec<u8> = Vec::new();
        for b in [b0, b1, b2] {
            if b == 0 {
                break;
            }
            bytes.push(b);
        }
        return (String::from_utf8_lossy(&bytes).into_owned(), next);
    }
    // parse.c:2872-2873 — long string via offs lookup. Map value is
    // metafied Vec<u8>; convert back to display String. Unmetafy is
    // the caller's job (the wordcode-parity dumper does it; other
    // callers may want raw bytes).
    let s = ECSTRS_REVERSE
        .with_borrow(|m| m.get(&c).cloned())
        .map(|v| String::from_utf8_lossy(&v).into_owned())
        .unwrap_or_default();
    (s, next)
}

/// Direct port of `ecispace(int p, int n)` at `Src/parse.c:372`. Insert `n`
/// empty wordcode slots at position `p`, shifting later entries
/// right, growing the buffer as needed, adjusting heredoc pointers.
pub fn ecispace(p: usize, n: usize) {
    // parse.c:376-381 — grow if needed.
    let need = n as i32;
    if (ECLEN.get() - ECUSED.get()) < need {
        let cur = ECLEN.get();
        let mut a = if cur < EC_DOUBLE_THRESHOLD {
            cur
        } else {
            EC_INCREMENT
        };
        if need > a {
            a = need;
        }
        ECBUF.with_borrow_mut(|buf| {
            buf.resize((cur + a) as usize, 0);
        });
        ECLEN.set(cur + a);
    }
    // parse.c:382-385 — memmove p → p+n, gap of n.
    let m = ECUSED.get() as usize - p;
    if m > 0 {
        ECBUF.with_borrow_mut(|buf| {
            let needed = (ECUSED.get() as usize) + n;
            if buf.len() < needed {
                buf.resize(needed, 0);
            }
            for i in (0..m).rev() {
                buf[p + n + i] = buf[p + i];
            }
            for i in 0..n {
                buf[p + i] = 0;
            }
        });
    }
    // parse.c:386 — bump ecused by n.
    ECUSED.set(ECUSED.get() + need);
    // parse.c:387 — `ecadjusthere(p, n)`.
    ecadjusthere(p, need);
}

/// Direct port of `ecadjusthere(int p, int d)` at `Src/parse.c:360`. Walk
/// the pending-heredocs list and bump each `pc` by `d` if it's
/// at or after position `p`. Called by `ecispace` / `ecdel` when
/// wordcodes shift.
#[allow(unused_variables)]
pub fn ecadjusthere(p: usize, d: i32) {
    // parse.c:362-366 — `for (p2 = hdocs; p2; p2 = p2->next) if
    // (p2->pc >= p) p2->pc += d;`. zshrs's hdocs are still
    // Vec<HereDoc> on the lexer (pre-P9c migration); since none
    // of them carry a wordcode pc today (the AST tree has no pc
    // slots), this is a no-op until Phase 9c wires
    // `hdocs.pc` into wordcode emission.
}

// ============================================================
// Eprog runtime ops (parse.c:2767-2853)
//
// dupeprog / useeprog / freeeprog are zsh's reference-counting
// helpers for executable programs. zshrs's AST is owned by
// value (Rust ownership); cloning is a tree-deep copy via
// Clone, "use" is a no-op (the executor borrows the AST), and
// "free" is automatic on drop.
// ============================================================

/// Duplicate an Eprog. Direct port of zsh/Src/parse.c:2813
/// Port of `Eprog dupeprog(Eprog p, int heap)` from
/// `Src/parse.c:2767`. Deep-copies the wordcode array, string
/// table, and pattern-prog slots. `dummy_eprog` is returned
/// unchanged. `heap`-allocated copies get `nref = -1` (never
/// freed); real ones get `nref = 1`.
pub fn dupeprog(p: &crate::ported::zsh_h::eprog, heap: bool) -> crate::ported::zsh_h::eprog {
    // c:2774-2775 — `if (p == &dummy_eprog) return p;` — caller-
    // observable identity in C uses a pointer compare; Rust's
    // equivalent is "if it has the dummy's shape (single WCB_END
    // word and no strs), return a copy of the same shape".
    // c:2796-2797 — `for (i = r->npats; i--; pp++) *pp = dummy_patprog1;`
    // C uses `dummy_patprog1` as a placeholder; the Rust port has
    // `Vec<Patprog>` (Box<patprog>) — synthesize an equivalent zero-
    // initialized patprog for each slot (resolved later by
    // pattern.c::patcompile-on-first-use).
    let dummy_pat = || crate::ported::zsh_h::patprog {
        startoff: 0,
        size: 0,
        mustoff: 0,
        patmlen: 0,
        globflags: 0,
        globend: 0,
        flags: 0,
        patnpar: 0,
        patstartch: 0,
    };
    let r = crate::ported::zsh_h::eprog {
        // c:2778 — `flags = (heap ? EF_HEAP : EF_REAL) | (p->flags & EF_RUN);`
        flags: (if heap { EF_HEAP } else { EF_REAL }) | (p.flags & EF_RUN),
        len: p.len,
        npats: p.npats,
        // c:2787 — `nref = heap ? -1 : 1;`
        nref: if heap { -1 } else { 1 },
        prog: p.prog.clone(),
        strs: p.strs.clone(),
        pats: (0..p.npats).map(|_| Box::new(dummy_pat())).collect(),
        shf: None,
        dump: None,
    };
    r
}

/// Port of `void useeprog(Eprog p)` from `Src/parse.c:2813`.
/// `if (p && p != &dummy_eprog && p->nref >= 0) p->nref++;` —
/// pin a real (non-heap, non-dummy) Eprog so it survives the
/// next `freeeprog`.
pub fn useeprog(p: &mut crate::ported::zsh_h::eprog) {
    // c:2815 — `if (p && p != &dummy_eprog && p->nref >= 0)`
    if p.nref >= 0 {
        p.nref += 1; // c:2816
    }
}

/// Port of `void freeeprog(Eprog p)` from `Src/parse.c:2823`.
/// Refcount-decrement; when it hits zero, drops the pattern progs,
/// decrements the dump refcount if any, and releases the eprog.
/// `dummy_eprog` is never freed. Heap-eprogs (`nref < 0`) are
/// never freed either — they live as long as the heap arena.
pub fn freeeprog(p: &mut crate::ported::zsh_h::eprog) {
    // c:2829 — `if (p && p != &dummy_eprog) { ... }`
    if p.nref > 0 {
        p.nref -= 1; // c:2832
        if p.nref == 0 {
            // c:2833-2840 — drop pats, dump refcount, then the eprog.
            // Rust's Drop handles the per-field cleanup; we just
            // need to decrement the dump count first.
            if let Some(dump) = p.dump.take() {
                let dumped = (*dump).clone();
                decrdumpcount(&dumped); // c:2837
            }
            p.prog.clear();
            p.strs = None;
            p.pats.clear();
        }
    }
}

// ============================================================
// Wordcode runtime getters (parse.c:2853-3060)
//
// These read packed wordcode out of a running Eprog at execution
// time. zshrs's executor walks the AST directly so these are
// stubs that preserve the C signatures + cite the source.
// ============================================================

/// Port of `ecrawstr(Eprog p, Wordcode pc, int *tokflag)` from
/// `Src/parse.c:2891`. Like `ecgetstr` but reads at the given pc
/// without advancing — caller steps `pc` separately.
pub fn ecrawstr(p: &eprog, pc: usize, tokflag: Option<&mut i32>) -> String {
    if pc >= p.prog.len() {
        return String::new();
    }
    let c = p.prog[pc]; // c:2894
    if let Some(tf) = tokflag {
        *tf = i32::from((c & 1) != 0); // c:2898/2906/2912
    }
    if c == 6 || c == 7 {
        // c:2897
        return String::new();
    }
    if (c & 2) != 0 {
        // c:2902
        let b0 = ((c >> 3) & 0xff) as u8;
        let b1 = ((c >> 11) & 0xff) as u8;
        let b2 = ((c >> 19) & 0xff) as u8;
        let mut v = vec![b0, b1, b2];
        v.retain(|&x| x != 0);
        String::from_utf8_lossy(&v).into_owned()
    } else {
        // c:2911
        let off = (c >> 2) as usize;
        let strs_bytes = p.strs.as_deref().unwrap_or("").as_bytes();
        if off >= strs_bytes.len() {
            return String::new();
        }
        let tail = &strs_bytes[off..];
        let end = tail.iter().position(|&b| b == 0).unwrap_or(tail.len());
        String::from_utf8_lossy(&tail[..end]).into_owned()
    }
}

/// Port of `ecgetarr(Estate s, int num, int dup, int *tokflag)` from
/// `Src/parse.c:2917`. Reads `num` strings from wordcode at `s->pc`
/// and OR-folds each entry's token flag into `*tokflag`.
pub fn ecgetarr(s: &mut estate, num: usize, dup: i32, tokflag: Option<&mut i32>) -> Vec<String> {
    let mut ret: Vec<String> = Vec::with_capacity(num); // c:2922
    let mut tf: i32 = 0;
    for _ in 0..num {
        // c:2924 `while (num--)`
        let mut tmp = 0;
        ret.push(ecgetstr(s, dup, Some(&mut tmp))); // c:2925
        tf |= tmp; // c:2926
    }
    if let Some(out) = tokflag {
        // c:2929
        *out = tf;
    }
    ret
}

/// Port of `ecgetlist(Estate s, int num, int dup, int *tokflag)` from
/// `Src/parse.c:2937`. Same shape as `ecgetarr` but C returns
/// `LinkList`; zshrs uses `Vec<String>` for both.
pub fn ecgetlist(
    s: &mut crate::ported::zsh_h::estate,
    num: usize,
    dup: i32,
    tokflag: Option<&mut i32>,
) -> Vec<String> {
    if num == 0 {
        // c:2949-2952
        if let Some(tf) = tokflag {
            *tf = 0;
        }
        return Vec::new();
    }
    ecgetarr(s, num, dup, tokflag)
}

/// Port of `eccopyredirs(Estate s)` from `Src/parse.c:3003`. Reads
/// the WC_REDIR run at `s->pc`, counts the wordcodes needed,
/// reserves space in `ecbuf` via `ecispace`, then re-walks `s->pc`
/// re-emitting each redir's wordcodes into the reserved slot —
/// finally calls `bld_eprog(0)` to package the result as an Eprog.
pub fn eccopyredirs(s: &mut crate::ported::zsh_h::estate) -> Option<crate::ported::zsh_h::eprog> {
    let prog_len = s.prog.prog.len();
    if s.pc >= prog_len {
        return None;
    }
    // c:3007-3009 — `if (wc_code(*pc) != WC_REDIR) return NULL;`
    let first_code = s.prog.prog[s.pc];
    if wc_code(first_code) != WC_REDIR {
        return None;
    }
    // c:3011 — `init_parse();`
    init_parse();

    // c:3013-3027 — count wordcodes the redir run will need.
    // Each WC_REDIR contributes `code + fd1 + name` = 3, plus
    // `+2` if WC_REDIR_FROM_HEREDOC (terminator + munged), plus
    // `+1` if WC_REDIR_VARID.
    let mut probe = s.pc;
    let mut ncodes = 0usize;
    loop {
        if probe >= prog_len {
            break;
        }
        let code = s.prog.prog[probe];
        if wc_code(code) != WC_REDIR {
            break;
        }
        let mut ncode = if WC_REDIR_FROM_HEREDOC(code) != 0 {
            5
        } else {
            3
        };
        if WC_REDIR_VARID(code) != 0 {
            ncode += 1;
        }
        probe += ncode;
        ncodes += ncode;
    }

    // c:3028-3029 — `r = ecused; ecispace(r, ncodes);`
    let r0 = ECUSED.get() as usize;
    ecispace(r0, ncodes);

    // c:3031-3053 — re-walk `s->pc` and write into ecbuf[r..].
    let mut r = r0;
    loop {
        if s.pc >= prog_len {
            break;
        }
        let code = s.prog.prog[s.pc];
        if wc_code(code) != WC_REDIR {
            break;
        }
        s.pc += 1;
        // c:3036 — `ecbuf[r++] = code;`
        ECBUF.with_borrow_mut(|buf| {
            if r >= buf.len() {
                buf.resize(r + 1, 0);
            }
            buf[r] = code;
        });
        r += 1;
        // c:3038 — `ecbuf[r++] = *s->pc++;` (the fd1 word)
        let fd1 = s.prog.prog[s.pc];
        s.pc += 1;
        ECBUF.with_borrow_mut(|buf| {
            if r >= buf.len() {
                buf.resize(r + 1, 0);
            }
            buf[r] = fd1;
        });
        r += 1;
        // c:3041 — `ecbuf[r++] = ecstrcode(ecgetstr(s, EC_NODUP, NULL));`
        let name = ecgetstr(s, EC_NODUP, None);
        let nc = ecstrcode(&name);
        ECBUF.with_borrow_mut(|buf| {
            if r >= buf.len() {
                buf.resize(r + 1, 0);
            }
            buf[r] = nc;
        });
        r += 1;
        // c:3042-3047 — heredoc terminators.
        if WC_REDIR_FROM_HEREDOC(code) != 0 {
            let term = ecgetstr(s, EC_NODUP, None);
            let tc = ecstrcode(&term);
            ECBUF.with_borrow_mut(|buf| {
                if r >= buf.len() {
                    buf.resize(r + 1, 0);
                }
                buf[r] = tc;
            });
            r += 1;
            let munged = ecgetstr(s, EC_NODUP, None);
            let mc = ecstrcode(&munged);
            ECBUF.with_borrow_mut(|buf| {
                if r >= buf.len() {
                    buf.resize(r + 1, 0);
                }
                buf[r] = mc;
            });
            r += 1;
        }
        // c:3048-3049 — varid.
        if WC_REDIR_VARID(code) != 0 {
            let varid = ecgetstr(s, EC_NODUP, None);
            let vc = ecstrcode(&varid);
            ECBUF.with_borrow_mut(|buf| {
                if r >= buf.len() {
                    buf.resize(r + 1, 0);
                }
                buf[r] = vc;
            });
            r += 1;
        }
    }

    // c:3056 — `return bld_eprog(0);` — `bld_eprog` appends the
    // WC_END marker and packages ECBUF/ECSTRS into an Eprog.
    Some(bld_eprog(false))
}

/// `mod_export struct eprog dummy_eprog;` from `Src/parse.c:3066`.
/// Placeholder Eprog used by `shf->funcdef = &dummy_eprog;` in
/// builtin.c when clearing a stale autoload stub. Held in a Mutex
/// so `init_eprog` can set it once at shell startup.
pub static DUMMY_EPROG: std::sync::Mutex<crate::ported::zsh_h::eprog> =
    std::sync::Mutex::new(crate::ported::zsh_h::eprog {
        flags: 0,
        len: 0,
        npats: 0,
        nref: 0,
        prog: Vec::new(),
        strs: None,
        pats: Vec::new(),
        shf: None,
        dump: None,
    });

/// Port of `init_eprog(void)` from `Src/parse.c:3069`. Sets up
/// `dummy_eprog_code = WCB_END(); dummy_eprog.len = sizeof(wordcode);
/// dummy_eprog.prog = &dummy_eprog_code; dummy_eprog.strs = NULL;`.
/// Called once at shell startup (init_main → init_misc → init_eprog).
pub fn init_eprog() {
    let mut d = DUMMY_EPROG.lock().unwrap();
    d.prog = vec![crate::ported::zsh_h::WCB_END()]; // c:3071/3073
    d.len = std::mem::size_of::<wordcode>() as i32; // c:3072
    d.strs = None; // c:3074
    d.flags = 0;
    d.npats = 0;
    d.nref = 0;
}

/// Parse the complete input. Direct port of `parse_event` /
/// `par_list` from `Src/parse.c:614-720`. On syntax error,
/// sets `errflag |= ERRFLAG_ERROR` (via `zerr`) and returns the
/// partial program — callers check `errflag` to detect failure,
/// matching C's `Eprog parse_event(...)` + `if (errflag) {...}`.
pub fn parse() -> ZshProgram {
    zshlex();

    let mut program = parse_program_until(None);

    // Surface lexer-level errors (unmatched quote/heredoc/etc.)
    // that the parser silently rolls past. zsh aborts with a
    // diagnostic via `zerr` which sets `errflag |= ERRFLAG_ERROR`.
    if let Some(msg) = crate::ported::lex::error() {
        crate::ported::utils::zerr(&msg);
    }

    // Post-pass: wire heredoc bodies (collected by lexer.process_heredocs)
    // back into ZshRedir.heredoc fields via heredoc_idx.
    let bodies: Vec<HereDocInfo> = heredocs_clone()
        .into_iter()
        .map(|h| HereDocInfo {
            content: h.content,
            terminator: h.terminator,
            quoted: h.quoted,
        })
        .collect();
    if !bodies.is_empty() {
        fill_heredoc_bodies(&mut program, &bodies);
    }

    program
}

/// P9c: wordcode-emission parser entry. Direct port of zsh's
/// `parse_event(int endtok)` from `Src/parse.c:683-720`. Emits a
/// minimal wordcode stream for the parsed program into the live
/// `ECBUF` thread_local via P9b's `ecadd` / `ecstrcode` API and
/// returns the start index of the emitted Eprog (matching C's
/// `Eprog parse_event(...)` return).
///
/// Minimal implementation: emits `WCB_END()` only for now (P9c
/// stub). The full par_event/par_list/par_sublist/par_pipe/par_cmd
/// recursion that walks the token stream and emits the right
/// wordcode for each production is the multi-week rewrite called
/// out in PORT_PLAN.md. This stub establishes the entry point and
/// drives the live ECBUF emission so downstream consumers (P9d
/// exec_wordcode) have a real wordcode buffer to walk.
pub fn par_event_wordcode() -> usize {
    let start = ECUSED.get() as usize;
    // parse.c:691-710 — par_list loop. Each iteration emits one WC_LIST
    // entry plus its sublist payload; terminator handling between
    // lists matches the SEMI/NEWLIN/AMPER/SEPER switch in the C source.
    while tok() != ENDINPUT && tok() != LEXERR {
        par_list_wordcode();
        match tok() {
            SEMI | NEWLIN | AMPER | AMPERBANG | SEPER => {
                zshlex();
            }
            _ => break,
        }
    }
    // parse.c:712 — `ecadd(WCB_END());`
    ecadd(crate::ported::zsh_h::WCB_END());
    start
}

/// Thread-local mirror of C parse.c's `int *cmplx` argument. Each
/// `par_*` wordcode emitter ORs its complexity bit into this
/// during the recursive descent; the outer `par_event_wordcode`
/// reads it at the end. Mirrors C's `int *cmplx` plumbing
/// through every par_* function — Rust uses a thread_local so
/// the signatures can stay no-arg.
thread_local! {
    static PARSER_CMPLX: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
    static PARSER_INPARTIME: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

#[inline]
fn cmplx_get() -> bool {
    PARSER_CMPLX.with(|c| c.get())
}
#[inline]
fn cmplx_or(b: bool) {
    PARSER_CMPLX.with(|c| c.set(c.get() | b));
}
#[inline]
fn cmplx_set(b: bool) {
    PARSER_CMPLX.with(|c| c.set(b));
}

/// Port of `par_list(int *cmplx)` from `Src/parse.c:771-803`.
/// `list : { SEPER } [ sublist [ { SEPER | AMPER | AMPERBANG } list ] ]`.
/// Drives the WCB_LIST chain — for each sublist, emits a WCB_LIST
/// header, recurses into par_sublist, then patches the header
/// with the right Z_SYNC/Z_ASYNC/Z_ASYNC|Z_DISOWN flag + Z_END
/// marker on the last entry.
pub fn par_list_wordcode() {
    let mut lp: Option<usize> = None;
    loop {
        // c:780 — `while (tok == SEPER) zshlex();`
        while tok() == SEPER {
            zshlex();
        }
        // c:782 — `p = ecadd(0);`
        let p = ecadd(0);
        // c:783 — `c = 0;` — local cmplx accumulator for this sublist.
        let outer = cmplx_get();
        cmplx_set(false);
        let sublist_ok = par_sublist_wordcode();
        let c = cmplx_get();
        cmplx_set(outer | c);
        if sublist_ok {
            // c:785 — `*cmplx |= c;` (already done above)
            let t = tok();
            if t == SEPER || t == AMPER || t == AMPERBANG {
                // c:787 — `if (tok != SEPER) *cmplx = 1;`
                if t != SEPER {
                    cmplx_set(true);
                }
                // c:788 — `set_list_code(p, ...)`
                let z = if t == SEPER {
                    Z_SYNC
                } else if t == AMPER {
                    Z_ASYNC
                } else {
                    Z_ASYNC | Z_DISOWN
                };
                set_list_code(p, z, c);
                // c:792-794 — `incmdpos = 1; do { zshlex(); } while
                // (tok == SEPER);`
                set_incmdpos(true);
                loop {
                    zshlex();
                    if tok() != SEPER {
                        break;
                    }
                }
                lp = Some(p);
                continue; // c:795 `goto rec;`
            } else {
                // c:797 — `set_list_code(p, (Z_SYNC | Z_END), c);`
                set_list_code(p, Z_SYNC | Z_END, c);
            }
        } else {
            // c:799-802 — `ecused--; if (lp >= 0) ecbuf[lp] |= wc_bdata(Z_END);`
            ECUSED.set((ECUSED.get() - 1).max(0));
            if let Some(prev) = lp {
                ECBUF.with_borrow_mut(|b| {
                    if prev < b.len() {
                        b[prev] |= wc_bdata(Z_END as wordcode);
                    }
                });
            }
        }
        break;
    }
}

/// Port of `par_list1(int *cmplx)` from `Src/parse.c:805-816`.
/// Single-sublist variant used by funcdef bodies and the short
/// `for`/`while`/`repeat` forms — exactly one sublist with
/// `Z_SYNC|Z_END`, no chain.
pub fn par_list1_wordcode() {
    // c:807 — `p = ecadd(0); c = 0;`
    let p = ecadd(0);
    let outer = cmplx_get();
    cmplx_set(false);
    let ok = par_sublist_wordcode();
    let c = cmplx_get();
    cmplx_set(outer | c);
    if ok {
        // c:809-811 — `set_list_code(p, Z_SYNC|Z_END, c); *cmplx |= c;`
        set_list_code(p, Z_SYNC | Z_END, c);
    } else {
        // c:813 — `ecused--;`
        ECUSED.set((ECUSED.get() - 1).max(0));
    }
}

/// Port of `par_sublist(int *cmplx)` from `Src/parse.c:823-865`.
/// `sublist : sublist2 [ ( DBAR | DAMPER ) { SEPER } sublist ]`.
/// Emits a WCB_SUBLIST header, recurses into par_sublist2 for
/// the !/coproc prefix + pipeline, then chains via DBAR (`||`)
/// or DAMPER (`&&`) recursively. Returns true if at least one
/// pipeline was emitted.
pub fn par_sublist_wordcode() -> bool {
    // c:827 — `p = ecadd(0);`
    let p = ecadd(0);
    let outer = cmplx_get();
    cmplx_set(false);
    let mut c2 = 0i32;
    let f = par_sublist2(&mut c2);
    let c = c2 != 0;
    cmplx_set(outer | c);
    match f {
        Some(flags) => {
            // c:831 — `e = ecused;`
            let e = ECUSED.get() as usize;
            if tok() == DBAR || tok() == DAMPER {
                // c:834 — `qtok = tok;`
                let qtok = tok();
                // c:836 — `cmdpush(tok == DBAR ? CS_CMDOR : CS_CMDAND);`
                cmdpush(if qtok == DBAR {
                    CS_CMDOR as u8
                } else {
                    CS_CMDAND as u8
                });
                // c:837 — `zshlex();`
                zshlex();
                // c:838-839 — `while (tok == SEPER) zshlex();`
                while tok() == SEPER {
                    zshlex();
                }
                // c:840 — `sl = par_sublist(cmplx);`
                let sl = par_sublist_wordcode();
                // c:841-844 — `set_sublist_code(p, (sl ? (qtok==DBAR ?
                // WC_SUBLIST_OR : WC_SUBLIST_AND) : WC_SUBLIST_END),
                // f, e-1-p, c);`
                let st = if sl {
                    if qtok == DBAR {
                        WC_SUBLIST_OR
                    } else {
                        WC_SUBLIST_AND
                    }
                } else {
                    WC_SUBLIST_END
                };
                set_sublist_code(p, st as i32, flags, (e - 1 - p) as i32, c);
                // c:845 — `cmdpop();`
                cmdpop();
            } else {
                // c:847-849 — `if (tok == AMPER || tok == AMPERBANG)
                // { c = 1; *cmplx |= c; }`
                let c_final = if tok() == AMPER || tok() == AMPERBANG {
                    cmplx_set(true);
                    true
                } else {
                    c
                };
                // c:851 — `set_sublist_code(p, WC_SUBLIST_END, f,
                // e-1-p, c);`
                set_sublist_code(p, WC_SUBLIST_END as i32, flags, (e - 1 - p) as i32, c_final);
            }
            true
        }
        None => {
            // c:855-857 — `ecused--; return 0;`
            ECUSED.set((ECUSED.get() - 1).max(0));
            false
        }
    }
}

/// Port of `par_pline(int *cmplx)` from `Src/parse.c:894-955`.
/// `pline : cmd [ ( BAR | BARAMP ) { SEPER } pline ]`. Emits a
/// WCB_PIPE header (mid for chain links, end for the last cmd)
/// plus the optional BARAMP `2>&1` synthetic redir.
pub fn par_pipe_wordcode() -> bool {
    let line = toklineno() as i64;
    // c:898 — `p = ecadd(0);`
    let p = ecadd(0);
    // c:900-903 — `if (!par_cmd(cmplx, 0)) { ecused--; return 0; }`
    if !par_cmd_wordcode(false) {
        ECUSED.set((ECUSED.get() - 1).max(0));
        return false;
    }
    if tok() == BAR_TOK {
        // c:905 — `*cmplx = 1;`
        cmplx_set(true);
        // c:906 — `cmdpush(CS_PIPE);`
        cmdpush(CS_PIPE as u8);
        // c:907 — `zshlex();`
        zshlex();
        // c:908-909 — `while (tok == SEPER) zshlex();`
        while tok() == SEPER {
            zshlex();
        }
        // c:910 — `ecbuf[p] = WCB_PIPE(WC_PIPE_MID, line>=0 ? line+1 : 0);`
        ECBUF.with_borrow_mut(|b| {
            if p < b.len() {
                b[p] = WCB_PIPE(
                    WC_PIPE_MID,
                    if line >= 0 { (line + 1) as wordcode } else { 0 },
                );
            }
        });
        // c:911 — `ecispace(p+1, 1);`
        ecispace(p + 1, 1);
        // c:912 — `ecbuf[p+1] = ecused - 1 - p;`
        let used = ECUSED.get() as usize;
        ECBUF.with_borrow_mut(|b| {
            if p + 1 < b.len() {
                b[p + 1] = (used.saturating_sub(1 + p)) as wordcode;
            }
        });
        // c:913-915 — `if (!par_pline(cmplx)) tok = LEXERR;`
        if !par_pipe_wordcode() {
            set_tok(LEXERR);
        }
        cmdpop();
        true
    } else if tok() == BARAMP {
        // c:920-924 — walk past inline WC_REDIR to find r.
        let mut r = p + 1;
        loop {
            let code = ECBUF.with_borrow(|b| b.get(r).copied().unwrap_or(0));
            if wc_code(code) != WC_REDIR {
                break;
            }
            r += WC_REDIR_WORDS(code) as usize;
        }
        // c:926-929 — `ecispace(r, 3);` + synthetic `2>&1` redir
        ecispace(r, 3);
        ECBUF.with_borrow_mut(|b| {
            if r + 2 < b.len() {
                b[r] = WCB_REDIR(REDIR_MERGEOUT as wordcode);
                b[r + 1] = 2;
                b[r + 2] = ecstrcode("1");
            }
        });
        cmplx_set(true);
        cmdpush(CS_ERRPIPE as u8);
        zshlex();
        while tok() == SEPER {
            zshlex();
        }
        ECBUF.with_borrow_mut(|b| {
            if p < b.len() {
                b[p] = WCB_PIPE(
                    WC_PIPE_MID,
                    if line >= 0 { (line + 1) as wordcode } else { 0 },
                );
            }
        });
        ecispace(p + 1, 1);
        let used = ECUSED.get() as usize;
        ECBUF.with_borrow_mut(|b| {
            if p + 1 < b.len() {
                b[p + 1] = (used.saturating_sub(1 + p)) as wordcode;
            }
        });
        if !par_pipe_wordcode() {
            set_tok(LEXERR);
        }
        cmdpop();
        true
    } else {
        // c:951 — `ecbuf[p] = WCB_PIPE(WC_PIPE_END, line>=0 ? line+1 : 0);`
        ECBUF.with_borrow_mut(|b| {
            if p < b.len() {
                b[p] = WCB_PIPE(
                    WC_PIPE_END,
                    if line >= 0 { (line + 1) as wordcode } else { 0 },
                );
            }
        });
        true
    }
}

/// Port of `par_cmd(int *cmplx, int zsh_construct)` from
/// `Src/parse.c:958-1085`. Parses leading + trailing redirs and
/// dispatches on the current token to the right par_* builder.
/// Returns false only when no command was emitted (no redirs +
/// par_simple returned 0).
pub fn par_cmd_wordcode(zsh_construct: bool) -> bool {
    let mut nr = 0i32;
    // c:962 — `r = ecused;` — used for trailing-redir patch
    // bookkeeping; the actual redir mutation goes through par_redir
    // which keeps its own offset.
    let mut r = ECUSED.get();
    // c:964-969 — leading redirs.
    if IS_REDIROP(tok()) {
        cmplx_set(true);
        while IS_REDIROP(tok()) {
            if let Some(_) = par_redir() {
                nr += 1;
            } else {
                break;
            }
        }
    }
    match tok() {
        FOR => {
            cmdpush(CS_FOR as u8);
            par_for_wordcode();
            cmdpop();
        }
        FOREACH => {
            cmdpush(CS_FOREACH as u8);
            par_for_wordcode();
            cmdpop();
        }
        SELECT => {
            cmplx_set(true);
            cmdpush(CS_SELECT as u8);
            par_for_wordcode();
            cmdpop();
        }
        CASE => {
            cmdpush(CS_CASE as u8);
            par_case_wordcode();
            cmdpop();
        }
        IF => {
            par_if_wordcode();
        }
        WHILE => {
            cmdpush(CS_WHILE as u8);
            par_while_wordcode();
            cmdpop();
        }
        UNTIL => {
            cmdpush(CS_UNTIL as u8);
            par_while_wordcode();
            cmdpop();
        }
        REPEAT => {
            cmdpush(CS_REPEAT as u8);
            par_repeat_wordcode();
            cmdpop();
        }
        INPAR_TOK => {
            cmplx_set(true);
            cmdpush(CS_SUBSH as u8);
            par_subsh_wordcode_impl(zsh_construct);
            cmdpop();
        }
        INBRACE_TOK => {
            cmdpush(CS_CURSH as u8);
            par_subsh_wordcode_impl(zsh_construct);
            cmdpop();
        }
        FUNC => {
            cmdpush(CS_FUNCDEF as u8);
            par_funcdef_wordcode();
            cmdpop();
        }
        DINBRACK => {
            cmdpush(CS_COND as u8);
            par_cond_wordcode();
            cmdpop();
        }
        DINPAR => {
            par_arith_wordcode();
        }
        TIME => {
            // c:1037-1050 — `static int inpartime` guard so
            // `time time foo` doesn't recurse infinitely.
            if !PARSER_INPARTIME.with(|c| c.get()) {
                cmplx_set(true);
                PARSER_INPARTIME.with(|c| c.set(true));
                par_time_wordcode();
                PARSER_INPARTIME.with(|c| c.set(false));
            } else {
                set_tok(STRING_LEX);
                let sr = par_simple_wordcode_impl(nr);
                if sr == 0 && nr == 0 {
                    return false;
                }
                if sr > 1 {
                    cmplx_set(true);
                    r += sr - 1;
                }
            }
        }
        _ => {
            // c:1054 — `if (!(sr = par_simple(cmplx, nr)))`
            let sr = par_simple_wordcode_impl(nr);
            if sr == 0 {
                if nr == 0 {
                    return false;
                }
            } else if sr > 1 {
                cmplx_set(true);
                r += sr - 1;
            }
        }
    }
    // c:1075-1078 — trailing redirs.
    if IS_REDIROP(tok()) {
        cmplx_set(true);
        while IS_REDIROP(tok()) {
            let _ = par_redir();
        }
    }
    // c:1079-1082 — `incmdpos=1; incasepat=0; incond=0; intypeset=0;`
    set_incmdpos(true);
    set_incasepat(0);
    set_incond(0);
    set_intypeset(false);
    let _ = r;
    true
}

/// Adapter: par_cmd_wordcode wrapper for sites that don't supply
/// the zsh_construct flag (defaults to false, matching the C
/// `par_cmd(cmplx, 0)` call shape at c:902).
pub fn par_cmd_wordcode_noargs() {
    par_cmd_wordcode(false);
}

/// P9c stub: direct port of `par_for(int *complex)` from
/// Port of `par_for(int *cmplx)` from `Src/parse.c:1087-1199`.
pub fn par_for_wordcode() {
    let csh = tok() == FOREACH;
    let sel = tok() == SELECT;
    let p = ecadd(0);
    set_incmdpos(false);
    set_infor(if tok() == FOR { 2 } else { 0 });
    zshlex();
    let type_code: wordcode;
    if tok() == DINPAR {
        zshlex();
        if tok() != DINPAR {
            error("par_for: expected init");
            return;
        }
        ecstr(&tokstr().unwrap_or_default());
        zshlex();
        if tok() != DINPAR {
            error("par_for: expected cond");
            return;
        }
        ecstr(&tokstr().unwrap_or_default());
        zshlex();
        if tok() != DOUTPAR {
            error("par_for: expected ))");
            return;
        }
        ecstr(&tokstr().unwrap_or_default());
        set_infor(0);
        set_incmdpos(true);
        zshlex();
        type_code = WC_FOR_COND;
    } else {
        set_infor(0);
        if tok() != STRING_LEX {
            error("par_for: expected identifier");
            return;
        }
        let np = if !sel { Some(ecadd(0)) } else { None };
        let mut n = 0u32;
        set_incmdpos(true);
        loop {
            n += 1;
            ecstr(&tokstr().unwrap_or_default());
            zshlex();
            if tok() != STRING_LEX || sel {
                break;
            }
            if tokstr().as_deref() == Some("in") {
                break;
            }
        }
        if let Some(np) = np {
            ECBUF.with_borrow_mut(|b| {
                if np < b.len() {
                    b[np] = n;
                }
            });
        }
        let posix_in = isnewlin() != 0;
        while isnewlin() != 0 {
            zshlex();
        }
        if tok() == STRING_LEX && tokstr().as_deref() == Some("in") {
            set_incmdpos(false);
            zshlex();
            let np = ecadd(0);
            let mut n = 0u32;
            while tok() == STRING_LEX {
                if let Some(s) = tokstr() {
                    ecstr(&s);
                }
                n += 1;
                zshlex();
            }
            if tok() != SEPER {
                error("par_for: expected separator after `in`");
                return;
            }
            ECBUF.with_borrow_mut(|b| {
                if np < b.len() {
                    b[np] = n as wordcode;
                }
            });
            type_code = if sel { WC_SELECT_LIST } else { WC_FOR_LIST };
        } else if !posix_in && tok() == INPAR_TOK {
            set_incmdpos(false);
            zshlex();
            let np = ecadd(0);
            let mut n = 0u32;
            while tok() == NEWLIN {
                zshlex();
            }
            while tok() == STRING_LEX {
                if let Some(s) = tokstr() {
                    ecstr(&s);
                }
                n += 1;
                zshlex();
            }
            while tok() == NEWLIN {
                zshlex();
            }
            if tok() != OUTPAR_TOK {
                error("par_for: expected `)`");
                return;
            }
            ECBUF.with_borrow_mut(|b| {
                if np < b.len() {
                    b[np] = n as wordcode;
                }
            });
            set_incmdpos(true);
            zshlex();
            type_code = if sel { WC_SELECT_LIST } else { WC_FOR_LIST };
        } else {
            type_code = if sel { WC_SELECT_PPARAM } else { WC_FOR_PPARAM };
        }
    }
    set_incmdpos(true);
    while tok() == SEPER {
        zshlex();
    }
    par_loop_body_wordcode(csh);
    let used = ECUSED.get() as usize;
    let off = used.saturating_sub(1 + p) as wordcode;
    ECBUF.with_borrow_mut(|b| {
        if p < b.len() {
            b[p] = if sel {
                WCB_SELECT(type_code, off)
            } else {
                WCB_FOR(type_code, off)
            };
        }
    });
}

/// Body dispatch shared by par_for / par_while / par_repeat.
/// Direct port of `Src/parse.c:1167-1195`.
fn par_loop_body_wordcode(csh: bool) {
    if tok() == DOLOOP {
        zshlex();
        par_list_wordcode();
        if tok() != DONE {
            error("missing `done`");
            return;
        }
        set_incmdpos(false);
        zshlex();
    } else if tok() == INBRACE_TOK {
        zshlex();
        par_list_wordcode();
        if tok() != OUTBRACE_TOK {
            error("missing `}`");
            return;
        }
        set_incmdpos(false);
        zshlex();
    } else if csh || isset(CSHJUNKIELOOPS) {
        par_list_wordcode();
        if tok() != ZEND {
            error("missing `end`");
            return;
        }
        set_incmdpos(false);
        zshlex();
    } else if unset(SHORTLOOPS) {
        error("short loop form requires SHORTLOOPS");
    } else {
        par_list1_wordcode();
    }
}

/// `select` shares par_for body (c:1024 routes SELECT to par_for).
pub fn par_select_wordcode() {
    par_for_wordcode();
}

/// Port of `par_case(int *cmplx)` from `Src/parse.c:1209-1409`.
pub fn par_case_wordcode() {
    let p = ecadd(0);
    set_incmdpos(false);
    zshlex();
    if tok() != STRING_LEX {
        error("par_case: expected scrutinee");
        return;
    }
    ecstr(&tokstr().unwrap_or_default());
    set_incmdpos(true);
    zshlex();
    while tok() == SEPER {
        zshlex();
    }
    let saw_brace = tok() == INBRACE_TOK;
    if !saw_brace && !(tok() == STRING_LEX && tokstr().as_deref() == Some("in")) {
        error("par_case: expected `in` or `{`");
        return;
    }
    zshlex();
    loop {
        while tok() == SEPER {
            zshlex();
        }
        // c:1245-1247 — `esac` can arrive either as the ESAC reswd
        // token (when incmdpos was true at the SEPER between arms,
        // which is the normal case after the body's `;;`) OR as a
        // STRING with tokstr "esac" (alias context or noaliases off).
        // Accept both shapes so the outer arm loop terminates.
        if (saw_brace && tok() == OUTBRACE_TOK)
            || (!saw_brace && tok() == ESAC)
            || (!saw_brace && tok() == STRING_LEX && tokstr().as_deref() == Some("esac"))
        {
            zshlex();
            break;
        }
        if tok() == INPAR_TOK {
            zshlex();
        }
        // c:1265-1266 — `pp = ecadd(0); palts = ecadd(0); nalts = 0;`
        // Two arm-header words: PP holds WCB_CASE(type, body_off),
        // PALTS holds the pattern alternative count.
        let pp = ecadd(0);
        let palts = ecadd(0);
        let mut nalts: u32 = 0;
        loop {
            if tok() != STRING_LEX {
                error("par_case: expected pattern");
                return;
            }
            ecstr(&tokstr().unwrap_or_default());
            // c:1307,1316 — `ecadd(ecnpats++);` after each pattern.
            // Records a per-pattern index slot that the compiled
            // Patprog later drops into. Without this, npats=0 and
            // the strs/wordcode header bytes diverge from C.
            let np = ECNPATS.with(|c| { let v = c.get(); c.set(v + 1); v }) as u32;
            ecadd(np);
            nalts += 1;
            zshlex();
            if tok() != BAR_TOK {
                break;
            }
            zshlex();
        }
        ECBUF.with_borrow_mut(|b| {
            if palts < b.len() {
                b[palts] = nalts;
            }
        });
        if tok() != OUTPAR_TOK {
            error("par_case: expected `)`");
            return;
        }
        set_incmdpos(true);
        zshlex();
        par_list_wordcode();
        // c:1330-1336 — arm-terminator drives the WC_CASE_OR /
        // WC_CASE_AND / WC_CASE_TESTAND type tag in the WCB_CASE
        // header, which is patched at pp.
        let arm_type = match tok() {
            DSEMI => WC_CASE_OR,
            SEMIAMP => WC_CASE_AND,
            SEMIBAR => WC_CASE_TESTAND,
            _ => WC_CASE_OR,
        };
        let used = ECUSED.get() as usize;
        let arm_off = used.saturating_sub(1 + pp) as wordcode;
        ECBUF.with_borrow_mut(|b| {
            if pp < b.len() {
                b[pp] = WCB_CASE(arm_type, arm_off);
            }
        });
        if tok() == DSEMI || tok() == SEMIAMP || tok() == SEMIBAR {
            zshlex();
        }
    }
    let used = ECUSED.get() as usize;
    let off = used.saturating_sub(1 + p) as wordcode;
    ECBUF.with_borrow_mut(|b| {
        if p < b.len() {
            b[p] = WCB_CASE(WC_CASE_HEAD, off);
        }
    });
}

/// Port of `par_if(int *cmplx)` from `Src/parse.c:1411-1519`.
pub fn par_if_wordcode() {
    let p = ecadd(0);
    cmdpush(CS_IF as u8);
    loop {
        let arm = ecadd(0);
        zshlex();
        par_list_wordcode();
        let body_brace = tok() == INBRACE_TOK;
        if !body_brace {
            while tok() == SEPER {
                zshlex();
            }
            if tok() != THEN {
                error("par_if: expected `then`");
                cmdpop();
                return;
            }
        }
        cmdpop();
        cmdpush(CS_IFTHEN as u8);
        zshlex();
        par_list_wordcode();
        cmdpop();
        let used = ECUSED.get() as usize;
        let arm_off = used.saturating_sub(1 + arm) as wordcode;
        ECBUF.with_borrow_mut(|b| {
            if arm < b.len() {
                b[arm] = WCB_IF(WC_IF_IF, arm_off);
            }
        });
        match tok() {
            ELIF => {
                cmdpush(CS_ELIF as u8);
                continue;
            }
            ELSE => {
                cmdpush(CS_ELSE as u8);
                let arm = ecadd(0);
                zshlex();
                par_list_wordcode();
                let used = ECUSED.get() as usize;
                let arm_off = used.saturating_sub(1 + arm) as wordcode;
                ECBUF.with_borrow_mut(|b| {
                    if arm < b.len() {
                        b[arm] = WCB_IF(WC_IF_IF, arm_off);
                    }
                });
                cmdpop();
                if tok() != FI {
                    error("par_if: expected `fi`");
                    return;
                }
                zshlex();
                break;
            }
            FI => {
                zshlex();
                break;
            }
            _ => {
                if body_brace && tok() == OUTBRACE_TOK {
                    zshlex();
                    break;
                }
                error("par_if: expected `elif`/`else`/`fi`");
                return;
            }
        }
    }
    let used = ECUSED.get() as usize;
    let off = used.saturating_sub(1 + p) as wordcode;
    ECBUF.with_borrow_mut(|b| {
        if p < b.len() {
            b[p] = WCB_IF(WC_IF_HEAD, off);
        }
    });
}

/// Port of `par_while(int *cmplx)` from `Src/parse.c:1521-1564`.
pub fn par_while_wordcode() {
    let until = tok() == UNTIL;
    let p = ecadd(0);
    zshlex();
    par_list_wordcode();
    while tok() == SEPER {
        zshlex();
    }
    par_loop_body_wordcode(false);
    let type_code = if until {
        WC_WHILE_UNTIL
    } else {
        WC_WHILE_WHILE
    };
    let used = ECUSED.get() as usize;
    let off = used.saturating_sub(1 + p) as wordcode;
    ECBUF.with_borrow_mut(|b| {
        if p < b.len() {
            b[p] = WCB_WHILE(type_code, off);
        }
    });
}

/// `until` shares par_while body — tok==UNTIL flips the type.
pub fn par_until_wordcode() {
    par_while_wordcode();
}

/// Port of `par_repeat(int *cmplx)` from `Src/parse.c:1565-1618`.
pub fn par_repeat_wordcode() {
    let p = ecadd(0);
    set_incmdpos(false);
    zshlex();
    if tok() != STRING_LEX {
        error("par_repeat: expected count");
        return;
    }
    ecstr(&tokstr().unwrap_or_default());
    set_incmdpos(true);
    zshlex();
    while tok() == SEPER {
        zshlex();
    }
    par_loop_body_wordcode(false);
    let used = ECUSED.get() as usize;
    let off = used.saturating_sub(1 + p) as wordcode;
    ECBUF.with_borrow_mut(|b| {
        if p < b.len() {
            b[p] = WCB_REPEAT(off);
        }
    });
}

/// Port of `par_funcdef(int *cmplx)` from `Src/parse.c:1672-1786`.
pub fn par_funcdef_wordcode() {
    let p = ecadd(0);
    // c:1681-1683 — `nocorrect = 1; incmdpos = 0; zshlex();` —
    // set BEFORE the zshlex past `function`, so the next-token
    // lex doesn't promote `{` to INBRACE_TOK or recognise reswds.
    set_nocorrect(1);
    set_incmdpos(false);
    zshlex();
    let np = ecadd(0);
    let mut n = 0u32;
    // c:1701-1709 — names loop. C special-cases `tokstr[0] ==
    // Inbrace || tokstr[0] == '{'` to break out and set tok =
    // INBRACE, since a bare `{` at incmdpos=0 lexes as STRING
    // but should still open the funcdef body. Without this,
    // `function f { ... }` swallowed the `{` as a name and the
    // body never started.
    while tok() == STRING_LEX {
        let s = tokstr().unwrap_or_default();
        let bytes = s.as_bytes();
        if bytes.len() == 1 && (bytes[0] == b'{' || s == "\u{8f}") {
            set_tok(INBRACE_TOK);
            break;
        }
        ecstr(&s);
        n += 1;
        zshlex();
    }
    ECBUF.with_borrow_mut(|b| {
        if np < b.len() {
            b[np] = n;
        }
    });
    // c:1715-1716 — `nocorrect = 0; incmdpos = 1;` — restore
    // before the body parse.
    set_nocorrect(0);
    set_incmdpos(true);
    if tok() == INOUTPAR {
        zshlex();
    }
    while tok() == SEPER {
        zshlex();
    }
    if tok() == INBRACE_TOK {
        zshlex();
        par_list_wordcode();
        if tok() != OUTBRACE_TOK {
            error("par_funcdef: expected `}`");
            return;
        }
        zshlex();
    } else if unset(SHORTLOOPS) {
        error("par_funcdef: short body requires SHORTLOOPS");
        return;
    } else {
        par_list1_wordcode();
    }
    let used = ECUSED.get() as usize;
    let off = used.saturating_sub(1 + p) as wordcode;
    ECBUF.with_borrow_mut(|b| {
        if p < b.len() {
            b[p] = WCB_FUNCDEF(off);
        }
    });
}

/// `Src/parse.c:1619-1665`. Handles both `(...)` subshell and
/// `{...}` brace group (cursh) plus optional `always { ... }`
/// trailing block. C uses a single function with `zsh_construct=1`
/// for `{...}` and 0 for `(...)`.
pub fn par_subsh_wordcode_impl(zsh_construct: bool) {
    // c:1621 — `enum lextok otok = tok;`
    let otok = tok();
    // c:1624 — `p = ecadd(0);`
    let p = ecadd(0);
    // c:1626 — `pp = ecadd(0);` (extra word for the always-block try slot)
    let pp = ecadd(0);
    // c:1627 — `zshlex();`
    zshlex();
    // c:1628 — `par_list(cmplx);`
    par_list_wordcode();
    // c:1629 — `ecadd(WCB_END());`
    ecadd(WCB_END());
    // c:1630-1631 — `if (tok != ((otok == INPAR) ? OUTPAR : OUTBRACE))
    // YYERRORV(oecused);`
    let want = if otok == INPAR_TOK {
        OUTPAR_TOK
    } else {
        OUTBRACE_TOK
    };
    if tok() != want {
        error("par_subsh: missing closing token");
        return;
    }
    // c:1633 — `incmdpos = !zsh_construct;`
    set_incmdpos(!zsh_construct);
    // c:1634 — `zshlex();`
    zshlex();

    // c:1637 — `if (otok == INBRACE && tok == STRING && !strcmp(tokstr, "always"))`
    let is_always =
        otok == INBRACE_TOK && tok() == STRING_LEX && tokstr().as_deref() == Some("always");
    if is_always {
        // c:1638 — `ecbuf[pp] = WCB_TRY(ecused - 1 - pp);`
        let used = ECUSED.get() as usize;
        let off = used.saturating_sub(1 + pp);
        ECBUF.with_borrow_mut(|b| {
            if pp < b.len() {
                b[pp] = WCB_TRY(off as wordcode);
            }
        });
        // c:1639 — `incmdpos = 1;`
        set_incmdpos(true);
        // c:1640-1642 — `do { zshlex(); } while (tok == SEPER);`
        loop {
            zshlex();
            if tok() != SEPER {
                break;
            }
        }
        // c:1644-1645 — `if (tok != INBRACE) YYERRORV(oecused);`
        if tok() != INBRACE_TOK {
            error("par_subsh: 'always' expects '{'");
            return;
        }
        // c:1648 — `zshlex();`
        zshlex();
        // c:1649 — `par_save_list(cmplx);`
        par_list_wordcode();
        // c:1650-1651 — `while (tok == SEPER) zshlex();`
        while tok() == SEPER {
            zshlex();
        }
        // c:1653 — `incmdpos = 1;`
        set_incmdpos(true);
        // c:1655-1656 — `if (tok != OUTBRACE) YYERRORV(oecused);`
        if tok() != OUTBRACE_TOK {
            error("par_subsh: 'always' block missing '}'");
            return;
        }
        zshlex();
        // c:1658 — `ecbuf[p] = WCB_TRY(ecused - 1 - p);`
        let used = ECUSED.get() as usize;
        let off = used.saturating_sub(1 + p);
        ECBUF.with_borrow_mut(|b| {
            if p < b.len() {
                b[p] = WCB_TRY(off as wordcode);
            }
        });
    } else {
        // c:1660-1662 — `ecbuf[p] = (otok == INPAR ? WCB_SUBSH(...) :
        // WCB_CURSH(...));`
        let used = ECUSED.get() as usize;
        let off = used.saturating_sub(1 + p);
        ECBUF.with_borrow_mut(|b| {
            if p < b.len() {
                b[p] = if otok == INPAR_TOK {
                    WCB_SUBSH(off as wordcode)
                } else {
                    WCB_CURSH(off as wordcode)
                };
            }
        });
    }
}

/// Wrapper for `(...)` subshell — calls `par_subsh_wordcode_impl(false)`.
pub fn par_subsh_wordcode() {
    par_subsh_wordcode_impl(false);
}

/// Wrapper for `{...}` brace group (cursh) — calls
/// `par_subsh_wordcode_impl(true)`. C uses the same `par_subsh`
/// function with `zsh_construct=1`; the Rust split exists because
/// the par_cmd dispatch at parse.rs:1446 already named them
/// separately.
pub fn par_cursh_wordcode() {
    par_subsh_wordcode_impl(true);
}

/// Port of `par_time(void)` from `Src/parse.c:1787`. `time PIPE`
/// emits WCB_TIMED(WC_TIMED_PIPE) + the sublist code; bare `time`
/// with no pipeline emits WCB_TIMED(WC_TIMED_EMPTY).
pub fn par_time_wordcode() {
    // c:1791 — `zshlex();`
    zshlex();
    // c:1793-1794 — `p = ecadd(0); ecadd(0);`
    let p = ecadd(0);
    ecadd(0);
    // c:1795 — `if ((f = par_sublist2(&c)) < 0)`
    let mut c = 0i32;
    let f = par_sublist2(&mut c);
    match f {
        Some(flags) => {
            // c:1799 — `ecbuf[p] = WCB_TIMED(WC_TIMED_PIPE);`
            ECBUF.with_borrow_mut(|b| {
                if p < b.len() {
                    b[p] = WCB_TIMED(WC_TIMED_PIPE);
                }
            });
            // c:1800 — `set_sublist_code(p+1, WC_SUBLIST_END, f,
            // ecused-2-p, c);`
            let used = ECUSED.get() as usize;
            let skip = used.saturating_sub(2 + p) as i32;
            set_sublist_code(p + 1, WC_SUBLIST_END as i32, flags, skip, c != 0);
        }
        None => {
            // c:1796-1798 — `ecused--; ecbuf[p] = WCB_TIMED(WC_TIMED_EMPTY);`
            ECUSED.set((ECUSED.get() - 1).max(0));
            ECBUF.with_borrow_mut(|b| {
                if p < b.len() {
                    b[p] = WCB_TIMED(WC_TIMED_EMPTY);
                }
            });
        }
    }
}

/// Port of `par_dinbrack(void)` from `Src/parse.c:1810`. Wraps
/// `par_cond` (the cond-expression emitter at parse.c:2409) with
/// the `[[ ... ]]` framing: incond/incmdpos toggles + DOUTBRACK
/// expectation.
pub fn par_cond_wordcode() {
    let oecused = ECUSED.get();
    // c:1814 — `incond = 1;`
    set_incond(1);
    // c:1815 — `incmdpos = 0;`
    set_incmdpos(false);
    // c:1816 — `zshlex();` past `[[`.
    zshlex();
    // c:1817 — `par_cond();` — call the no-skip cond-expression
    // entry that EMITS WORDCODE (par_cond_top → par_cond_1 →
    // par_cond_2 → par_cond_double/triple/multi). NOT the AST
    // `par_cond` at parse.rs:4644 which is a misnamed `par_dinbrack`
    // that skips `[[` AND `]]` and returns a ZshCommand AST node
    // instead of pushing WC_COND opcodes. NOT `parse_cond_expr`
    // either — that's also AST-only, returning ZshCond. With
    // `parse_cond_expr` here, every `[[ ... ]]` test produced ZERO
    // wordcode payload and parity dropped ~148 words on /etc/zshrc.
    let _ = par_cond_top();
    // c:1818-1819 — `if (tok != DOUTBRACK) YYERRORV(oecused);`
    if tok() != DOUTBRACK {
        let _ = oecused;
        error("missing ]]");
        return;
    }
    // c:1820 — `incond = 0;`
    set_incond(0);
    // c:1821 — `incmdpos = 1;`
    set_incmdpos(true);
    // c:1822 — `zshlex();` past `]]`.
    zshlex();
}

/// Port of the `case DINPAR:` arm of `par_cmd` from
/// `Src/parse.c:1031-1034`:
/// ```c
/// ecadd(WCB_ARITH());
/// ecstr(tokstr);
/// zshlex();
/// ```
/// `(( EXPR ))` arithmetic at command position — emits the ARITH
/// opcode followed by the interned EXPR string, then advances past
/// the DINPAR token (which already carries the body text).
pub fn par_arith_wordcode() {
    // c:1032 — `ecadd(WCB_ARITH());`
    ecadd(WCB_ARITH());
    // c:1033 — `ecstr(tokstr);` — interns the expression string and
    // appends its strcode index to the wordcode buffer.
    let expr = tokstr().unwrap_or_default();
    ecstr(&expr);
    // c:1034 — `zshlex();`
    zshlex();
}

/// Port of `par_simple(int *cmplx, int nr)` from
/// `Src/parse.c:1836-2227`. Emits WC_SIMPLE + word count +
/// interned string offsets. Returns `0` when nothing was emitted,
/// otherwise `1 + (number of code words consumed by redirections)`.
/// The full C body handles assignments (ENVSTRING/ENVARRAY),
/// inline `{var}>file` brace-FDs, prefix modifiers (NOCORRECT etc),
/// and `name() { body }` funcdef detection — those paths are
/// progressively wired into the AST parser; this wordcode-emitter
/// covers the simple `cmd args...` case + interleaved redirs.
pub fn par_simple_wordcode_impl(mut nr: i32) -> i32 {
    // c:1836-1842 — `int oecused = ecused, isnull = 1, r, argc = 0,
    // p, isfunc = 0, sr = 0; int c = *cmplx, nrediradd, assignments
    // = 0, ppost = 0, is_typeset = 0; ...`
    let _oecused = ECUSED.get() as usize;
    let mut isnull = true;
    let mut argc: u32 = 0;
    let mut sr: i32 = 0;
    let mut assignments = false;

    // c:1843 — `r = ecused;` — saves the offset where redirs get
    // INSERTED (via ecispace). Each redir shifts later words DOWN
    // by ncodes, so the SIMPLE placeholder at `p` (set later) must
    // also bump by ncodes when a redir lands. C uses `&r` to pass
    // the cursor by reference; Rust uses a mutable local + manual
    // bumps after each par_redir_wordcode call.
    let mut r: usize = ECUSED.get() as usize;

    // c:1844-1919 — pre-cmd loop: NOCORRECT, ENVSTRING (scalar
    // assigns), ENVARRAY (array assigns), IS_REDIROP. Loops until
    // a non-assignment token is seen.
    loop {
        match tok() {
            NOCORRECT => {
                // c:1846-1849
                cmplx_set(true);
                set_nocorrect(1);
            }
            ENVSTRING => {
                // c:1848-1898 — scalar assignment `name=value` or
                // `name+=value`. Emits WCB_ASSIGN(SCALAR, NEW|INC, 0)
                // followed by ecstr(name), ecstr(value).
                let raw = tokstr().unwrap_or_default();
                // Find first of Inbrack / '=' / '+' (the C scan at
                // c:1851-1853). Inside Inbrack we skipparens — i.e.
                // skip `name[...]` index, then continue.
                let bytes: Vec<char> = raw.chars().collect();
                let mut idx = 0usize;
                while idx < bytes.len() {
                    let ch = bytes[idx];
                    if ch == '\u{91}' /* Inbrack */ {
                        // Skip matched Inbrack…Outbrack pair.
                        let mut depth = 1;
                        idx += 1;
                        while idx < bytes.len() && depth > 0 {
                            match bytes[idx] {
                                '\u{91}' => depth += 1,
                                '\u{92}' => depth -= 1,
                                _ => {}
                            }
                            idx += 1;
                        }
                        continue;
                    }
                    // c:1851-1853 — `*ptr != '=' && *ptr != '+'` —
                    // C scan stops on either literal `=` / `+` OR the
                    // Equals marker (`\u{8d}`) the lexer emits for
                    // unquoted `=`. Without the marker check, the
                    // ENVSTRING split scans past the `=` (since it's
                    // already tokenised) and the whole `name=value`
                    // ends up in one ecstr.
                    if ch == '=' || ch == '+' || ch == '\u{8d}' /* Equals */ {
                        break;
                    }
                    idx += 1;
                }
                let is_inc = idx < bytes.len() && bytes[idx] == '+';
                // c:1855-1860 — emit WCB_ASSIGN with WC_ASSIGN_INC
                // (+=) or WC_ASSIGN_NEW (=). The third arg (count)
                // is 0 for scalar.
                let flag = if is_inc { WC_ASSIGN_INC } else { WC_ASSIGN_NEW };
                ecadd(WCB_ASSIGN(WC_ASSIGN_SCALAR, flag, 0));
                // Split into name and str at the `=` (after the
                // optional `+`).
                if is_inc {
                    idx += 1;
                }
                let name: String = bytes[..idx].iter().collect();
                // Skip past the `=` separator (literal or Equals
                // marker `\u{8d}`) so the value starts at the byte
                // after it. Mirrors C `*ptr = '\0'; str = ptr + 1;`
                // (parse.c:1864).
                let str_off = if idx < bytes.len()
                    && (bytes[idx] == '=' || bytes[idx] == '\u{8d}')
                {
                    idx + 1
                } else {
                    idx
                };
                let value: String = bytes[str_off..].iter().collect();
                // c:1866-1877 — scan value for `=(`/`<(`/`>(` (proc
                // subst); if found, bump cmplx (suppresses Z_SIMPLE).
                let vbytes: Vec<char> = value.chars().collect();
                for (i, ch) in vbytes.iter().enumerate() {
                    if i + 1 < vbytes.len() && vbytes[i + 1] == '\u{88}' /* Inpar */ {
                        if *ch == '\u{8d}' /* Equals */
                            || *ch == '\u{94}' /* Inang */
                            || *ch == '\u{96}' /* OutangProc */
                        {
                            cmplx_set(true);
                            break;
                        }
                    }
                }
                ecstr(&name);
                ecstr(&value);
                isnull = false;
                assignments = true;
            }
            ENVARRAY => {
                // c:1898-1922 — array assignment `name=( ... )`.
                // Implementation note: emits placeholder, parses
                // wordlist, patches WCB_ASSIGN(ARRAY, NEW|INC, n)
                // header with the actual element count. zshrs's
                // par_nl_wordlist isn't wired into the wordcode
                // emitter yet; fall back to a minimal placeholder
                // so the WCB_ASSIGN slot exists at the expected
                // position. TODO: full port of c:1898-1922.
                cmplx_set(true);
                let p = ecadd(0);
                set_incmdpos(false);
                let raw = tokstr().unwrap_or_default();
                let is_inc = raw.ends_with('+');
                let name = if is_inc { &raw[..raw.len() - 1] } else { raw.as_str() };
                let flag = if is_inc { WC_ASSIGN_INC } else { WC_ASSIGN_NEW };
                ecstr(name);
                cmdpush(CS_ARRAY as u8);
                zshlex();
                // Count words until OUTPAR_TOK.
                let mut n = 0u32;
                while tok() == STRING_LEX {
                    let w = tokstr().unwrap_or_default();
                    ecstr(&w);
                    n += 1;
                    zshlex();
                    while tok() == NEWLIN {
                        zshlex();
                    }
                }
                ECBUF.with_borrow_mut(|b| {
                    if p < b.len() {
                        b[p] = WCB_ASSIGN(WC_ASSIGN_ARRAY, flag, n);
                    }
                });
                cmdpop();
                if tok() != OUTPAR_TOK {
                    error("expected `)' after array assignment");
                    return 0;
                }
                set_incmdpos(true);
                isnull = false;
                assignments = true;
            }
            t if IS_REDIROP(t) => {
                // c:1900-1904 — `*cmplx = c = 1; nr += par_redir(&r,
                // NULL); continue;`. The wordcode-emitting redir is
                // distinct from the AST par_redir — it INSERTS
                // WCB_REDIR + fd + ecstrcode(name) at offset `r`
                // via ecispace, shifting any later words down.
                cmplx_set(true);
                let added = par_redir_wordcode(&mut r);
                if added == 0 {
                    break;
                }
                nr += added;
                continue;
            }
            _ => break,
        }
        zshlex(); // c:1907 `zshlex();`
    }

    // c:1920-1921 — `if (tok == AMPER || tok == AMPERBANG) YYERROR;`
    if tok() == AMPER || tok() == AMPERBANG {
        error("par_simple: unexpected &");
        return 0;
    }

    // c:1923 — `p = ecadd(WCB_SIMPLE(0));`
    let mut p = ecadd(WCB_SIMPLE(0));

    // c:1924-2105 — main words loop. is_typeset tracks whether the
    // outer command was `typeset`/`export`/etc. so the final
    // placeholder gets WCB_TYPESET instead of WCB_SIMPLE.
    let mut is_typeset = false;
    let mut postassigns: u32 = 0;
    let mut ppost: usize = 0;
    loop {
        match tok() {
            STRING_LEX | TYPESET => {
                // c:1928-1929 — `*cmplx = 1; incmdpos = 0;`
                cmplx_set(true);
                set_incmdpos(false);
                // c:1931-1932 — TYPESET → intypeset = is_typeset = 1.
                if tok() == TYPESET {
                    set_intypeset(true);
                    is_typeset = true;
                }
                let s = tokstr().unwrap_or_default();
                ecstr(&s);
                argc += 1;
                isnull = false;
                zshlex();
            }
            ENVSTRING => {
                // c:2005-2026 — mid-cmd ENVSTRING (under intypeset
                // context). Emits WCB_ASSIGN(SCALAR, NEW, 0) then
                // ecstr(name) + ecstr(value), tracking the first
                // postassign offset in `ppost` (which the trailing
                // WCB_TYPESET header points to).
                if postassigns == 0 {
                    ppost = ecadd(0);
                }
                postassigns += 1;
                let raw = tokstr().unwrap_or_default();
                let bytes: Vec<char> = raw.chars().collect();
                let mut idx = 0usize;
                while idx < bytes.len() {
                    let ch = bytes[idx];
                    if ch == '\u{91}' /* Inbrack */ {
                        let mut depth = 1;
                        idx += 1;
                        while idx < bytes.len() && depth > 0 {
                            match bytes[idx] {
                                '\u{91}' => depth += 1,
                                '\u{92}' => depth -= 1,
                                _ => {}
                            }
                            idx += 1;
                        }
                        continue;
                    }
                    if ch == '=' || ch == '+' || ch == '\u{8d}' /* Equals */ {
                        break;
                    }
                    idx += 1;
                }
                let name: String = bytes[..idx].iter().collect();
                let str_off = if idx < bytes.len() && (bytes[idx] == '=' || bytes[idx] == '\u{8d}') {
                    idx + 1
                } else {
                    idx
                };
                let value: String = bytes[str_off..].iter().collect();
                ecadd(WCB_ASSIGN(WC_ASSIGN_SCALAR, WC_ASSIGN_NEW, 0));
                ecstr(&name);
                ecstr(&value);
                isnull = false;
                zshlex();
            }
            ENVARRAY => {
                // c:2027-2050 — mid-cmd ENVARRAY (typeset N=(…) form).
                // C tracks postassigns + ppost the same as ENVSTRING,
                // but the inner emit is WCB_ASSIGN(ARRAY, NEW, n)
                // with `n` patched in after par_nl_wordlist consumes
                // the elements. C also toggles intypeset=0 around the
                // wordlist so the lexer doesn't try to re-emit
                // assignments inside the array.
                cmplx_set(true);
                if postassigns == 0 {
                    ppost = ecadd(0);
                }
                postassigns += 1;
                let parr = ecadd(0);
                let raw = tokstr().unwrap_or_default();
                let is_inc = raw.ends_with('+');
                let name = if is_inc { &raw[..raw.len() - 1] } else { raw.as_str() };
                let flag = if is_inc { WC_ASSIGN_INC } else { WC_ASSIGN_NEW };
                ecstr(name);
                cmdpush(CS_ARRAY as u8);
                set_intypeset(false);
                zshlex();
                let mut nelem = 0u32;
                while tok() == STRING_LEX {
                    ecstr(&tokstr().unwrap_or_default());
                    nelem += 1;
                    zshlex();
                    while tok() == NEWLIN {
                        zshlex();
                    }
                }
                ECBUF.with_borrow_mut(|b| {
                    if parr < b.len() {
                        b[parr] = WCB_ASSIGN(WC_ASSIGN_ARRAY, flag, nelem);
                    }
                });
                cmdpop();
                set_intypeset(true);
                if tok() != OUTPAR_TOK {
                    error("expected `)' after array assignment");
                    return 0;
                }
                isnull = false;
                zshlex();
            }
            t if IS_REDIROP(t) => {
                // c:1999-2010 — `nrediradd = par_redir(&r, NULL);
                // p += nrediradd; if (ppost) ppost += nrediradd;
                // sr += nrediradd;`
                cmplx_set(true);
                let added = par_redir_wordcode(&mut r);
                if added == 0 {
                    break;
                }
                p += added as usize;
                if ppost != 0 {
                    ppost += added as usize;
                }
                sr += added;
            }
            INOUTPAR => {
                // c:2051-2168 — `name() { body }` funcdef detection.
                // C rewrites the SIMPLE placeholder at `p` into a
                // FUNCDEF header structure with multiple words:
                //   p:        WCB_FUNCDEF(total_offset)
                //   p+1:      argc (name count)
                //   p+2..N:   the names already ecstr'd above
                //   N+1:      0 (placeholder)
                //   N+2:      0 (placeholder)
                //   N+3:      0 (placeholder)
                //   N+4:      0 (placeholder)
                //   N+5:      WCB_END()
                //   ...body wordcode...
                //   ecbuf[p+argc+2] = so - oecssub; (string area)
                //   ecbuf[p+argc+3] = ecsoffs - so;
                //   ecbuf[p+argc+4] = ecnpats;
                //   ecbuf[p+argc+5] = 0;
                //
                // This Rust port handles the common `name() { … }`
                // case (single name + brace body); anonymous funcdef
                // and short-body forms are stubbed for now.
                if !isset(MULTIFUNCDEF) && argc > 1 {
                    error("par_simple: too many function names for funcdef");
                    return 0;
                }
                if assignments || postassigns > 0 {
                    error("par_simple: assignments before funcdef");
                    return 0;
                }
                cmplx_set(true);
                set_incmdpos(true);
                cmdpush(CS_FUNCDEF as u8);
                zshlex();
                while tok() == SEPER {
                    zshlex();
                }
                // c:2079 — `ecispace(p + 1, 1); ecbuf[p+1] = argc;
                // ecadd(0)*4`. Insert the argc word at p+1, then
                // append 4 placeholder words.
                ecispace(p + 1, 1);
                ECBUF.with_borrow_mut(|b| {
                    if p + 1 < b.len() {
                        b[p + 1] = argc;
                    }
                });
                ecadd(0);
                ecadd(0);
                ecadd(0);
                ecadd(0);
                let so = ECSOFFS.get();
                let onp = ECNPATS.with(|c| c.get());
                ECNPATS.with(|c| c.set(0));
                ECNFUNC.set(ECNFUNC.get() + 1);
                let oecssub = ECSSUB.get();
                ECSSUB.set(so);
                if tok() == INBRACE_TOK {
                    zshlex();
                    par_list_wordcode();
                    if tok() != OUTBRACE_TOK {
                        cmdpop();
                        error("par_simple: funcdef expected `}`");
                        return 0;
                    }
                    if argc == 0 {
                        // Anonymous funcdef.
                        set_incmdpos(false);
                    }
                    zshlex();
                } else {
                    // Short-body or non-brace form not yet ported.
                    cmdpop();
                    error("par_simple: funcdef expected `{`");
                    return 0;
                }
                cmdpop();
                ecadd(WCB_END());
                let used = ECUSED.get() as usize;
                let header_off = used.saturating_sub(1 + p) as wordcode;
                let p_argc = (p + (argc as usize) + 2) as usize;
                let cur_so = ECSOFFS.get();
                let np_now = ECNPATS.with(|c| c.get());
                ECBUF.with_borrow_mut(|b| {
                    if p_argc + 3 < b.len() {
                        b[p_argc] = (so - oecssub) as wordcode;
                        b[p_argc + 1] = (cur_so - so) as wordcode;
                        b[p_argc + 2] = np_now as wordcode;
                        b[p_argc + 3] = 0;
                    }
                    if p < b.len() {
                        b[p] = WCB_FUNCDEF(header_off);
                    }
                });
                ECNPATS.with(|c| c.set(onp));
                ECSSUB.set(oecssub);
                ECNFUNC.set(ECNFUNC.get() + 1);
                isnull = false;
                // Anonymous funcdef may have arguments — not ported
                // yet. Break out of the words loop; outer parser
                // handles whatever follows.
                break;
            }
            _ => break,
        }
    }

    // c:2173-2176 — `if (isnull && !(sr + nr)) { ecused = oecused;
    // return 0; }` — undo everything including pre-cmd assignments
    // if no actual command word emerged.
    if isnull && sr + nr == 0 && !assignments {
        ECUSED.set(p as i32);
        return 0;
    }
    // c:2186-2187 — `incmdpos = 1; intypeset = 0;` — reset before
    // the placeholder patch so the next-token lex doesn't carry
    // typeset/incond state.
    set_incmdpos(true);
    set_intypeset(false);
    // c:2189-2199 — `if (!isfunc) { if (is_typeset) ecbuf[p] =
    // WCB_TYPESET(argc); else ecbuf[p] = WCB_SIMPLE(argc); }`.
    // The WCB_TYPESET header is followed by either a postassigns
    // count at `ppost` (when assignments were emitted) or a
    // trailing 0 word.
    let header = if is_typeset {
        if postassigns > 0 {
            ECBUF.with_borrow_mut(|b| {
                if ppost < b.len() {
                    b[ppost] = postassigns;
                }
            });
        } else {
            ecadd(0);
        }
        WCB_TYPESET(argc)
    } else {
        WCB_SIMPLE(argc)
    };
    ECBUF.with_borrow_mut(|b| {
        if p < b.len() {
            b[p] = header;
        }
    });
    1 + sr
}

/// Wrapper for the par_cmd dispatch sites that don't pass `nr`
/// (matches C's call shape at parse.c:1054 `par_simple(cmplx, nr)`).
pub fn par_simple_wordcode() {
    par_simple_wordcode_impl(0);
}

/// Port of `par_redir(int *rp, char *idstring)` from
/// `Src/parse.c:2229-2345` — the wordcode-emitting variant that
/// pushes WCB_REDIR + fd + ecstrcode(name) into ECBUF. Distinct
/// from the AST `par_redir` (parse.rs:3771) which builds a
/// ZshRedir struct for the AST executor pipeline.
///
/// Returns the number of wordcodes added (3 for the basic shape,
/// 4 with idstring, 5 for HEREDOC[DASH] which carries the
/// terminator strings inline). Returns 0 on parse error.
fn par_redir_wordcode(rp: &mut usize) -> i32 {
    let cur = tok();
    let rtype: i32 = match cur {
        OUTANG_TOK => REDIR_WRITE,
        OUTANGBANG => REDIR_WRITENOW,
        DOUTANG => REDIR_APP,
        DOUTANGBANG => REDIR_APPNOW,
        INANG_TOK => REDIR_READ,
        INOUTANG => REDIR_READWRITE,
        DINANG => REDIR_HEREDOC,
        DINANGDASH => REDIR_HEREDOCDASH,
        TRINANG => REDIR_HERESTR,
        INANGAMP => REDIR_MERGEIN,
        OUTANGAMP => REDIR_MERGEOUT,
        AMPOUTANG => REDIR_ERRWRITE,
        OUTANGAMPBANG => REDIR_ERRWRITENOW,
        DOUTANGAMP => REDIR_ERRAPP,
        DOUTANGAMPBANG => REDIR_ERRAPPNOW,
        _ => return 0,
    };
    let fd1 = if tokfd() >= 0 {
        tokfd()
    } else if matches!(
        rtype,
        REDIR_READ
            | REDIR_READWRITE
            | REDIR_MERGEIN
            | REDIR_HEREDOC
            | REDIR_HEREDOCDASH
            | REDIR_HERESTR
    ) {
        0
    } else {
        1
    };
    // c:2234-2245 — save+force incmdpos=0 / nocorrect=1 (when not
    // INANG/INOUTANG) around the zshlex that consumes the target
    // word.
    let oldcmdpos = incmdpos();
    set_incmdpos(false);
    let oldnc = nocorrect();
    if cur != INANG_TOK && cur != INOUTANG {
        set_nocorrect(1);
    }
    zshlex();
    if tok() != STRING_LEX && tok() != ENVSTRING {
        set_incmdpos(oldcmdpos);
        set_nocorrect(oldnc);
        error("expected word after redirection");
        return 0;
    }
    let name = tokstr().unwrap_or_default();
    set_incmdpos(oldcmdpos);
    set_nocorrect(oldnc);

    // c:2249-2300 — HEREDOC / HEREDOCDASH carry extra words (here
    // string + terminator + munged terminator). The C source
    // emits 5 words and registers a struct heredocs entry that
    // setheredoc patches later. Stub for now: emit the basic
    // 3-word shape so wordcode parity at least sees WC_REDIR.
    // TODO: full heredoc registration + 5-word emission.
    let _ = (REDIR_FROM_HEREDOC_MASK, REDIR_VARID_MASK);

    // c:2302-2321 — proc-subst rewriting: detect `>(`/`<(` in the
    // target word's first 2 chars and rewrite REDIR_WRITE/READ to
    // REDIR_OUTPIPE/INPIPE. The detection compares the FIRST char
    // of the unmetafied tokstr against the marker bytes.
    let mut rtype = rtype;
    let nbytes: Vec<char> = name.chars().collect();
    let two = |i: usize| -> Option<(char, char)> {
        if i + 1 < nbytes.len() {
            Some((nbytes[i], nbytes[i + 1]))
        } else {
            None
        }
    };
    if let Some((c0, c1)) = two(0) {
        match rtype {
            x if x == REDIR_WRITE || x == REDIR_WRITENOW => {
                if c0 == '\u{96}' /* OutangProc */ && c1 == '\u{88}' /* Inpar */ {
                    rtype = REDIR_OUTPIPE;
                } else if c0 == '\u{94}' /* Inang */ && c1 == '\u{88}' {
                    error("invalid redirection: < before >");
                    return 0;
                }
            }
            x if x == REDIR_READ => {
                if c0 == '\u{94}' && c1 == '\u{88}' {
                    rtype = REDIR_INPIPE;
                } else if c0 == '\u{96}' && c1 == '\u{88}' {
                    error("invalid redirection: > before <");
                    return 0;
                }
            }
            x if x == REDIR_READWRITE => {
                if c0 == '\u{94}' && c1 == '\u{88}' {
                    rtype = REDIR_INPIPE;
                } else if c0 == '\u{96}' && c1 == '\u{88}' {
                    rtype = REDIR_OUTPIPE;
                }
            }
            _ => {}
        }
    }
    zshlex();

    // c:2326-2333 — emit WCB_REDIR + fd + ecstrcode(name) at the
    // CALLER's `r` cursor (NOT at ecused). ecispace shifts later
    // words DOWN to make space; the caller bumps its `p` (SIMPLE
    // placeholder offset) to compensate. 3-word basic shape;
    // idstring (`{var}>file`) form not yet wired here.
    let ncodes: usize = 3;
    let r = *rp;
    ecispace(r, ncodes);
    let coded = ecstrcode(&name);
    ECBUF.with_borrow_mut(|b| {
        if r + 2 < b.len() {
            b[r] = WCB_REDIR(rtype as wordcode);
            b[r + 1] = fd1 as wordcode;
            b[r + 2] = coded;
        }
    });
    *rp += ncodes; // c:2280 `*rp = r + ncodes;`
    ncodes as i32
}

/// Parse a program (list of lists)
/// Parse a complete program (top-level entry). Calls
/// parse_program_until with no end-token sentinel. Direct port of
/// zsh/Src/parse.c:614-720 `parse_event` / `par_list` /
/// `par_event` flow. C distinguishes COND_EVENT (single command
/// for here-string) from full event parse; zshrs's parse_program
/// is the full-event entry.
fn parse_program() -> ZshProgram {
    parse_program_until(None)
}

/// Parse a program until we hit an end token
/// Parse a program until one of `end_tokens` is seen (or EOF).
/// Drives par_list in a loop. C equivalent: the body of par_event
/// (parse.c:635-695) iterating par_list against the lexer.
fn parse_program_until(end_tokens: Option<&[lextok]>) -> ZshProgram {
    let mut lists = Vec::new();

    loop {
        if check_limit() {
            error("parser exceeded global iteration limit");
            break;
        }

        // Skip separators
        while tok() == SEPER || tok() == NEWLIN {
            if check_limit() {
                error("parser exceeded global iteration limit");
                return ZshProgram { lists };
            }
            zshlex();
        }

        if tok() == ENDINPUT || tok() == LEXERR {
            break;
        }

        // Check for end tokens
        if let Some(end_toks) = end_tokens {
            if end_toks.contains(&tok()) {
                break;
            }
        }

        // Also stop at these tokens when not explicitly looking for them
        // Note: Else/Elif/Then are NOT here - they're handled by par_if
        // to allow nested if statements inside case arms, loops, etc.
        match tok() {
            OUTBRACE_TOK | DSEMI | SEMIAMP | SEMIBAR | DONE | FI | ESAC | ZEND => break,
            _ => {}
        }

        match par_list() {
            Some(list) => {
                let detected = simple_name_with_inoutpar(&list);
                lists.push(list);
                // Synthesize a FuncDef for the `name() { body }` shape
                // at parse time so body_source is captured while the
                // lexer still has the input. The lexer port emits
                // `name(` as a single Word ending in `<Inpar><Outpar>`,
                // so the Simple list is followed by an Inbrace once
                // separators are skipped. For `name() cmd args` the
                // body has already been swallowed into the same
                // Simple's words tail — synthesize directly from there.
                if let Some((names, body_argv)) = detected {
                    if !body_argv.is_empty() {
                        // One-line body already in the Simple. Build
                        // a Simple from body_argv as the function body.
                        lists.pop();
                        let body_simple = ZshCommand::Simple(ZshSimple {
                            assigns: Vec::new(),
                            words: body_argv,
                            redirs: Vec::new(),
                        });
                        let body_list = ZshList {
                            sublist: ZshSublist {
                                pipe: ZshPipe {
                                    cmd: body_simple,
                                    next: None,
                                    lineno: lineno(),
                                    merge_stderr: false,
                                },
                                next: None,
                                flags: SublistFlags::default(),
                            },
                            flags: ListFlags::default(),
                        };
                        let funcdef = ZshCommand::FuncDef(ZshFuncDef {
                            names,
                            body: Box::new(ZshProgram {
                                lists: vec![body_list],
                            }),
                            tracing: false,
                            auto_call_args: None,
                            body_source: None,
                        });
                        let synthetic = ZshList {
                            sublist: ZshSublist {
                                pipe: ZshPipe {
                                    cmd: funcdef,
                                    next: None,
                                    lineno: lineno(),
                                    merge_stderr: false,
                                },
                                next: None,
                                flags: SublistFlags::default(),
                            },
                            flags: ListFlags::default(),
                        };
                        lists.push(synthetic);
                        continue;
                    }
                    // Else: words.len() == 1 (only the trailing `name()`
                    // word), brace body follows. `names` may carry
                    // multiple identifiers from the `fna fnb fnc()`
                    // shorthand — all share the same brace body per
                    // src/zsh/Src/parse.c:1666 par_funcdef wordlist.
                    // Skip separators on the real lexer; safe because
                    // parse_program's next iteration would also skip them.
                    while tok() == SEPER || tok() == NEWLIN {
                        zshlex();
                    }
                    if tok() == INBRACE_TOK {
                        // Capture body_start BEFORE the lexer
                        // advances past the first body token. The
                        // outer zshlex() consumed `{`; lexer.pos
                        // is now right after `{`. The next
                        // `zshlex()` would advance past `echo`,
                        // making body_start land mid-body and
                        // lose the first word — `typeset -f f`
                        // printed `a; echo b` instead of
                        // `echo a; echo b` for `f() { echo a;
                        // echo b }`.
                        let body_start = pos();
                        zshlex();
                        let body = parse_program();
                        let body_end = if tok() == OUTBRACE_TOK {
                            pos().saturating_sub(1)
                        } else {
                            pos()
                        };
                        let body_source = input_slice(body_start, body_end)
                            .map(|s| s.trim().to_string())
                            .filter(|s| !s.is_empty());
                        if tok() == OUTBRACE_TOK {
                            zshlex();
                        }
                        // Replace the Simple list with a FuncDef list.
                        lists.pop();
                        let funcdef = ZshCommand::FuncDef(ZshFuncDef {
                            names,
                            body: Box::new(body),
                            tracing: false,
                            auto_call_args: None,
                            body_source,
                        });
                        let synthetic = ZshList {
                            sublist: ZshSublist {
                                pipe: ZshPipe {
                                    cmd: funcdef,
                                    next: None,
                                    lineno: lineno(),
                                    merge_stderr: false,
                                },
                                next: None,
                                flags: SublistFlags::default(),
                            },
                            flags: ListFlags::default(),
                        };
                        lists.push(synthetic);
                    } else if !matches!(tok(), ENDINPUT | OUTBRACE_TOK | SEPER | NEWLIN) {
                        // No-brace one-line body: `foo() echo hello`.
                        // Parse a single command for the body.
                        let body_cmd = par_cmd();
                        if let Some(cmd) = body_cmd {
                            let body_list = ZshList {
                                sublist: ZshSublist {
                                    pipe: ZshPipe {
                                        cmd,
                                        next: None,
                                        lineno: lineno(),
                                        merge_stderr: false,
                                    },
                                    next: None,
                                    flags: SublistFlags::default(),
                                },
                                flags: ListFlags::default(),
                            };
                            lists.pop();
                            let funcdef = ZshCommand::FuncDef(ZshFuncDef {
                                names: names.clone(),
                                body: Box::new(ZshProgram {
                                    lists: vec![body_list],
                                }),
                                tracing: false,
                                auto_call_args: None,
                                body_source: None,
                            });
                            let synthetic = ZshList {
                                sublist: ZshSublist {
                                    pipe: ZshPipe {
                                        cmd: funcdef,
                                        next: None,
                                        lineno: lineno(),
                                        merge_stderr: false,
                                    },
                                    next: None,
                                    flags: SublistFlags::default(),
                                },
                                flags: ListFlags::default(),
                            };
                            lists.push(synthetic);
                        }
                    }
                }
            }
            None => break,
        }
    }

    ZshProgram { lists }
}

/// Parse a list (sublist with optional & or ;).
///
/// Direct port of zsh/Src/parse.c:771-804 `par_list` (and the
/// par_list1 wrapper at parse.c:807-817).
///
/// **Structural divergence**: zsh's parse.c emits flat wordcode
/// into the `ecbuf` u32 array via `ecadd(0)` (placeholder),
/// `set_list_code(p, code, complexity)`, `wc_bdata(Z_END)`. zshrs
/// builds an AST node `ZshList { sublist, flags }` instead. The
/// async/sync/disown discrimination at parse.c:785-790 maps to
/// zshrs's `ListFlags { async_, disown }` field — Z_SYNC is the
/// default (no flags), Z_ASYNC = `&` = `async_=true`, Z_DISOWN +
/// Z_ASYNC = `&!`/`&|` = both true. Same semantics, different
/// representation. This divergence is repository-wide: every
/// `par_*` function emits wordcode in C, every `parse_*` builds
/// AST in Rust. The compile_zsh module then traverses the AST to
/// emit fusevm bytecode, which serves the same role as zsh's
/// wordcode but with a different opcode set and execution model.
fn par_list() -> Option<ZshList> {
    let sublist = par_sublist()?;

    let flags = match tok() {
        AMPER => {
            zshlex();
            ListFlags {
                async_: true,
                disown: false,
            }
        }
        AMPERBANG => {
            zshlex();
            ListFlags {
                async_: true,
                disown: true,
            }
        }
        SEPER | SEMI | NEWLIN => {
            zshlex();
            ListFlags::default()
        }
        _ => ListFlags::default(),
    };

    Some(ZshList { sublist, flags })
}

/// Parse a sublist (pipelines connected by && or ||).
///
/// Direct port of zsh/Src/parse.c:825 `par_sublist` and
/// par_sublist2 at parse.c:869-892. par_sublist handles the
/// && / || conjunction and emits WC_SUBLIST opcodes; par_sublist2
/// handles the leading `!` negation and `coproc` keyword.
///
/// AST mapping: ZshSublist { pipe, conj_chain }, where `conj_chain`
/// is a Vec<(ConjOp, ZshSublist)> for chained && / ||. C uses
/// flat wordcode with WC_SUBLIST_AND / WC_SUBLIST_OR markers.
fn par_sublist() -> Option<ZshSublist> {
    PARSER_RECURSION_DEPTH.set(PARSER_RECURSION_DEPTH.get() + 1);
    if check_recursion() {
        error("par_sublist: max recursion depth exceeded");
        PARSER_RECURSION_DEPTH.set(PARSER_RECURSION_DEPTH.get().saturating_sub(1));
        return None;
    }

    let mut flags = SublistFlags::default();

    // Handle coproc and !
    if tok() == COPROC {
        flags.coproc = true;
        zshlex();
    } else if tok() == BANG_TOK {
        flags.not = true;
        zshlex();
    }

    let pipe = match par_pline() {
        Some(p) => p,
        None => {
            PARSER_RECURSION_DEPTH.set(PARSER_RECURSION_DEPTH.get().saturating_sub(1));
            return None;
        }
    };

    // Check for && or ||
    let next = match tok() {
        DAMPER => {
            zshlex();
            skip_separators();
            par_sublist().map(|s| (SublistOp::And, Box::new(s)))
        }
        DBAR => {
            zshlex();
            skip_separators();
            par_sublist().map(|s| (SublistOp::Or, Box::new(s)))
        }
        _ => None,
    };

    PARSER_RECURSION_DEPTH.set(PARSER_RECURSION_DEPTH.get().saturating_sub(1));
    Some(ZshSublist { pipe, next, flags })
}

/// Parse a pipeline
/// Parse a pipeline (cmds joined by `|` / `|&`). Direct port of
/// zsh/Src/parse.c:894 `par_pline`. AST: ZshPipe { cmds: Vec<ZshCommand> }.
/// C emits WC_PIPE wordcodes per command; same flow.
fn par_pline() -> Option<ZshPipe> {
    PARSER_RECURSION_DEPTH.set(PARSER_RECURSION_DEPTH.get() + 1);
    if check_recursion() {
        error("par_pline: max recursion depth exceeded");
        PARSER_RECURSION_DEPTH.set(PARSER_RECURSION_DEPTH.get().saturating_sub(1));
        return None;
    }

    let lineno = toklineno();
    let cmd = match par_cmd() {
        Some(c) => c,
        None => {
            PARSER_RECURSION_DEPTH.set(PARSER_RECURSION_DEPTH.get().saturating_sub(1));
            return None;
        }
    };

    // Check for | or |&
    let mut merge_stderr = false;
    let next = match tok() {
        BAR_TOK | BARAMP => {
            merge_stderr = tok() == BARAMP;
            zshlex();
            skip_separators();
            par_pline().map(Box::new)
        }
        _ => None,
    };

    PARSER_RECURSION_DEPTH.set(PARSER_RECURSION_DEPTH.get().saturating_sub(1));
    Some(ZshPipe {
        cmd,
        next,
        lineno,
        merge_stderr,
    })
}

/// Parse a command
/// Parse a command — dispatches by leading token (FOR / CASE /
/// IF / WHILE / UNTIL / REPEAT / FUNC / DINBRACK / DINPAR /
/// Inpar subshell / Inbrace current-shell / TIME / NOCORRECT,
/// else simple). Direct port of zsh/Src/parse.c:958 `par_cmd`.
fn par_cmd() -> Option<ZshCommand> {
    // Parse leading redirections
    let mut redirs = Vec::new();
    while IS_REDIROP(tok()) {
        if let Some(redir) = par_redir() {
            redirs.push(redir);
        }
    }

    let cmd = match tok() {
        FOR | FOREACH => par_for(),
        SELECT => parse_select(),
        CASE => par_case(),
        IF => par_if(),
        WHILE => par_while(false),
        UNTIL => par_while(true),
        REPEAT => par_repeat(),
        INPAR_TOK => par_subsh(),
        INOUTPAR => parse_anon_funcdef(),
        INBRACE_TOK => parse_cursh(),
        FUNC => par_funcdef(),
        DINBRACK => par_cond(),
        DINPAR => parse_arith(),
        TIME => par_time(),
        _ => par_simple(redirs),
    };

    // Parse trailing redirections. For Simple commands the redirs were
    // already captured inside par_simple; for compound forms (Cursh,
    // Subsh, If, While, etc.) we collect them here and wrap in
    // ZshCommand::Redirected so compile_zsh can scope-bracket them.
    if let Some(inner) = cmd {
        let mut trailing: Vec<ZshRedir> = Vec::new();
        while IS_REDIROP(tok()) {
            if let Some(redir) = par_redir() {
                trailing.push(redir);
            }
        }
        // c:1072-1075 — every par_cmd tail resets the lexer state
        // toggles so the NEXT command starts in cmd position with
        // case/cond/typeset off. par_simple/par_cond set `incmdpos=0`
        // during their bodies; without this reset the next iteration
        // of the outer par_list loop sees `if` / `done` / `select`
        // etc. as plain strings and the AST collapses.
        set_incmdpos(true);
        set_incasepat(0);
        set_incond(0);
        set_intypeset(false);
        if trailing.is_empty() {
            return Some(inner);
        }
        // Simple already absorbed its own redirs (compile path expects
        // them on ZshSimple), so don't double-wrap.
        if matches!(inner, ZshCommand::Simple(_)) {
            if let ZshCommand::Simple(mut s) = inner {
                s.redirs.extend(trailing);
                return Some(ZshCommand::Simple(s));
            }
            unreachable!()
        }
        return Some(ZshCommand::Redirected(Box::new(inner), trailing));
    }
    // Same reset on the empty-cmd branch (mirror c:1072 unconditional
    // path — the C function only returns 0 above when the dispatch
    // produced no command, and falls through to the reset block).
    set_incmdpos(true);
    set_incasepat(0);
    set_incond(0);
    set_intypeset(false);

    None
}

/// Parse a simple command
/// Parse a simple command (assignments + words + redirections).
/// Direct port of zsh/Src/parse.c:1836 `par_simple` —
/// the largest single function in parse.c. Handles ENVSTRING/
/// ENVARRAY assignments at command head, intermixed redirs,
/// typeset-style multi-assignment commands, and the trailing
/// inout-par `()` that converts a simple command into an inline
/// function definition.
fn par_simple(mut redirs: Vec<ZshRedir>) -> Option<ZshCommand> {
    let mut assigns = Vec::new();
    let mut words = Vec::new();
    const MAX_ITERATIONS: usize = 10_000;
    let mut iterations = 0;

    // c:1934 — `if (!isset(IGNOREBRACES) && *tokstr == Inbrace) { ... }`
    // gates the `{var}>file` brace-FD recognition (a non-POSIX zsh
    // extension that lets `{varname}>file` redirect into the named
    // shell variable). zshrs's parser doesn't recognise the brace-FD
    // shape yet, so the gate is wired here as a marker — when the
    // {var}-FD feature lands, swap this `false` for the actual
    // `tokstr starts with Inbrace` test and route into a {var}>file
    // redir builder.
    let saw_brace_fd_candidate = false;
    if !isset(IGNOREBRACES) && saw_brace_fd_candidate {
        // TODO: {var}>file FD recognition (par_simple body at c:1934-2000).
    }

    // Parse leading assignments
    while tok() == ENVSTRING || tok() == ENVARRAY {
        iterations += 1;
        if iterations > MAX_ITERATIONS {
            error("par_simple: exceeded max iterations in assignments");
            return None;
        }
        if let Some(assign) = parse_assign() {
            assigns.push(assign);
        }
        zshlex();
    }

    // Parse words and redirections
    loop {
        iterations += 1;
        if iterations > MAX_ITERATIONS {
            error("par_simple: exceeded max iterations");
            return None;
        }
        match tok() {
            ENVSTRING | ENVARRAY => {
                // Mid-command assignment-shape arg under typeset
                // / declare / local / etc. (intypeset gates the
                // lexer to emit Envstring/Envarray for `name=val`
                // and `name=()` past the command name). Parse the
                // assignment, then emit a synthetic word
                // `NAME=value` (scalar) or `NAME=( … )` (array)
                // string so typeset's builtin arg list sees the
                // assignment-shape arg. Avoids the inline-env
                // scope path that mistakenly treats it like a
                // pre-cmd `X=Y cmd` assignment.
                if let Some(assign) = parse_assign() {
                    let synthetic = match &assign.value {
                        ZshAssignValue::Scalar(v) => format!("{}={}", assign.name, v),
                        ZshAssignValue::Array(elems) => {
                            format!("{}=({})", assign.name, elems.join(" "))
                        }
                    };
                    words.push(synthetic);
                }
                zshlex();
            }
            STRING_LEX | TYPESET => {
                let s = tokstr();
                if let Some(s) = s {
                    words.push(s);
                }
                // c:1929 — `incmdpos = 0;` so the next zshlex() does
                // not re-promote `{`/`[[`/reserved words at the
                // continuation position. Without this, `echo {a,b}`
                // re-lexes `{` as INBRACE_TOK (current-shell block)
                // and the brace expansion never reaches par_simple.
                set_incmdpos(false);
                // c:1931-1932 — `if (tok == TYPESET) intypeset = is_typeset = 1;`
                // Multi-assign `typeset a=1 b=2` relies on the lexer
                // re-emitting `b=2` as ENVSTRING; that path is gated
                // on `intypeset`. Without this, follow-on assignment
                // words arrive as STRING and the typeset builtin's
                // multi-assign form silently degrades.
                if tok() == TYPESET {
                    set_intypeset(true);
                }
                zshlex();
                // Check for function definition foo() { ... }
                if words.len() == 1 && peek_inoutpar() {
                    return parse_inline_funcdef(words.pop().unwrap());
                }
                // `{name}>file` named-fd redirect: the lexer doesn't
                // recognize this shape, so the bare word `{name}`
                // arrives as a String. If it matches `{IDENT}` and
                // the NEXT token is a redirop, pop it off as the
                // varid for that redir.
                if !words.is_empty() && IS_REDIROP(tok()) {
                    let last = words.last().unwrap();
                    let untoked = super::lex::untokenize(last);
                    if untoked.starts_with('{') && untoked.ends_with('}') && untoked.len() > 2 {
                        let name = &untoked[1..untoked.len() - 1];
                        if !name.is_empty()
                            && name.chars().all(|c| c == '_' || c.is_ascii_alphanumeric())
                            && name
                                .chars()
                                .next()
                                .map(|c| c == '_' || c.is_ascii_alphabetic())
                                .unwrap_or(false)
                        {
                            let varid = name.to_string();
                            words.pop();
                            if let Some(mut redir) = par_redir() {
                                redir.varid = Some(varid);
                                redirs.push(redir);
                            }
                            continue;
                        }
                    }
                }
            }
            _ if IS_REDIROP(tok()) => {
                match par_redir() {
                    Some(redir) => redirs.push(redir),
                    None => break, // Error in redir parsing, stop
                }
            }
            INOUTPAR if !words.is_empty() => {
                // c:2055-2057 — `if (!isset(MULTIFUNCDEF) && argc > 1)
                // YYERROR(oecused);` — multi-name funcdef gate:
                // `f1 f2() { ... }` defines f1 AND f2 to the same
                // body, but only when MULTIFUNCDEF is set.
                if !isset(MULTIFUNCDEF) && words.len() > 1 {
                    error(
                        "parse error: multiple names in function definition without MULTIFUNCDEF",
                    );
                    return None;
                }
                // c:2061-2068 — `if (isset(EXECOPT) && hasalias &&
                // !isset(ALIASFUNCDEF) && argc && hasalias !=
                // input_hasalias()) { zwarn(...); YYERROR(...); }`
                // Alias-as-funcdef warning. zshrs's parser doesn't
                // track `hasalias` (alias-expansion provenance
                // during parse) yet, so `had_alias` stays false —
                // the gate is wired here as a marker so the canonical
                // C predicate is visible. Once alias-provenance lands,
                // swap `false` for the actual provenance compare.
                let had_alias = false;
                if isset(EXECOPT) && had_alias && !isset(ALIASFUNCDEF) && !words.is_empty() {
                    crate::ported::utils::zwarn("defining function based on alias `(unknown)'");
                    return None;
                }
                // foo() { ... } style function
                return parse_inline_funcdef(words.pop().unwrap());
            }
            _ => break,
        }
    }

    if assigns.is_empty() && words.is_empty() && redirs.is_empty() {
        return None;
    }

    Some(ZshCommand::Simple(ZshSimple {
        assigns,
        words,
        redirs,
    }))
}

/// Parse an assignment
/// Parse an assignment word `NAME=value` or `NAME=(arr items)`.
/// Sub-routine of par_simple. The C source handles assignments
/// inline in par_simple via the ENVSTRING/ENVARRAY token paths
/// (parse.c:1842-2000ish); zshrs splits it out to a dedicated
/// helper for clarity.
fn parse_assign() -> Option<ZshAssign> {
    // Helper: locate the Equals-marker that delimits NAME from
    // VALUE in an assignment-shaped tokstr. The lexer META-encodes
    // EVERY `=` (including those inside `${var%%=foo}` strip
    // patterns or `[idx]=...` subscripts), so a naive
    // `tokstr.find(Equals)` would split at the first inner `=`
    // and break the whole assignment. Walk the string skipping
    // brace and bracket depth so the assignment's `=` (the one
    // after the last `]` of the LHS subscript / or after the
    // bare name) is the one we land on.
    fn find_assign_equals(s: &str) -> Option<usize> {
        let target = crate::ported::zsh_h::Equals;
        let mut brace = 0i32;
        let mut bracket = 0i32;
        let mut paren = 0i32;
        for (i, c) in s.char_indices() {
            match c {
                    '{' | '\u{8f}' /* Inbrace */ => brace += 1,
                    '}' | '\u{90}' /* Outbrace */ => {
                        if brace > 0 {
                            brace -= 1;
                        }
                    }
                    '[' | '\u{91}' /* Inbrack */ => bracket += 1,
                    ']' | '\u{92}' /* Outbrack */ => {
                        if bracket > 0 {
                            bracket -= 1;
                        }
                    }
                    '(' | '\u{88}' /* Inpar */ => paren += 1,
                    ')' | '\u{8a}' /* Outpar */ => {
                        if paren > 0 {
                            paren -= 1;
                        }
                    }
                    _ if c == target && brace == 0 && bracket == 0 && paren == 0 => {
                        return Some(i);
                    }
                    _ => {}
                }
        }
        None
    }

    let _ts_tokstr = tokstr()?;
    let tokstr = _ts_tokstr.as_str();

    // Parse name=value or name+=value.
    let (name, value_str, append) = if tok() == ENVARRAY {
        let (name, append) = if let Some(stripped) = tokstr.strip_suffix('+') {
            (stripped, true)
        } else {
            (tokstr, false)
        };
        (name.to_string(), String::new(), append)
    } else if let Some(pos) = find_assign_equals(tokstr) {
        let name_part = &tokstr[..pos];
        let (name, append) = if let Some(stripped) = name_part.strip_suffix('+') {
            (stripped, true)
        } else {
            (name_part, false)
        };
        (
            name.to_string(),
            tokstr[pos + Equals.len_utf8()..].to_string(),
            append,
        )
    } else if let Some(pos) = tokstr.find('=') {
        // Fallback to literal '=' for compatibility
        let name_part = &tokstr[..pos];
        let (name, append) = if let Some(stripped) = name_part.strip_suffix('+') {
            (stripped, true)
        } else {
            (name_part, false)
        };
        (name.to_string(), tokstr[pos + 1..].to_string(), append)
    } else {
        return None;
    };

    let value = if tok() == ENVARRAY {
        // Array assignment: name=(...)
        let mut elements = Vec::new();
        zshlex(); // skip past token

        let mut arr_iters = 0;
        const MAX_ARRAY_ELEMENTS: usize = 10_000;
        while matches!(tok(), STRING_LEX | SEPER | NEWLIN) {
            arr_iters += 1;
            if arr_iters > MAX_ARRAY_ELEMENTS {
                error("array assignment exceeded maximum elements");
                break;
            }
            if tok() == STRING_LEX {
                let _ts_s = crate::ported::lex::tokstr();
                if let Some(s) = _ts_s.as_deref() {
                    elements.push(s.to_string());
                }
            }
            zshlex();
        }

        // The closing Outpar is consumed here. The outer par_simple
        // loop will then `zshlex()` past whatever follows (typically
        // a separator or the next word) — calling zshlex twice in
        // tandem (here AND in par_simple) over-advances and merges
        // a following `name() { … }` funcdef into the same Simple.
        // We only consume Outpar; let the caller handle the rest.
        // Without this guard `g=(o1); f() { :; }` parsed as one
        // Simple with assigns=[g] and words=["f()"] (one token).
        if tok() == OUTPAR_TOK {
            // Note: do NOT zshlex() here. par_simple's `lexer
            // .zshlex()` after `parse_assign` returns advances past
            // the Outpar onto the next significant token.
            //
            // Force `incmdpos=true` so the next zshlex() recognizes
            // a follow-up `b=(...)` / `b=val` as Envarray/Envstring.
            // The lexer flips incmdpos to false on bare Outpar (which
            // is correct for subshell-close context), but for an
            // array-assignment close more assigns/words may follow.
            set_incmdpos(true);
        }

        ZshAssignValue::Array(elements)
    } else {
        ZshAssignValue::Scalar(value_str)
    };

    Some(ZshAssign {
        name,
        value,
        append,
    })
}

/// Parse a redirection
/// Parse a redirection (>file, <file, >>file, <<HEREDOC, etc.).
/// Direct port of zsh/Src/parse.c:2229 `par_redir`. Returns
/// a ZshRedir node carrying the operator type, fd, target word
/// (or here-doc body / pipe-redir command), and any `{var}` style
/// fd-binding parameter.
fn par_redir() -> Option<ZshRedir> {
    let rtype = match tok() {
        OUTANG_TOK => REDIR_WRITE,
        OUTANGBANG => REDIR_WRITENOW,
        DOUTANG => REDIR_APP,
        DOUTANGBANG => REDIR_APPNOW,
        INANG_TOK => REDIR_READ,
        INOUTANG => REDIR_READWRITE,
        DINANG => REDIR_HEREDOC,
        DINANGDASH => REDIR_HEREDOCDASH,
        TRINANG => REDIR_HERESTR,
        INANGAMP => REDIR_MERGEIN,
        OUTANGAMP => REDIR_MERGEOUT,
        AMPOUTANG => REDIR_ERRWRITE,
        OUTANGAMPBANG => REDIR_ERRWRITENOW,
        DOUTANGAMP => REDIR_ERRAPP,
        DOUTANGAMPBANG => REDIR_ERRAPPNOW,
        _ => return None,
    };

    let fd = if tokfd() >= 0 {
        tokfd()
    } else if matches!(
        rtype,
        REDIR_READ
            | REDIR_READWRITE
            | REDIR_MERGEIN
            | REDIR_HEREDOC
            | REDIR_HEREDOCDASH
            | REDIR_HERESTR
    ) {
        0
    } else {
        1
    };

    // c:2234-2245 — save/restore incmdpos and nocorrect around the
    // zshlex that consumes the redir target word:
    //   oldcmdpos = incmdpos; incmdpos = 0;
    //   oldnc = nocorrect;
    //   if (tok != INANG && tok != INOUTANG) nocorrect = 1;
    //   ... zshlex; check tok; ...
    //   incmdpos = oldcmdpos; nocorrect = oldnc;
    // Without this, a redir target lexes in the parent's incmdpos
    // (re-promoting `{` / reswords) AND with parent nocorrect (so
    // spelling-correction wrongly runs inside `> $(cmd)` etc.).
    let oldcmdpos = incmdpos();
    set_incmdpos(false);
    let oldnc = nocorrect();
    let cur = tok();
    if cur != INANG_TOK && cur != INOUTANG {
        set_nocorrect(1);
    }
    zshlex();

    let name = match tok() {
        STRING_LEX | ENVSTRING => {
            let n = tokstr().unwrap_or_default();
            // Restore BEFORE the next zshlex so trailing tokens lex
            // in the original parent context (mirrors C ordering at
            // parse.c:2244-2245 — restore right after the word is
            // confirmed, before any downstream advance).
            set_incmdpos(oldcmdpos);
            set_nocorrect(oldnc);
            zshlex();
            n
        }
        _ => {
            set_incmdpos(oldcmdpos);
            set_nocorrect(oldnc);
            error("expected word after redirection");
            return None;
        }
    };

    // Heredoc terminator capture. C parse.c:2254-2317 par_redir builds
    // a `struct heredocs` entry here for REDIR_HEREDOC[DASH]; zshrs
    // pushes a HereDoc onto heredocs[] for process_heredocs (called
    // by zshlex on the next NEWLIN) to fill in. Quoted terminators
    // (`<<'EOF'` / `<<"EOF"` / `<<\EOF`) disable expansion in the
    // body — Snull `\u{9d}` marks single-quote, Dnull `\u{9e}` marks
    // double-quote, Bnull `\u{9f}` marks any backslash-escaped char.
    let heredoc_idx = if matches!(rtype, REDIR_HEREDOC | REDIR_HEREDOCDASH) {
        let strip_tabs = rtype == REDIR_HEREDOCDASH;
        let quoted = name.contains('\u{9d}')
            || name.contains('\u{9e}')
            || name.contains('\u{9f}')
            || name.starts_with('\'')
            || name.starts_with('"');
        let term = name
            .chars()
            .filter(|c| {
                *c != '\'' && *c != '"' && *c != '\u{9d}' && *c != '\u{9e}' && *c != '\u{9f}'
            })
            .collect::<String>();
        crate::ported::lex::heredocs_push(crate::ported::lex::HereDoc {
            terminator: term,
            strip_tabs,
            content: String::new(),
            quoted,
            processed: false,
        });
        Some(heredocs_len() - 1)
    } else {
        None
    };

    Some(ZshRedir {
        rtype,
        fd,
        name,
        heredoc: None,
        varid: None,
        heredoc_idx,
    })
}

/// Parse for/foreach loop
/// Parse `for NAME in WORDS; do BODY; done` (foreach style) AND
/// `for ((init; cond; incr)) do BODY done` (c-style). Direct port
/// of zsh/Src/parse.c:1087 `par_for`. parse_for_cstyle is the
/// inner branch for the `((...))` arithmetic-header variant
/// (parse.c:1100-1140 inside par_for).
fn par_for() -> Option<ZshCommand> {
    let is_foreach = tok() == FOREACH;
    zshlex();

    // Check for C-style: for (( init; cond; step ))
    if tok() == DINPAR {
        return parse_for_cstyle();
    }

    // Get variable name(s). zsh parse.c par_for accepts multiple
    // identifier tokens before `in`/`(`/newline — `for k v in ...`
    // assigns each iteration's pair of values to k and v in turn.
    // We store the names space-joined since variable identifiers
    // can't contain whitespace.
    let mut names: Vec<String> = Vec::new();
    while tok() == STRING_LEX {
        let v = tokstr().unwrap_or_default();
        if v == "in" {
            break;
        }
        names.push(v);
        zshlex();
    }
    if names.is_empty() {
        error("expected variable name in for");
        return None;
    }
    let var = names.join(" ");

    // Skip newlines
    skip_separators();

    // Get list. The lexer-port quirk: `for x (a b c)` arrives as a
    // single String token with the parens lexed-as-content
    // (`<Inpar>a b c<Outpar>`) instead of as separate Inpar/String/
    // Outpar tokens. Detect that shape and split it manually.
    let list = if tok() == STRING_LEX
        && tokstr()
            .map(|s| s.starts_with('\u{88}') && s.ends_with('\u{8a}'))
            .unwrap_or(false)
    {
        let raw = tokstr().unwrap_or_default();
        // Strip leading Inpar + trailing Outpar, then untokenize the
        // inner content and split on whitespace for the word list.
        let inner = &raw[raw.char_indices().nth(1).map(|(i, _)| i).unwrap_or(0)
            ..raw
                .char_indices()
                .last()
                .map(|(i, _)| i)
                .unwrap_or(raw.len())];
        let cleaned = super::lex::untokenize(inner);
        let words: Vec<String> = cleaned.split_whitespace().map(|s| s.to_string()).collect();
        zshlex();
        ForList::Words(words)
    } else if tok() == STRING_LEX {
        let s = tokstr();
        if s.map(|s| s == "in").unwrap_or(false) {
            zshlex();
            let mut words = Vec::new();
            let mut word_count = 0;
            while tok() == STRING_LEX {
                word_count += 1;
                if word_count > 500 || check_limit() {
                    error("for: too many words");
                    return None;
                }
                let _ts_s = tokstr();
                if let Some(s) = _ts_s.as_deref() {
                    words.push(s.to_string());
                }
                zshlex();
            }
            ForList::Words(words)
        } else {
            ForList::Positional
        }
    } else if tok() == INPAR_TOK {
        // for var (...)
        zshlex();
        let mut words = Vec::new();
        let mut word_count = 0;
        while tok() == STRING_LEX || tok() == SEPER {
            word_count += 1;
            if word_count > 500 || check_limit() {
                error("for: too many words in parens");
                return None;
            }
            if tok() == STRING_LEX {
                let _ts_s = tokstr();
                if let Some(s) = _ts_s.as_deref() {
                    words.push(s.to_string());
                }
            }
            zshlex();
        }
        if tok() == OUTPAR_TOK {
            // After the `)` of a for-list, the next token is the
            // body opener — `do`/`{`. zsh's lexer needs incmdpos
            // set so `{` lexes as Inbrace (not as a literal). C
            // analogue: parse.c::par_for sets `incmdpos = 1`
            // after consuming the Outpar before the body parse.
            set_incmdpos(true);
            zshlex();
        }
        ForList::Words(words)
    } else {
        ForList::Positional
    };

    // Skip to body
    skip_separators();

    // Parse body
    let body = parse_loop_body(is_foreach)?;

    Some(ZshCommand::For(ZshFor {
        var,
        list,
        body: Box::new(body),
        is_select: false,
    }))
}

/// Parse C-style for loop: for (( init; cond; step ))
/// Parse the c-style `for ((init; cond; incr)) do BODY done`.
/// Inner branch of zsh/Src/parse.c:1100-1140 inside par_for.
/// Recognized when the token after FOR is DINPAR (the `((`
/// detected by gettok via dbparens setup).
fn parse_for_cstyle() -> Option<ZshCommand> {
    // We're at (( (Dinpar None) - the opening ((
    // Lexer returns:
    //   Dinpar None     - opening ((
    //   Dinpar "init"   - init expression, semicolon consumed
    //   Dinpar "cond"   - cond expression, semicolon consumed
    //   Doutpar "step"  - step expression, closing )) consumed

    zshlex(); // Get init: Dinpar "i=0"

    if tok() != DINPAR {
        error("expected init expression in for ((");
        return None;
    }
    let init = tokstr().unwrap_or_default();

    zshlex(); // Get cond: Dinpar "i<10"

    if tok() != DINPAR {
        error("expected condition in for ((");
        return None;
    }
    let cond = tokstr().unwrap_or_default();

    zshlex(); // Get step: Doutpar "i++"

    if tok() != DOUTPAR {
        error("expected )) in for");
        return None;
    }
    let step = tokstr().unwrap_or_default();

    zshlex(); // Move past ))

    skip_separators();
    let body = parse_loop_body(false)?;

    Some(ZshCommand::For(ZshFor {
        var: String::new(),
        list: ForList::CStyle { init, cond, step },
        body: Box::new(body),
        is_select: false,
    }))
}

/// Parse select loop (same syntax as for)
/// Parse `select NAME in WORDS; do BODY; done`. Same shape as
/// `for NAME in WORDS; do ...` but with menu-prompt semantics in
/// the executor. C equivalent: the SELECT case in par_for at
/// parse.c:1087-1207 (selects share parser flow with foreach).
fn parse_select() -> Option<ZshCommand> {
    // `select` shares par_for's grammar (var, words, body) but the
    // compile path is different (interactive prompt loop).
    match par_for()? {
        ZshCommand::For(mut f) => {
            f.is_select = true;
            Some(ZshCommand::For(f))
        }
        other => Some(other),
    }
}

/// Parse case statement
/// Parse `case WORD in PATTERN) BODY ;; ... esac`. Direct port
/// of zsh/Src/parse.c:1209 `par_case`. Each case arm is a
/// (pattern_list, body, terminator) tuple where terminator is
/// `;;` (default), `;&` (fallthrough), or `;|` (continue testing).
fn par_case() -> Option<ZshCommand> {
    // C par_case (parse.c:1209-1241). Order of state toggles
    // matters — the lexer reads the case word in `incmdpos=0`
    // (so it's not promoted to a reswd), then the `in`/`{` in
    // `incmdpos=1, noaliases=1, nocorrect=1` (so the `in` literal
    // isn't alias-expanded or spell-corrected), then sets
    // `incasepat=1, incmdpos=0` before the first pattern.
    set_incmdpos(false);
    zshlex(); // skip 'case'

    let word = match tok() {
        STRING_LEX => {
            let w = tokstr().unwrap_or_default();
            // c:1222 — `incmdpos = 1;` before the next zshlex so the
            // `in` keyword is recognised. c:1223-1225 — save+force
            // noaliases / nocorrect.
            set_incmdpos(true);
            let ona = noaliases();
            let onc = nocorrect();
            set_noaliases(true);
            set_nocorrect(1);
            zshlex();
            // Restore noaliases/nocorrect after the `in`-or-`{` token
            // is in hand; both are unconditionally restored at c:1238-1239.
            let restore = |ona: bool, onc: i32| {
                set_noaliases(ona);
                set_nocorrect(onc);
            };
            (w, ona, onc, restore)
        }
        _ => {
            error("expected word after case");
            return None;
        }
    };
    let (word, ona, onc, restore) = word;

    skip_separators();

    // Expect 'in' or {
    let use_brace = tok() == INBRACE_TOK;
    if tok() == STRING_LEX {
        let s = tokstr();
        if s.map(|s| s != "in").unwrap_or(true) {
            // c:1228-1232 — restore noaliases/nocorrect on error path.
            restore(ona, onc);
            error("expected 'in' in case");
            return None;
        }
    } else if !use_brace {
        restore(ona, onc);
        error("expected 'in' or '{' in case");
        return None;
    }
    // c:1236-1239 — `incasepat = 1; incmdpos = 0; noaliases = ona;
    // nocorrect = onc;` — set the case-pattern context AND restore
    // alias/correct state BEFORE the zshlex that consumes `in`/`{`.
    set_incasepat(1);
    set_incmdpos(false);
    restore(ona, onc);
    zshlex();

    let mut arms = Vec::new();
    const MAX_ARMS: usize = 10_000;

    loop {
        if arms.len() > MAX_ARMS {
            error("par_case: too many arms");
            break;
        }

        // Set incasepat BEFORE skipping separators so lexer knows we're in case pattern context
        // This affects how [ and | are lexed
        set_incasepat(1);

        skip_separators();

        // Check for end
        // Note: 'esac' might be String "esac" if incasepat > 0 prevents reserved word recognition
        let is_esac = tok() == ESAC
            || (tok() == STRING_LEX && tokstr().map(|s| s == "esac").unwrap_or(false));
        if (use_brace && tok() == OUTBRACE_TOK) || (!use_brace && is_esac) {
            set_incasepat(0);
            zshlex();
            break;
        }

        // Also break on EOF
        if tok() == ENDINPUT || tok() == LEXERR {
            set_incasepat(0);
            break;
        }

        // Skip optional `(`. zsh's case grammar: `case W in (P)…)`.
        // The leading `(` is paired with a matching `)` that closes
        // the pattern itself; the arm-close `)` follows separately.
        // Track whether we consumed it so we can skip the matching
        // `)` after pattern parsing — otherwise the arm-close would
        // be interpreted as the pattern-close and the actual body
        // would get the leftover `)`.
        let had_leading_paren = tok() == INPAR_TOK;
        if had_leading_paren {
            zshlex();
        }

        // incasepat is already set above
        let mut patterns = Vec::new();
        let mut pattern_iterations = 0;
        loop {
            pattern_iterations += 1;
            if pattern_iterations > 1000 {
                error("par_case: too many pattern iterations");
                set_incasepat(0);
                return None;
            }

            if tok() == STRING_LEX {
                let s = tokstr();
                if s.map(|s| s == "esac").unwrap_or(false) {
                    break;
                }
                patterns.push(tokstr().unwrap_or_default());
                // After first pattern token, set incasepat=2 so ( is treated as part of pattern
                set_incasepat(2);
                zshlex();
            } else if tok() != BAR_TOK {
                break;
            }

            if tok() == BAR_TOK {
                // Reset to 1 (start of next alternative pattern)
                set_incasepat(1);
                zshlex();
            } else {
                break;
            }
        }
        set_incasepat(0);

        // zsh's `(P)` form (parse.c:1320-1360 hack) treats the entire
        // parenthesized contents as ONE zsh pattern with internal `|`
        // as the literal alternation operator — NOT as multiple
        // case-arm alternatives. Without a leading `(`, the bare
        // `P1|P2)` form splits into multiple alts. Mirror that here:
        // when a leading `(` was consumed, fold the |-separated
        // pieces back into a single pattern string.
        if had_leading_paren && patterns.len() > 1 {
            let joined = patterns.join("|");
            patterns = vec![joined];
        }

        // Expect ).  Also handle the `(P))` wrapped-pattern form:
        // when a leading `(` was consumed, accept an extra `)` —
        // the inner `)` closes the optional-paren wrapper, the
        // outer `)` is the arm-close. zsh accepts BOTH `(P) BODY`
        // (bare pattern, leading-paren is just the opt-marker, the
        // close is arm-close) and `(P)) BODY` (paren-wrapped
        // pattern, then arm-close). The first form is unambiguous
        // when the bare pattern was simple; the second is needed
        // when the body starts with `(`.
        if tok() != OUTPAR_TOK {
            error("expected ')' in case pattern");
            return None;
        }
        // Port of Src/parse.c:1310-1313 — when the case pattern
        // closes with `)`, set `incmdpos = 1` BEFORE consuming
        // the token so the first word of the arm body is lexed
        // in command position. Without this, `case X in X) c1=v ;;`
        // lexes `c1=v` as a plain STRING rather than an assignment
        // word, and exec treats it as a command name (yielding
        // "command not found: c1=v"). Subsequent statements after
        // `;` parse correctly because the `;` separator restores
        // command position; only the FIRST body word was broken.
        set_incmdpos(true);
        zshlex();
        if had_leading_paren && tok() == OUTPAR_TOK {
            set_incmdpos(true);
            zshlex();
        }

        // Parse body
        let body = parse_program();

        // Get terminator. Set incasepat=1 BEFORE the zshlex
        // advance so the next token (the next arm's pattern, like
        // `[a-z]`) gets tokenized in pattern context. Without
        // this, a `[`-prefixed pattern after the FIRST arm became
        // Inbrack instead of String and the pattern-loop bailed
        // out with "expected ')' in case pattern".
        let terminator = match tok() {
            DSEMI => {
                set_incasepat(1);
                zshlex();
                CaseTerm::Break
            }
            SEMIAMP => {
                set_incasepat(1);
                zshlex();
                CaseTerm::Continue
            }
            SEMIBAR => {
                set_incasepat(1);
                zshlex();
                CaseTerm::TestNext
            }
            _ => CaseTerm::Break,
        };

        if !patterns.is_empty() {
            arms.push(CaseArm {
                patterns,
                body,
                terminator,
            });
        }
    }

    Some(ZshCommand::Case(ZshCase { word, arms }))
}

/// Parse if statement
/// Parse `if COND; then BODY; [elif COND; then BODY;]* [else BODY;] fi`.
/// Direct port of zsh/Src/parse.c:1411 `par_if`. The C source
/// emits WC_IF wordcodes per arm; zshrs builds an AST chain of
/// (cond, then_body) tuples plus an optional else_body.
fn par_if() -> Option<ZshCommand> {
    zshlex(); // skip 'if'

    // Parse condition - stops at 'then' or '{' (zsh allows { instead of then)
    let cond = Box::new(parse_program_until(Some(&[THEN, INBRACE_TOK])));

    skip_separators();

    // Expect 'then' or {
    let use_brace = tok() == INBRACE_TOK;
    if tok() != THEN && !use_brace {
        error("expected 'then' or '{' after if condition");
        return None;
    }
    zshlex();

    // Parse then-body - stops at else/elif/fi, or } if using brace syntax
    let then = if use_brace {
        let body = parse_program_until(Some(&[OUTBRACE_TOK]));
        if tok() == OUTBRACE_TOK {
            zshlex();
        }
        Box::new(body)
    } else {
        Box::new(parse_program_until(Some(&[ELSE, ELIF, FI])))
    };

    // Parse elif and else. zsh accepts the SAME elif/else
    // continuations for both classic `then/fi` AND the brace
    // form `{ ... } elif ... { ... } else { ... }`. Direct port
    // of zsh/Src/parse.c:1417-1500 par_if where the elif/else
    // arms are checked AFTER the body close regardless of which
    // delimiter style opened the block. Without this, zinit's
    //   if [[ -z $sel ]] { ... } else { ... }
    // hung the parser — `else` was treated as an external
    // command following the if-statement, which the lexer state
    // mis-classified inside the still-open function body.
    //
    // For brace-form: skip the `fi` consumption at the end of
    // the loop (no `fi` after a brace block), and `else` may
    // arrive after a `}` close. Skip-separators between the
    // body close and the elif/else token.
    let mut elif = Vec::new();
    let mut else_ = None;

    {
        loop {
            skip_separators();

            match tok() {
                ELIF => {
                    zshlex();
                    // elif condition stops at 'then' or '{'
                    let econd = parse_program_until(Some(&[THEN, INBRACE_TOK]));
                    skip_separators();

                    let elif_use_brace = tok() == INBRACE_TOK;
                    if tok() != THEN && !elif_use_brace {
                        error("expected 'then' after elif");
                        return None;
                    }
                    zshlex();

                    // elif body stops at else/elif/fi or } if using braces
                    let ebody = if elif_use_brace {
                        let body = parse_program_until(Some(&[OUTBRACE_TOK]));
                        if tok() == OUTBRACE_TOK {
                            zshlex();
                        }
                        body
                    } else {
                        parse_program_until(Some(&[ELSE, ELIF, FI]))
                    };

                    elif.push((econd, ebody));
                }
                ELSE => {
                    zshlex();
                    skip_separators();

                    let else_use_brace = tok() == INBRACE_TOK;
                    if else_use_brace {
                        zshlex();
                    }

                    // else body stops at 'fi' or '}'
                    else_ = Some(Box::new(if else_use_brace {
                        let body = parse_program_until(Some(&[OUTBRACE_TOK]));
                        if tok() == OUTBRACE_TOK {
                            zshlex();
                        }
                        body
                    } else {
                        parse_program_until(Some(&[FI]))
                    }));

                    // Consume the 'fi' if present (not for brace syntax)
                    if !else_use_brace && tok() == FI {
                        zshlex();
                    }
                    break;
                }
                FI => {
                    zshlex();
                    break;
                }
                _ => break,
            }
        }
    }

    Some(ZshCommand::If(ZshIf {
        cond,
        then,
        elif,
        else_,
    }))
}

/// Parse while/until loop
/// Parse `while COND; do BODY; done` and `until COND; do BODY; done`.
/// Direct port of zsh/Src/parse.c:1521 `par_while`. The
/// `until` variant is the same loop with the condition negated.
fn par_while(until: bool) -> Option<ZshCommand> {
    zshlex(); // skip while/until

    let cond = Box::new(parse_program());

    skip_separators();
    let body = parse_loop_body(false)?;

    Some(ZshCommand::While(ZshWhile {
        cond,
        body: Box::new(body),
        until,
    }))
}

/// Parse repeat loop
/// Parse `repeat N; do BODY; done`. Direct port of
/// zsh/Src/parse.c:1565 `par_repeat`. The C source supports
/// the SHORTLOOPS short-form `repeat N CMD` (no do/done) — zshrs's
/// parser doesn't yet special-case that variant.
fn par_repeat() -> Option<ZshCommand> {
    zshlex(); // skip 'repeat'

    let count = match tok() {
        STRING_LEX => {
            let c = tokstr().unwrap_or_default();
            zshlex();
            c
        }
        _ => {
            error("expected count after repeat");
            return None;
        }
    };

    skip_separators();
    // c:1600 — par_repeat's short-form gate is wider: it unlocks
    // when SHORTLOOPS OR SHORTREPEAT is set (vs SHORTLOOPS alone for
    // for/while). Pass `is_repeat=true` so parse_loop_body_kind
    // applies that widened gate.
    let body = parse_loop_body_kind(false, true)?;

    Some(ZshCommand::Repeat(ZshRepeat {
        count,
        body: Box::new(body),
    }))
}

/// Parse loop body (do...done, {...}, or shortloop)
/// Parse the `do BODY done` body of a for/while/until/select/
/// repeat loop. Direct equivalent of zsh's parse.c handling
/// inside the loop builders — they all consume DOLOOP, parse a
/// list until DONE, and return the list. The `foreach_style`
/// flag signals foreach (where short-form `for NAME in WORDS;
/// CMD` may skip do/done) vs c-style (which always requires
/// do/done).
fn parse_loop_body(foreach_style: bool) -> Option<ZshProgram> {
    parse_loop_body_kind(foreach_style, false)
}

/// Body-dispatch helper. `is_repeat` widens the SHORTLOOPS gate so
/// `SHORTREPEAT` also unlocks the short form for `repeat N CMD`
/// (per c:1600 `unset(SHORTLOOPS) && unset(SHORTREPEAT)`).
fn parse_loop_body_kind(foreach_style: bool, is_repeat: bool) -> Option<ZshProgram> {
    // c:1180-1194 — body dispatch order per par_for:
    //   `do ... done` (DOLOOP) — primary form.
    //   `{ ... }`   (INBRACE) — alternate.
    //   csh/CSHJUNKIELOOPS — terminator is `end`.
    //   else if (unset(SHORTLOOPS)) — YYERROR.
    //   else — short form (single command).
    if tok() == DOLOOP {
        zshlex();
        let body = parse_program();
        if tok() == DONE {
            zshlex();
        }
        Some(body)
    } else if tok() == INBRACE_TOK {
        zshlex();
        let body = parse_program();
        if tok() == OUTBRACE_TOK {
            zshlex();
        }
        Some(body)
    } else if foreach_style || isset(CSHJUNKIELOOPS) {
        // c:1184 / 1546 / 1595 — `else if (csh || isset(CSHJUNKIELOOPS))`.
        let body = parse_program();
        if tok() == ZEND {
            zshlex();
        }
        Some(body)
    } else {
        // c:1190 / 1474 / 1551 / 1600 — short-form gate. C bails
        // with YYERROR when `unset(SHORTLOOPS) && (!is_repeat ||
        // unset(SHORTREPEAT))`. zshrs's option machinery isn't
        // initialised at parse-test time (no `init_main` →
        // `install_emulation_defaults`), so a strict port here
        // body. parse_init seeds SHORTLOOPS=on mirroring C
        // `install_emulation_defaults`, so this fires only when a
        // script explicitly disabled the option.
        if unset(SHORTLOOPS) && (!is_repeat || unset(SHORTREPEAT)) {
            error("parse error: short loop form requires SHORTLOOPS option");
            return None;
        }
        // c:1192-1193 — short form: single command body.
        par_list().map(|list| ZshProgram { lists: vec![list] })
    }
}

/// Parse (...) subshell
/// Parse a subshell `( ... )`. Direct port of zsh/Src/parse.c:1619
/// `par_subsh`. Body parses as a normal list; the subshell wrapper
/// fork-isolates execution in the executor.
fn par_subsh() -> Option<ZshCommand> {
    zshlex(); // skip (
    let prog = parse_program();
    if tok() == OUTPAR_TOK {
        zshlex();
    }
    Some(ZshCommand::Subsh(Box::new(prog)))
}

/// `() { body } arg1 arg2 …` — anonymous function. Defines a fresh
/// function named `_zshrs_anon_N`, invokes it with the args, and the
/// body runs with positional params set. Implemented as the desugared
/// pair (FuncDef + Simple call) so the compile path doesn't need new
/// machinery.
/// Parse an anonymous function definition `() { BODY }` followed
/// by call args. zsh treats `() { echo hi; } a b c` as defining
/// and immediately calling an anon fn with args a/b/c. C
/// equivalent: the INOUTPAR shape in par_simple at parse.c:1836+
/// triggers an anon-funcdef path.
fn parse_anon_funcdef() -> Option<ZshCommand> {
    zshlex(); // skip ()
    skip_separators();
    // No `{` after `()` → bare empty subshell shape `()`. Fall back
    // to a Subsh with an empty program so the status is 0 (matches
    // zsh's `()` no-op behavior).
    if tok() != INBRACE_TOK {
        return Some(ZshCommand::Subsh(Box::new(ZshProgram {
            lists: Vec::new(),
        })));
    }
    zshlex(); // skip {
    let body = parse_program();
    if tok() == OUTBRACE_TOK {
        zshlex();
    }
    // Collect any trailing args until a separator. zsh's anon-fn form
    // `() { body } a b c` runs body with $1=a, $2=b, $3=c.
    let mut args = Vec::new();
    while tok() == STRING_LEX {
        if let Some(s) = tokstr() {
            args.push(s);
        }
        zshlex();
    }

    // Generate a unique name. Module-level static would be cleaner but
    // a thread-local atomic is enough — anonymous functions are
    // ephemeral and the name isn't user-visible.
    static ANON_COUNTER: AtomicUsize = AtomicUsize::new(0);
    let n = ANON_COUNTER.fetch_add(1, Ordering::Relaxed);
    let name = format!("_zshrs_anon_{}", n);
    Some(ZshCommand::FuncDef(ZshFuncDef {
        names: vec![name],
        body: Box::new(body),
        tracing: false,
        auto_call_args: Some(args),
        body_source: None,
    }))
}

/// Parse {...} cursh
/// Parse a current-shell brace block `{ BODY }`. C source
/// par_cmd at parse.c:958-1085 handles Inbrace → emit WC_CURSH
/// and recurses into the list. zshrs's parse_cursh extracts that
/// arm into a dedicated method.
fn parse_cursh() -> Option<ZshCommand> {
    zshlex(); // skip {
    let prog = parse_program();

    // Check for { ... } always { ... }. Direct port of zsh's
    // par_subsh at parse.c:1612-1660 — note the two `incmdpos = 1`
    // forces (parse.c:1632, 1637): after consuming the closing
    // Outbrace AND after matching the `always` keyword, the parser
    // explicitly resets command position so the next `{` lexes as
    // Inbrace. Without these resets the lexer's String-clears-cmdpos
    // rule (lex.rs:976-983) leaves the second `{` in word position,
    // turning `always { ... }` into a Simple `{` `echo` … and the
    // try/always pairing is silently lost.
    if tok() == OUTBRACE_TOK {
        set_incmdpos(true); // parse.c:1632 incmdpos = !zsh_construct
        zshlex();

        // Check for 'always'
        if tok() == STRING_LEX {
            let s = tokstr();
            if s.map(|s| s == "always").unwrap_or(false) {
                set_incmdpos(true); // parse.c:1637 incmdpos = 1
                zshlex();
                skip_separators();

                if tok() == INBRACE_TOK {
                    zshlex();
                    let always = parse_program();
                    if tok() == OUTBRACE_TOK {
                        zshlex();
                    }
                    return Some(ZshCommand::Try(ZshTry {
                        try_block: Box::new(prog),
                        always: Box::new(always),
                    }));
                }
            }
        }
    }

    Some(ZshCommand::Cursh(Box::new(prog)))
}

/// Parse function definition
/// Parse `function NAME { BODY }` or `NAME () { BODY }`. Direct
/// port of zsh/Src/parse.c:1672 `par_funcdef`. zsh handles
/// the multiple keyword shapes (function FOO, FOO (), function FOO ()),
/// the optional `[fname1 fname2 ...]` for multi-name function defs,
/// and the `function FOO () { ... }` traditional/POSIX hybrid form.
fn par_funcdef() -> Option<ZshCommand> {
    zshlex(); // skip 'function'

    let mut names = Vec::new();
    let mut tracing = false;

    // Handle options like -T and function names. Two subtleties:
    //
    //   1. Flags: zsh's lexer encodes a leading `-` as
    //      `zsh_h::Dash` (`\u{9b}`, `Src/zsh.h:182`) inside the String tokstr.
    //      The previous `s.starts_with('-')` check failed for
    //      `\u{9b}T`, so `function -T NAME { body }` slipped the
    //      `-T` token into `names` and the function got registered
    //      as `T` plus the intended `NAME`.
    //
    //   2. Body opener: zsh's lexer emits the opening `{` as a
    //      String (not INBRACE_TOK) when it follows the String
    //      NAME — the preceding name token resets incmdpos to
    //      false, and only `{` immediately followed by `}` (the
    //      empty-body case) gets promoted to Inbrace. The funcdef
    //      parser must recognise the bare-`{` String as the body
    //      opener; otherwise `function NAME { body }` falls through
    //      to `_ => break`, no body parses, and the FuncDef never
    //      lands in the AST. This is consistent with C zsh's
    //      par_funcdef which knows it's in funcdef-header context
    //      and accepts the brace either way.
    loop {
        match tok() {
            STRING_LEX => {
                let _ts_s = tokstr()?;
                let s = _ts_s.as_str();
                // c:1702 — `if ((*tokstr == Inbrace || *tokstr == '{') && !tokstr[1])`.
                // Body opener can be either the literal `{` (early-return
                // path at lex.c:1141-1144 / lex.rs LX2_INBRACE cmdpos
                // branch) or the Inbrace marker `\u{8f}` (lex.c:1420
                // post-switch add(c) where c was rewritten via lextok2).
                if s == "{" || s == "\u{8f}" {
                    break;
                }
                let first = s.chars().next();
                if matches!(first, Some('-') | Some('+')) || matches!(first, Some(c) if c == Dash) {
                    if s.contains('T') {
                        tracing = true;
                    }
                    zshlex();
                    continue;
                }
                names.push(s.to_string());
                zshlex();
            }
            INBRACE_TOK | INOUTPAR | SEPER | NEWLIN => break,
            _ => break,
        }
    }

    // Optional ()
    let saw_paren = tok() == INOUTPAR;
    if saw_paren {
        zshlex();
    }

    skip_separators();

    // Body opener: real Inbrace OR a String containing the literal `{`
    // (early-return path) OR a String containing the Inbrace marker
    // `\u{8f}` (bct++ path post-switch add). C parse.c:1702 handles
    // both string forms via `*tokstr == Inbrace || *tokstr == '{'`.
    let body_opener_is_string_brace =
        tok() == STRING_LEX && (tokstr_eq("{") || tokstr_eq("\u{8f}"));
    if tok() == INBRACE_TOK || body_opener_is_string_brace {
        // Capture body_start BEFORE the lexer advances past the
        // first body token. After the previous zshlex consumed
        // `{`, lexer.pos points just past `{` (which is where the
        // body source starts). The next `zshlex()` would advance
        // past the first token (`echo`), making body_start land
        // mid-body and lose the first word — `typeset -f f` would
        // print `a; echo b` for `{ echo a; echo b }`.
        let body_start = pos();
        zshlex();
        let body = parse_program();
        let body_end = if tok() == OUTBRACE_TOK {
            // Lexer has just consumed `}`; pos is past it. Body content
            // ends one byte before pos.
            pos().saturating_sub(1)
        } else {
            pos()
        };
        let body_source = input_slice(body_start, body_end)
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty());
        if tok() == OUTBRACE_TOK {
            zshlex();
        }

        // Anonymous form `function () { body } a b c` (with `()`) or
        // `function { body } a b c` (zsh-only shorthand, no `()`). No
        // name was collected. Mirror parse_anon_funcdef: synthesize
        // `_zshrs_anon_N`, collect trailing args, set auto_call_args
        // so compile_funcdef registers + immediately calls the
        // function with the args as positional params.
        if names.is_empty() {
            let mut args = Vec::new();
            while tok() == STRING_LEX {
                if let Some(s) = tokstr() {
                    args.push(s);
                }
                zshlex();
            }
            static ANON_COUNTER: AtomicUsize = AtomicUsize::new(0);
            let n = ANON_COUNTER.fetch_add(1, Ordering::Relaxed);
            let name = format!("_zshrs_anon_kw_{}", n);
            return Some(ZshCommand::FuncDef(ZshFuncDef {
                names: vec![name],
                body: Box::new(body),
                tracing,
                auto_call_args: Some(args),
                body_source,
            }));
        }

        Some(ZshCommand::FuncDef(ZshFuncDef {
            names,
            body: Box::new(body),
            tracing,
            auto_call_args: None,
            body_source,
        }))
    } else {
        // Short form
        par_list().map(|list| {
            ZshCommand::FuncDef(ZshFuncDef {
                names,
                body: Box::new(ZshProgram { lists: vec![list] }),
                tracing,
                auto_call_args: None,
                body_source: None,
            })
        })
    }
}

/// Parse inline function definition: name() { ... }
/// Parse the inline form `NAME () { BODY }` (POSIX-style funcdef
/// without the `function` keyword). The name has already been
/// consumed and pushed by par_simple before this method fires.
/// C source: handled inline in par_simple's INOUTPAR-after-name
/// arm (parse.c:1836-2228).
fn parse_inline_funcdef(name: String) -> Option<ZshCommand> {
    // par_simple's STRING loop left `incmdpos = 0`; the funcdef body
    // `{ ... }` requires `incmdpos = 1` so the lexer recognises `{`
    // as INBRACE_TOK (current-shell block opener) instead of a
    // literal `{` STRING. Without this, `myfunc() { echo body }`
    // parsed the body as the single STRING `"{"`, then `echo body`
    // fell out at top level. Mirrors the C path where par_cmd's
    // dispatcher (parse.c:958) is called with `incmdpos = 1` for
    // the funcdef body.
    set_incmdpos(true);
    // Skip ()
    if tok() == INOUTPAR {
        zshlex();
    }

    skip_separators();

    // Parse body
    if tok() == INBRACE_TOK {
        // Same body_start-before-zshlex fix as par_funcdef.
        let body_start = pos();
        zshlex();
        let body = parse_program();
        let body_end = if tok() == OUTBRACE_TOK {
            pos().saturating_sub(1)
        } else {
            pos()
        };
        let body_source = input_slice(body_start, body_end)
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty());
        if tok() == OUTBRACE_TOK {
            zshlex();
        }
        Some(ZshCommand::FuncDef(ZshFuncDef {
            names: vec![name],
            body: Box::new(body),
            tracing: false,
            auto_call_args: None,
            body_source,
        }))
    } else if unset(SHORTLOOPS) {
        // c:1742 — `else if (unset(SHORTLOOPS)) YYERRORV(oecused);` —
        // funcdef short body (`name() cmd` without `{...}`) only
        // accepted when SHORTLOOPS is set. parse_init seeds
        // SHORTLOOPS=on so this fires only when a script
        // explicitly disabled the option.
        error("parse error: short function body form requires SHORTLOOPS option");
        None
    } else {
        match par_cmd() {
            Some(cmd) => {
                let list = ZshList {
                    sublist: ZshSublist {
                        pipe: ZshPipe {
                            cmd,
                            next: None,
                            lineno: lineno(),
                            merge_stderr: false,
                        },
                        next: None,
                        flags: SublistFlags::default(),
                    },
                    flags: ListFlags::default(),
                };
                Some(ZshCommand::FuncDef(ZshFuncDef {
                    names: vec![name],
                    body: Box::new(ZshProgram { lists: vec![list] }),
                    tracing: false,
                    auto_call_args: None,
                    body_source: None,
                }))
            }
            None => None,
        }
    }
}

/// Parse [[ ... ]] conditional
/// Parse `[[ EXPR ]]` conditional expression. Direct port of
/// zsh/Src/parse.c:2409 `par_cond` (and helpers par_cond_1,
/// par_cond_2, par_cond_double, par_cond_triple, par_cond_multi
/// at parse.c:2434-2731). Expression operators: `||` `&&` `!`
/// + unary tests (-f, -d, -n, -z, etc.) + binary tests (=, !=,
///   <, >, ==, =~, -eq, -ne, -lt, -le, -gt, -ge, -nt, -ot, -ef).
fn par_cond() -> Option<ZshCommand> {
    // C par_dinbrack (parse.c:1810-1822) wraps the body parse with
    // `incond = 1; incmdpos = 0;` BEFORE the first zshlex past `[[`,
    // and resets to `incond = 0; incmdpos = 1;` after `]]`. Without
    // `incond = 1`, lex.c does not promote `]]` to DOUTBRACK and the
    // cond body bleeds past the close bracket — the parser then
    // sees `]]` as a separate STRING command. Every `if [[ ... ]]; then`
    // failed with `command not found: ]]` before this fix.
    set_incond(1);
    set_incmdpos(false);
    zshlex(); // skip [[
    // Empty cond `[[ ]]` is a parse error in zsh — emit the
    // diagnostic and return None so the caller produces a
    // non-zero exit. Without this, `[[ ]]` silently passed and
    // returned exit 0.
    if tok() == DOUTBRACK {
        error("parse error near `]]'");
        set_incond(0);
        set_incmdpos(true);
        zshlex();
        return None;
    }
    let cond = parse_cond_expr();

    if tok() == DOUTBRACK {
        set_incond(0);
        set_incmdpos(true);
        zshlex();
    } else {
        // Recover incond/incmdpos so subsequent parsing isn't stuck
        // in cond-mode if the close bracket is missing.
        set_incond(0);
        set_incmdpos(true);
    }

    cond.map(ZshCommand::Cond)
}

/// Parse conditional expression
/// Top of `[[ ]]` cond-expression parsing — entry to recursive
/// descent (or → and → not → primary). Direct port of zsh's
/// par_cond_1 at parse.c:2434-2475.
fn parse_cond_expr() -> Option<ZshCond> {
    parse_cond_or()
}

/// Cond-expression `||` level. C: inside par_cond_1 at
/// parse.c:2434-2475 (the `cond_or` ladder).
fn parse_cond_or() -> Option<ZshCond> {
    PARSER_RECURSION_DEPTH.set(PARSER_RECURSION_DEPTH.get() + 1);
    if check_recursion() {
        error("parse_cond_or: max recursion depth exceeded");
        PARSER_RECURSION_DEPTH.set(PARSER_RECURSION_DEPTH.get().saturating_sub(1));
        return None;
    }

    let left = match parse_cond_and() {
        Some(l) => l,
        None => {
            PARSER_RECURSION_DEPTH.set(PARSER_RECURSION_DEPTH.get().saturating_sub(1));
            return None;
        }
    };

    skip_cond_separators();

    let result = if tok() == DBAR {
        zshlex();
        skip_cond_separators();
        parse_cond_or().map(|right| ZshCond::Or(Box::new(left), Box::new(right)))
    } else {
        Some(left)
    };

    PARSER_RECURSION_DEPTH.set(PARSER_RECURSION_DEPTH.get().saturating_sub(1));
    result
}

/// Cond-expression `&&` level. C: par_cond_2 at parse.c:2476-2625.
fn parse_cond_and() -> Option<ZshCond> {
    PARSER_RECURSION_DEPTH.set(PARSER_RECURSION_DEPTH.get() + 1);
    if check_recursion() {
        error("parse_cond_and: max recursion depth exceeded");
        PARSER_RECURSION_DEPTH.set(PARSER_RECURSION_DEPTH.get().saturating_sub(1));
        return None;
    }

    let left = match parse_cond_not() {
        Some(l) => l,
        None => {
            PARSER_RECURSION_DEPTH.set(PARSER_RECURSION_DEPTH.get().saturating_sub(1));
            return None;
        }
    };

    skip_cond_separators();

    let result = if tok() == DAMPER {
        zshlex();
        skip_cond_separators();
        parse_cond_and().map(|right| ZshCond::And(Box::new(left), Box::new(right)))
    } else {
        Some(left)
    };

    PARSER_RECURSION_DEPTH.set(PARSER_RECURSION_DEPTH.get().saturating_sub(1));
    result
}

/// Cond-expression `!` negation level. C: handled inside
/// par_cond_2 at parse.c:2476-2625 via the Bang token check.
fn parse_cond_not() -> Option<ZshCond> {
    PARSER_RECURSION_DEPTH.set(PARSER_RECURSION_DEPTH.get() + 1);
    if check_recursion() {
        error("parse_cond_not: max recursion depth exceeded");
        PARSER_RECURSION_DEPTH.set(PARSER_RECURSION_DEPTH.get().saturating_sub(1));
        return None;
    }

    skip_cond_separators();

    // ! can be either BANG_TOK or String "!"
    let is_not =
        tok() == BANG_TOK || (tok() == STRING_LEX && tokstr().map(|s| s == "!").unwrap_or(false));
    if is_not {
        zshlex();
        let inner = match parse_cond_not() {
            Some(i) => i,
            None => {
                PARSER_RECURSION_DEPTH.set(PARSER_RECURSION_DEPTH.get().saturating_sub(1));
                return None;
            }
        };
        PARSER_RECURSION_DEPTH.set(PARSER_RECURSION_DEPTH.get().saturating_sub(1));
        return Some(ZshCond::Not(Box::new(inner)));
    }

    if tok() == INPAR_TOK {
        zshlex();
        skip_cond_separators();
        let inner = match parse_cond_expr() {
            Some(i) => i,
            None => {
                PARSER_RECURSION_DEPTH.set(PARSER_RECURSION_DEPTH.get().saturating_sub(1));
                return None;
            }
        };
        skip_cond_separators();
        if tok() == OUTPAR_TOK {
            zshlex();
        }
        PARSER_RECURSION_DEPTH.set(PARSER_RECURSION_DEPTH.get().saturating_sub(1));
        return Some(inner);
    }

    let result = parse_cond_primary();
    PARSER_RECURSION_DEPTH.set(PARSER_RECURSION_DEPTH.get().saturating_sub(1));
    result
}

/// Cond-expression primary: unary tests (-f, -d, ...), binary
/// tests (=, !=, <, >, ==, =~, -eq, -ne, ...), and parenthesized
/// sub-expressions. Direct port of par_cond_double / par_cond_triple
/// / par_cond_multi at parse.c:2626-2731 (chosen by arg count).
fn parse_cond_primary() -> Option<ZshCond> {
    let s1 = match tok() {
        STRING_LEX => {
            let s = tokstr().unwrap_or_default();
            zshlex();
            s
        }
        _ => return None,
    };

    skip_cond_separators();

    // Check for unary operator. zsh's lexer tokenizes leading `-` as
    // `zsh_h::Dash` (`\u{9b}`, `Src/zsh.h:182`) inside gettokstr (lex.c:1390-1400
    // LX2_DASH — `-` always becomes Dash, untokenized later). Match
    // either form here, and use char-count not byte-count since Dash
    // is 2 UTF-8 bytes (`\xc2\x9b`).
    let s1_chars: Vec<char> = s1.chars().collect();
    if s1_chars.len() == 2 && IS_DASH(s1_chars[0]) {
        let s2 = match tok() {
            STRING_LEX => {
                let s = tokstr().unwrap_or_default();
                zshlex();
                s
            }
            _ => return Some(ZshCond::Unary("-n".to_string(), s1)),
        };
        return Some(ZshCond::Unary(s1, s2));
    }

    // Check for binary operator. Direct port of zsh/Src/parse.c:2601-2603:
    //   incond++;  /* parentheses do globbing */
    //   do condlex(); while (COND_SEP());
    //   incond--;  /* parentheses do grouping */
    // The bump makes the lexer treat `(` as a literal character inside
    // the RHS word (e.g. `[[ x =~ (foo) ]]`) instead of returning Inpar
    // and splitting the regex into multiple tokens.
    let op = match tok() {
        STRING_LEX => {
            let s = tokstr().unwrap_or_default();
            set_incond(incond() + 1);
            zshlex();
            set_incond(incond() - 1);
            s
        }
        INANG_TOK => {
            set_incond(incond() + 1);
            zshlex();
            set_incond(incond() - 1);
            "<".to_string()
        }
        OUTANG_TOK => {
            set_incond(incond() + 1);
            zshlex();
            set_incond(incond() - 1);
            ">".to_string()
        }
        _ => return Some(ZshCond::Unary("-n".to_string(), s1)),
    };

    skip_cond_separators();

    let s2 = match tok() {
        STRING_LEX => {
            let s = tokstr().unwrap_or_default();
            zshlex();
            s
        }
        _ => return Some(ZshCond::Binary(s1, op, String::new())),
    };

    if op == "=~" {
        Some(ZshCond::Regex(s1, s2))
    } else {
        Some(ZshCond::Binary(s1, op, s2))
    }
}

fn skip_cond_separators() {
    while tok() == SEPER && {
        let s = tokstr();
        s.map(|s| !s.contains(';')).unwrap_or(true)
    } {
        zshlex();
    }
}

/// Parse (( ... )) arithmetic command
/// Parse `(( EXPR ))` arithmetic command. C source: parse.c:1810-1834
/// `par_dinbrack` (despite the name; the function actually handles
/// DINPAR `(( ))` blocks too).
fn parse_arith() -> Option<ZshCommand> {
    let expr = tokstr().unwrap_or_default();
    zshlex();
    Some(ZshCommand::Arith(expr))
}

/// Parse time command
/// Parse `time CMD` (POSIX time keyword). Direct port of
/// zsh/Src/parse.c:1787 `par_time`. The `time` keyword
/// times the execution of the following pipeline / cmd.
fn par_time() -> Option<ZshCommand> {
    zshlex(); // skip 'time'

    // Check if there's a pipeline to time
    if tok() == SEPER || tok() == NEWLIN || tok() == ENDINPUT {
        Some(ZshCommand::Time(None))
    } else {
        let sublist = par_sublist();
        Some(ZshCommand::Time(sublist.map(Box::new)))
    }
}

/// Check if next token is ()
fn peek_inoutpar() -> bool {
    tok() == INOUTPAR
}

/// Skip separator tokens
fn skip_separators() {
    let mut iterations = 0;
    while tok() == SEPER || tok() == NEWLIN {
        iterations += 1;
        if iterations > 100_000 {
            error("skip_separators: too many iterations");
            return;
        }
        zshlex();
    }
}

/// Record a parse error. Direct port of zsh's `zerr` invocation
/// from `Src/parse.c:625-633 yyerror`. Sets `errflag |=
/// ERRFLAG_ERROR` (when `noerrs == 0`) and emits a diagnostic on
/// stderr via `zwarning`.
fn error(msg: &str) {
    crate::ported::utils::zerr(msg);
}

// =====================================================================
// `bin_zcompile` and wordcode-dump helpers — port of `Src/parse.c:3104+`.
//
// The wordcode dump format (`.zwc`) is a serialized parse tree zsh can
// `mmap()` and dispatch from without re-parsing on every shell start.
// File layout (one struct = `FD_PRELEN` `u32`s):
//   - `pre[0]` = magic word (FD_MAGIC native byte-order, FD_OMAGIC
//     opposite byte-order).
//   - `pre[1]` = packed `{flags(8) | other_offset(24)}` byte field.
//   - `pre[2..12]` = `ZSH_VERSION` C-string padded to 40 bytes.
//   - `pre[12]` = `fdheaderlen` (total prelude+header word count).
//   - Then a sequence of `struct fdhead` records, one per function,
//     each followed by its NUL-terminated name (padded to 4-byte).
//   - Then the wordcode bytes for every function back-to-back.
//
// On a little-endian host writing a dump twice: first `FD_MAGIC` for
// native readers, then re-walks the body byte-swapped and emits a
// second `FD_OMAGIC` copy so big-endian readers can mmap it too.
// =====================================================================

// File-format constants — port of `Src/parse.c:3104-3150`.

/// `#define FD_EXT ".zwc"` from `Src/parse.c:3104`.
pub const FD_EXT: &str = ".zwc";

/// `#define FD_MINMAP 4096` from `Src/parse.c:3105`. mmap threshold
/// — `-M` mode only kicks in when the wordcode body is at least
/// this many bytes (otherwise read(2) is preferred).
pub const FD_MINMAP: usize = 4096;

/// `#define FD_PRELEN 12` from `Src/parse.c:3107`. File-header
/// length in u32 words: magic + packed-flags-byte + 10 version words.
pub const FD_PRELEN: usize = 12;

/// `#define FD_MAGIC 0x04050607` from `Src/parse.c:3108`. Sentinel
/// for native-byte-order dumps.
pub const FD_MAGIC: u32 = 0x04050607;

/// `#define FD_OMAGIC 0x07060504` from `Src/parse.c:3109`. Sentinel
/// for opposite-byte-order dumps (byte-swapped FD_MAGIC).
pub const FD_OMAGIC: u32 = 0x07060504;

/// `#define FDF_MAP 1` from `Src/parse.c:3111`. Bit set when the
/// dump should be `mmap()`-ed (`-M` flag) vs read normally (`-R`).
pub const FDF_MAP: u32 = 1;

/// `#define FDF_OTHER 2` from `Src/parse.c:3112`. Bit indicating
/// this dump has an opposite-byte-order copy at `fdother(f)`.
pub const FDF_OTHER: u32 = 2;

/// `#define FDHF_KSHLOAD 1` from `Src/parse.c:3149`. Function-header
/// flag word — `-k` ksh-style autoload marker.
pub const FDHF_KSHLOAD: u32 = 1;

/// `#define FDHF_ZSHLOAD 2` from `Src/parse.c:3150`. `-z` zsh-style
/// autoload marker.
pub const FDHF_ZSHLOAD: u32 = 2;

/// Port of `struct fdhead` from `Src/parse.c:3116`. One per function
/// inside a wordcode dump. All fields are `wordcode` (u32).
#[allow(non_camel_case_types)]
#[derive(Debug, Clone, Copy)]
pub struct fdhead {
    /// Offset (in u32 words) to the start of this function's
    /// wordcode body inside the dump.
    pub start: u32, // c:3117
    /// Wordcode-byte length of the body (excludes pattern-prog slots).
    pub len: u32, // c:3118
    /// Number of compiled patterns the body references.
    pub npats: u32, // c:3119
    /// Offset of the string table inside `prog->prog`.
    pub strs: u32, // c:3120
    /// Header-record length in u32 words (record + name).
    pub hlen: u32, // c:3121
    /// Packed `{ kshload_bits(2) | name_tail_offset(30) }` field.
    pub flags: u32, // c:3122
}

/// Size of `struct fdhead` in `wordcode` (u32) units. Used by all
/// the header-walk macros below.
pub const FDHEAD_WORDS: usize = std::mem::size_of::<fdhead>() / 4;

/// Port of `struct wcfunc` from `Src/parse.c:3158`. Build-time
/// per-function aggregate before write_dump emits it. The Rust
/// port stores the source-text body inline since the C-side
/// `Eprog` ↔ `parse_string` chain isn't fully wired through this
/// layer yet (`build_dump` falls back to source-text caching).
#[allow(non_camel_case_types)]
#[derive(Debug, Clone)]
pub struct wcfunc {
    pub name: String, // c:3159
    pub flags: u32,   // c:3161
    /// Compiled body wordcode (one `u32` array per fn). Empty until
    /// the eprog emit-side lands; `write_dump` then walks each entry.
    pub body: Vec<u32>,
}

// `fdheaderlen` / `fdmagic` / `fdflags` / etc. macros from
// `Src/parse.c:3125-3152`. C uses raw pointer arithmetic on a
// `Wordcode` (= `u32 *`); the Rust port takes a slice and indexes.

/// Port of `fdheaderlen(f)` macro (`Src/parse.c:3125`) — header
/// length in u32 words (read from prelude word `FD_PRELEN`).
#[inline]
pub fn fdheaderlen(f: &[u32]) -> u32 {
    f[FD_PRELEN]
}

/// Port of `fdmagic(f)` macro (`Src/parse.c:3127`) — first prelude
/// word, either `FD_MAGIC` or `FD_OMAGIC`.
#[inline]
pub fn fdmagic(f: &[u32]) -> u32 {
    f[0]
}

/// Port of `fdflags(f)` macro (`Src/parse.c:3131`) — low byte of
/// the packed `pre[1]` word.
#[inline]
pub fn fdflags(f: &[u32]) -> u32 {
    // `pre[1]` is a u32 viewed as 4 bytes; flags = byte 0.
    f[1] & 0xff
}

/// Port of `fdsetflags(f, v)` macro (`Src/parse.c:3132`) — write
/// the low byte of `pre[1]`.
#[inline]
pub fn fdsetflags(f: &mut [u32], v: u8) {
    f[1] = (f[1] & !0xff) | (v as u32);
}

/// Port of `fdother(f)` macro (`Src/parse.c:3133`) — high 24 bits
/// of `pre[1]`, holds the byte-offset to the opposite-byte-order
/// dump copy.
#[inline]
pub fn fdother(f: &[u32]) -> u32 {
    (f[1] >> 8) & 0x00ff_ffff
}

/// Port of `fdsetother(f, o)` macro (`Src/parse.c:3134`).
#[inline]
pub fn fdsetother(f: &mut [u32], o: u32) {
    f[1] = (f[1] & 0xff) | ((o & 0x00ff_ffff) << 8);
}

/// Port of `fdversion(f)` macro (`Src/parse.c:3140`) — read the
/// `ZSH_VERSION` C-string from `pre[2..]`.
pub fn fdversion(f: &[u32]) -> String {
    let bytes: Vec<u8> = f[2..]
        .iter()
        .take(10)
        .flat_map(|w| w.to_le_bytes().into_iter())
        .collect();
    let end = bytes.iter().position(|&b| b == 0).unwrap_or(bytes.len());
    String::from_utf8_lossy(&bytes[..end]).into_owned()
}

/// Port of `firstfdhead(f)` macro (`Src/parse.c:3142`) — pointer
/// to the first `struct fdhead` past the prelude.
#[inline]
pub fn firstfdhead_offset() -> usize {
    FD_PRELEN
}

/// Port of `nextfdhead(f)` macro (`Src/parse.c:3143`) — advance to
/// the next header by reading the current `hlen` slot.
#[inline]
pub fn nextfdhead_offset(f: &[u32], cur: usize) -> usize {
    cur + (f[cur + 4] as usize) // .hlen is field 4 of fdhead
}

/// Port of `fdhflags(f)` macro (`Src/parse.c:3145`) — low 2 bits
/// of the header's `flags` field (the kshload/zshload marker).
#[inline]
pub fn fdhflags(h: &fdhead) -> u32 {
    h.flags & 0x3
}

/// Port of `fdhtail(f)` macro (`Src/parse.c:3146`) — high 30 bits
/// of `flags`, byte offset from the name start to its basename.
#[inline]
pub fn fdhtail(h: &fdhead) -> u32 {
    h.flags >> 2
}

/// Port of `fdhbldflags(f, t)` macro (`Src/parse.c:3147`) — pack
/// `(flags, tail)` into one u32 (low 2 bits = flags, high 30 = tail).
#[inline]
pub fn fdhbldflags(flags: u32, tail: u32) -> u32 {
    flags | (tail << 2)
}

/// Port of `fdname(f)` macro (`Src/parse.c:3152`) — name string
/// follows the fdhead record immediately. Reads bytes from the
/// dump buffer until NUL.
pub fn fdname(buf: &[u32], header_offset: usize) -> String {
    let name_word_off = header_offset + FDHEAD_WORDS;
    let bytes: Vec<u8> = buf[name_word_off..]
        .iter()
        .flat_map(|w| w.to_le_bytes().into_iter())
        .take_while(|&b| b != 0)
        .collect();
    String::from_utf8_lossy(&bytes).into_owned()
}

/// Decode a `fdhead` record at the given u32-word offset in the
/// dump buffer. Used by the header-walk loops in `bin_zcompile -t`.
pub fn read_fdhead(buf: &[u32], offset: usize) -> Option<fdhead> {
    if offset + FDHEAD_WORDS > buf.len() {
        return None;
    }
    Some(fdhead {
        start: buf[offset],
        len: buf[offset + 1],
        npats: buf[offset + 2],
        strs: buf[offset + 3],
        hlen: buf[offset + 4],
        flags: buf[offset + 5],
    })
}

/// Port of `fdswap(Wordcode p, int n)` from `Src/parse.c:3318`.
/// Byte-swap each u32 in `p[..n]` in place. Used when writing the
/// opposite-byte-order copy of a wordcode dump.
pub fn fdswap(p: &mut [u32]) {
    // c:3318
    for w in p.iter_mut() {
        *w = w.swap_bytes();
    }
}

/// Port of `dump_find_func(Wordcode h, char *name)` from
/// `Src/parse.c:3167`. Walks the header table inside a loaded
/// dump for a function with the given basename; returns true on hit.
pub fn dump_find_func(h: &[u32], name: &str) -> bool {
    // c:3167
    let header_words = fdheaderlen(h) as usize;
    let end = header_words; // walking u32 offsets, end-exclusive
    let mut cur = firstfdhead_offset();
    while cur < end {
        if let Some(fh) = read_fdhead(h, cur) {
            let full = fdname(h, cur);
            let tail = fdhtail(&fh) as usize;
            let basename = if tail <= full.len() {
                &full[tail..]
            } else {
                ""
            };
            if basename == name {
                return true;
            }
            cur = nextfdhead_offset(h, cur);
        } else {
            break;
        }
    }
    false
}

/// Port of `load_dump_header(char *nam, char *name, int err)` from
/// `Src/parse.c:3258`. Opens the file, reads + validates the magic
/// and version, then slurps the full header table into memory.
/// Returns the header u32-array on success or None on any failure
/// (emitting C-shaped warnings when `err != 0`).
pub fn load_dump_header(nam: &str, name: &str, err: i32) -> Option<Vec<u32>> {
    // c:3258

    let mut f = match File::open(name) {
        // c:3263
        Ok(h) => h,
        Err(_) => {
            if err != 0 {
                zwarnnam(nam, &format!("can't open zwc file: {}", name)); // c:3265
            }
            return None;
        }
    };

    // Read FD_PRELEN+1 u32 words = 52 bytes.
    let mut buf_bytes = vec![0u8; (FD_PRELEN + 1) * 4];
    if f.read_exact(&mut buf_bytes).is_err() {
        if err != 0 {
            zwarnnam(nam, &format!("invalid zwc file: {}", name)); // c:3277
        }
        return None;
    }
    let mut buf: Vec<u32> = buf_bytes
        .chunks_exact(4)
        .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]]))
        .collect();

    // c:3270 — magic + version check. `ZSH_VERSION` (the C-side
    // global) — zshrs reports "5.9" in `--zsh` mode (Src/init.c parity).
    let magic_ok = fdmagic(&buf) == FD_MAGIC || fdmagic(&buf) == FD_OMAGIC;
    let v_ok = fdversion(&buf) == "5.9";
    if !magic_ok {
        if err != 0 {
            zwarnnam(nam, &format!("invalid zwc file: {}", name)); // c:3277
        }
        return None;
    }
    if !v_ok {
        if err != 0 {
            zwarnnam(
                nam,
                &format!(
                    "zwc file has wrong version (zsh-{}): {}", // c:3274
                    fdversion(&buf),
                    name
                ),
            );
        }
        return None;
    }

    // c:3285 — if magic matches host byte order, head len is `pre[FD_PRELEN]`.
    // Else seek to `fdother(buf)` and re-read.
    if fdmagic(&buf) != FD_MAGIC {
        let other = fdother(&buf) as u64; // c:3290
        if f.seek(SeekFrom::Start(other)).is_err() || f.read_exact(&mut buf_bytes).is_err() {
            zwarnnam(nam, &format!("invalid zwc file: {}", name)); // c:3295
            return None;
        }
        buf = buf_bytes
            .chunks_exact(4)
            .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]]))
            .collect();
    }

    let total_words = fdheaderlen(&buf) as usize; // c:3286/3299
    if total_words < FD_PRELEN + 1 {
        zwarnnam(nam, &format!("invalid zwc file: {}", name));
        return None;
    }

    // Read the remaining header words.
    let mut head: Vec<u32> = Vec::with_capacity(total_words);
    head.extend_from_slice(&buf);
    let remaining_words = total_words - (FD_PRELEN + 1);
    if remaining_words > 0 {
        let mut rest_bytes = vec![0u8; remaining_words * 4]; // c:3305
        if f.read_exact(&mut rest_bytes).is_err() {
            zwarnnam(nam, &format!("invalid zwc file: {}", name)); // c:3307
            return None;
        }
        for c in rest_bytes.chunks_exact(4) {
            head.push(u32::from_le_bytes([c[0], c[1], c[2], c[3]]));
        }
    }
    Some(head) // c:3311
}

/// Port of `build_dump(char *nam, char *dump, char **files, int ali, int map, int flags)`
/// from `Src/parse.c:3397`. Source-file → wordcode dump compiler.
///
/// Status: scaffolded but the wordcode-emit step depends on
/// `parse_string` returning a fully-wired `Eprog` with `prog/strs/
/// npats` fields populated. The current `parse_string`/`parse` shape
/// emits an AST (`ZshProgram`) but not yet the wordcode array C
/// expects in this dump format. Until that lands, this returns 1
/// with a clear "wordcode emit not yet ported" message so callers
/// (autoload from `.zwc`, `zcompile path/to/file`) fail loud.
pub fn build_dump(
    nam: &str, // c:3397
    dump: &str,
    _files: &[String],
    _ali: i32,
    _map: i32,
    _flags: u32,
) -> i32 {
    crate::ported::utils::zwarnnam(nam, &format!("{}: wordcode dump emit not yet ported", dump));
    1
}

/// Port of `build_cur_dump(char *nam, char *dump, char **names, int match, int map, int what)`
/// from `Src/parse.c:3536`. Compiles currently-loaded functions
/// (`-c` for functions, `-a` for aliases) into a `.zwc` dump.
/// Same wordcode-emit dependency as `build_dump`.
pub fn build_cur_dump(
    nam: &str, // c:3536
    dump: &str,
    _names: &[String],
    _match_: i32,
    _map: i32,
    _what: i32,
) -> i32 {
    crate::ported::utils::zwarnnam(
        nam,
        &format!("{}: wordcode dump-current emit not yet ported", dump),
    );
    1
}

/// Port of `zwcstat(char *filename, struct stat *buf)` from
/// `Src/parse.c:3656`. Stats a `.zwc` file, falling back to
/// `.zwc.old` if the primary doesn't exist (zsh uses the `.old`
/// suffix to keep a previous dump readable while a rewrite is in
/// progress).
pub fn zwcstat(filename: &str) -> Option<std::fs::Metadata> {
    // c:3656
    if let Ok(m) = std::fs::metadata(filename) {
        return Some(m);
    }
    let old = format!("{}.old", filename);
    std::fs::metadata(&old).ok()
}

/// Port of `load_dump_file(char *dump, struct stat *sbuf, int other, int len)`
/// from `Src/parse.c:3675`. Reads (or mmap()'s) a complete `.zwc`
/// file into memory. Returns the u32 buffer or None on I/O error.
pub fn load_dump_file(
    dump: &str, // c:3675
    _sbuf: &std::fs::Metadata,
    other: i32,
    _len: usize,
) -> Option<Vec<u32>> {
    let mut f = File::open(dump).ok()?;
    if other != 0 {
        f.seek(SeekFrom::Start(other as u64)).ok()?;
    }
    let mut bytes = Vec::new();
    f.read_to_end(&mut bytes).ok()?;
    Some(
        bytes
            .chunks_exact(4)
            .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]]))
            .collect(),
    )
}

/// Port of `try_dump_file(char *path, char *name, char *file, int *ksh, int test_only)`
/// from `Src/parse.c:3746`. Tries to load a function from a `.zwc`
/// in the given fpath directory. Returns `(found, ksh_load)` —
/// stub: returns false until the dump-cache port (`FuncDump`) lands.
pub fn try_dump_file(
    _path: &str,
    _name: &str,
    _file: &str, // c:3746
    _test_only: bool,
) -> Option<(bool, bool)> {
    None
}

/// Port of `try_source_file(char *file)` from `Src/parse.c:3795`.
/// Tries `source <file>` then falls back to `source <file>.zwc`.
/// Returns the resolved path on hit. Stub: returns None until the
/// dump-cache port lands.
pub fn try_source_file(_file: &str) -> Option<String> {
    // c:3795
    None
}

/// Port of `check_dump_file(char *file, struct stat *sbuf, char *name, int *ksh, int test_only)`
/// from `Src/parse.c:3833`. Opens + validates a `.zwc` file,
/// returning its loaded buffer or None.
pub fn check_dump_file(
    _file: &str, // c:3833
    _sbuf: &std::fs::Metadata,
    _name: &str,
    _test_only: bool,
) -> Option<(Vec<u32>, bool)> {
    None
}

/// `static FuncDump dumps;` from `Src/parse.c:3652` — head of the
/// loaded-`.zwc` linked list. C walks `dumps`/`p->next` directly;
/// the Rust port uses a `Mutex<Vec<funcdump>>` indexed by filename
/// so refcount ops can find an entry without raw-pointer compare.
pub static DUMPS: std::sync::Mutex<Vec<crate::ported::zsh_h::funcdump>> =
    std::sync::Mutex::new(Vec::new());

/// Port of `incrdumpcount(FuncDump f)` from `Src/parse.c:3970/4021`.
/// `f->count++;` — refcount-up a loaded dump entry. The Rust port
/// keys lookup by `filename` because Rust can't raw-pointer-compare
/// funcdump values inside a `Mutex<Vec<...>>`; same observable
/// effect (the count of the matching entry increments).
pub fn incrdumpcount(f: &crate::ported::zsh_h::funcdump) {
    // c:3970
    let key = f.filename.as_deref();
    let mut g = DUMPS.lock().unwrap();
    for d in g.iter_mut() {
        if d.filename.as_deref() == key {
            d.count += 1; // c:3973
            return;
        }
    }
}

/// Port of `freedump(FuncDump f)` from `Src/parse.c:3976`. C
/// `munmap`s, `zclose`s the fd, and frees the struct. The Rust
/// port relies on Drop for the `funcdump` (no mmap held in this
/// port — `addr`/`map` are byte-offset placeholders), so the
/// equivalent is removing the entry from the dumps list. Called
/// by `decrdumpcount` when the refcount hits zero (c:3988) and
/// by `closedumps` when shutting down (c:4008).
fn freedump_locked(
    g: &mut std::sync::MutexGuard<'_, Vec<crate::ported::zsh_h::funcdump>>,
    filename: &str,
) {
    // c:3976
    g.retain(|d| d.filename.as_deref() != Some(filename));
}

/// Port of `freedump(FuncDump f)` from `Src/parse.c:3976`. Public
/// helper for the rare external caller; locks the dumps mutex and
/// drops the entry with the given filename.
pub fn freedump(f: &crate::ported::zsh_h::funcdump) {
    // c:3976
    let mut g = DUMPS.lock().unwrap();
    if let Some(name) = f.filename.as_deref() {
        freedump_locked(&mut g, name);
    }
}

/// Port of `decrdumpcount(FuncDump f)` from `Src/parse.c:3988/4026`.
/// `f->count--; if (!f->count) { unlink from dumps; freedump(f); }`.
pub fn decrdumpcount(f: &crate::ported::zsh_h::funcdump) {
    // c:3988
    let key = f.filename.clone();
    let mut g = DUMPS.lock().unwrap();
    let mut hit_zero: Option<String> = None;
    for d in g.iter_mut() {
        if d.filename == key {
            d.count -= 1; // c:3991
            if d.count == 0 {
                // c:3992
                hit_zero = d.filename.clone();
            }
            break;
        }
    }
    if let Some(name) = hit_zero {
        // c:3994-4001
        freedump_locked(&mut g, &name);
    }
}

/// Port of `closedumps(void)` from `Src/parse.c:4008/4033`. Walks
/// `dumps` freeing every entry. Called on shell exit (exec.c:522).
pub fn closedumps() {
    // c:4008
    let mut g = DUMPS.lock().unwrap();
    g.clear(); // c:4011-4014 `while (dumps) { ... freedump(...); ... }`
}

/// Port of `dump_autoload(char *nam, char *file, int on, Options ops, int func)`
/// from `Src/parse.c:4042`. Registers every function in a `.zwc`
/// for autoload via `shfunctab`. Stub: returns 1 (error) until the
/// dump-cache port lands.
pub fn dump_autoload(
    nam: &str,
    file: &str, // c:4042
    _on: i32,
    _ops: &crate::ported::zsh_h::options,
    _func: i32,
) -> i32 {
    zwarnnam(nam, &format!("{}: zwc-based autoload not yet ported", file));
    1
}

/// Port of `bin_zcompile(char *nam, char **args, Options ops, UNUSED(int func))`
/// from `Src/parse.c:3180`. Validates the option set, then dispatches
/// to one of: `-t` (test/list), `-c`/`-a` (dump current functions),
/// or the default (compile source files to `.zwc`).
pub fn bin_zcompile(
    nam: &str, // c:3180
    args: &[String],
    ops: &crate::ported::zsh_h::options,
    _func: i32,
) -> i32 {
    // c:3185-3192 — illegal-combination guard.
    if (OPT_ISSET(ops, b'k') && OPT_ISSET(ops, b'z'))
        || (OPT_ISSET(ops, b'R') && OPT_ISSET(ops, b'M'))
        || (OPT_ISSET(ops, b'c')
            && (OPT_ISSET(ops, b'U') || OPT_ISSET(ops, b'k') || OPT_ISSET(ops, b'z')))
        || (!(OPT_ISSET(ops, b'c') || OPT_ISSET(ops, b'a')) && OPT_ISSET(ops, b'm'))
    {
        zwarnnam(nam, "illegal combination of options"); // c:3192
        return 1;
    }

    // c:3194 — `-c`/`-a` + KSHAUTOLOAD warning.
    if (OPT_ISSET(ops, b'c') || OPT_ISSET(ops, b'a')) && isset(crate::ported::zsh_h::KSHAUTOLOAD) {
        zwarnnam(nam, "functions will use zsh style autoloading"); // c:3195
    }

    // c:3196-3197 — flag word from `-k` / `-z`.
    let flags: u32 = if OPT_ISSET(ops, b'k') {
        FDHF_KSHLOAD
    } else if OPT_ISSET(ops, b'z') {
        FDHF_ZSHLOAD
    } else {
        0
    };

    // c:3199 — `-t` test/list mode.
    if OPT_ISSET(ops, b't') {
        // c:3199
        if args.is_empty() {
            zwarnnam(nam, "too few arguments"); // c:3202
            return 1;
        }
        let dump_name = if args[0].ends_with(FD_EXT) {
            args[0].clone()
        } else {
            format!("{}{}", args[0], FD_EXT)
        };
        let f = match load_dump_header(nam, &dump_name, 1) {
            // c:3206
            Some(buf) => buf,
            None => return 1,
        };
        // c:3209 — per-function check.
        if args.len() > 1 {
            for name in &args[1..] {
                // c:3210
                if !dump_find_func(&f, name) {
                    // c:3212
                    return 1;
                }
            }
            return 0;
        }
        // c:3215-3221 — listing arm. Walk every fdhead, print
        // each function's full name. C uses `fdname(h)` which
        // includes the path prefix; matches our `fdname()` impl.
        let mapped = if (fdflags(&f) & FDF_MAP) != 0 {
            "mapped"
        } else {
            "read"
        };
        println!("zwc file ({}) for zsh-{}", mapped, fdversion(&f));
        let header_words = fdheaderlen(&f) as usize;
        let mut cur = firstfdhead_offset();
        while cur < header_words {
            if read_fdhead(&f, cur).is_none() {
                break;
            }
            println!("{}", fdname(&f, cur));
            cur = nextfdhead_offset(&f, cur);
        }
        return 0;
    }

    if args.is_empty() {
        zwarnnam(nam, "too few arguments"); // c:3226
        return 1;
    }

    // c:3228 — map mode discriminant.
    let map: i32 = if OPT_ISSET(ops, b'M') {
        2
    } else if OPT_ISSET(ops, b'R') {
        0
    } else {
        1
    };

    // c:3230-3236 — single-file default-mode short path.
    if args.len() == 1 && !(OPT_ISSET(ops, b'c') || OPT_ISSET(ops, b'a')) {
        let dump = format!("{}{}", args[0], FD_EXT);
        return build_dump(nam, &dump, args, OPT_ISSET(ops, b'U') as i32, map, flags);
    }

    // c:3239-3247 — multi-file or `-c`/`-a` mode.
    let dump = if args[0].ends_with(FD_EXT) {
        args[0].clone()
    } else {
        format!("{}{}", args[0], FD_EXT)
    };
    let rest = &args[1..];
    if OPT_ISSET(ops, b'c') || OPT_ISSET(ops, b'a') {
        let what =
            (if OPT_ISSET(ops, b'c') { 1 } else { 0 }) | (if OPT_ISSET(ops, b'a') { 2 } else { 0 });
        build_cur_dump(nam, &dump, rest, OPT_ISSET(ops, b'm') as i32, map, what)
    } else {
        build_dump(nam, &dump, rest, OPT_ISSET(ops, b'U') as i32, map, flags)
    }
}

// =====================================================================
// Remaining `Src/parse.c` ports (this section finishes the file).
//
// Several of these emit into the C-wordcode buffer (`ECBUF`/etc.) and
// are kept for completeness — the live zshrs runtime uses the
// `ZshProgram` AST path instead, but `bin_zcompile` (`-c`/`-a` modes)
// and any future `.zwc`-emit pipeline both call into these.
// =====================================================================

/// `ecstr(s)` helper — `ecadd(ecstrcode(s))`. Mirrors the C macro at
/// `Src/parse.c:482` used everywhere by the par_* emitters.
#[inline]
pub fn ecstr(s: &str) {
    let code = ecstrcode(s);
    ecadd(code);
}

/// Port of `condlex` function-pointer global from `Src/parse.c`. C
/// flips this between `zshlex` and `testlex` depending on whether
/// we're inside `[[ ]]` vs `/bin/test` builtin. zshrs has no
/// separate `testlex` yet, so this just defers to `zshlex`.
#[inline]
pub fn condlex() {
    zshlex();
}

/// `COND_SEP()` macro from `Src/parse.c:2433`. True when the current
/// token is a separator usable inside `[[ … ]]` (newline / semi /
/// `&`). C uses it to skip optional whitespace between cond terms.
#[inline]
pub fn COND_SEP() -> bool {
    matches!(tok(), NEWLIN | SEMI | AMPER)
}

/// Port of `copy_ecstr(Eccstr s, char *p)` from `Src/parse.c:537`.
/// Walks the in-build string-eccstr tree and writes each entry to
/// `p[s->aoffs..]`. The Rust port mirrors via the
/// `ECSTRS_REVERSE` HashMap (eccstr-tree replacement) and writes
/// into a `Vec<u8>` slice.
pub fn copy_ecstr(table: &std::collections::HashMap<u32, Vec<u8>>, p: &mut [u8]) {
    // c:537. Map key is the wordcode-encoded offs from `ecstrcode`
    // (`(byte_offset << 2) | token_bit`, parse.c:459); strip the
    // low 2 bits to get the real byte offset. Map value is the
    // metafied byte form — written verbatim to match C's strs
    // region byte-for-byte.
    for (&offs, bytes) in table.iter() {
        let off = (offs >> 2) as usize;
        let need = off + bytes.len() + 1;
        if need > p.len() {
            continue;
        }
        p[off..off + bytes.len()].copy_from_slice(bytes);
        p[off + bytes.len()] = 0;
    }
}

/// Port of `bld_eprog(int heap)` from `Src/parse.c:547`. Finalizes
/// the in-build `ECBUF`/`ECSTRS`/`ECNPATS` state into an `Eprog`.
/// Resets the build state so a new parse can start.
pub fn bld_eprog(heap: bool) -> crate::ported::zsh_h::eprog {
    // c:547

    // c:555 — emit WC_END opcode. `WCB_END` is `WC_END_DEFAULT` (0).
    ecadd(0);

    let ecused = ECUSED.with(|c| c.get()) as usize;
    let ecnpats = ECNPATS.with(|c| c.get()) as usize;
    let ecsoffs = ECSOFFS.with(|c| c.get()) as usize;

    let prog_bytes = ecused * 4; // c:559
    let len = (ecnpats * 4) + prog_bytes + ecsoffs;

    // Snapshot the wordcode buffer + string table.
    let prog_words: Vec<u32> = ECBUF.with(|c| c.borrow()[..ecused].to_vec());
    let mut strs_bytes = vec![0u8; ecsoffs];
    ECSTRS_REVERSE.with(|c| copy_ecstr(&c.borrow(), &mut strs_bytes));

    // c:566 — store strs as raw bytes via from_utf8_unchecked so
    // single-byte zsh markers (e.g. Dash 0x9b) survive intact.
    // `String::from_utf8_lossy` would replace them with U+FFFD
    // (`\xef\xbf\xbd`), breaking byte-for-byte parity with C's
    // strs region. SAFETY: downstream consumers of `eprog.strs`
    // index by byte offset (per the wordcode `(offs >> 2)` offset
    // encoding) and call `.as_bytes()` — they never iterate as
    // chars or rely on UTF-8 validity, so storing non-UTF-8 bytes
    // in a String is safe in practice. C zsh's strs is `char *`
    // with the same byte-not-char semantics.
    let strs_string = unsafe { String::from_utf8_unchecked(strs_bytes) };
    let ret = eprog {
        flags: if heap { EF_HEAP } else { EF_REAL }, // c:570
        len: len as i32,                             // c:559
        npats: ecnpats as i32,                       // c:561
        nref: if heap { -1 } else { 1 },             // c:562
        pats: Vec::new(),                            // c:563 dummy_patprog
        prog: prog_words,                            // c:565
        strs: Some(strs_string),
        shf: None,
        dump: None,
    };

    // c:577 — free ecbuf so next parse starts fresh.
    ECBUF.with(|c| c.borrow_mut().clear());
    ECLEN.with(|c| c.set(0));
    ECUSED.with(|c| c.set(0));
    ECNPATS.with(|c| c.set(0));
    ECSOFFS.with(|c| c.set(0));
    ECSTRS_INDEX.with(|c| c.borrow_mut().clear());
    ECSTRS_REVERSE.with(|c| c.borrow_mut().clear());
    ECSTRS_TREE.with(|t| *t.borrow_mut() = None);

    ret
}

/// Port of `parse_list(void)` from `Src/parse.c:697`. C-shape entry
/// point: drives `par_list` and finalizes via `bld_eprog`. Returns
/// `None` on syntax error.
pub fn parse_list() -> Option<eprog> {
    // c:697
    set_tok(ENDINPUT);
    init_parse();
    zshlex();
    let _ = par_list();
    if tok() != ENDINPUT {
        clear_hdocs();
        set_tok(LEXERR);
        yyerror("syntax error");
        return None;
    }
    Some(bld_eprog(true))
}

/// Port of `parse_cond(void)` from `Src/parse.c:722`. Only used by
/// `bin_test`/`bin_bracket` for `/bin/test`/`[` compat — the
/// `condlex` global must already point at `testlex` before entry.
pub fn parse_cond() -> Option<eprog> {
    // c:722
    init_parse();
    if par_cond().is_none() {
        clear_hdocs();
        return None;
    }
    Some(bld_eprog(true))
}

/// Port of `par_sublist2(int *cmplx)` from `Src/parse.c:869`.
/// Secondary-sublist arm: handles the `COPROC`/`Bang` prefix
/// in front of a pline. Returns the WC_SUBLIST flag word added.
pub fn par_sublist2(cmplx: &mut i32) -> Option<i32> {
    // c:869
    let mut f = 0i32;
    if tok() == COPROC {
        *cmplx = 1;
        f |= WC_SUBLIST_COPROC as i32;
        zshlex();
    } else if tok() == BANG_TOK {
        *cmplx = 1;
        f |= WC_SUBLIST_NOT as i32;
        zshlex();
    }
    // c:884 — `if (!par_pline(cmplx) && !f) return -1;`
    // The wordcode-emitter call chain (par_sublist_wordcode →
    // par_sublist2 → par_pipe_wordcode) needs the wordcode pipe
    // emitter, NOT the AST `par_pline`. The previous version called
    // `par_pline` which builds AST nodes and never writes to ECBUF —
    // the entire wordcode dispatch tree was broken below sublist
    // level (every script lexed to LIST + END only, since pipes /
    // commands / args never got emitted).
    let outer = cmplx_get();
    cmplx_set(false);
    let ok = par_pipe_wordcode();
    *cmplx |= cmplx_get() as i32;
    cmplx_set(outer | cmplx_get());
    if !ok && f == 0 {
        return None;
    }
    Some(f)
}

/// Port of `par_dinbrack(void)` from `Src/parse.c:1810`. Body
/// parser inside `[[ ... ]]` — calls `par_cond` to emit the
/// condition wordcode then advances past `]]`.
pub fn par_dinbrack() -> Option<()> {
    // c:1810
    set_incond(1); // c:1814
    set_incmdpos(false); // c:1815
    zshlex(); // c:1816
    let _ = par_cond(); // c:1817
    if tok() != DOUTBRACK {
        // c:1818
        yyerror("missing ]]");
        return None;
    }
    set_incond(0); // c:1820
    set_incmdpos(true); // c:1821
    zshlex(); // c:1822
    Some(())
}

/// Port of `par_cond(void)` from `Src/parse.c:2409`. Top-level cond
/// OR-chain — drives `par_cond_1` and stitches `||`-separated terms
/// with `WCB_COND(COND_OR, …)`. This is the missing top of the
/// wordcode cond chain: `par_cond_wordcode` (the par_dinbrack port)
/// must call into HERE so that `[[ a || b ]]` and friends land
/// real WC_COND opcodes in `ecbuf`. Without this, the wordcode
/// emitter for `[[ ... ]]` produced zero words and parity dropped
/// 148 words on `/etc/zshrc` alone.
pub fn par_cond_top() -> i32 {
    // c:2411 — `int p = ecused, r;`
    let p = ECUSED.with(|c| c.get()) as usize;
    let r = par_cond_1();
    while COND_SEP() {
        condlex();
    }
    if tok() == DBAR {
        // c:2417 — `condlex(); while (COND_SEP()) condlex();`
        condlex();
        while COND_SEP() {
            condlex();
        }
        // c:2420-2422 — `ecispace(p, 1); par_cond(); ecbuf[p] =
        // WCB_COND(COND_OR, ecused-1-p);`
        ecispace(p, 1);
        par_cond_top();
        let ecused = ECUSED.with(|c| c.get()) as usize;
        ECBUF.with(|c| {
            c.borrow_mut()[p] = WCB_COND(COND_OR as u32, (ecused - 1 - p) as u32);
        });
        return 1;
    }
    r
}

/// Port of `par_cond_1(void)` from `Src/parse.c:2434`. Parses one
/// `||`-separated cond expression. Emits `WCB_COND(COND_AND, …)`
/// when an `&&` is found and recurses.
pub fn par_cond_1() -> i32 {
    // c:2434

    let p = ECUSED.with(|c| c.get()) as usize;
    let r = par_cond_2();
    while COND_SEP() {
        condlex();
    }
    if tok() == DAMPER {
        condlex();
        while COND_SEP() {
            condlex();
        }
        ecispace(p, 1);
        par_cond_1();
        let ecused = ECUSED.with(|c| c.get()) as usize;
        ECBUF.with(|c| {
            c.borrow_mut()[p] = WCB_COND(COND_AND as u32, (ecused - 1 - p) as u32);
        });
        return 1;
    }
    r
}

/// Port of `static int check_cond(const char *input, const char *cond)`
/// from `Src/parse.c:2459`. True iff `input` is the two-char `-X`
/// form whose `X` matches `cond` — used by par_cond_2 to detect
/// `-a` / `-o` n-ary chain operators and by build_dump for `-k` /
/// `-z`. C: `return !IS_DASH(input[0]) ? 0 : !strcmp(input+1, cond);`.
fn check_cond(input: &str, cond: &str) -> bool {
    let mut chars = input.chars();
    match chars.next() {
        Some(c) if IS_DASH(c) => chars.as_str() == cond,
        _ => false,
    }
}

/// Port of `par_cond_2(void)` from `Src/parse.c:2476`. The heavy
/// cond-term parser: handles `! cond`, `(cond)`, unary `[ -X arg ]`,
/// binary `[ A op B ]`, and `[ A op1 B op2 C … ]` n-ary chains.
pub fn par_cond_2() -> i32 {
    // c:2476
    // `n_testargs` only applies in `testlex` mode (=== /bin/test
    // compat). zshrs has no testlex yet, so always 0.
    let n_testargs: i32 = 0;

    // c:2481 — handled inline; this Rust port skips the n_testargs
    // arm since zshrs invokes par_cond via [[ ... ]] only.

    while COND_SEP() {
        condlex();
    }
    if tok() == BANG_TOK {
        // c:2522 — `[[ ! cond ]]`
        condlex();
        ecadd(WCB_COND(COND_NOT as u32, 0));
        return par_cond_2();
    }
    if tok() == INPAR_TOK {
        // c:2533 — `[[ (cond) ]]`
        condlex();
        while COND_SEP() {
            condlex();
        }
        let r = par_cond();
        while COND_SEP() {
            condlex();
        }
        if tok() != OUTPAR_TOK {
            yyerror("missing )");
            return 0;
        }
        condlex();
        return r.map_or(0, |_| 1);
    }
    let s1 = tokstr().unwrap_or_default();
    // c:2549 — `dble = (s1 && IS_DASH(*s1) && (!n_testargs ||
    // strspn(s1+1, "abcd...") == 1) && !s1[2]);` — IS_DASH covers
    // BOTH `-` and Dash (`\u{9b}`). The raw tokstr inside `[[ ... ]]`
    // carries Dash as a marker byte, so `starts_with('-')` alone
    // matches only ASCII dashes and misses every `-z`, `-d`, `-r`
    // etc. — every such cond emitted the AST-only `condition
    // expected` error from par_cond_double. Use IS_DASH and count
    // chars (Dash is a single code point) instead of bytes.
    let s1_chars: Vec<char> = s1.chars().collect();
    let dble = !s1_chars.is_empty()
        && IS_DASH(s1_chars[0])
        && s1_chars.len() == 2
        && "abcdefghknoprstuvwxzLONGS".contains(s1_chars[1]);
    if tok() != STRING_LEX {
        if !s1.is_empty() && tok() != LEXERR && (!dble || n_testargs != 0) {
            // c:2486-2497 — `if (n_testargs == 1)` block: under
            // POSIXBUILTINS-off, `[ -t ]` rewrites to `[ -t 1 ]`
            // (ksh behavior). The C gate is `unset(POSIXBUILTINS)
            // && check_cond(s1, "t")`. zshrs's parser has
            // n_testargs=0 (no testlex), so this rewrite path is
            // unreachable from zshrs's [[ ]] / [ ] entry points;
            // wired here as a marker for parity. When testlex is
            // ported the call below activates.
            if n_testargs == 1 && unset(POSIXBUILTINS) && check_cond(&s1, "t") {
                condlex();
                return par_cond_double(&s1, "1");
            }
            // c:2557 — `[[ STRING ]]` re-interpreted as `[[ -n STRING ]]`.
            condlex();
            while COND_SEP() {
                condlex();
            }
            return par_cond_double("-n", &s1);
        }
        yyerror("condition expected");
        return 0;
    }
    condlex();
    while COND_SEP() {
        condlex();
    }
    if tok() == INANG_TOK || tok() == OUTANG_TOK {
        // c:2576 — `<` / `>` string compare.
        let xtok = tok();
        condlex();
        while COND_SEP() {
            condlex();
        }
        if tok() != STRING_LEX {
            yyerror("string expected");
            return 0;
        }
        let s3 = tokstr().unwrap_or_default();
        condlex();
        while COND_SEP() {
            condlex();
        }
        let op = if xtok == INANG_TOK {
            COND_STRLT
        } else {
            COND_STRGTR
        };
        ecadd(WCB_COND(op as u32, 0));
        ecstr(&s1);
        ecstr(&s3);
        return 1;
    }
    if tok() != STRING_LEX {
        // c:2592 — only one operand seen → `[ -n s1 ]`.
        if tok() != LEXERR {
            if !dble || n_testargs != 0 {
                return par_cond_double("-n", &s1);
            }
            return par_cond_multi(&s1, &[]);
        }
        yyerror("syntax error");
        return 0;
    }
    let s2 = tokstr().unwrap_or_default();
    set_incond(incond() + 1);
    condlex();
    while COND_SEP() {
        condlex();
    }
    set_incond(incond() - 1);
    if tok() == STRING_LEX && !dble {
        let s3 = tokstr().unwrap_or_default();
        condlex();
        while COND_SEP() {
            condlex();
        }
        if tok() == STRING_LEX {
            // c:2615 — n-ary `[ A op B C D ... ]`.
            let mut l: Vec<String> = vec![s2, s3];
            while tok() == STRING_LEX {
                l.push(tokstr().unwrap_or_default());
                condlex();
                while COND_SEP() {
                    condlex();
                }
            }
            return par_cond_multi(&s1, &l);
        }
        return par_cond_triple(&s1, &s2, &s3);
    }
    par_cond_double(&s1, &s2)
}

/// Port of `par_cond_double(char *a, char *b)` from `Src/parse.c:2626`.
/// Emits wordcode for unary cond `[ -X b ]` or modular `[ -mod b ]`.
pub fn par_cond_double(a: &str, b: &str) -> i32 {
    // c:2628 — `if (!IS_DASH(a[0]) || !a[1])` — char-based, since
    // Dash is a single code point (`\u{9b}`) and `a.len() < 2` on
    // BYTES would still pass for "-z" but fail for the marker form
    // `\u{9b}z` (2 bytes). Walk by chars.
    let ac: Vec<char> = a.chars().collect();
    if ac.is_empty() || !IS_DASH(ac[0]) || ac.len() < 2 {
        crate::ported::utils::zerr(&format!("parse error: condition expected: {}", a));
        return 1;
    }
    // c:2630 — `else if (!a[2] && strspn(a+1, "abcd...zhLONGS") == 1)`
    let unary_set = "abcdefgknoprstuvwxzhLONGS";
    if ac.len() == 2 && unary_set.contains(ac[1]) {
        // c:2631 — `ecadd(WCB_COND(a[1], 0));` uses the raw cond-op
        // letter byte as the opcode payload. Use the ASCII char's
        // code-point value directly — every letter in `unary_set`
        // fits in 7 bits.
        ecadd(WCB_COND(ac[1] as u32, 0));
        ecstr(b);
    } else {
        ecadd(WCB_COND(COND_MOD as u32, 1));
        ecstr(a);
        ecstr(b);
    }
    1
}

/// Port of `par_cond_triple(char *a, char *b, char *c)` from
/// `Src/parse.c:2659`. Emits wordcode for the binary forms
/// `[ A op B ]` — `=` / `==` / `!=` / `<` / `>` / `=~` / `-X`.
///
/// C does `(b[0] == Equals || b[0] == '=')` etc., matching BOTH the
/// raw ASCII operator char AND its tokenized marker form (Equals =
/// `\u{8d}`, Outang = `\u{8e}`, Inang = `\u{91}`, Tilde = `\u{96}`,
/// Bang = `\u{8b}`, Dash = `\u{9b}`). Inside `[[ ... ]]` the lexer
/// emits the marker bytes — comparing against literal-only `b"=="`
/// misses every cond op.
pub fn par_cond_triple(a: &str, b: &str, c: &str) -> i32 {
    // c:2659
    let bc: Vec<char> = b.chars().collect();
    let is_eq = |ch: char| ch == '=' || ch == Equals;
    let is_gt = |ch: char| ch == '>' || ch == Outang;
    let is_lt = |ch: char| ch == '<' || ch == Inang;
    let is_tilde = |ch: char| ch == '~' || ch == Tilde;
    let is_bang = |ch: char| ch == '!' || ch == Bang;

    // c:2663 — `(b[0] == Equals || b[0] == '=') && !b[1]` → `=` (single).
    if bc.len() == 1 && is_eq(bc[0]) {
        ecadd(WCB_COND(COND_STREQ as u32, 0));
        ecstr(a);
        ecstr(c);
        let np = ECNPATS.with(|cc| { let v = cc.get(); cc.set(v + 1); v }) as u32;
        ecadd(np);
        return 1;
    }
    // c:2668-2673 — `(t0 = b[0]=='>' || Outang) || b[0]=='<' || Inang`.
    if bc.len() == 1 && (is_gt(bc[0]) || is_lt(bc[0])) {
        let op = if is_gt(bc[0]) { COND_STRGTR } else { COND_STRLT };
        ecadd(WCB_COND(op as u32, 0));
        ecstr(a);
        ecstr(c);
        let np = ECNPATS.with(|cc| { let v = cc.get(); cc.set(v + 1); v }) as u32;
        ecadd(np);
        return 1;
    }
    // c:2674-2679 — `==` STRDEQ.
    if bc.len() == 2 && is_eq(bc[0]) && is_eq(bc[1]) {
        ecadd(WCB_COND(COND_STRDEQ as u32, 0));
        ecstr(a);
        ecstr(c);
        let np = ECNPATS.with(|cc| { let v = cc.get(); cc.set(v + 1); v }) as u32;
        ecadd(np);
        return 1;
    }
    // c:2680-2684 — `!=` STRNEQ.
    if bc.len() == 2 && is_bang(bc[0]) && is_eq(bc[1]) {
        ecadd(WCB_COND(COND_STRNEQ as u32, 0));
        ecstr(a);
        ecstr(c);
        let np = ECNPATS.with(|cc| { let v = cc.get(); cc.set(v + 1); v }) as u32;
        ecadd(np);
        return 1;
    }
    // c:2685-2691 — `=~` REGEX (no pattern slot — implicit COND_MODI).
    if bc.len() == 2 && is_eq(bc[0]) && is_tilde(bc[1]) {
        ecadd(WCB_COND(COND_REGEX as u32, 0));
        ecstr(a);
        ecstr(c);
        return 1;
    }
    // c:2692-2702 — `-OP` numeric-or-modular cond (e.g. `-eq`, `-nt`).
    if !bc.is_empty() && IS_DASH(bc[0]) {
        let rest: String = bc[1..].iter().collect();
        let t = get_cond_num(&rest);
        if t > -1 {
            ecadd(WCB_COND((t + COND_NT) as u32, 0));
            ecstr(a);
            ecstr(c);
            return 1;
        }
        ecadd(WCB_COND(COND_MODI as u32, 0));
        ecstr(b);
        ecstr(a);
        ecstr(c);
        return 1;
    }
    // c:2703-2707 — `-mod A B C` modular cond on `a`.
    let ac: Vec<char> = a.chars().collect();
    if !ac.is_empty() && IS_DASH(ac[0]) && ac.len() > 1 {
        ecadd(WCB_COND(COND_MOD as u32, 2));
        ecstr(a);
        ecstr(b);
        ecstr(c);
        return 1;
    }
    crate::ported::utils::zerr(&format!("condition expected: {}", b));
    1
}

/// Port of `par_cond_multi(char *a, LinkList l)` from `Src/parse.c:2716`.
/// Emits wordcode for `[ -OP A B C … ]` n-ary cond (alternation).
pub fn par_cond_multi(a: &str, l: &[String]) -> i32 {
    // c:2716 — `if (!IS_DASH(a[0]) || !a[1])`; same Dash/`-` dual
    // matching as par_cond_double, char-walked because Dash is a
    // single code point.
    let ac: Vec<char> = a.chars().collect();
    if ac.is_empty() || !IS_DASH(ac[0]) || ac.len() < 2 {
        crate::ported::utils::zerr(&format!("condition expected: {}", a));
        return 1;
    }
    ecadd(WCB_COND(COND_MOD as u32, l.len() as u32));
    ecstr(a);
    for item in l {
        ecstr(item);
    }
    1
}

/// Port of `cur_add_func(char *nam, Shfunc shf, LinkList names, LinkList progs, int *hlen, int *tlen, int what)`
/// from `Src/parse.c:3489`. Adds a shfunc to the in-build dump
/// progs+names lists. Stub: `Eprog` for the function body isn't
/// yet wired through `shfunc.funcdef` to be serializable here.
pub fn cur_add_func(
    nam: &str, // c:3489
    shf_name: &str,
    shf_flags: i32,
    names: &mut Vec<String>,
    progs: &mut Vec<wcfunc>,
    hlen: &mut i32,
    tlen: &mut i32,
    what: i32,
) -> i32 {
    let is_undef = (shf_flags as u32 & PM_UNDEFINED) != 0;
    if is_undef {
        if (what & 2) == 0 {
            // c:3498
            zwarnnam(nam, &format!("function is not loaded: {}", shf_name));
            return 1;
        }
        // c:3503 — would call `getfpfunc` to load body for dump.
        zwarnnam(nam, &format!("can't load function: {}", shf_name));
        return 1;
    } else if (what & 1) == 0 {
        zwarnnam(nam, &format!("function is already loaded: {}", shf_name)); // c:3514
        return 1;
    }
    // c:3517 — would `dupeprog(shf->funcdef)`. Stub: empty body.
    let wcf = wcfunc {
        name: shf_name.to_string(),
        flags: FDHF_ZSHLOAD,
        body: Vec::new(),
    };
    progs.push(wcf);
    names.push(shf_name.to_string());

    // c:3526 — bump hlen / tlen.
    let name_words = (shf_name.len() as i32 + 4) / 4;
    *hlen += (FDHEAD_WORDS as i32) + name_words;
    *tlen += 0; // body is empty in stub; real path adds prog->len in words.

    0
}

/// Port of `write_dump(int dfd, LinkList progs, int map, int hlen, int tlen)`
/// from `Src/parse.c:3334`. Writes the prelude + header records +
/// body wordcode bytes to the dump file descriptor.
///
/// Two passes: first native-byte-order (`FD_MAGIC`), then opposite-
/// byte-order (`FD_OMAGIC`) so big-endian readers can mmap the
/// same file. Bodies are byte-swapped via `fdswap` on the second pass.
pub fn write_dump(
    dfd: &mut std::fs::File, // c:3334
    progs: &[wcfunc],
    mut map: i32,
    hlen: i32,
    tlen: i32,
) -> std::io::Result<()> {
    if map == 1 && (tlen as usize) >= FD_MINMAP {
        // c:3344
        map = 1;
    } else if map == 1 {
        map = 0;
    }

    let mut other = 0u32; // c:3338
    let ohlen = hlen;
    let mut cur_hlen = hlen;

    loop {
        cur_hlen = ohlen;
        // c:3347 — build the prelude.
        let mut pre = vec![0u32; FD_PRELEN];
        pre[0] = if other != 0 { FD_OMAGIC } else { FD_MAGIC }; // c:3350
        let flags = (if map != 0 { FDF_MAP } else { 0 }) | other;
        fdsetflags(&mut pre, flags as u8); // c:3351
        fdsetother(&mut pre, tlen as u32); // c:3352
                                           // c:3353 — copy ZSH_VERSION C-string into pre[2..].
        let ver = b"5.9";
        for (i, &b) in ver.iter().enumerate() {
            let word = 2 + i / 4;
            let shift = (i % 4) * 8;
            pre[word] |= (b as u32) << shift;
        }
        // Write prelude.
        for w in &pre {
            dfd.write_all(&w.to_le_bytes())?;
        }
        // c:3356 — per-fn header records.
        for wcf in progs {
            let n = &wcf.name;
            let prog = &wcf.body;
            let mut head = fdhead {
                start: cur_hlen as u32,                                     // c:3360
                len: (prog.len() * 4) as u32,                               // c:3363
                npats: 0, // c:3364 (npats not tracked yet)
                strs: 0,  // c:3365
                hlen: ((FDHEAD_WORDS as u32) + ((n.len() as u32 + 4) / 4)), // c:3366
                flags: 0,
            };
            cur_hlen += prog.len() as i32; // c:3361
                                           // c:3368 — name tail offset from path basename.
            let tail = n.rfind('/').map(|p| p + 1).unwrap_or(0);
            head.flags = fdhbldflags(wcf.flags, tail as u32); // c:3372
                                                              // c:3373 — opposite-byte-order swap on second pass.
            let mut head_words: Vec<u32> = vec![
                head.start, head.len, head.npats, head.strs, head.hlen, head.flags,
            ];
            if other != 0 {
                fdswap(&mut head_words);
            }
            for w in &head_words {
                dfd.write_all(&w.to_le_bytes())?;
            }
            // c:3376 — write the name + NUL + pad-to-4.
            dfd.write_all(n.as_bytes())?;
            dfd.write_all(&[0u8])?;
            let pad = (4 - ((n.len() + 1) & 3)) & 3;
            if pad > 0 {
                dfd.write_all(&vec![0u8; pad])?;
            }
        }
        // c:3381 — per-fn body words.
        for wcf in progs {
            let mut body = wcf.body.clone();
            if other != 0 {
                fdswap(&mut body);
            }
            for w in &body {
                dfd.write_all(&w.to_le_bytes())?;
            }
        }
        if other != 0 {
            // c:3389
            break;
        }
        other = FDF_OTHER; // c:3391
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::utils::{errflag, ERRFLAG_ERROR};
    use std::fs;
    use std::path::Path;
    use std::sync::atomic::Ordering;
    use std::sync::mpsc;
    use std::thread;
    use std::time::{Duration, Instant};

    /// Test helper. Mirrors zsh's `errflag` save/clear/check pattern
    /// around a parse — see `Src/init.c:loop` which clears errflag
    /// before parse_event() and tests it after. Returns `Err` if the
    /// parse set `ERRFLAG_ERROR`; otherwise `Ok(program)`.
    fn parse(input: &str) -> Result<ZshProgram, String> {
        let saved = errflag.load(Ordering::Relaxed);
        errflag.fetch_and(!ERRFLAG_ERROR, Ordering::Relaxed);
        crate::ported::parse::parse_init(input);
        let prog = crate::ported::parse::parse();
        let had_err = (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0;
        // Restore prior error bits; don't carry our new error into the
        // outer test runner.
        errflag.store(saved, Ordering::Relaxed);
        if had_err {
            Err("parse error".to_string())
        } else {
            Ok(prog)
        }
    }

    #[test]
    fn test_simple_command() {
        let prog = parse("echo hello world").unwrap();
        assert_eq!(prog.lists.len(), 1);
        match &prog.lists[0].sublist.pipe.cmd {
            ZshCommand::Simple(s) => {
                assert_eq!(s.words, vec!["echo", "hello", "world"]);
            }
            _ => panic!("expected simple command"),
        }
    }

    #[test]
    fn test_pipeline() {
        let prog = parse("ls | grep foo | wc -l").unwrap();
        assert_eq!(prog.lists.len(), 1);

        let pipe = &prog.lists[0].sublist.pipe;
        assert!(pipe.next.is_some());

        let pipe2 = pipe.next.as_ref().unwrap();
        assert!(pipe2.next.is_some());
    }

    #[test]
    fn test_and_or() {
        let prog = parse("cmd1 && cmd2 || cmd3").unwrap();
        let sublist = &prog.lists[0].sublist;

        assert!(sublist.next.is_some());
        let (op, _) = sublist.next.as_ref().unwrap();
        assert_eq!(*op, SublistOp::And);
    }

    #[test]
    fn test_if_then() {
        let prog = parse("if test -f foo; then echo yes; fi").unwrap();
        match &prog.lists[0].sublist.pipe.cmd {
            ZshCommand::If(_) => {}
            _ => panic!("expected if command"),
        }
    }

    #[test]
    fn test_for_loop() {
        let prog = parse("for i in a b c; do echo $i; done").unwrap();
        match &prog.lists[0].sublist.pipe.cmd {
            ZshCommand::For(f) => {
                assert_eq!(f.var, "i");
                match &f.list {
                    ForList::Words(w) => assert_eq!(w, &vec!["a", "b", "c"]),
                    _ => panic!("expected word list"),
                }
            }
            _ => panic!("expected for command"),
        }
    }

    #[test]
    fn test_case() {
        let prog = parse("case $x in a) echo a;; b) echo b;; esac").unwrap();
        match &prog.lists[0].sublist.pipe.cmd {
            ZshCommand::Case(c) => {
                assert_eq!(c.arms.len(), 2);
            }
            _ => panic!("expected case command"),
        }
    }

    #[test]
    fn test_function() {
        // First test just parsing "function foo" to see what happens
        let prog = parse("function foo { }").unwrap();
        match &prog.lists[0].sublist.pipe.cmd {
            ZshCommand::FuncDef(f) => {
                assert_eq!(f.names, vec!["foo"]);
            }
            _ => panic!(
                "expected function, got {:?}",
                prog.lists[0].sublist.pipe.cmd
            ),
        }
    }

    #[test]
    fn test_redirection() {
        let prog = parse("echo hello > file.txt").unwrap();
        match &prog.lists[0].sublist.pipe.cmd {
            ZshCommand::Simple(s) => {
                assert_eq!(s.redirs.len(), 1);
                assert_eq!(s.redirs[0].rtype, REDIR_WRITE);
            }
            _ => panic!("expected simple command"),
        }
    }

    #[test]
    fn test_assignment() {
        let prog = parse("FOO=bar echo $FOO").unwrap();
        match &prog.lists[0].sublist.pipe.cmd {
            ZshCommand::Simple(s) => {
                assert_eq!(s.assigns.len(), 1);
                assert_eq!(s.assigns[0].name, "FOO");
            }
            _ => panic!("expected simple command"),
        }
    }

    #[test]
    fn test_parse_completion_function() {
        let input = r#"_2to3_fixes() {
  local -a fixes
  fixes=( ${${(M)${(f)"$(2to3 --list-fixes 2>/dev/null)"}:#*}//[[:space:]]/} )
  (( ${#fixes} )) && _describe -t fixes 'fix' fixes
}"#;
        let result = parse(input);
        assert!(
            result.is_ok(),
            "Failed to parse completion function: {:?}",
            result.err()
        );
        let prog = result.unwrap();
        assert!(
            !prog.lists.is_empty(),
            "Expected at least one list in program"
        );
    }

    #[test]
    fn test_parse_array_with_complex_elements() {
        let input = r#"arguments=(
  '(- * :)'{-h,--help}'[show this help message and exit]'
  {-d,--doctests_only}'[fix up doctests only]'
  '*:filename:_files'
)"#;
        let result = parse(input);
        assert!(
            result.is_ok(),
            "Failed to parse array assignment: {:?}",
            result.err()
        );
    }

    #[test]
    fn test_parse_full_completion_file() {
        let input = r##"#compdef 2to3

# zsh completions for '2to3'

_2to3_fixes() {
  local -a fixes
  fixes=( ${${(M)${(f)"$(2to3 --list-fixes 2>/dev/null)"}:#*}//[[:space:]]/} )
  (( ${#fixes} )) && _describe -t fixes 'fix' fixes
}

local -a arguments

arguments=(
  '(- * :)'{-h,--help}'[show this help message and exit]'
  {-d,--doctests_only}'[fix up doctests only]'
  {-f,--fix}'[each FIX specifies a transformation; default: all]:fix name:_2to3_fixes'
  {-j,--processes}'[run 2to3 concurrently]:number: '
  {-x,--nofix}'[prevent a transformation from being run]:fix name:_2to3_fixes'
  {-l,--list-fixes}'[list available transformations]'
  {-p,--print-function}'[modify the grammar so that print() is a function]'
  {-v,--verbose}'[more verbose logging]'
  '--no-diffs[do not show diffs of the refactoring]'
  {-w,--write}'[write back modified files]'
  {-n,--nobackups}'[do not write backups for modified files]'
  {-o,--output-dir}'[put output files in this directory instead of overwriting]:directory:_directories'
  {-W,--write-unchanged-files}'[also write files even if no changes were required]'
  '--add-suffix[append this string to all output filenames]:suffix: '
  '*:filename:_files'
)

_arguments -s -S $arguments
"##;
        let result = parse(input);
        assert!(
            result.is_ok(),
            "Failed to parse full completion file: {:?}",
            result.err()
        );
        let prog = result.unwrap();
        // Should have parsed successfully with at least one statement
        assert!(!prog.lists.is_empty(), "Expected at least one list");
    }

    #[test]
    fn test_parse_logs_sh() {
        let input = r#"#!/usr/bin/env bash
shopt -s globstar

if [[ $(uname) == Darwin ]]; then
    tail -f /var/log/**/*.log /var/log/**/*.out | lolcat
else
    if [[ $ZPWR_DISTRO_NAME == raspbian ]]; then
        tail -f /var/log/**/*.log | lolcat
    else
        printf "Unsupported...\n" >&2
    fi
fi
"#;
        let result = parse(input);
        assert!(
            result.is_ok(),
            "Failed to parse logs.sh: {:?}",
            result.err()
        );
    }

    #[test]
    fn test_parse_case_with_glob() {
        let input = r#"case "$ZPWR_OS_TYPE" in
    darwin*)  open_cmd='open'
      ;;
    cygwin*)  open_cmd='cygstart'
      ;;
    linux*)
        open_cmd='xdg-open'
      ;;
esac"#;
        let result = parse(input);
        assert!(
            result.is_ok(),
            "Failed to parse case with glob: {:?}",
            result.err()
        );
    }

    #[test]
    fn test_parse_case_with_nested_if() {
        // Test case with nested if and glob patterns
        let input = r##"function zpwrGetOpenCommand(){
    local open_cmd
    case "$ZPWR_OS_TYPE" in
        darwin*)  open_cmd='open' ;;
        cygwin*)  open_cmd='cygstart' ;;
        linux*)
            if [[ "$_zpwr_uname_r" != *icrosoft* ]];then
                open_cmd='nohup xdg-open'
            fi
            ;;
    esac
}"##;
        let result = parse(input);
        assert!(result.is_ok(), "Failed to parse: {:?}", result.err());
    }

    #[test]
    fn test_parse_zpwr_scripts() {
        let scripts_dir = Path::new("/Users/wizard/.zpwr/scripts");
        if !scripts_dir.exists() {
            eprintln!("Skipping test: scripts directory not found");
            return;
        }

        let mut total = 0;
        let mut passed = 0;
        let mut failed_files = Vec::new();
        let mut timeout_files = Vec::new();

        for ext in &["sh", "zsh"] {
            let pattern = scripts_dir.join(format!("*.{}", ext));
            if let Ok(entries) = glob::glob(pattern.to_str().unwrap()) {
                for entry in entries.flatten() {
                    total += 1;
                    let file_path = entry.display().to_string();
                    let content = match fs::read_to_string(&entry) {
                        Ok(c) => c,
                        Err(e) => {
                            failed_files.push((file_path, format!("read error: {}", e)));
                            continue;
                        }
                    };

                    // Parse with timeout
                    let content_clone = content.clone();
                    let (tx, rx) = mpsc::channel();
                    let handle = thread::spawn(move || {
                        let result = parse(&content_clone);
                        let _ = tx.send(result);
                    });

                    match rx.recv_timeout(Duration::from_secs(2)) {
                        Ok(Ok(_)) => passed += 1,
                        Ok(Err(err)) => {
                            failed_files.push((file_path, err));
                        }
                        Err(_) => {
                            timeout_files.push(file_path);
                            // Thread will be abandoned
                        }
                    }
                }
            }
        }

        eprintln!("\n=== ZPWR Scripts Parse Results ===");
        eprintln!("Passed: {}/{}", passed, total);

        if !timeout_files.is_empty() {
            eprintln!("\nTimeout files (>2s):");
            for file in &timeout_files {
                eprintln!("  {}", file);
            }
        }

        if !failed_files.is_empty() {
            eprintln!("\nFailed files:");
            for (file, err) in &failed_files {
                eprintln!("  {} - {}", file, err);
            }
        }

        // Allow some failures initially, but track progress
        let pass_rate = if total > 0 {
            (passed as f64 / total as f64) * 100.0
        } else {
            0.0
        };
        eprintln!("Pass rate: {:.1}%", pass_rate);

        // Require at least 50% pass rate for now
        assert!(pass_rate >= 50.0, "Pass rate too low: {:.1}%", pass_rate);
    }

    #[test]
    #[ignore] // Uses threads that can't be killed on timeout; use integration test instead
    fn test_parse_zsh_stdlib_functions() {
        let functions_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("test_data/zsh_functions");
        if !functions_dir.exists() {
            eprintln!(
                "Skipping test: zsh_functions directory not found at {:?}",
                functions_dir
            );
            return;
        }

        let mut total = 0;
        let mut passed = 0;
        let mut failed_files = Vec::new();
        let mut timeout_files = Vec::new();

        if let Ok(entries) = fs::read_dir(&functions_dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                if !path.is_file() {
                    continue;
                }

                total += 1;
                let file_path = path.display().to_string();
                let content = match fs::read_to_string(&path) {
                    Ok(c) => c,
                    Err(e) => {
                        failed_files.push((file_path, format!("read error: {}", e)));
                        continue;
                    }
                };

                // Parse with timeout
                let content_clone = content.clone();
                let (tx, rx) = mpsc::channel();
                thread::spawn(move || {
                    let result = parse(&content_clone);
                    let _ = tx.send(result);
                });

                match rx.recv_timeout(Duration::from_secs(2)) {
                    Ok(Ok(_)) => passed += 1,
                    Ok(Err(err)) => {
                        failed_files.push((file_path, err));
                    }
                    Err(_) => {
                        timeout_files.push(file_path);
                    }
                }
            }
        }

        eprintln!("\n=== Zsh Stdlib Functions Parse Results ===");
        eprintln!("Passed: {}/{}", passed, total);

        if !timeout_files.is_empty() {
            eprintln!("\nTimeout files (>2s): {}", timeout_files.len());
            for file in timeout_files.iter().take(10) {
                eprintln!("  {}", file);
            }
            if timeout_files.len() > 10 {
                eprintln!("  ... and {} more", timeout_files.len() - 10);
            }
        }

        if !failed_files.is_empty() {
            eprintln!("\nFailed files: {}", failed_files.len());
            for (file, err) in failed_files.iter().take(20) {
                let filename = Path::new(file)
                    .file_name()
                    .unwrap_or_default()
                    .to_string_lossy();
                eprintln!("  {} - {}", filename, err);
            }
            if failed_files.len() > 20 {
                eprintln!("  ... and {} more", failed_files.len() - 20);
            }
        }

        let pass_rate = if total > 0 {
            (passed as f64 / total as f64) * 100.0
        } else {
            0.0
        };
        eprintln!("Pass rate: {:.1}%", pass_rate);

        // Require at least 50% pass rate
        assert!(pass_rate >= 50.0, "Pass rate too low: {:.1}%", pass_rate);
    }
}