zshrs 0.11.29

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
//! Shell executor state for zshrs.
//!
//! ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
//! !!! LAST-RESORT FILE — NOT FOR NEW LOGIC !!!
//!
//! This file holds the `ShellExecutor` runtime state struct + VM-adjacent
//! helpers. It is **not** the place to add zsh logic — every line here that
//! does real shell work is a tax we pay because zshrs uses fusevm bytecode
//! instead of C zsh's wordcode walker.
//!
//! **Before adding code to this file, STOP and ask:**
//!
//!   1. Does the C source have a fn that does this? (Check `src/zsh/Src/*.c`)
//!      → Port it into `src/ported/<file>.rs` with line-by-line citations.
//!        Then call the canonical fn from here.
//!
//!   2. Does `src/ported/` already have a port?
//!      → Call it directly. Don't reimplement.
//!
//!   3. Is this purely a Rust-only state-struct accessor (getter/setter on
//!      ShellExecutor fields, VM init plumbing, executor-context guards)?
//!      → OK to put it here. Mark it `WARNING: RUST-ONLY HELPER` per memory
//!        `feedback_rust_only_helpers_need_warning`.
//!
//! **NEVER:** reinvent paramsubst/expansion/glob/typeset/redirect/scope
//! management here. Every one of those has a canonical port in `src/ported/`.
//! When a bridge-side fn grows past ~30 lines of shell logic, that's a
//! signal the work belongs in `src/ported/` — port it, don't inline.
//!
//! This file should be SHRINKING over time. Every PR that adds lines here
//! should justify it; every PR that moves lines OUT to `src/ported/` is
//! aligned with the project direction.
//!
//! See also: memory `feedback_no_shortcuts_in_porting`, `feedback_true_port_pattern`,
//! `feedback_no_shellexecutor_in_ported` (the inverse direction).
//! ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
//!
//! **Not a port of Src/exec.c.** C zsh runs compiled programs on the native
//! **wordcode walker** in `Src/exec.c` (`execlist` / `execpline` / `execcmd`).
//! zshrs uses fusevm bytecode instead; the bridge lives in `src/fusevm_bridge.rs`.
//! This file holds:
//! - `ShellExecutor` — the runtime state struct that the VM and
//!   every ported builtin/utility threads through
//! - VM-adjacent helpers that read/write that state
//!
//! Path-wise this file lives at the crate root (`src/vm_helper`) rather
//! than in `src/ported/` because nothing here corresponds 1:1 to a
//! `Src/*.c` source file. `crate::ported::exec` is kept as a
//! re-export alias so existing call-sites continue to compile.

use crate::compsys::cache::CompsysCache;
use crate::compsys::CompInitResult;
use crate::history::HistoryEngine;
use crate::options::ZSH_OPTIONS_SET;
use crate::ported::builtin::{BREAKS, CONTFLAG};
use crate::ported::math::mathevali;
use crate::ported::modules::parameter::*;
use crate::ported::subst::singsub;
use crate::ported::utils::{errflag, ERRFLAG_ERROR};
use crate::ported::zsh_h::PM_UNDEFINED;
use crate::ported::zsh_h::WC_SIMPLE;
use crate::ported::zsh_h::{options, MAX_OPS};
use crate::ported::zsh_h::{PM_ARRAY, PM_HASHED, PM_INTEGER, PM_READONLY};
use parking_lot::Mutex;
use std::collections::HashSet;
use std::ffi::CStr;
use std::ffi::CString;
use std::fs;
use std::io::Read;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::FileTypeExt;
use std::os::unix::fs::PermissionsExt;
use std::os::unix::io::FromRawFd;
use std::sync::atomic::AtomicI32;
use std::sync::atomic::Ordering;
use std::time::{SystemTime, UNIX_EPOCH};
use walkdir::WalkDir;

// Backward-compat re-exports for free ported recently relocated to their
// canonical-C-file Rust modules. Existing call-sites in this file (and
// elsewhere) still reference these unqualified.
#[allow(unused_imports)]
pub(crate) use crate::func_body_fmt::FuncBodyFmt;
#[allow(unused_imports)]
pub(crate) use crate::ported::glob::expand_glob_alternation;
#[allow(unused_imports)]
pub(crate) use crate::ported::hist::bufferwords as bufferwords_z_tuple;
#[allow(unused_imports)]
pub(crate) use crate::ported::math::{parse_assign, parse_compound, parse_pre_inc};
#[allow(unused_imports)]
pub use crate::ported::params::convbase as format_int_in_base;
pub use crate::ported::params::convbase_underscore;
#[allow(unused_imports)]
pub(crate) use crate::ported::params::getarrvalue;
#[allow(unused_imports)]
pub(crate) use crate::ported::utils::base64_decode;
#[allow(unused_imports)]
pub(crate) use crate::ported::utils::{ispwd, printprompt4, quotedzputs};

pub(crate) use crate::intercepts::intercept_matches;
/// AOP advice type — before, after, or around.
pub use crate::intercepts::{AdviceKind, Intercept};

/// Result from background compinit thread.
pub use crate::compinit_bg::CompInitBgResult;
use std::io::Write;
use std::sync::LazyLock;

/// State snapshot for plugin delta computation.
pub(crate) use crate::plugin_cache::PluginSnapshot;

/// Cached compiled regexes for hot paths
pub(crate) static REGEX_CACHE: LazyLock<Mutex<HashMap<String, Regex>>> =
    LazyLock::new(|| Mutex::new(HashMap::with_capacity(64)));

// fusevm VM bridge (extension; not a port of Src/exec.c) lives in
// src/fusevm_bridge.rs. Re-exports below let the rest of the codebase
// reference symbols as `crate::ported::exec::X`.
pub(crate) use crate::fusevm_bridge::ExecutorContext;
pub use crate::fusevm_bridge::*;

/// `ZSH_VERSION` / `ZSH_PATCHLEVEL` / `ZSH_VERSION_DATE` consts
/// generated by `build.rs` from `src/zsh/Config/version.mk`. Use
/// `zsh_version::ZSH_VERSION` etc. at call sites so version bumps
/// pick up automatically.
pub mod zsh_version {
    include!(concat!(env!("OUT_DIR"), "/zsh_version.rs"));
}

/// Match an intercept pattern against a command name or full command string.
/// Supports: exact match, glob ("git *", "_*", "*"), or "all".

/// O(1) builtin-name lookup set derived from the canonical
/// `BUILTINS` table (`src/ported/builtin.rs:122`, the 1:1 port of
/// `static struct builtin builtins[]` at `Src/builtin.c:40-137`).
/// Earlier incarnation hardcoded a separate 130-entry list which
/// drifted whenever new builtins landed in the canonical table — and
/// shadowed the `fusevm::shell_builtins::BUILTIN_SET` u16 opcode
/// constant. Renaming to `BUILTIN_NAMES` removes the shadow; the
/// initialiser walks `BUILTINS` so the set stays in sync.
///
/// The hardcoded entries inside `LazyLock::new` below are kept as
/// the union of: (1) names from `BUILTINS` (walked at first access),
/// (2) zshrs daemon-side builtins from `ZSHRS_BUILTIN_NAMES`. Both
/// arms run once at static init.
pub(crate) static BUILTIN_NAMES: LazyLock<HashSet<String>> = LazyLock::new(|| {
    let mut s: HashSet<String> = HashSet::new();
    // Walk the canonical `BUILTINS` table — the 1:1 port of
    // `static struct builtin builtins[]` at `Src/builtin.c:40-137`
    // (ported at `src/ported/builtin.rs:122`). Every name in there is
    // a real zsh builtin; the set stays in sync as new ports land.
    for b in crate::ported::builtin::BUILTINS.iter() {
        s.insert(b.node.nam.clone());
    }
    // Daemon-side (zshrs-specific extensions).
    for &n in crate::daemon::builtins::ZSHRS_BUILTIN_NAMES.iter() {
        s.insert(n.to_string());
    }
    s
});

use crate::exec_jobs::{JobState, JobTable};
use crate::parse::{Redirect, RedirectOp, ShellCommand, ShellWord, VarModifier, ZshParamFlag};
use indexmap::IndexMap;
use std::collections::HashMap;
use std::env;
use std::fs::{File, OpenOptions};
use std::io;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};

// Re-exports for call-sites that reference `crate::ported::exec::<Name>`.
pub use crate::bash_complete::CompSpec;
pub use crate::ported::builtin::AutoloadFlags;
pub use crate::ported::modules::zutil::zstyle_entry;

/// Snapshot of subshell-isolated state. Captured at `(` entry, restored at
/// `)` exit. zsh subshell semantics: assignments inside `(…)` don't leak to
/// the outer scope — and that includes `export`. zsh forks a child for the
/// subshell so the child's env::set_var dies with the child; without a fork
/// (zshrs runs subshells in-process for perf), we snapshot+restore the OS
/// env table around the subshell. Otherwise `(export y=v)` would leak `y`
/// to the parent shell, breaking every script that uses a subshell to
/// scope an env override.
/// Snapshot of mutable executor state across a subshell
/// boundary.
/// Port of the `entersubsh()` save/restore Src/exec.c does at
/// line 1084 — captures everything that must be replaced when a
/// `(...)` group fires.
pub struct SubshellSnapshot {
    /// Snapshot of `paramtab` (the C-canonical parameter store) at
    /// subshell entry. Step 1 of the unification mirrors writes to
    /// paramtab, so subshell-scoped assignments now show up there
    /// too — without this snapshot, restoring only `variables` /
    /// `arrays` / `assoc_arrays` leaks the subshell's writes to the
    /// parent via paramtab (e.g. `x=outer; (x=inner); echo $x` returned
    /// `inner` because paramsubst reads through paramtab).
    pub paramtab: HashMap<String, crate::ported::zsh_h::Param>,
    /// `paramtab_hashed_storage` field.
    pub paramtab_hashed_storage: HashMap<String, IndexMap<String, String>>,
    /// `positional_params` field.
    pub positional_params: Vec<String>,
    /// `env_vars` field.
    pub env_vars: HashMap<String, String>,
    /// Process working directory at subshell entry. `cd` inside the
    /// subshell shouldn't leak to the parent; we restore on End.
    pub cwd: Option<PathBuf>,
    /// File-creation mask at subshell entry. zsh forks for `(...)` so
    /// `umask` set inside dies with the child; we run subshells in
    /// process so we must restore the mask on End. Otherwise
    /// `umask 022; (umask 077); umask` shows 077 in the parent.
    pub umask: u32,
    /// Parent's traps at subshell entry. zsh's `(trap "echo X" EXIT;
    /// true)` runs the trap when the subshell exits — BEFORE the parent
    /// continues. Without this snapshot, the trap inherited from parent
    /// would fire, OR a trap set inside the subshell would leak to the
    /// parent's process exit. Restored on subshell_end after the
    /// subshell's own EXIT trap (if any) has fired. Stores a snapshot
    /// of `crate::ported::builtin::traps_table()` (canonical).
    pub traps: HashMap<String, String>,
    /// Parent's shell options at subshell entry. `(set -e)` /
    /// `(setopt extendedglob)` mustn't leak; zsh forks the subshell
    /// so child options die with the child. We run in-process, so we
    /// must restore the option store on subshell_end.
    pub opts: HashMap<String, bool>,
    /// Parent's alias entries at subshell entry. zsh forks for
    /// `(...)` so `(alias x=y)` inside a subshell dies with the
    /// child and doesn't leak to the parent. zshrs runs subshells
    /// in-process, so we must restore the alias table on
    /// subshell_end. Bug #209 in docs/BUGS.md. Stored as a flat
    /// Vec<(name, text)> snapshot — the underlying alias_table holds
    /// an IndexMap<String, alias> but `alias` carries hashnode
    /// metadata we don't need to round-trip; only name + text are
    /// observable via `alias NAME` lookup.
    pub aliases: Vec<(String, String)>,
    /// Parent's shell-function table at subshell entry. C zsh's
    /// `entersubsh` (`Src/exec.c`) forks before running the
    /// subshell body so `(f() { ... })` defining a function dies
    /// with the child and never leaks to the parent. zshrs runs
    /// subshells in-process, so we must clone `shfunctab` on entry
    /// and restore on exit. Bug #208 in docs/BUGS.md. Stored as
    /// the full `HashMap<String, Box<shfunc>>` clone — shfunc is
    /// `Clone` and the table snapshot is bounded by the user's
    /// declared function set.
    pub shfuncs:
        std::collections::HashMap<String, Box<crate::ported::zsh_h::shfunc>>,
    /// Parent's compiled-function chunks at subshell entry. Companion
    /// to `shfuncs` above — `ShellExecutor.functions_compiled` is the
    /// runtime dispatch table that `Op::CallFunction` reads through;
    /// without restoring it, a subshell `(g() { override; })` leaves
    /// the override bytecode chunk in place so the parent's
    /// `g` call still runs the override after `subshell_end`
    /// restored shfunctab. Bug #208 in docs/BUGS.md.
    pub functions_compiled: HashMap<String, fusevm::Chunk>,
    /// Parent's function source map at subshell entry. Companion to
    /// `functions_compiled` so `typeset -f` / `whence` show the
    /// parent's source after subshell exit, not the subshell's
    /// overridden body. Bug #208 in docs/BUGS.md.
    pub function_source: HashMap<String, String>,
    /// Parent's modulestab `modules` map at subshell entry. zsh forks
    /// for `(...)` so a `(zmodload zsh/X)` inside the subshell sets
    /// MOD_INIT_B on the child's modulestab; when the child exits the
    /// flag dies with it and the parent's modulestab is untouched.
    /// zshrs runs subshells in-process, so a subshell `zmodload`
    /// would otherwise flip the parent's `${modules[zsh/X]}` from
    /// unset to "loaded". Snapshot here and restore on subshell_end.
    /// Bug #210 in docs/BUGS.md. Stored as `(name → flags)`
    /// since `module` struct doesn't derive Clone (LinkList/
    /// Linkedmod) — and the only thing `zmodload` mutates that
    /// affects introspection is the flags bitmask (MOD_INIT_B
    /// for loaded, MOD_UNLOAD for unloaded).
    pub modules: HashMap<String, i32>,
}

#[allow(unused_imports)]
pub(crate) use crate::ported::pattern::{
    extract_numeric_ranges, numeric_range_contains, numeric_ranges_to_star,
};

/// Top-level shell executor state.
/// Port of the file-static globals + `Estate` chain Src/exec.c
/// uses — `execlist()` (line 1349) drives every list, with
/// `execpline()` (line 1668), `execpline2()` (line 1991),
/// `execsimple()` (line 1290), and the per-`WC_*` `execfuncs[]`
/// table (line 268) feeding off it. The Rust port collapses
/// everything into one `ShellExecutor` so we don't need
/// thread-local globals.
pub struct ShellExecutor {
    /// Mirrors C zsh's file-static `scriptname` (Src/init.c). Used by
    /// PS4's `%N` and the `scriptname:line: …` prefix on error
    /// messages. Inside a function, MUTATES to the function name
    /// (Src/exec.c:5903 `scriptname = dupstring(name)`). Init sets
    /// this in `-c` mode to the binary basename per init.c:479; when
    /// sourcing a file via `source`/`bin_dot`, it becomes the
    /// resolved file path; otherwise it falls back through `$0` →
    /// `$ZSH_ARGZERO`.
    pub scriptname: Option<String>,
    /// Mirrors C zsh's `scriptfilename` global (Src/init.c). Tracks
    /// the FILE BEING READ (vs scriptname which tracks the active
    /// function name during a call). Used by PS4's `%x` and certain
    /// error-message prefixes that want the file location, NOT the
    /// function name.
    ///
    /// At -c-mode init, scriptname == scriptfilename == "zsh"
    /// (Src/init.c:479). When entering a function, ONLY scriptname
    /// updates (exec.c:5903); scriptfilename stays at the outer
    /// file path, so `%x` inside a function still shows the file
    /// the function was called from.
    pub scriptfilename: Option<String>,
    /// Stack of subshell-state snapshots. Each `(…)` subshell pushes a copy
    /// of variables/arrays/assoc_arrays at entry and pops/restores at exit.
    /// Without this, `(x=inner; …); echo $x` shows `inner` instead of the
    /// outer-scope value.
    pub subshell_snapshots: Vec<SubshellSnapshot>,
    /// Stack of inline-assignment scopes — `X=foo Y=bar cmd` pushes
    /// a frame at the start, the assigns run inside it, and `cmd`
    /// returns into END_INLINE_ENV which restores both shell-vars
    /// and process-env to the pre-frame state. Each frame holds
    /// `(name, prev_var, prev_env)` per assigned name. zsh's
    /// equivalent is the parser-level "addvar" list executed under
    /// `addvars()` (Src/exec.c) right before the command exec.
    pub inline_env_stack: Vec<Vec<(String, Option<String>, Option<String>)>>,
    /// Set by `expand_glob`'s no-match arm when `nomatch` is on (zsh
    /// default) — instructs the simple-command dispatcher to skip
    /// executing the current command, set last_status=1, and continue
    /// to the next command in the script. zsh's bin_simple uses the
    /// errflag global for the same role: error printed, command
    /// suppressed, script continues. Without this we were calling
    /// `process::exit(1)` deep inside expand_glob, killing the whole
    /// shell on any unmatched glob even with multi-statement input.
    /// `Cell` because the no-match site only has a `&self` borrow.
    pub current_command_glob_failed: std::cell::Cell<bool>,
    /// `jobs` field.
    pub jobs: JobTable,
    /// `fpath` field.
    pub fpath: Vec<PathBuf>,
    /// `history` field.
    pub history: Option<HistoryEngine>,
    pub(crate) process_sub_counter: u32,
    pub completions: HashMap<String, CompSpec>, // command -> completion spec
    pub zstyles: Vec<zstyle_entry>,             // zstyle configurations
    /// Current function scope depth for `local` tracking.
    pub local_scope_depth: usize,
    /// Last arg of the currently-running command, deferred into `$_`
    /// when the next command dispatches. zsh: `$_` reflects the LAST
    /// command's last arg, so `echo hi; echo $_` prints `hi` (not the
    /// `_` arg of `echo $_` itself). Promoted in `pop_args` and
    /// `host.exec` before the command's args are read.
    pub pending_underscore: Option<String>,
    /// True while expanding inside a double-quoted context. Set by
    /// `BUILTIN_EXPAND_TEXT` mode 1 around `expand_string` calls.
    /// Used by parameter-flag application to suppress array-only flags
    /// (`(o)`/`(O)`/`(n)`/`(i)`/`(M)`/`(u)`) — zsh's behaviour: those
    /// flags only fire in array context.
    pub in_dq_context: u32,
    /// True (>0) while expanding the RHS of a scalar assignment.
    /// Direct port of zsh's `PREFORK_SINGLE` bit set by
    /// Src/exec.c::addvars line 2546 (`prefork(vl, isstr ?
    /// (PREFORK_SINGLE|PREFORK_ASSIGN) : PREFORK_ASSIGN, ...)`).
    /// Subst_port's paramsubst reads this via `ssub` and suppresses
    /// `(f)` / `(s:STR:)` / `(0)` / `(z)` split flags per
    /// Src/subst.c:1759 + 3902, so `y="${(f)x}"` preserves x's
    /// original separator (newlines) instead of re-joining with
    /// IFS-first-char (space).
    pub in_scalar_assign: u32,
    /// `profiling_enabled` field.
    pub profiling_enabled: bool,
    // compsys - completion system cache
    /// `compsys_cache` field.
    pub compsys_cache: Option<CompsysCache>,
    // Background compinit — receiver for async fpath scan result
    /// `compinit_pending` field.
    pub compinit_pending: Option<(
        std::sync::mpsc::Receiver<CompInitBgResult>,
        std::time::Instant,
    )>,
    // Plugin source cache — stores side effects of source/. in SQLite
    /// `plugin_cache` field.
    pub plugin_cache: Option<crate::plugin_cache::PluginCache>,
    // cdreplay - deferred compdef calls for zinit turbo mode
    /// `deferred_compdefs` field.
    pub deferred_compdefs: Vec<Vec<String>>,
    // Control flow signals
    pub returning: Option<i32>, // Set by return builtin, cleared after function returns
    /// zsh compatibility mode - use .zcompdump, fpath scanning, etc.
    /// Also serves as the `--zsh` parity-test flag: caches off, daemon
    /// off, plugin_cache replay off so every `source` re-runs the file
    /// fresh per Src/builtin.c:6080-6123 bin_dot semantics.
    pub zsh_compat: bool,
    /// bash compatibility mode (`--bash`). Same parity-mode semantics
    /// as `zsh_compat` (caches/daemon/replay off) plus bash-specific
    /// behavior tweaks where bash 5.x diverges from zsh — e.g.
    /// `BASH_VERSION` / `BASH_REMATCH` exposed, `[[ =~ ]]` populates
    /// match indices the bash way, mapfile/readarray as builtins.
    pub bash_compat: bool,
    /// POSIX sh strict mode — no SQLite, no worker pool, no zsh extensions
    pub posix_mode: bool,
    /// Worker thread pool for background tasks (compinit, process subs, etc.)
    pub worker_pool: std::sync::Arc<crate::worker::WorkerPool>,
    /// AOP intercept table: command/function name → advice chain.
    /// Glob patterns supported (e.g. "git *", "*").
    pub intercepts: Vec<Intercept>,
    /// Async job handles: id → receiver for (status, stdout)
    pub async_jobs: HashMap<u32, crossbeam_channel::Receiver<(i32, String)>>,
    /// Next async job ID
    pub next_async_id: u32,
    /// Per-scope saved-fd stacks for `Op::WithRedirectsBegin/End`. Each entry
    /// is a Vec of (fd, saved_dup_fd) pairs taken from `dup(fd)` before the
    /// redirect was applied; `with_redirects_end` `dup2`s them back and closes.
    pub redirect_scope_stack: Vec<Vec<(i32, i32)>>,
    /// Per-scope MULTIOS tee state. Each entry is `(pipe_write_fd,
    /// JoinHandle)`: the pipe write-end currently dup2'd onto the
    /// command's fd, and the splitter thread that reads from the
    /// pipe read-end and writes to every collected target. Closed
    /// + joined by `host_redirect_scope_end` BEFORE the saved fds
    /// are restored so the splitter drains every byte the body
    /// wrote into the pipe. Bug #36 in docs/BUGS.md.
    pub multios_scope_stack: Vec<Vec<(i32, std::thread::JoinHandle<()>)>>,
    /// Set by `host_apply_redirect` when a redirect target couldn't be
    /// opened (permission denied, no such directory, etc). The next
    /// builtin/command checks this at entry and short-circuits with
    /// status 1 instead of running. Mirrors zsh's "command skip" on
    /// redirect failure.
    pub redirect_failed: bool,
    /// Compiled function bodies — name → fusevm::Chunk. Populated by
    /// `BUILTIN_REGISTER_FUNCTION` (from `FunctionDef` lowering) and lazily by
    /// `ZshrsHost::call_function` when only an AST exists in `self.functions`
    /// (autoloaded, sourced, etc.). `Op::CallFunction` dispatches through here.
    pub functions_compiled: HashMap<String, fusevm::Chunk>,
    /// Canonical source text for functions. Populated by autoload paths (the
    /// raw file/cache body), runtime FuncDef compile (the parsed source span),
    /// and `unfunction` removal. Used by introspection (`whence`, `which`,
    /// `typeset -f`) instead of reconstructing from a ShellCommand AST. When a
    /// function is in `functions_compiled` but not here, introspection falls
    /// back to `text::getpermtext(self.functions[name])`.
    pub function_source: HashMap<String, String>,
    /// `first_body_line - 1` per compiled function — matches inner
    /// `ZshCompiler::lineno_offset` / zsh `funcstack->flineno` combined with
    /// relative `$LINENO` for Src/prompt.c:909 `%I`.
    pub function_line_base: HashMap<String, i64>,
    /// `scriptfilename` when `BUILTIN_REGISTER_COMPILED_FN` ran — `%x` inside
    /// a function (prompt.c:931-934) reads `funcstack->filename`.
    pub function_def_file: HashMap<String, Option<String>>,
    /// Innermost-last stack of active compiled-call frames for prompt `%I` / `%x`.
    pub prompt_funcstack: Vec<(String, i64, Option<String>)>,
    /// Scalar→(array, sep) tie table set up by `typeset -T VAR var [SEP]`.
    /// Array→(scalar, sep) reverse-tie table. Used by BUILTIN_SET_ARRAY to
    /// join the array elements with `sep` and mirror to the scalar side.
    pub tied_array_to_scalar: HashMap<String, (String, String)>,
}

impl ShellExecutor {
    /// Set a scalar parameter via the canonical `paramtab`
    /// (`Src/params.c:3350 setsparam`). The single store.
    pub fn set_scalar(&mut self, name: String, value: String) {
        setsparam(&name, &value); // c:params.c:3350
    }

    /// Read positional parameters from canonical `PPARAMS`
    /// `Mutex<Vec<String>>` (Src/init.c:pparams). The single store.
    pub fn pparams(&self) -> Vec<String> {
        crate::ported::builtin::PPARAMS
            .lock()
            .map(|p| p.clone())
            .unwrap_or_default()
    }

    /// Write positional parameters to canonical `PPARAMS`.
    pub fn set_pparams(&mut self, params: Vec<String>) {
        if let Ok(mut p) = crate::ported::builtin::PPARAMS.lock() {
            *p = params;
        }
    }

    /// Read PM_* type flags from the paramtab Param entry. Used by
    /// SET_VAR / `+=` arms (case-fold, integer-add, readonly guard).
    /// Returns 0 when the name isn't in paramtab. Mirrors the C
    /// source's direct `pm->node.flags & PM_INTEGER` checks.
    pub fn param_flags(&self, name: &str) -> i32 {
        paramtab()
            .read()
            .ok()
            .and_then(|t| t.get(name).map(|p| p.node.flags))
            .unwrap_or(0)
    }

    /// `readonly` / `typeset -r` — Param has PM_READONLY.
    pub fn is_readonly_param(&self, name: &str) -> bool {
        (self.param_flags(name) as u32 & PM_READONLY) != 0
    }

    /// Most-recent-command exit status. Reads canonical
    /// `builtin::LASTVAL` AtomicI32 (`Src/builtin.c:6443`).
    pub fn last_status(&self) -> i32 {
        crate::ported::builtin::LASTVAL.load(Ordering::Relaxed)
    }

    /// Write the most-recent-command exit status. The canonical
    /// store is `builtin::LASTVAL`; this is the single setter.
    /// Used everywhere `$?` / `%?` / errexit / ZERR trap read.
    pub fn set_last_status(&mut self, status: i32) {
        crate::ported::builtin::LASTVAL.store(status, Ordering::Relaxed);
    }

    /// Set an indexed array parameter via canonical paramtab
    /// (`setaparam`, `Src/params.c:3595`). The single store.
    pub fn set_array(&mut self, name: String, value: Vec<String>) {
        setaparam(&name, value); // c:params.c:3595
    }

    /// Set an associative array parameter via canonical
    /// `sethparam` (`Src/params.c:3602`). The single store.
    pub fn set_assoc(&mut self, name: String, value: IndexMap<String, String>) {
        let mut flat: Vec<String> = Vec::with_capacity(value.len() * 2);
        for (k, v) in &value {
            flat.push(k.clone());
            flat.push(v.clone());
        }
        sethparam(&name, flat); // c:params.c:3602
    }

    /// Read a scalar parameter. Mirrors C `getsparam` at
    /// `Src/params.c:3076` — reads through paramtab, falls back to
    /// special-var hooks and env.
    pub fn scalar(&self, name: &str) -> Option<String> {
        getsparam(name)
    }

    /// Read an array parameter via canonical `getaparam`
    /// (`Src/params.c:3101`).
    pub fn array(&self, name: &str) -> Option<Vec<String>> {
        getaparam(name)
    }

    /// Read an associative array parameter from canonical
    /// `paramtab_hashed_storage`. Mirrors C `gethparam` at
    /// `Src/params.c:3115` — returns the typed `IndexMap`.
    pub fn assoc(&self, name: &str) -> Option<IndexMap<String, String>> {
        paramtab_hashed_storage()
            .lock()
            .ok()
            .and_then(|m| m.get(name).cloned())
    }

    /// Test whether a scalar parameter exists in paramtab.
    /// Mirrors the C `paramtab->getnode(name) != NULL` check.
    pub fn has_scalar(&self, name: &str) -> bool {
        getsparam(name).is_some()
    }

    /// Test whether an array parameter exists in paramtab. Routes
    /// through canonical `getaparam` (PM_TYPE check + digit-first-name
    /// rejection).
    pub fn has_array(&self, name: &str) -> bool {
        getaparam(name).is_some()
    }

    /// Test whether an associative array parameter exists. Reads
    /// canonical `paramtab_hashed_storage` (Src/params.c hashed
    /// PM_HASHED slot).
    pub fn has_assoc(&self, name: &str) -> bool {
        paramtab_hashed_storage()
            .lock()
            .ok()
            .map(|m| m.contains_key(name))
            .unwrap_or(false)
    }

    /// Unset an associative array parameter via canonical
    /// `unsetparam` (Src/params.c:3819) — PM_READONLY rejection,
    /// stdunsetfn dispatch, env clear. Also clears the zshrs-side
    /// `paramtab_hashed_storage` parallel IndexMap shadow.
    pub fn unset_assoc(&mut self, name: &str) {
        unsetparam(name);
        let _ = paramtab_hashed_storage()
            .lock()
            .ok()
            .as_deref_mut()
            .map(|m| m.remove(name));
    }

    /// Read a regular (non-global) alias value. Reads canonical
    /// `aliastab` (Src/hashtable.c:1186). Filters out aliases that
    /// have the ALIAS_GLOBAL flag set so the regular-alias slot is
    /// distinct from the global-alias slot, mirroring C's two
    /// separate dispatch paths via `aliasflags` checks.
    pub fn alias(&self, name: &str) -> Option<String> {
        let tab = crate::ported::hashtable::aliastab_lock().read().ok()?;
        let a = tab.get(name)?;
        if (a.node.flags & crate::ported::zsh_h::ALIAS_GLOBAL as i32) != 0 {
            None
        } else {
            Some(a.text.clone())
        }
    }

    /// Set a regular alias. Writes canonical aliastab with
    /// ALIAS_GLOBAL bit cleared.
    pub fn set_alias(&mut self, name: String, value: String) {
        if let Ok(mut tab) = crate::ported::hashtable::aliastab_lock().write() {
            tab.add(crate::ported::hashtable::createaliasnode(&name, &value, 0));
        }
    }

    /// Set a global alias (`alias -g`). Writes canonical aliastab
    /// with ALIAS_GLOBAL bit set.
    pub fn set_global_alias(&mut self, name: String, value: String) {
        if let Ok(mut tab) = crate::ported::hashtable::aliastab_lock().write() {
            tab.add(crate::ported::hashtable::createaliasnode(
                &name,
                &value,
                crate::ported::zsh_h::ALIAS_GLOBAL as u32,
            ));
        }
    }

    /// Set a suffix alias (`alias -s ext=cmd`). Writes canonical
    /// sufaliastab with ALIAS_SUFFIX node flag — mirrors C
    /// Src/builtin.c:4480-4481 (`flags1 |= ALIAS_SUFFIX; ht =
    /// sufaliastab;`) → c:4527 (`createaliasnode(value, flags1)`).
    /// Without ALIAS_SUFFIX in node.flags, `${saliases[k]}` /
    /// `${(k)saliases}` introspection (parameter.c:1953/2018) fails
    /// because both paths strict-equality-match flags == ALIAS_SUFFIX.
    pub fn set_suffix_alias(&mut self, name: String, value: String) {
        if let Ok(mut tab) = crate::ported::hashtable::sufaliastab_lock().write() {
            tab.add(crate::ported::hashtable::createaliasnode(
                &name,
                &value,
                crate::ported::zsh_h::ALIAS_SUFFIX as u32,
            ));
        }
    }

    /// Snapshot the alias map as a sorted `Vec<(name, value)>`,
    /// only entries WITHOUT the ALIAS_GLOBAL flag (regular aliases).
    pub fn alias_entries(&self) -> Vec<(String, String)> {
        if let Ok(tab) = crate::ported::hashtable::aliastab_lock().read() {
            tab.iter_sorted()
                .into_iter()
                .filter(|(_, a)| (a.node.flags & crate::ported::zsh_h::ALIAS_GLOBAL as i32) == 0)
                .map(|(k, a)| (k.clone(), a.text.clone()))
                .collect()
        } else {
            Vec::new()
        }
    }

    /// Snapshot the global-alias entries (ALIAS_GLOBAL flag set).
    pub fn global_alias_entries(&self) -> Vec<(String, String)> {
        if let Ok(tab) = crate::ported::hashtable::aliastab_lock().read() {
            tab.iter_sorted()
                .into_iter()
                .filter(|(_, a)| (a.node.flags & crate::ported::zsh_h::ALIAS_GLOBAL as i32) != 0)
                .map(|(k, a)| (k.clone(), a.text.clone()))
                .collect()
        } else {
            Vec::new()
        }
    }

    /// Snapshot the suffix-alias entries.
    pub fn suffix_alias_entries(&self) -> Vec<(String, String)> {
        if let Ok(tab) = crate::ported::hashtable::sufaliastab_lock().read() {
            tab.iter_sorted()
                .into_iter()
                .map(|(k, a)| (k.clone(), a.text.clone()))
                .collect()
        } else {
            Vec::new()
        }
    }

    /// Unset an array parameter. Direct port of `unsetparam_pm` for
    /// a PM_ARRAY Param. Mirrors are kept for now while the field
    /// transitions.
    /// Unset an array parameter via canonical `unsetparam`
    /// (Src/params.c:3819). Routes through the C-faithful port
    /// that runs PM_NAMEREF skip + PM_READONLY rejection via
    /// unsetparam_pm + stdunsetfn dispatch + pm.old scope restore.
    /// Inline `tab.remove(name)` skipped all four.
    pub fn unset_array(&mut self, name: &str) {
        unsetparam(name);
    }

    /// Unset a scalar parameter via canonical `unsetparam`. Same
    /// C-faithful path as `unset_array`; the C `unsetparam` itself
    /// is type-agnostic and dispatches through PM_TYPE inside.
    pub fn unset_scalar(&mut self, name: &str) {
        unsetparam(name);
    }
    /// `new` — see implementation.
    pub fn new() -> Self {
        tracing::debug!("ShellExecutor::new() initializing");

        // Validate the inherited $PWD against the real cwd before any
        // builtin reads it as a logical-path base. Direct port of zsh's
        // ispwd() at src/zsh/Src/utils.c:809-829: $PWD is honored only
        // when it (a) is absolute, (b) stat's to the same dev+inode as
        // ".", and (c) contains no `.`/`..` components. Otherwise zsh
        // resets it to getcwd() (init.c:1247-1253).
        //
        // Without this check, a child process that inherits $PWD from
        // a parent run in a different directory (cargo test setting
        // current_dir(/tmp) but leaking PWD=/project/root) sees the
        // stale PWD and `cd .` later snaps the real cwd to wherever
        // PWD points, escaping the parent's sandbox. ztst harnesses
        // hit this and polluted the project root with test artifacts.
        if let Ok(pwd_env) = env::var("PWD") {
            let valid = ispwd(&pwd_env);
            if !valid {
                if let Ok(real) = env::current_dir() {
                    env::set_var("PWD", &real);
                }
            }
        } else if let Ok(real) = env::current_dir() {
            env::set_var("PWD", &real);
        }

        // Initialize fpath from FPATH env var or use defaults
        let fpath = env::var("FPATH")
            .unwrap_or_default()
            .split(':')
            .filter(|s| !s.is_empty())
            .map(PathBuf::from)
            .collect();

        let history = HistoryEngine::new().ok();

        // Seed canonical OPTS_LIVE with defaults BEFORE any setsparam
        // call. assignstrvalue early-returns when `unset(EXECOPT)`
        // (c:2701 guard); without the option table populated, EXECOPT
        // reads false and every paramtab write below is a silent no-op.
        if opt_state_len() == 0 {
            for (k, v) in Self::default_options() {
                opt_state_set(&k, v);
            }
        }

        // Standard zsh scalar param defaults — direct port of
        // `createparamtable` (Src/params.c:817-988) + the `setupvals`
        // tail. Writes through canonical `setsparam` (Src/params.c:3350).
        //
        // c:params.c:972-973 — ZSH_VERSION / ZSH_PATCHLEVEL.
        // `zsh_version::ZSH_VERSION` (emitted by build.rs from the
        // vendored `Config/version.mk`) is the development snapshot
        // tag `5.9.0.3-test`; shipped zsh binaries report the clean
        // release form (`5.9`). Bug #73 in docs/BUGS.md — cross-shell
        // scripts that gate on `[[ $ZSH_VERSION = 5.9 ]]` or split on
        // `.` expecting MAJOR.MINOR break on the `-test` suffix.
        //
        // Use the cleaned `patchlevel::ZSH_VERSION` here ("5.9") and
        // surface the full snapshot tag as `$ZSHRS_VERSION` for
        // zshrs-specific identity checks.
        setsparam(
            "ZSH_VERSION",
            crate::ported::patchlevel::ZSH_VERSION,
        );
        // c:Src/params.c:43 + Src/patchlevel.h — `ZSH_PATCHLEVEL` is
        // a git-describe-style identifier (`zsh-MAJOR.MINOR-N-gHASH`)
        // of the upstream commit zshrs targets. `build.rs` emits
        // "unknown" because the vendored zsh tarball doesn't ship a
        // CUSTOM_PATCHLEVEL define; use the canonical const in
        // `patchlevel.rs` instead (snapshot of `src/zsh/Src/patchlevel.h`).
        // Bug #90 in docs/BUGS.md — scripts that fingerprint by
        // $ZSH_PATCHLEVEL fell to the wildcard arm under "unknown".
        setsparam(
            "ZSH_PATCHLEVEL",
            crate::ported::patchlevel::ZSH_PATCHLEVEL,
        );
        setsparam(
            "ZSHRS_VERSION",
            crate::ported::patchlevel::ZSHRS_VERSION,
        );
        setsparam("ZSH_NAME", "zsh");
        // c:params.c:971 — ZSH_ARGZERO from `posixzero` (Src/init.c:271).
        // The bin entrypoint overrides this with the script path for
        // -c / runscript invocations.
        setsparam(
            "ZSH_ARGZERO",
            &env::args().next().unwrap_or_else(|| "zsh".to_string()),
        );
        setsparam("WORDCHARS", "*?_-.[]~=/&;!#$%^(){}<>");
        let shlvl = env::var("SHLVL")
            .ok()
            .and_then(|v| v.parse::<i32>().ok())
            .map(|n| (n + 1).to_string())
            .unwrap_or_else(|| "1".to_string());
        setsparam("SHLVL", &shlvl);
        // POSIX/zsh default IFS: space + tab + newline + NUL.
        setsparam("IFS", " \t\n\0");
        // POSIX getopts: OPTIND starts at 1.
        setsparam("OPTIND", "1");
        // Note: OPTERR is NOT pre-initialised. zsh leaves it unset
        // even after `getopts` calls (verified: `getopts ":a" opt -a`
        // does not set it). It's a user-writable variable that
        // starts unset. Bug #150 in docs/BUGS.md.
        // zsh wipes inherited `$_` (unlike bash).
        setsparam("_", "");
        // c:params.c:5064 — histchars derives from bangchar+hatchar+
        // hashchar (defaults `!`, `^`, `#`). At init the special
        // entry may not exist yet — fall back to the literal default.
        let histchars_val = paramtab()
            .read()
            .ok()
            .and_then(|t| {
                t.get("histchars")
                    .or_else(|| t.get("HISTCHARS"))
                    .map(|pm| histcharsgetfn(pm))
            })
            .unwrap_or_else(|| "!^#".to_string());
        setsparam("histchars", &histchars_val);
        // c:Src/init.c:1186-1193 — default prompt strings. zsh sets
        // PS4 to "+%N:%i> " for ZSH emulation ("+ " for KSH/SH).
        // Without seeding, PS4 reads empty and `set -x` output has
        // no prefix at all. Bug #92 in docs/BUGS.md. Only seed if
        // the slot is currently empty — preserve user's exported
        // PS4 from the inherited env.
        if crate::ported::params::getsparam("PS4")
            .map_or(true, |s| s.is_empty())
        {
            setsparam("PS4", "+%N:%i> ");
        }
        // c:Src/init.c:1188-1189 — `prompt = ztrdup("%m%# "); prompt2
        // = ztrdup("%_> ");` for the interactive primary/secondary
        // prompts. PS1 may be reset by the prompt-theme layer; only
        // seed when the slot is empty so any prior theme write wins.
        if crate::ported::params::getsparam("PS1")
            .map_or(true, |s| s.is_empty())
        {
            setsparam("PS1", "%m%# ");
        }
        if crate::ported::params::getsparam("PS2")
            .map_or(true, |s| s.is_empty())
        {
            setsparam("PS2", "%_> ");
        }
        // c:Src/init.c:1191 — `prompt3 = ztrdup("?# ");`
        if crate::ported::params::getsparam("PS3")
            .map_or(true, |s| s.is_empty())
        {
            setsparam("PS3", "?# ");
        }
        // c:Src/init.c:1194 — `sprompt = ztrdup("zsh: correct '%R'
        // to '%r' [nyae]? ");` — spelling-correction prompt.
        if crate::ported::params::getsparam("SPROMPT")
            .map_or(true, |s| s.is_empty())
        {
            setsparam("SPROMPT", "zsh: correct '%R' to '%r' [nyae]? ");
        }
        // c:Src/params.c:417-422 — `PROMPT*` aliases for `PS*`.
        // C zsh's IPDEF7("PROMPT", &prompt), IPDEF7("PROMPT2",
        // &prompt2), IPDEF7("PROMPT3", &prompt3), IPDEF7("PROMPT4",
        // &prompt4) all point to the same C globals as the matching
        // IPDEF7("PS{1..4}", ...) entries — they're aliases in C,
        // sharing storage. zshrs's paramtab keeps them as separate
        // entries; mirror the alias by mirroring the value here.
        // Bug #274 in docs/BUGS.md (PROMPT3 was the visible report;
        // PROMPT/PROMPT2/PROMPT4 had the same gap silently).
        for (alias, source) in &[
            ("PROMPT", "PS1"),
            ("PROMPT2", "PS2"),
            ("PROMPT3", "PS3"),
            ("PROMPT4", "PS4"),
        ] {
            if crate::ported::params::getsparam(alias)
                .map_or(true, |s| s.is_empty())
            {
                if let Some(v) = crate::ported::params::getsparam(source) {
                    setsparam(alias, &v);
                }
            }
        }
        // c:params.c:858-860 — standard non-special param defaults.
        // C uses `setiparam(...)` (PM_INTEGER) for these so
        // `(t)MAILCHECK` etc. report `integer`. zshrs previously
        // routed through `setsparam` (PM_SCALAR) — the value worked
        // but the type bit was wrong, breaking
        // `case "${(t)LISTMAX}" in *integer*)` and any path that
        // gates on arithmetic-typed semantics. Bug #268 in
        // docs/BUGS.md.
        crate::ported::params::setiparam("MAILCHECK", 60); // c:858
        // c:Src/params.c:859 — original `KEYTIMEOUT = 40` but
        // zsh 5.9.1 observably reports 10 (Homebrew arm-darwin).
        // Match the observed default so vi-mode / multi-key
        // bindings feel responsive. Bug #321 in docs/BUGS.md.
        crate::ported::params::setiparam("KEYTIMEOUT", 10); // c:859
        crate::ported::params::setiparam("LISTMAX", 100); // c:860
        // c:config.h:1004 — MAX_FUNCTION_DEPTH=500. Advisory cap;
        // dispatch_function_call enforces against this.
        crate::ported::params::setiparam("FUNCNEST", 500);

        // Run setlocale(LC_ALL, "") so nl_langinfo() (used by the
        // `langinfo` module) returns the host's actual locale instead
        // of the C/POSIX default ("US-ASCII"). Direct port of zsh's
        // Src/init.c:1208 setlocale call. unsafe { } around libc is
        // standard for this exact use-case — setlocale is process-
        // global and must run once at startup.
        unsafe {
            libc::setlocale(libc::LC_ALL, c"".as_ptr());
        }

        // c:hashtable.c:1206 createaliastables() — seeds aliastab with
        // the `run-help` / `which-command` defaults. Run once at shell
        // init so the canonical port owns the default-alias set; the
        // Executor's `aliases` HashMap then mirrors aliastab.
        crate::ported::hashtable::createaliastables();
        // Build the initial $path tied array as a local — fans out
        // to paramtab below; no ShellExecutor mirror anymore.
        let mut arrays: HashMap<String, Vec<String>> = HashMap::new();
        let path_dirs: Vec<String> = env::var("PATH")
            .unwrap_or_default()
            .split(':')
            .map(|s| s.to_string())
            .collect();
        arrays.insert("path".to_string(), path_dirs);
        let mut exec = Self {
            // c:Src/init.c:479 — `-c` mode: scriptname = scriptfilename
            // = ztrdup("zsh"). Both start at the literal "zsh".
            // dispatch_function_call overrides scriptname per c:5903;
            // scriptfilename stays at the outer file.
            scriptname: Some("zsh".to_string()),
            scriptfilename: Some("zsh".to_string()),
            subshell_snapshots: Vec::new(),
            inline_env_stack: Vec::new(),
            current_command_glob_failed: std::cell::Cell::new(false),
            jobs: JobTable::new(),
            fpath,
            history,
            completions: HashMap::new(),
            process_sub_counter: 0,
            zstyles: Vec::new(),
            local_scope_depth: 0,
            pending_underscore: None,
            in_dq_context: 0,
            in_scalar_assign: 0,
            profiling_enabled: false,
            compsys_cache: {
                let cache_path = crate::compsys::cache::default_cache_path();
                if cache_path.exists() {
                    let db_size = fs::metadata(&cache_path).map(|m| m.len()).unwrap_or(0);
                    match CompsysCache::open(&cache_path) {
                        Ok(c) => {
                            tracing::info!(
                                db_bytes = db_size,
                                path = %cache_path.display(),
                                "compsys: sqlite cache opened"
                            );
                            Some(c)
                        }
                        Err(e) => {
                            tracing::warn!(error = %e, "compsys: failed to open cache");
                            None
                        }
                    }
                } else {
                    tracing::debug!("compsys: no cache at {}", cache_path.display());
                    None
                }
            },
            compinit_pending: None, // (receiver, start_time)
            plugin_cache: {
                let pc_path = crate::plugin_cache::default_cache_path();
                if let Some(parent) = pc_path.parent() {
                    let _ = fs::create_dir_all(parent);
                }
                match crate::plugin_cache::PluginCache::open(&pc_path) {
                    Ok(pc) => {
                        let (plugins, functions) = pc.stats();
                        tracing::info!(
                            plugins,
                            cached_functions = functions,
                            path = %pc_path.display(),
                            "plugin_cache: sqlite opened"
                        );
                        Some(pc)
                    }
                    Err(e) => {
                        tracing::warn!(error = %e, "plugin_cache: failed to open");
                        None
                    }
                }
            },
            deferred_compdefs: Vec::new(),
            returning: None,
            zsh_compat: false,
            bash_compat: false,
            posix_mode: false,
            worker_pool: {
                let config = crate::config::load();
                let pool_size = crate::config::resolve_pool_size(&config.worker_pool);
                std::sync::Arc::new(crate::worker::WorkerPool::new(pool_size))
            },
            intercepts: Vec::new(),
            async_jobs: HashMap::new(),
            next_async_id: 1,
            redirect_scope_stack: Vec::new(),
            multios_scope_stack: Vec::new(),
            redirect_failed: false,
            functions_compiled: HashMap::new(),
            function_source: HashMap::new(),
            function_line_base: HashMap::new(),
            function_def_file: HashMap::new(),
            prompt_funcstack: Vec::new(),
            tied_array_to_scalar: HashMap::new(),
        };
        // Mirror env-derived path arrays into the `arrays` table so
        // user-level `fpath` / `path` array reads see the inherited
        // entries. zsh: `fpath+=…` should append to the inherited
        // 43-entry array, not replace it. Same for `path` (PATH).
        let fpath_arr: Vec<String> = exec
            .fpath
            .iter()
            .map(|p| p.to_string_lossy().to_string())
            .collect();
        if !fpath_arr.is_empty() {
            exec.set_array("fpath".to_string(), fpath_arr);
        }
        if let Ok(path) = env::var("PATH") {
            let path_arr: Vec<String> = path
                .split(':')
                .filter(|s| !s.is_empty())
                .map(String::from)
                .collect();
            if !path_arr.is_empty() {
                exec.set_array("path".to_string(), path_arr);
            }
        }
        // Register the standard tied path-family pairs so `path+=` /
        // `fpath+=` / etc. mirror through the array→scalar sync hook
        // in BUILTIN_APPEND_ARRAY (and the SET_ARRAY tied path).
        // Direct port of the implicit ties that zsh wires up at
        // startup for PATH/path, FPATH/fpath, etc. Source-of-truth
        // for the pairs is Src/init.c's `setupvals()` PM_TIED entries.
        for (scalar, arr) in [
            ("PATH", "path"),
            ("FPATH", "fpath"),
            ("MANPATH", "manpath"),
            ("CDPATH", "cdpath"),
            ("MODULE_PATH", "module_path"),
        ] {
            exec.tied_array_to_scalar
                .insert(arr.to_string(), (scalar.to_string(), ":".to_string()));
        }

        // Pour `path` (from env PATH split) into paramtab before the
        // special_paramdef stamping loop below so the canonical tied
        // entry exists when PM_SPECIAL bits are applied.
        for (k, v) in &arrays {
            setaparam(k, v.clone()); // c:params.c:3595
        }
        // c:Src/params.c:384-394 — IPDEF8/IPDEF9 macros stamp
        // `PM_SCALAR|PM_SPECIAL` (IPDEF8 for `PATH`/`FPATH`/etc.) and
        // `PM_ARRAY|PM_SPECIAL|PM_DONTIMPORT` (IPDEF9 for `path`/
        // `fpath`/etc.) on every entry in the createparamtable table.
        // setsparam/setaparam above create plain PM_SCALAR/PM_ARRAY
        // entries; this loop applies the PM_SPECIAL + PM_TIED bits
        // (plus the IPDEF9 PM_DONTIMPORT bit on the array side) so
        // `${(t)PATH}` reads `scalar-tied-export-special` and
        // `${(t)path}` reads `array-tied-special`.
        //
        // Walks the `special_params` table (params.rs:464+) which is
        // the Rust port of the C IPDEF list. For each entry: OR the
        // declared pm_flags onto the existing paramtab entry. The
        // tied-pair entries (PM_TIED) also need PM_SPECIAL OR'd in
        // since the IPDEF8/IPDEF9 macros add PM_SPECIAL implicitly;
        // the table declares only the per-entry-distinct flags.
        {
            use crate::ported::params::{paramtab, special_params};
            use crate::ported::zsh_h::{PM_ARRAY, PM_DONTIMPORT, PM_SCALAR, PM_SPECIAL, PM_TIED};
            if let Ok(mut tab) = paramtab().write() {
                // Stamp PM_SPECIAL onto every entry the special_params
                // table declares. For tied scalars (PATH/FPATH/etc),
                // also walks `tied_name` to apply IPDEF9-flag bits
                // (PM_ARRAY|PM_SPECIAL|PM_DONTIMPORT|PM_TIED) onto the
                // partner array entry (path/fpath/etc) — those array
                // names aren't in the special_params table directly
                // but C zsh's createparamtable emits IPDEF9 rows for
                // them at Src/params.c:425-432.
                use crate::ported::zsh_h::{hashnode, param, PM_DONTIMPORT as PM_DI, PM_UNSET};
                for entry in special_params.iter() {
                    // c:384/394 IPDEF8/9 — `D|PM_SCALAR|PM_SPECIAL` or
                    // `D|PM_ARRAY|PM_SPECIAL|PM_DONTIMPORT`.
                    //
                    // Mask `entry.pm_flags` to ONLY the attribute bits
                    // safe to OR onto an existing Param without changing
                    // assignment semantics. PM_READONLY is excluded
                    // here because many internal-runtime writes go
                    // through setsparam (subshell ZSH_SUBSHELL bump,
                    // ZSH_EVAL_CONTEXT push, etc.) and would be
                    // rejected by assignstrvalue's PM_READONLY guard.
                    // C zsh's PM_SPECIAL GSU setfn bypasses the guard;
                    // the Rust port lacks that vtable wiring, so keep
                    // the entries writable.
                    //
                    // PM_UNSET is included: lookup_special_var arms for
                    // TRY_BLOCK_ERROR / TRY_BLOCK_INTERRUPT (and other
                    // PM_UNSET entries with sentinel defaults) check
                    // this bit to decide between "stored value" vs
                    // "uninitialized → return -1 sentinel". The flag
                    // gets cleared by assignstrvalue at c:3660 on any
                    // write, so it correctly tracks "ever assigned".
                    // Bug #143 in docs/BUGS.md.
                    let safe_pm_flags = entry.pm_flags & (PM_TIED | PM_DI | PM_UNSET);
                    let mut bits = safe_pm_flags | PM_SPECIAL;
                    // c:Src/params.c — IPDEF4/IPDEF1 set
                    // PM_READONLY_SPECIAL = PM_SPECIAL | PM_READONLY |
                    // PM_RO_BY_DESIGN. zshrs masks PM_READONLY out
                    // (see above) but the introspection bit can still
                    // ride along. Replace dropped PM_READONLY with
                    // PM_RO_BY_DESIGN so `typeset -r` recognises these
                    // entries as logically-readonly without blocking
                    // internal writes. The listing filter in
                    // `bin_typeset` expands its PM_READONLY match to
                    // also pick up PM_RO_BY_DESIGN. Bug #97 in
                    // docs/BUGS.md.
                    if (entry.pm_flags & crate::ported::zsh_h::PM_READONLY) != 0 {
                        bits |= crate::ported::zsh_h::PM_RO_BY_DESIGN;
                    }
                    if entry.pm_type == PM_ARRAY {
                        bits |= PM_DI;
                    }
                    let _ = PM_SCALAR;
                    let _ = PM_DONTIMPORT;
                    if let Some(pm) = tab.get_mut(entry.name) {
                        pm.node.flags |= bits as i32;
                        // c:Src/params.c:344 IPDEF4 / c:353 IPDEF5 — the
                        // C struct literal initialises the `base` field
                        // to 10 for every PM_INTEGER special. zshrs's
                        // initial paramtab seeding doesn't carry that
                        // through (the special_paramdef table has no
                        // `base` field). Set the default here so
                        // `printparamnode`'s PMTF_USE_BASE arm at
                        // params.rs:9341 emits "10" between
                        // `integer` and the name (`integer 10 readonly
                        // !=0`). Bug #297 in docs/BUGS.md.
                        if entry.pm_type == crate::ported::zsh_h::PM_INTEGER
                            && pm.base == 0
                        {
                            pm.base = 10;
                        }
                        // c:Src/zsh.h IPDEF8/IPDEF9 — the third macro
                        // arg is the tied partner name; mapped into
                        // `pm->ename` so `typeset -p` can find the
                        // peer for the PM_TIED swap. Bug #410.
                        if let Some(peer) = entry.tied_name {
                            pm.ename = Some(peer.to_string());
                        }
                    } else {
                        // Param hasn't been created yet (e.g. PATH gets
                        // imported lazily via the env fallback in
                        // getsparam at params.rs:4104; array specials
                        // like `pipestatus` / `funcstack` / `dirstack`
                        // / `zsh_scheduled_events` aren't pre-populated).
                        // Seed an empty placeholder carrying the
                        // canonical flag set so subsequent setsparam /
                        // `(t)X` / `${+X}` observers see the IPDEF
                        // attribute bits AND `${+X}` returns 1.
                        let u_arr = if entry.pm_type == PM_ARRAY {
                            Some(Vec::new())
                        } else {
                            None
                        };
                        let pm: crate::ported::zsh_h::Param = Box::new(param {
                            node: hashnode {
                                next: None,
                                nam: entry.name.to_string(),
                                flags: (entry.pm_type as i32) | bits as i32,
                            },
                            u_data: 0,
                            u_arr,
                            u_str: None,
                            u_val: 0,
                            u_dval: 0.0,
                            u_hash: None,
                            gsu_s: None,
                            gsu_i: None,
                            gsu_f: None,
                            gsu_a: None,
                            gsu_h: None,
                            // c:Src/params.c:344 IPDEF4 / c:353 IPDEF5 —
                            // PM_INTEGER specials default base=10.
                            base: if entry.pm_type == crate::ported::zsh_h::PM_INTEGER {
                                10
                            } else {
                                0
                            },
                            width: 0,
                            env: None,
                            // c:Src/zsh.h IPDEF8/IPDEF9 — tied partner
                            // name. Bug #410.
                            ename: entry.tied_name.map(|s| s.to_string()),
                            old: None,
                            level: 0,
                        });
                        tab.insert(entry.name.to_string(), pm);
                    }
                    // Tied partner side. The previous loop body ORed
                    // PM_ARRAY|PM_SPECIAL|PM_DONTIMPORT|PM_TIED onto the
                    // partner indiscriminately, but for a SCALAR ↔
                    // ARRAY tied pair (PATH ↔ path, FIGNORE ↔ fignore),
                    // that incorrectly stamped PM_ARRAY onto the scalar
                    // partner (FIGNORE, PATH, FPATH, MAILPATH, MANPATH,
                    // PSVAR, CDPATH, MODULE_PATH). Result: `(t)PATH`
                    // returned `array-tied-export-special` instead of
                    // `scalar-tied-export-special`.
                    //
                    // Both partners are already listed in `special_params`
                    // (the scalar at the IPDEF8 block, the array at the
                    // IPDEF9 block past the sentinel), so each gets its
                    // own pass through this loop and ends up with the
                    // correct flags. No cross-stamping needed.
                    let _ = entry.tied_name;
                }
                // c:Src/params.c:893-924 environment-import loop —
                // every env var gets either a fresh exported paramtab
                // entry OR (when the entry pre-exists from
                // special_params) PM_EXPORTED OR'd onto its flags.
                // Without this, `declare -p PATH` printed `typeset -T
                // PATH=''` and `declare -p USER` printed nothing at
                // all because USER was never in paramtab.
                use crate::ported::zsh_h::hashnode as _hn;
                use crate::ported::zsh_h::{PM_EXPORTED, PM_SCALAR};
                for (env_name, env_value) in std::env::vars() {
                    if env_name.is_empty() || env_name.contains('[') {
                        continue;
                    }
                    if env_name.as_bytes()[0].is_ascii_digit() {
                        continue;
                    }
                    if !crate::ported::params::isident(&env_name) {
                        continue;
                    }
                    if let Some(pm) = tab.get_mut(&env_name) {
                        pm.node.flags |= PM_EXPORTED as i32;
                    } else {
                        // Fresh entry — PM_SCALAR + PM_EXPORTED, value
                        // taken from env. Mirrors C zsh's c:907-908
                        // `assignsparam(..., ASSPM_ENV_IMPORT)` for
                        // names not already in the special table.
                        let pm: crate::ported::zsh_h::Param = Box::new(param {
                            node: _hn {
                                next: None,
                                nam: env_name.clone(),
                                flags: (PM_SCALAR | PM_EXPORTED) as i32,
                            },
                            u_data: 0,
                            u_arr: None,
                            u_str: Some(env_value.clone()),
                            u_val: 0,
                            u_dval: 0.0,
                            u_hash: None,
                            gsu_s: None,
                            gsu_i: None,
                            gsu_f: None,
                            gsu_a: None,
                            gsu_h: None,
                            base: 0,
                            width: 0,
                            env: Some(format!("{}={}", env_name, env_value)),
                            ename: None,
                            old: None,
                            level: 0,
                        });
                        tab.insert(env_name, pm);
                    }
                }
            }
        }
        // Populate paramtab with PM_SPECIAL placeholder Params for
        // every PARTAB / PARTAB_ARRAY magic-assoc name. Mirrors
        // what C's zsh/parameter module boot_ → handlefeatures
        // chain does at startup. Makes `${+aliases}` / `${(t)commands}`
        // / `typeset -p modules` etc. see the special entries.
        init_partab_params(); // c:Src/Modules/parameter.c:2341 boot_/enables_ chain

        // c:Src/init.c:1703 init_bltinmods — must run before user
        // code so default-loaded modules (zsh/watch, …) get their
        // boot_ entry points called and their params (e.g. `watch`,
        // `WATCH`) seeded in paramtab. Without this, `${(t)watch}`
        // returned empty even though zsh treats zsh/watch as loaded
        // by default. The bin entry skips zsh_main → init_bltinmods,
        // so we run it here from ShellExecutor::new for the same
        // effect. Bug #270.
        crate::ported::init::init_bltinmods();

        // c:Src/params.c:873-876 — `gethostname(hostnam,256);
        //                            setsparam("HOST", ztrdup_metafy(hostnam));`
        // Plain port of the createparamtable HOST init. Direct
        // libc::gethostname call; result written via canonical
        // setsparam. createparamtable() itself isn't called from the
        // bin entry yet (full init port pending); this is the minimum
        // for `$HOST` to read non-empty.
        let mut host_buf = [0u8; 256];
        let host_rc = unsafe { libc::gethostname(host_buf.as_mut_ptr() as *mut libc::c_char, 256) }; // c:874
        if host_rc == 0 {
            if let Ok(c) = std::ffi::CStr::from_bytes_until_nul(&host_buf) {
                if let Ok(name) = c.to_str() {
                    crate::ported::params::setsparam("HOST", name); // c:875
                }
            }
        }
        // c:Src/init.c:479 — `-c` mode: scriptname = scriptfilename
        // = ztrdup("zsh"). Both globals start as the literal "zsh"
        // (not the binary path) so PS4's %x / %N print "zsh" not
        // "/path/to/zshrs" at the top level. Function dispatch
        // overrides scriptname per c:5903; scriptfilename stays.
        crate::ported::utils::set_scriptname(Some("zsh".to_string()));
        crate::ported::utils::set_scriptfilename(Some("zsh".to_string()));

        // c:Src/params.c:961-970 — uname-derived host/arch
        // identification params: MACHTYPE / CPUTYPE / OSTYPE /
        // VENDOR. C zsh reads from compile-time `#define`s (set by
        // ./configure) for MACHTYPE / OSTYPE / VENDOR, and from
        // uname().machine at runtime for CPUTYPE.
        //
        // Rust port: probe uname() at startup for CPUTYPE, and use
        // const strings parameterized by build-target for the
        // others. Match homebrew zsh's values where possible.
        let mut uname_buf: libc::utsname = unsafe { std::mem::zeroed() };
        let _ = unsafe { libc::uname(&mut uname_buf) };
        let to_str = |b: &[libc::c_char]| -> String {
            // c-string → owned String, truncated at first NUL.
            let bytes: Vec<u8> = b
                .iter()
                .take_while(|&&c| c != 0)
                .map(|&c| c as u8)
                .collect();
            String::from_utf8_lossy(&bytes).into_owned()
        };
        let cputype = to_str(&uname_buf.machine);
        crate::ported::params::setsparam("CPUTYPE", &cputype); // c:961
        let sysname = to_str(&uname_buf.sysname).to_lowercase();
        let release = to_str(&uname_buf.release);
        let ostype = format!("{}{}", sysname, release); // c:968 (OSTYPE)
        crate::ported::params::setsparam("OSTYPE", &ostype);
        // MACHTYPE / VENDOR: hardcoded per platform. macOS uses
        // "arm" or "arm64" or "x86_64" for arm-derived MACHTYPE.
        // Approximate the canonical homebrew value: short-form of
        // the cputype.
        let machtype = if cputype.starts_with("arm") {
            "arm".to_string()
        } else {
            cputype.clone()
        };
        crate::ported::params::setsparam("MACHTYPE", &machtype); // c:967
        let vendor = if sysname == "darwin" {
            "apple"
        } else {
            "unknown"
        };
        crate::ported::params::setsparam("VENDOR", vendor); // c:970

        // c:Src/params.c:878-882 — `setsparam("LOGNAME", getlogin() ?:
        // cached_username);`. C's createparamtable also assigns
        // USERNAME from the same source (cached_username) via the
        // special_paramdefs table. Here mirror the LOGNAME +
        // USERNAME seeding so the canonical paramtab entries exist
        // (usernamegetfn at c:4655 reads through Param.u_str).
        // Same one-shot init pattern as the HOST gethostname call
        // above — full createparamtable() port is pending.
        let logname = unsafe {
            let p = libc::getlogin();
            if p.is_null() {
                None
            } else {
                Some(std::ffi::CStr::from_ptr(p).to_string_lossy().into_owned())
            }
        }; // c:880
        if let Some(name) = logname {
            crate::ported::params::setsparam("LOGNAME", &name); // c:881
                                                                // DO NOT setsparam("USERNAME", ...) here. `$USERNAME` is
                                                                // a special parameter whose SETTER (`usernamesetfn` in
                                                                // params.rs) performs setgid(2) + setuid(2) to actually
                                                                // change the effective user — that's a deliberate upstream
                                                                // zsh feature for `USERNAME=other-user cmd`. Calling it at
                                                                // init seeds the value AND tries to change uid/gid; when
                                                                // the resolved pwd's pw_uid differs from `getuid()` (sudo
                                                                // launches, macOS Keychain-helper inherited env, container
                                                                // entry points, etc.) the setgid call fails with EPERM and
                                                                // emits `zsh:1: failed to change group ID: Operation not
                                                                // permitted`. Upstream seeds `$USERNAME` via the GETTER
                                                                // path (`usernamegetfn` reads through `cached_username`
                                                                // populated by `inittyptab` → `get_username`), no setter
                                                                // call needed.
        }
        exec
    }

    /// Execute a script file with bytecode caching — skips lex+parse+compile on cache hit.
    /// Bytecode is stored in rkyv keyed by (path, mtime).
    pub fn execute_script_file(&mut self, file_path: &str) -> Result<i32, String> {
        let path = Path::new(file_path);
        let abs_path = path
            .canonicalize()
            .unwrap_or_else(|_| path.to_path_buf())
            .to_string_lossy()
            .to_string();

        // Try bytecode cache first — rkyv shard at ~/.zshrs/scripts.rkyv.
        // The cache validates path + mtime + zshrs binary mtime; on any
        // miss we fall through to lex/parse/compile. Cached path uses
        // `run_chunk` (the shared VM-execution helper); script-eval
        // path delegates to `execute_script_zsh_pipeline` so the
        // full parse/compile/cache-save/run flow stays in one place.
        if let Some(bc_blob) = crate::script_cache::try_load_bytes(path) {
            if let Ok(chunk) = bincode::deserialize::<fusevm::Chunk>(&bc_blob) {
                if !chunk.ops.is_empty() {
                    tracing::trace!(
                        path = %abs_path,
                        ops = chunk.ops.len(),
                        "execute_script_file: bytecode cache hit"
                    );
                    return self.run_chunk(chunk, &format!("execute_script_file:cache:{abs_path}"));
                }
            }
        }

        // Cache miss — read, parse, compile via execute_script_zsh_pipeline,
        // then snapshot the resulting chunk into the cache for next
        // time. Direct port of Src/init.c source() which calls
        // `lex_init_buf` / `loop()` without engaging the history layer.
        // (zsh fires `!` history sub only on interactive input, so
        // sourced files run verbatim.)
        let content = fs::read_to_string(file_path).map_err(|e| format!("{}: {}", file_path, e))?;
        let status = self.execute_script_zsh_pipeline(&content)?;

        // Best-effort cache save — failures don't block execution.
        // Re-parse/-compile here instead of trying to thread the chunk
        // back out of execute_script_zsh_pipeline; the cost is one extra
        // compile per CACHE MISS, paid back on every subsequent run.
        let saved_errflag = errflag.load(Ordering::Relaxed);
        errflag.fetch_and(!ERRFLAG_ERROR, Ordering::Relaxed);
        crate::ported::parse::parse_init(&content);
        let program = crate::ported::parse::parse();
        let parse_failed = (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0;
        errflag.store(saved_errflag, Ordering::Relaxed);
        if !parse_failed {
            let compiler = crate::compile_zsh::ZshCompiler::new();
            let chunk = compiler.compile(&program);
            if let Ok(blob) = bincode::serialize(&chunk) {
                let _ = crate::script_cache::try_save_bytes(path, &blob);
                tracing::trace!(
                    path = %abs_path,
                    bytes = blob.len(),
                    "execute_script_file: bytecode cached"
                );
            }
        }

        Ok(status)
    }

    /// Run a compiled `fusevm::Chunk` to completion inside this
    /// executor's context. Shared by `execute_script_zsh_pipeline`,
    /// `execute_script_file`'s bytecode-cache hit path, and the
    /// function-dispatch body_runner. Centralises the VM setup so
    /// `register_builtins` and `ExecutorContext::enter` invariants
    /// stay in lockstep.
    fn run_chunk(&mut self, chunk: fusevm::Chunk, label: &str) -> Result<i32, String> {
        if chunk.ops.is_empty() {
            return Ok(self.last_status());
        }
        crate::fusevm_disasm::maybe_print_stdout(label, &chunk);
        let mut vm = fusevm::VM::new(chunk);
        register_builtins(&mut vm);
        // Seed vm.last_status with the executor's current LASTVAL so
        // sub-VMs (EXIT trap bodies, eval, source) see the inherited
        // `$?` from the caller's last command — matching C zsh where
        // lastval is a process global. Without this, the new VM
        // started at 0 and BUILTIN_GET_VAR's sync_status would write
        // 0 back into LASTVAL on the first `$?` read.
        vm.last_status = self.last_status();
        let _ctx = ExecutorContext::enter(self);
        match vm.run() {
            fusevm::VMResult::Ok(_) | fusevm::VMResult::Halted => {
                self.set_last_status(vm.last_status);
            }
            fusevm::VMResult::Error(e) => return Err(format!("VM error: {}", e)),
        }
        Ok(self.last_status())
    }

    /// Execute via the lex+parse free ported + ZshCompiler pipeline.
    /// This is the only execution path; `execute_script` delegates here.
    pub fn execute_script_zsh_pipeline(&mut self, script: &str) -> Result<i32, String> {
        // Skip history expansion for non-interactive script execution
        // (`zsh -c '…'`, internal eval, sourced files). zsh's `!`
        // history sub only fires on the REPL command line, never on
        // a pre-parsed script body. The interactive REPL has its
        // own dedicated path that calls expand_history before
        // dispatching here.
        // Save & clear errflag around the parse so a fresh syntax
        // error is distinguishable from one already in flight. Mirrors
        // Src/init.c loop()'s pre-parse `errflag &= ~ERRFLAG_ERROR;`.
        let saved_errflag = errflag.load(Ordering::Relaxed);
        errflag.fetch_and(!ERRFLAG_ERROR, Ordering::Relaxed);
        crate::ported::parse::parse_init(script);
        let program = crate::ported::parse::parse();
        let parse_failed = (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0;
        errflag.store(saved_errflag, Ordering::Relaxed);
        if parse_failed {
            // c:Src/init.c — when the parser fires `zerr(...)`, the C
            // shell's `loop()` body skips the eval pass and continues;
            // there's no second "parse error" diagnostic. The Rust
            // binary's call sites print `zshrs: <e>` on Err, doubling
            // up on the message the parser already emitted via zerr.
            // Use a `__SILENCED__` sentinel that the binary's
            // execute_script wrapper recognizes as "already reported,
            // exit silently". Bug #142 in docs/BUGS.md (double-print
            // half).
            return Err("__SILENCED__".to_string());
        }

        let compiler = crate::compile_zsh::ZshCompiler::new();
        let chunk = compiler.compile(&program);
        let status = self.run_chunk(chunk, "execute_script_zsh_pipeline")?;

        // Fire EXIT trap if set. Two storage paths:
        //   (a) `trap 'cmd' EXIT` writes the body text into
        //       `traps_table` via bin_trap (Src/builtin.c) — fire
        //       directly via execute_script.
        //   (b) `TRAPEXIT() { ... }` function-named form goes
        //       through settrap(SIGEXIT, None, ZSIG_FUNC) at
        //       funcdef time (fusevm_bridge.rs BUILTIN_REGISTER_COMPILED_FN
        //       arm) and lives in shfunctab + sigtrapped — fire
        //       via dotrap(SIGEXIT) which dispatches the named
        //       shfunc. Bug #157 in docs/BUGS.md.
        // Remove the trap from `traps_table` first to prevent
        // infinite recursion of `(a)`; `(b)`'s sigtrapped flag
        // is cleared by dotrap's own intrap guard.
        let exit_body = crate::ported::builtin::traps_table()
            .lock()
            .ok()
            .and_then(|mut t| t.remove("EXIT"));
        if let Some(action) = exit_body {
            tracing::debug!("firing EXIT trap (new pipeline)");
            // c:Src/signals.c — the EXIT trap body sees $? at the
            // value the script left off (so `trap 'echo $?' EXIT;
            // (exit 7)` prints 7), but the SHELL's final exit code
            // is still the pre-trap value (running `echo` inside
            // the trap doesn't reset the script's exit status).
            // Preserve `status` and re-apply it after the trap
            // body returns.
            let _ = self.execute_script_zsh_pipeline(&action);
            self.set_last_status(status);
        }
        // c:Src/signals.c::dotrap(SIGEXIT) — fire TRAPEXIT() shfunc
        // if installed via the function-name path. The TRAPEXIT()
        // form goes through settrap(SIGEXIT, None, ZSIG_FUNC) at
        // funcdef time (sets sigtrapped[SIGEXIT] |= ZSIG_FUNC).
        // Dispatching from here AFTER run_chunk returns means we're
        // outside the VM context — dotrap can't safely re-enter
        // via dispatch_function_call (which uses with_executor).
        // Route through execute_script_zsh_pipeline which sets up
        // a fresh VM context — invoke the function by name.
        let trapped = crate::ported::signals::sigtrapped
            .lock()
            .ok()
            .and_then(|g| g.get(crate::signals_h::SIGEXIT as usize).copied())
            .unwrap_or(0);
        if (trapped & crate::ported::zsh_h::ZSIG_FUNC as i32) != 0 {
            // The TRAP<SIG> function is stored in shfunctab as
            // "TRAPEXIT"; calling it by name re-enters
            // execute_script_zsh_pipeline with a fresh VM context.
            let _ = self.execute_script_zsh_pipeline("TRAPEXIT");
        }
        // c:Src/init.c::zexit — `callhookfunc("zshexit", NULL, 1, NULL)`.
        // Fire the `zshexit` shfunc + walk `zshexit_functions` array.
        // Routed through execute_script_zsh_pipeline calls because
        // we're outside the VM context here (post-run_chunk). Iterate
        // the array directly + call zshexit by name. Bug #215 in
        // docs/BUGS.md.
        //
        // Re-entry guard: each call to execute_script_zsh_pipeline
        // (whether top-level script or the named-fn dispatch below)
        // hits this code at its tail. Without a guard, the zshexit
        // hook recurses infinitely (calls itself at end via this
        // path). Use a thread-local depth counter and skip the
        // dispatch when depth > 0.
        thread_local! {
            static ZSHEXIT_HOOK_DEPTH: std::cell::Cell<u32> = const {
                std::cell::Cell::new(0)
            };
        }
        let hook_depth = ZSHEXIT_HOOK_DEPTH.with(|c| c.get());
        if hook_depth == 0 {
            ZSHEXIT_HOOK_DEPTH.with(|c| c.set(hook_depth + 1));
            if crate::ported::hashtable::shfunctab_lock()
                .read()
                .ok()
                .map(|t| t.contains_key("zshexit"))
                .unwrap_or(false)
            {
                let _ = self.execute_script_zsh_pipeline("zshexit");
            }
            let exit_arr = crate::ported::params::paramtab()
                .read()
                .ok()
                .and_then(|t| t.get("zshexit_functions").and_then(|p| p.u_arr.clone()))
                .unwrap_or_default();
            for fn_name in exit_arr {
                let exists = crate::ported::hashtable::shfunctab_lock()
                    .read()
                    .ok()
                    .map(|t| t.contains_key(&fn_name))
                    .unwrap_or(false);
                if exists {
                    let _ = self.execute_script_zsh_pipeline(&fn_name);
                }
            }
            ZSHEXIT_HOOK_DEPTH.with(|c| c.set(hook_depth));
        }
        // Preserve script status; trap body shouldn't override it.
        self.set_last_status(status);

        let _ = status;
        Ok(self.last_status())
    }
    /// `execute_script` — see implementation.
    #[tracing::instrument(skip(self, script), fields(len = script.len()))]
    pub fn execute_script(&mut self, script: &str) -> Result<i32, String> {
        // lex+parse free ported + ZshCompiler is the only execution path.
        self.execute_script_zsh_pipeline(script)
    }

    /// Whether `name` is a known function. Checks the compiled-functions
    /// table and the autoload-pending registry — `autoload foo` should
    /// make `whence foo`/`type foo`/`functions foo` recognize `foo` as
    /// a function before it's actually loaded. Doesn't trigger autoload
    /// itself; use `maybe_autoload` first if you need to load before
    /// introspecting.
    pub fn function_exists(&self, name: &str) -> bool {
        // Either compiled (already loaded) or shfunctab has an
        // autoload stub with PM_UNDEFINED set (pending). Matches C's
        // `lookupshfunc(name)` semantics at `Src/exec.c:5215`.
        if self.functions_compiled.contains_key(name) {
            return true;
        }
        crate::ported::hashtable::shfunctab_lock()
            .read()
            .ok()
            .map(|t| t.get(name).is_some())
            .unwrap_or(false)
    }

    /// Sorted list of every known function name (union of compiled + source).
    pub fn function_names(&self) -> Vec<String> {
        let mut set: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
        for k in self.functions_compiled.keys() {
            set.insert(k.clone());
        }
        for k in self.function_source.keys() {
            set.insert(k.clone());
        }
        set.into_iter().collect()
    }

    /// Dispatch a function by name. Thin passthru — autoload-materialize
    /// the body if needed, build a synthetic `shfunc`, and hand off to
    /// the canonical `doshfunc` port (`Src/exec.c:5823` →
    /// `src/ported/exec.rs::doshfunc`). doshfunc owns ALL scope
    /// management (starttrapscope/endtrapscope, startparamscope/
    /// endparamscope, funcdepth bump, pipestats save/restore, scriptname
    /// snapshot, BREAKS/CONTFLAG/LOOPS/RETFLAG snapshot+restore, `$0`
    /// override via FUNCTIONARGZERO, etc.). The body run itself is the
    /// Rust-only adaptation passed via the `body_runner` closure because
    /// zshrs runs function bodies through fusevm bytecode (not C zsh's
    /// wordcode walker via `runshfunc`).
    ///
    /// Returns `None` when the name isn't a known function so the caller
    /// can fall through to external dispatch.
    /// Body-only counterpart to [`dispatch_function_call`] — runs
    /// the function body WITHOUT wrapping in `doshfunc`. Used as the
    /// `body_runner` closure target by `src/ported/` callers that
    /// already wrap their own `crate::ported::exec::doshfunc(...)`
    /// call (so going back through `dispatch_function_call` would
    /// double-wrap the scope). Mirrors C's `runshfunc(prog, wrappers,
    /// name)` at `exec.c:6042` from doshfunc's perspective.
    pub fn run_function_body_only(&mut self, name: &str, args: &[String]) -> Option<i32> {
        // Same Rust-port short-circuit as dispatch_function_call,
        // sans the doshfunc wrap.
        if let Some(rust_fn) = crate::compsys::router::try_rust_dispatch(name) {
            return Some(rust_fn(args));
        }
        // Autoload prelude (same as dispatch_function_call's).
        if !self.functions_compiled.contains_key(name) {
            if let Some(stub) = crate::ported::utils::getshfunc(name) {
                if (stub.node.flags as u32 & PM_UNDEFINED) != 0 {
                    let boxed = Box::new(stub.clone());
                    let ptr = Box::into_raw(boxed);
                    let _ = crate::ported::exec::loadautofn(ptr, 0, 0, 0);
                    unsafe {
                        let _ = Box::from_raw(ptr);
                    }
                    if let Some(body) = crate::ported::utils::getshfunc(name).and_then(|f| f.body) {
                        let wrapped = format!("{name}() {{\n{body}\n}}");
                        let _ = self.execute_script_zsh_pipeline(&wrapped);
                    }
                } else if let Some(body) = stub.body.clone() {
                    let wrapped = format!("{name}() {{\n{body}\n}}");
                    let _ = self.execute_script_zsh_pipeline(&wrapped);
                }
            }
        }
        let chunk = self.functions_compiled.get(name).cloned()?;
        let seed_status = self.last_status();
        let _ = args; // fusevm body reads $1..$N from PPARAMS
        let mut vm = fusevm::VM::new(chunk);
        register_builtins(&mut vm);
        vm.last_status = seed_status;
        let _ = vm.run();
        Some(vm.last_status)
    }

    pub fn dispatch_function_call(&mut self, name: &str, args: &[String]) -> Option<i32> {
        // c:Src/exec.c — `disable -f NAME` flips the DISABLED flag on
        // the shfunctab entry. `lookupshfunc` (which dispatch consults)
        // returns NULL for DISABLED entries, falling through to PATH
        // lookup → "command not found". zshrs keeps the compiled body
        // in functions_compiled independently of the flag, so check
        // shfunctab and short-circuit when DISABLED is set. Bug #221
        // in docs/BUGS.md.
        let is_disabled = crate::ported::hashtable::shfunctab_lock()
            .read()
            .ok()
            .and_then(|t| {
                let entry = t.get_including_disabled(name)?;
                Some(
                    (entry.node.flags as u32 & crate::ported::zsh_h::DISABLED as u32) != 0,
                )
            })
            .unwrap_or(false);
        if is_disabled {
            return None;
        }
        // zshrs-original: `[compsys] backend = "rust"` short-circuit.
        // When a `_NAME` has a Rust port AND the user opted into the
        // rust backend, run the Rust fn directly here — but still
        // through the canonical doshfunc scope-management path below
        // (we synthesize a body_runner from the fn pointer). Router
        // returns None for names without a Rust port → graceful
        // fallback to the shfunc autoload path.
        //
        // Note: `compcore::callcompfunc` (the compsys entry hit by
        // Tab) wraps doshfunc itself per C `compcore.c:835`, so the
        // Rust _main_complete dispatch lands HERE only when called
        // from a non-compcore caller (e.g. a user shell script
        // directly invoking `_main_complete`). The doshfunc scope
        // wrap below applies uniformly to both.
        let direct_rust_fn: Option<fn(&[String]) -> i32> =
            crate::compsys::router::try_rust_dispatch(name);
        // Autoload prelude skipped when a Rust port wins — no upstream
        // shell function to load.
        if direct_rust_fn.is_none() && !self.functions_compiled.contains_key(name) {
            if let Some(stub) = crate::ported::utils::getshfunc(name) {
                if (stub.node.flags as u32 & PM_UNDEFINED) != 0 {
                    let boxed = Box::new(stub.clone());
                    let ptr = Box::into_raw(boxed);
                    let _ = crate::ported::exec::loadautofn(ptr, 0, 0, 0);
                    unsafe {
                        let _ = Box::from_raw(ptr);
                    }
                    if let Some(body) = crate::ported::utils::getshfunc(name).and_then(|f| f.body) {
                        let wrapped = format!("{name}() {{\n{body}\n}}");
                        let _ = self.execute_script_zsh_pipeline(&wrapped);
                    }
                } else if let Some(body) = stub.body.clone() {
                    // c:Src/Modules/parameter.c::setpmfunction — function
                    // registered via `functions[name]=body` lives in
                    // shfunctab with `body` set but `functions_compiled`
                    // empty (the canonical port stores the parsed eprog,
                    // not a fusevm Chunk). Lazy-compile here by feeding
                    // the body through the standard funcdef pipeline so
                    // the next CallFunction op finds the chunk.
                    let wrapped = format!("{name}() {{\n{body}\n}}");
                    let _ = self.execute_script_zsh_pipeline(&wrapped);
                }
            }
        }
        // When a Rust port is registered, skip the fusevm Chunk
        // lookup entirely — the body_runner closure below will run
        // the Rust fn pointer directly. Otherwise require a compiled
        // chunk for the autoloaded body.
        let chunk_opt = if direct_rust_fn.is_some() {
            None
        } else {
            Some(self.functions_compiled.get(name).cloned()?)
        };

        // zshrs-specific bookkeeping that doshfunc doesn't own:
        // - prompt_funcstack (PS4 trace) push/pop
        // - local_scope_depth FUNCNEST guard
        //
        // c:Src/exec.c::funcnest_check — C zsh allows FUNCNEST=500 by
        // default and the per-call stack usage is small enough that
        // 500 nested calls fit comfortably in the default 8MB thread
        // stack. zshrs's per-call stack usage is heavier (vm_helper
        // state, fusevm closures, parse buffers) — empirically the
        // Rust stack overflows around depth 120. Cap the effective
        // check at a safe ceiling (80) so the user-visible
        // `maximum nested function level reached` diagnostic fires
        // before the SIGABRT crash. User-set FUNCNEST values above
        // 80 are silently clamped. Bug #519 — critical: previously
        // ANY infinite-recursion function crashed the shell with
        // `thread 'main' has overflowed its stack` exit 134.
        const FUNCNEST_RUST_CEILING: usize = 80;
        let funcnest_user: usize = self
            .scalar("FUNCNEST")
            .and_then(|s| s.parse().ok())
            .unwrap_or(100);
        let funcnest_limit = funcnest_user.min(FUNCNEST_RUST_CEILING);
        if self.local_scope_depth >= funcnest_limit {
            eprintln!(
                "{}: maximum nested function level reached; increase FUNCNEST?",
                name
            );
            return Some(1);
        }
        let display_name = if name.starts_with("_zshrs_anon_") {
            "(anon)".to_string()
        } else {
            name.to_string()
        };
        let line_base = self.function_line_base.get(name).copied().unwrap_or(0);
        let def_file = self.function_def_file.get(name).cloned().flatten();
        self.prompt_funcstack
            .push((name.to_string(), line_base, def_file));
        self.local_scope_depth += 1;

        // Synthetic shfunc for doshfunc — carries the name + def-file
        // info so funcstack push gets a proper filename. funcdef/body
        // stay None because the wordcode body is irrelevant on this
        // path (body_runner runs the fusevm Chunk directly).
        // c:Src/exec.c:5390-5410 — execfuncdef records the
        // current `scriptfilename` on the shfunc at definition
        // time so funcsourcetrace can show file:line of the
        // function's source. The function_def_file map stores
        // this; fall back to the live scriptfilename so dynamic
        // / non-`compile_funcdef`-routed definitions still get a
        // sensible filename. Without the fallback, the synth_shf
        // saw None and the funcstack push at exec.rs:5719
        // defaulted to an empty string, which the funcsourcetrace
        // getfn rendered as `:N` (or worse, picked up the
        // function name from a parallel field). Bug #515.
        let synth_filename = self
            .function_def_file
            .get(name)
            .cloned()
            .flatten()
            .or_else(|| self.scriptfilename.clone());
        // c:Src/exec.c:5409 — `shf->lineno = lineno;` (def line).
        // `function_line_base[name]` carries compile_funcdef's
        // `lineno_offset = first_body_line - 1` — equals the def line
        // for multi-line `f() {\n body }` but underflows to 0 for
        // INLINE `f() { body }` (def and body share a line). zsh's
        // funcsourcetrace reports the def line as 1-based, so clamp
        // to >= 1 to handle the inline case without rebuilding
        // line tracking through the parser. Bug #396.
        let synth_lineno =
            std::cmp::max(1i64, self.function_line_base.get(name).copied().unwrap_or(0));
        let mut synth_shf = crate::ported::zsh_h::shfunc {
            node: crate::ported::zsh_h::hashnode {
                next: None,
                nam: display_name.clone(),
                flags: 0,
            },
            filename: synth_filename,
            lineno: synth_lineno,
            funcdef: None,
            redir: None,
            sticky: None,
            body: None,
        };
        // doshargs: C convention — argv[0] = function name (for
        // FUNCTIONARGZERO `$0`), argv[1..] = real positional args.
        let mut doshargs: Vec<String> = vec![display_name.clone()];
        doshargs.extend(args.iter().cloned());

        // Seed `$?` with the parent's last status — C zsh's
        // doshfunc inherits lastval automatically because it's a
        // process-global; the fusevm VM creates a fresh
        // `vm.last_status = 0` per call, so we mirror the inherit
        // explicitly. Without this, a function reading `$?` BEFORE
        // running any command sees 0 instead of the caller's status.
        let seed_status = self.last_status();
        let body_args: Vec<String> = args.to_vec();
        let body_runner = move || -> i32 {
            // Branch: Rust port (direct fn call) or fusevm Chunk
            // (autoloaded shell body). Both run INSIDE doshfunc's
            // scope so prologue/epilogue applies identically.
            if let Some(f) = direct_rust_fn {
                return f(&body_args);
            }
            let chunk = chunk_opt
                .as_ref()
                .expect("chunk_opt must be Some when direct_rust_fn is None");
            crate::fusevm_disasm::maybe_print_stdout(
                &format!(
                    "function:{}",
                    body_args.first().map(|s| s.as_str()).unwrap_or("")
                ),
                chunk,
            );
            let mut vm = fusevm::VM::new(chunk.clone());
            register_builtins(&mut vm);
            vm.last_status = seed_status;
            let _ = vm.run();
            vm.last_status
        };

        // Enter executor context BEFORE doshfunc so the body_runner's
        // VM builtins can `with_executor(...)` to reach this state.
        let _ctx = ExecutorContext::enter(self);
        let status = crate::ported::exec::doshfunc(&mut synth_shf, doshargs, false, body_runner);
        drop(_ctx);

        self.prompt_funcstack.pop();
        self.local_scope_depth -= 1;

        // Honor explicit `return N` from inside the function body.
        if let Some(ret) = self.returning.take() {
            self.set_last_status(ret);
            Some(ret)
        } else {
            self.set_last_status(status);
            Some(status)
        }
    }

    pub(crate) fn execute_external(
        &mut self,
        cmd: &str,
        args: &[String],
        redirects: &[Redirect],
    ) -> Result<i32, String> {
        self.execute_external_bg(cmd, args, redirects, false)
    }

    fn execute_external_bg(
        &mut self,
        cmd: &str,
        args: &[String],
        _redirects: &[Redirect],
        background: bool,
    ) -> Result<i32, String> {
        tracing::trace!(cmd, bg = background, "exec external");
        // c:Src/exec.c:824-876 — when arg0 has no `/`, C zsh requires
        // a PATH search. With PATH unset, the search yields no hit
        // and C emits `command not found: <cmd>`. Rust's
        // `Command::new(name)` delegates to libc `execvp`, which on
        // many platforms falls back to a built-in default PATH when
        // the env entry is missing — so `unset PATH; ls` still finds
        // `/bin/ls` and runs it, breaking the security boundary the
        // unset is supposed to establish (#416). Gate explicitly:
        // when cmd is a bare name (no `/`) and zshrs's own PATH
        // param is unset OR empty, emit the canonical
        // "command not found" diagnostic and return 127 BEFORE
        // touching libc.
        if !cmd.contains('/') {
            let path_set_and_nonempty = crate::ported::params::getsparam("PATH")
                .map(|p| !p.is_empty())
                .unwrap_or(false);
            if !path_set_and_nonempty {
                let sn = crate::ported::utils::scriptname_get()
                    .unwrap_or_else(|| "zshrs".to_string());
                eprintln!("{}:1: command not found: {}", sn, cmd);
                return Ok(127);
            }
        }
        let mut command = Command::new(cmd);
        command.args(args);

        // Redirect handling lives in fusevm's WithRedirectsBegin/End
        // ops at compile time; `_redirects` arrives empty here.

        if background {
            match command.spawn() {
                Ok(child) => {
                    let pid = child.id();
                    let cmd_str = format!("{} {}", cmd, args.join(" "));
                    let job_id = self.jobs.add_job(child, cmd_str, JobState::Running);
                    println!("[{}] {}", job_id, pid);
                    Ok(0)
                }
                Err(e) => {
                    let sn = crate::ported::utils::scriptname_get()
                        .unwrap_or_else(|| "zshrs".to_string());
                    if e.kind() == io::ErrorKind::NotFound {
                        // zsh: absolute paths emit "no such file or
                        // directory" (the OS error, since the path was
                        // tried directly), not "command not found"
                        // (which implies PATH search).
                        if cmd.starts_with('/') {
                            eprintln!("{}:1: no such file or directory: {}", sn, cmd);
                        } else {
                            eprintln!("{}:1: command not found: {}", sn, cmd);
                        }
                        Ok(127)
                    } else {
                        Err(format!("{}: {}: {}", sn, cmd, e))
                    }
                }
            }
        } else {
            match command.status() {
                Ok(status) => Ok(status.code().unwrap_or(1)),
                Err(e) => {
                    // Use scriptname (the user-visible shell identifier
                    // — "zsh" in --zsh mode, "zshrs" otherwise) instead
                    // of a hardcoded "zshrs:" prefix so --zsh-mode
                    // diagnostics byte-match C zsh's stderr format.
                    let sn = crate::ported::utils::scriptname_get()
                        .unwrap_or_else(|| "zshrs".to_string());
                    if e.kind() == io::ErrorKind::NotFound {
                        // c:Src/exec.c — `command_not_found_handler` user
                        // hook: when a command lookup fails AND a function
                        // by that name is defined, call it with the cmd
                        // name + original args and return its rc instead
                        // of the default 127 + "command not found" error.
                        // Documented in zshmisc(1) under "Special
                        // Functions". Bug #426.
                        //
                        // The hook only fires for bare names (PATH search
                        // failed); absolute paths skip it and emit the
                        // OS-error path below — matches zsh behavior.
                        if !cmd.starts_with('/') {
                            let mut hook_args = Vec::with_capacity(args.len() + 1);
                            hook_args.push(cmd.to_string());
                            hook_args.extend_from_slice(args);
                            if let Some(rc) = self.dispatch_function_call(
                                "command_not_found_handler",
                                &hook_args,
                            ) {
                                return Ok(rc);
                            }
                        }
                        // zsh: absolute paths emit "no such file or
                        // directory" (the OS error, since the path was
                        // tried directly), not "command not found"
                        // (which implies PATH search).
                        if cmd.starts_with('/') {
                            eprintln!("{}:1: no such file or directory: {}", sn, cmd);
                        } else {
                            eprintln!("{}:1: command not found: {}", sn, cmd);
                        }
                        Ok(127)
                    } else if e.kind() == io::ErrorKind::PermissionDenied {
                        // zsh: non-executable file → "permission denied"
                        // on stderr and exit 126 (POSIX "command found
                        // but not executable").
                        eprintln!("{}:1: permission denied: {}", sn, cmd);
                        Ok(126)
                    } else {
                        Err(format!("{}: {}: {}", sn, cmd, e))
                    }
                }
            }
        }
    }
    /// Parse `cmd_str` via parse_init+parse and pull out the first Simple
    /// command's words, untokenized + variable-expanded, ready to spawn
    /// as argv. Used by process-substitution where we need raw argv to
    /// hand to `Command::new`. Returns empty vec if the cmd isn't a
    /// simple shape — pipelines / compound forms aren't process-sub
    /// friendly anyway.
    fn simple_cmd_words(&mut self, cmd_str: &str) -> Vec<String> {
        // Mirror Src/init.c-style errflag save/clear/check around the
        // parse. Process-sub argv extraction silently bails on syntax
        // errors (matches zsh's behavior when the inner command can't
        // be parsed).
        let saved_errflag = errflag.load(Ordering::Relaxed);
        errflag.fetch_and(!ERRFLAG_ERROR, Ordering::Relaxed);
        crate::ported::parse::parse_init(cmd_str);
        let prog = crate::ported::parse::parse();
        let parse_failed = (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0;
        errflag.store(saved_errflag, Ordering::Relaxed);
        if parse_failed {
            return Vec::new();
        }
        let first = match prog.lists.first() {
            Some(l) => l,
            None => return Vec::new(),
        };
        let pipe = &first.sublist.pipe;
        if let crate::parse::ZshCommand::Simple(simple) = &pipe.cmd {
            simple
                .words
                .iter()
                .map(|w| {
                    // Untokenize then variable-expand — text-based
                    // word expansion for the spawned argv.
                    let untoked = crate::lex::untokenize(w);
                    singsub(&untoked)
                })
                .collect()
        } else {
            Vec::new()
        }
    }
    /// `run_command_substitution` — see implementation.
    pub fn run_command_substitution(&mut self, cmd_str: &str) -> String {
        // `$(< FILE)` — zsh shorthand for "read FILE contents". Faster
        // than spawning `cat`. The leading `<` (after stripping
        // whitespace) means "read this file". Trailing newline is
        // stripped (same as command-substitution).
        let trimmed = cmd_str.trim_start();
        // Only treat as `$(<file)` shorthand when the SINGLE leading `<`
        // is followed by a filename, not another `<`. `$(<<<"hi" cat)`
        // starts with `<<<` (here-string) and must go through the full
        // parse path, not the read-file shortcut.
        if let Some(rest) = trimmed.strip_prefix('<').filter(|s| !s.starts_with('<')) {
            let filename = rest.trim();
            // c:Src/lex.c — the `$(<file)` shortcut ONLY applies when
            // the body is exactly `<` + ONE word. Anything else (extra
            // args, redirects, semicolons, pipes) is a regular command
            // list and must go through the full parse path so `2>/dev/null`
            // / `>file` / `|cmd` / `; next` etc. work. Without this
            // gate, `$(< file 2>/dev/null)` treated `file 2>/dev/null`
            // as the literal filename and errored on the missing file.
            // Bug #615.
            let is_single_word = !filename.is_empty()
                && !filename.chars().any(|c| {
                    matches!(c,
                        ' ' | '\t' | '\n' | ';' | '&' | '|' |
                        '<' | '>' | '(' | ')' | '`' | '"' | '\''
                    )
                });
            if is_single_word {
                // Expand any leading $ / tilde in the filename so
                // `$(< $f)` and `$(< ~/x)` work.
                let resolved = if filename.contains('$') || filename.starts_with('~') {
                    singsub(filename)
                } else {
                    filename.to_string()
                };
                let resolved = resolved.to_string();
                match fs::read_to_string(&resolved) {
                    Ok(contents) => {
                        return contents.trim_end_matches('\n').to_string();
                    }
                    Err(_) => {
                        eprintln!("zshrs:1: no such file or directory: {}", resolved);
                        return String::new();
                    }
                }
            }
            // Multi-word / has-redirects → fall through to full parse.
        }

        // Port of getoutput(char *cmd, int qt) from Src/exec.c. Parse and compile via
        // the lex+parse free ported + ZshCompiler pipeline, run on a
        // sub-VM with the host wired up. Stdout is captured through
        // an in-process pipe via dup2 — no fork. The sub-VM emits
        // Op::Exec for unknown command names, which forks/execs
        // through the host.

        // Set up the stdout-capture pipe. We dup the original stdout
        // so post-run we can restore it; the write end is dup2'd onto
        // STDOUT_FILENO so all output the sub-VM emits (including from
        // forked children, which inherit fd 1) lands in the pipe.
        let (read_fd, write_fd) = {
            let mut fds = [0i32; 2];
            if unsafe { libc::pipe(fds.as_mut_ptr()) } != 0 {
                return String::new();
            }
            (fds[0], fds[1])
        };
        let saved_stdout = unsafe { libc::dup(libc::STDOUT_FILENO) };
        if saved_stdout < 0 {
            unsafe {
                libc::close(read_fd);
                libc::close(write_fd);
            }
            return String::new();
        }
        // Flush Rust's stdout BufWriter against the ORIGINAL fd before
        // dup2 swaps fd 1 to the capture pipe. Without this, bytes left
        // buffered by a prior `print -n` get drained to fd 1 AFTER the
        // dup2, which routes them into the cmd-subst's pipe — they end
        // up in the captured result and disappear from terminal output.
        //
        // Bug #10 in docs/BUGS.md — `print -n "A"; v=$(true); print -n
        // "B"; v=$(true); print -n "C"; echo` printed only `C` because
        // `A` and `B` were redirected into the empty cmd-subst's pipe
        // and discarded as its "output". C zsh's getoutput() forks, so
        // the child inherits the buffer COPY and the parent's buffer
        // stays untouched; zshrs runs cmd-subst in-process so the
        // parent buffer is the only one — must flush before the swap.
        let _ = io::stdout().flush();
        // c:Bug #56 — publish the saved outer stdout so a trap firing
        // during the nested run routes body output to the parent's
        // real stdout instead of the cmdsub's pipe-bound fd 1.
        let saved_stderr_for_trap = unsafe { libc::dup(libc::STDERR_FILENO) };
        crate::fusevm_bridge::CMDSUBST_OUTER_FDS.with(|s| {
            s.borrow_mut()
                .push((saved_stdout, saved_stderr_for_trap))
        });
        unsafe {
            libc::dup2(write_fd, libc::STDOUT_FILENO);
            libc::close(write_fd);
        }

        // Parse + compile + run.
        // Push CS_CMDSUBST for `%_` xtrace prefix — direct port of
        // Src/exec.c:4783 `cmdpush(CS_CMDSUBST);` around execode().
        // Trace lines emitted by the inner program inherit this token
        // so their PS4 prefix shows "cmdsubst" matching zsh -x.
        cmdpush(crate::ported::zsh_h::CS_CMDSUBST as u8); // c:zsh.h:2799
                                                          // Save LINENO so the inner cmdsubst's line counter doesn't
                                                          // leak into the outer trace — direct port of Src/exec.c:1407
                                                          // `oldlineno = lineno;` followed by `lineno = oldlineno;`
                                                          // restore at line 1640. Inner program parses fresh as line 1
                                                          // and increments from there; once it returns, the outer
                                                          // line at the `$(…)` site must read the original outer
                                                          // lineno (so xtrace renders `+:5:> echo …` not `+:1:> …`).
        let saved_lineno = getsparam("LINENO");
        // Anchor the inner program's lineno to the outer's current
        // $LINENO so xtrace inside the cmdsubst renders the outer
        // line. zsh's execlist preserves lineno across the inner
        // exec — for our sub-VM (fresh compile) we use lineno_addend
        // to shift inner's line N → outer_lineno + (N - 1).
        let outer_lineno: u64 = self
            .scalar("LINENO")
            .and_then(|s| s.parse::<u64>().ok())
            .unwrap_or(0);
        // Mirror Src/init.c errflag save/clear/check pattern around
        // the nested parse so an inner syntax error doesn't bleed into
        // the outer execution.
        let saved_errflag = errflag.load(Ordering::Relaxed);
        errflag.fetch_and(!ERRFLAG_ERROR, Ordering::Relaxed);
        crate::ported::parse::parse_init(cmd_str);
        let parsed = crate::ported::parse::parse();
        let parse_failed = (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0;
        errflag.store(saved_errflag, Ordering::Relaxed);
        let prog = if parse_failed { None } else { Some(parsed) };
        let mut cmd_status: Option<i32> = None;
        if let Some(prog) = prog {
            let mut compiler = crate::compile_zsh::ZshCompiler::new();
            compiler.lineno_addend = outer_lineno.saturating_sub(1);
            let chunk = compiler.compile(&prog);
            if !chunk.ops.is_empty() {
                crate::fusevm_disasm::maybe_print_stdout("run_command_substitution", &chunk);
                // c:Src/exec.c:4783 — `$(...)` runs in a subshell, so
                // assignments / setopt / cd / trap changes inside
                // mustn't leak to the parent. zsh forks; we run
                // in-process and snapshot/restore manually. Same
                // snapshot shape used by host_subshell_begin/end for
                // the `(...)` subshell form.
                let paramtab_snap = crate::ported::params::paramtab()
                    .read()
                    .ok()
                    .map(|t| t.clone())
                    .unwrap_or_default();
                let paramtab_hashed_snap = crate::ported::params::paramtab_hashed_storage()
                    .lock()
                    .ok()
                    .map(|m| m.clone())
                    .unwrap_or_default();
                let pparams_snap = self.pparams();
                let opts_snap = crate::ported::options::opt_state_snapshot();
                let traps_snap = crate::ported::builtin::traps_table()
                    .lock()
                    .map(|t| t.clone())
                    .unwrap_or_default();
                let mut vm = fusevm::VM::new(chunk);
                register_builtins(&mut vm);
                vm.set_shell_host(Box::new(ZshrsHost));
                // Seed inner $? with the outer's last_status so the
                // sub-shell inherits the parent's exit code. Direct
                // port of Src/exec.c:4783 around execcmd_exec — the
                // child inherits `lastval` at fork time, so `false;
                // echo $(echo $?)` reads 1, not the freshly-zeroed
                // sub-VM default. Without this, every cmd-subst
                // started with $?==0 regardless of the parent's
                // last command.
                vm.last_status = self.last_status();
                // `exit N` inside a cmd-subst should terminate ONLY
                // the sub-shell (C zsh: cmd-subst forks, the child
                // `_exit(N)`s; status reaches the parent as
                // cmd-subst exit). zshrs runs in-process, so we
                // route through the SUBSHELL_DEPTH-gated deferred
                // path inside zexit (builtin.rs:7713): bump
                // SUBSHELL_DEPTH so `exit` sets EXIT_PENDING/
                // EXIT_VAL instead of calling realexit (which would
                // process::exit and kill the parent shell). After
                // the sub-VM returns, harvest EXIT_PENDING/EXIT_VAL
                // as the cmd-subst's status, then restore the
                // parent's flags so the outer VM continues normally.
                use crate::ported::builtin::{
                    BREAKS, EXIT_PENDING, EXIT_VAL, RETFLAG, SHELL_EXITING, SUBSHELL_DEPTH,
                };
                use std::sync::atomic::Ordering::Relaxed;
                let saved_exit_pending = EXIT_PENDING.swap(0, Relaxed);
                let saved_exit_val = EXIT_VAL.swap(0, Relaxed);
                let saved_shell_exiting = SHELL_EXITING.swap(0, Relaxed);
                let saved_retflag = RETFLAG.swap(0, Relaxed);
                let saved_breaks = BREAKS.swap(0, Relaxed);
                SUBSHELL_DEPTH.fetch_add(1, Relaxed);
                let _ctx = ExecutorContext::enter(self);
                let _ = vm.run();
                let inner_exit_pending = EXIT_PENDING.load(Relaxed);
                let inner_exit_val = EXIT_VAL.load(Relaxed);
                let inner_status = if inner_exit_pending != 0 {
                    inner_exit_val & 0xFF
                } else {
                    vm.last_status
                };
                cmd_status = Some(inner_status);
                SUBSHELL_DEPTH.fetch_sub(1, Relaxed);
                // c:Src/exec.c:4783 execcmdoutsubst — `$(...)` is a
                // subshell, and zsh fires the EXIT trap when the
                // subshell ends BUT only if the trap was installed
                // INSIDE the subshell. An EXIT trap inherited from
                // the parent fires when the parent shell exits, not
                // again at cmdsub end. Detect "installed inside" by
                // comparing the current traps_table["EXIT"] entry
                // against the pre-cmdsub snapshot — fire only when
                // the body differs (newly set, removed, or replaced).
                // Pop the body before execute_script to avoid the
                // re-fire inside execute_script_zsh_pipeline's own
                // EXIT-handler tail at vm_helper.rs:1490. Bug #354.
                let snap_exit = traps_snap.get("EXIT").cloned();
                let live_exit = crate::ported::builtin::traps_table()
                    .lock()
                    .ok()
                    .and_then(|t| t.get("EXIT").cloned());
                if live_exit != snap_exit {
                    if let Some(body) = live_exit {
                        if let Ok(mut t) = crate::ported::builtin::traps_table().lock() {
                            t.remove("EXIT");
                        }
                        let _ = crate::ported::exec_hooks::execute_script(&body);
                    }
                }
                // c:Src/signals.c::dotrap(SIGEXIT) — also fire the
                // TRAPEXIT() function-named form (ZSIG_FUNC) — but
                // only if it was defined INSIDE the subshell (the
                // parent's TRAPEXIT fires at parent exit, not here).
                // ZSIG_FUNC bit on sigtrapped[SIGEXIT] tells us
                // whether a TRAPEXIT function is registered; check
                // BEFORE the snapshot restore.
                // Skip for now — function-form detection mirrors the
                // raw-body check above; deferred until a clean
                // sigtrapped snapshot/restore pair exists.
                // Restore parent's exit / loop / function-return
                // state so the outer VM continues normally.
                EXIT_PENDING.store(saved_exit_pending, Relaxed);
                EXIT_VAL.store(saved_exit_val, Relaxed);
                SHELL_EXITING.store(saved_shell_exiting, Relaxed);
                RETFLAG.store(saved_retflag, Relaxed);
                BREAKS.store(saved_breaks, Relaxed);
                // Restore parent state. The inner cmd-subst's stdout
                // (the captured pipe contents) is the only thing
                // that leaks out.
                if let Ok(mut t) = crate::ported::params::paramtab().write() {
                    *t = paramtab_snap;
                }
                if let Ok(mut m) = crate::ported::params::paramtab_hashed_storage().lock() {
                    *m = paramtab_hashed_snap;
                }
                self.set_pparams(pparams_snap);
                crate::ported::options::opt_state_restore(opts_snap);
                if let Ok(mut t) = crate::ported::builtin::traps_table().lock() {
                    *t = traps_snap;
                }
            }
        }
        // Restore LINENO so outer xtrace sees the outer line.
        if let Some(ln) = saved_lineno {
            self.set_scalar("LINENO".to_string(), ln);
        }
        cmdpop();
        // Propagate the inner cmd's status to the parent shell. zsh:
        // `a=$(false); echo $?` → 1 because cmd-subst status leaks to
        // $?. Set last_status on the executor so $? reads the right
        // value for callers that don't have a SetStatus(0) overwrite
        // (echo, test, etc.). Bare assignment paths still get the
        // SetStatus(0) from compile_simple — that's a separate gap.
        // Empty cmd-subst (`\`\``, `$()`) resets status to 0 per
        // Src/exec.c — the inner ran no command so the "last
        // command's exit" is the implicit success of "did nothing".
        // Without this branch, a prior command's non-zero status
        // leaked through the empty cmd-subst.
        let final_status = cmd_status.unwrap_or(0);
        self.set_last_status(final_status);
        // c:Src/exec.c:4775 — `getoutput` (the C cmd-subst path used by
        // both `$(…)` and `` `…` ``) propagates the inner exit through
        // `cmdoutval`, then the caller does `LASTVAL = cmdoutval`. Mirror
        // by writing the cmd-subst's exit into the ported `cmdoutval`
        // global so `getoutput()`'s post-call `LASTVAL = cmdoutval` (at
        // exec.rs:559-562) and the C-equivalent `cmdoutval = lastval`
        // bookkeeping in execcmd_exec's assignment paths both see the
        // real exit. Without this, backtick assignments (`a=\`false\`;
        // echo $?`) reported 0 because getoutput's caller path read a
        // cmdoutval that was never updated by the in-process hook.
        crate::ported::exec::cmdoutval.store(final_status, std::sync::atomic::Ordering::Relaxed);

        // Flush any buffered Rust-side stdout so it reaches the pipe
        // before we restore.
        let _ = io::stdout().flush();

        // Pop the trap-routing stack BEFORE restoring stdout so any
        // trap that fires during the restore goes to the cmdsub's
        // pipe (matching what zsh's forked cmdsub would do — the
        // child's fd 1 is the pipe right up until the child exits).
        crate::fusevm_bridge::CMDSUBST_OUTER_FDS.with(|s| {
            s.borrow_mut().pop();
        });
        // c:Bug #353 — restore fd 2 from the saved outer stderr. A
        // body that ran `exec 2>&1` (no command, just redirects)
        // would have committed fd 2 → the cmdsub's pipe write end.
        // In zsh's forked cmdsub the committed redirect dies with
        // the child; zshrs's in-process cmdsub would leak the dup
        // back to the parent and keep the pipe write-end alive,
        // blocking the parent's read on the read_end forever.
        // Always restoring fd 2 here rolls back any commit so the
        // pipe write-end count drops to zero when we drop the
        // local write_fd reference (which already happened above).
        if saved_stderr_for_trap >= 0 {
            unsafe {
                libc::dup2(saved_stderr_for_trap, libc::STDERR_FILENO);
                libc::close(saved_stderr_for_trap);
            }
        }
        // Restore stdout and read what was captured.
        unsafe {
            libc::dup2(saved_stdout, libc::STDOUT_FILENO);
            libc::close(saved_stdout);
        }
        let read_file = unsafe { File::from_raw_fd(read_fd) };
        let mut output = String::new();
        let _ = io::BufReader::new(read_file).read_to_string(&mut output);

        // POSIX: trailing newlines stripped from cmd-sub result.
        while output.ends_with('\n') {
            output.pop();
        }
        output
    }
}

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

    #[test]
    fn test_simple_echo() {
        let _g = crate::test_util::global_state_lock();
        let mut exec = ShellExecutor::new();
        let status = exec.execute_script("true").unwrap();
        assert_eq!(status, 0);
    }

    #[test]
    fn test_if_true() {
        let _g = crate::test_util::global_state_lock();
        let mut exec = ShellExecutor::new();
        let status = exec.execute_script("if true; then true; fi").unwrap();
        assert_eq!(status, 0);
    }

    #[test]
    fn test_if_false() {
        let _g = crate::test_util::global_state_lock();
        let mut exec = ShellExecutor::new();
        let status = exec
            .execute_script("if false; then true; else false; fi")
            .unwrap();
        assert_eq!(status, 1);
    }

    #[test]
    fn test_for_loop() {
        let _g = crate::test_util::global_state_lock();
        let mut exec = ShellExecutor::new();
        exec.execute_script("for i in a b c; do true; done")
            .unwrap();
        assert_eq!(exec.last_status(), 0);
    }

    #[test]
    fn test_and_list() {
        let _g = crate::test_util::global_state_lock();
        let mut exec = ShellExecutor::new();
        let status = exec.execute_script("true && true").unwrap();
        assert_eq!(status, 0);

        let status = exec.execute_script("true && false").unwrap();
        assert_eq!(status, 1);
    }

    #[test]
    fn test_or_list() {
        let _g = crate::test_util::global_state_lock();
        let mut exec = ShellExecutor::new();
        let status = exec.execute_script("false || true").unwrap();
        assert_eq!(status, 0);
    }

    /// Pin: `forklevel` matches the C global declared at
    /// `Src/exec.c:1052` (`int forklevel;`). Like `int` in C, the
    /// Rust port is an AtomicI32 starting at 0 (no fork has occurred
    /// at process start). Per `Src/exec.c:1221` (`forklevel =
    /// locallevel;`), every subshell entry copies `locallevel` into
    /// the global; the SIGPIPE handler at `Src/signals.c:808` reads
    /// it back to distinguish the top-level shell from a subshell.
    #[test]
    fn test_forklevel_default_zero_and_roundtrip() {
        let _g = crate::test_util::global_state_lock();
        use std::sync::atomic::Ordering;
        let prev = crate::ported::exec::FORKLEVEL.load(Ordering::Relaxed);
        // Default state at process start: zero (matches C's BSS init
        // of `int forklevel;` to 0).
        crate::ported::exec::FORKLEVEL.store(0, Ordering::Relaxed);
        assert_eq!(crate::ported::exec::FORKLEVEL.load(Ordering::Relaxed), 0);
        // Simulate the c:1221 store: `forklevel = locallevel;`.
        crate::ported::exec::FORKLEVEL.store(3, Ordering::Relaxed);
        assert_eq!(crate::ported::exec::FORKLEVEL.load(Ordering::Relaxed), 3);
        crate::ported::exec::FORKLEVEL.store(prev, Ordering::Relaxed);
    }
}

// Plugin-Framework-Agnostic State-Modification Recorder hook helpers.
/// Recorder helper: emit one record for an array/scalar mutation
/// targeting a path-family parameter (path/fpath/manpath/module_path/
/// cdpath, lower- or upper-cased), or one `assign` record for any
/// other name. Centralises the path-family list so `BUILTIN_SET_ARRAY`,
/// `BUILTIN_APPEND_ARRAY`, and `BUILTIN_APPEND_SCALAR_OR_PUSH` share
/// the same routing.
///
/// `is_append` distinguishes `arr=(...)` from `arr+=(...)` so the
/// emitted event carries the APPEND attr bit and replay can choose
/// between fresh-set and extend semantics.
///
/// `attrs` carries any pre-existing type info from
/// `recorder_attrs_for(name)` (readonly/export/global) — array shape
/// and APPEND get OR'd in by emit_array_assign.
#[cfg(feature = "recorder")]
pub(crate) fn emit_path_or_assign(
    name: &str,
    values: &[String],
    attrs: crate::recorder::ParamAttrs,
    is_append: bool,
    ctx: &crate::recorder::RecordCtx,
) {
    let lower = name.to_ascii_lowercase();
    let kind_name: Option<&'static str> = match lower.as_str() {
        "path" => Some("path"),
        "fpath" => Some("fpath"),
        "manpath" => Some("manpath"),
        "module_path" => Some("module_path"),
        "cdpath" => Some("cdpath"),
        _ => None,
    };
    match kind_name {
        Some(k) => {
            for v in values {
                crate::recorder::emit_path_mod(v, k, ctx.clone());
                // Each fpath addition also surfaces every `_completion`
                // file inside the directory — matches zinit-report's
                // per-plugin "Completions:" listing. Only fpath dirs
                // get this treatment; PATH dirs hold executables, not
                // completion functions.
                if k == "fpath" {
                    crate::recorder::discover_completions_in_fpath_dir(v, ctx);
                }
            }
        }
        None => {
            // Non-path arrays: emit ONE `assign` event with the
            // ordered element list preserved in value_array. Replay
            // reconstructs `name=(elem1 elem2 ...)` exactly without
            // having to re-split a joined string.
            crate::recorder::emit_array_assign(
                name,
                values.to_vec(),
                attrs,
                is_append,
                ctx.clone(),
            );
        }
    }
}

use std::os::unix::fs::MetadataExt;

bitflags::bitflags! {
    /// Flags for zfork()
    #[derive(Debug, Clone, Copy, Default)]
    pub struct ForkFlags: u32 {
        const NOJOB = 1 << 0;    // Don't add to job table
        const NEWGRP = 1 << 1;   // Create new process group
        const FGTTY = 1 << 2;    // Take foreground terminal
        const KEEPSIGS = 1 << 3; // Keep signal handlers
    }
}

bitflags::bitflags! {
    /// Flags for entersubsh()
    #[derive(Debug, Clone, Copy, Default)]
    pub struct SubshellFlags: u32 {
        const NOMONITOR = 1 << 0; // Disable job control
        const KEEPFDS = 1 << 1;   // Keep file descriptors
        const KEEPTRAPS = 1 << 2; // Keep trap handlers
    }
}

/// Result of fork operation
#[derive(Debug)]
/// `fork()` outcome (parent / child / error).
/// Mirrors the integer return of `zfork()` from Src/exec.c:349.
pub enum ForkResult {
    /// `Parent` variant.
    Parent(i32), // Contains child PID
    /// `Child` variant.
    Child,
}

/// Redirection mode
#[derive(Debug, Clone, Copy)]
/// File-redirection mode (`>` / `>>` / `<` / etc.).
/// Mirrors the `REDIR_*` enum from Src/zsh.h.
pub enum RedirMode {
    /// `Dup` variant.
    Dup,
    /// `Close` variant.
    Close,
}

/// Builtin command type
#[derive(Debug, Clone, Copy)]
/// Builtin classification.
/// Mirrors the `BINF_*` flag set Src/builtin.c uses to
/// classify special vs regular builtins.
pub enum BuiltinType {
    /// `Normal` variant.
    Normal,
    /// `Disabled` variant.
    Disabled,
}

use crate::fusevm_bridge::with_executor;
use crate::ported::glob::*;
use crate::ported::hist::*;
use crate::ported::jobs::*;
use crate::ported::math::*;
use crate::ported::module::*;
use crate::ported::modules::cap::*;
use crate::ported::modules::terminfo::*;
use crate::ported::options::*;
use crate::ported::params::*;
use crate::ported::pattern::*;
use crate::ported::prompt::*;
use crate::ported::signals::*;
use crate::ported::subst::*;
use crate::ported::utils::{zerr, zerrnam, zwarn, zwarnnam};
use ::regex::{Error as RegexError, Regex, RegexBuilder};

impl ShellExecutor {
    /// Every option name in `ZSH_OPTIONS_SET` (port of `optns[]` at
    /// `Src/options.c:79+`).
    pub(crate) fn all_zsh_options() -> Vec<&'static str> {
        ZSH_OPTIONS_SET.iter().copied().collect()
    }

    /// `name → default-on` map via canonical `default_on_options`
    /// (port of `defset()` macro at `Src/options.c:73`).
    pub(crate) fn default_options() -> HashMap<String, bool> {
        let on = default_on_options();
        Self::all_zsh_options()
            .into_iter()
            .map(|n| (n.to_string(), on.contains(n)))
            .collect()
    }
}
impl ShellExecutor {
    /// PURE PASSTHRU to the canonical `params::getsparam` (C port of
    /// `Src/params.c::getsparam`). Every special-name case the old
    /// 316-line body handled lives in `params::lookup_special_var` +
    /// `getsparam`'s paramtab/env walk. Returns an empty string for
    /// unset names (matching the old fn's signature; callers that
    /// need the set/unset distinction call `scalar` / `has_scalar`
    /// directly).
    pub(crate) fn get_variable(&self, name: &str) -> String {
        getsparam(name).unwrap_or_default()
    }
}

// Push a label onto the static `zsh_eval_context` (port of C's
// `Src/exec.c:1251-1266`) AND mirror to the paramtab `zsh_eval_context`
// array entry + tied `ZSH_EVAL_CONTEXT` scalar so the shell-visible
// expansions reflect the call-chain context. Bug #262 in docs/BUGS.md.
// Lives in vm_helper (not src/ported/) because src/ported/ is reserved
// for direct C-source ports.
pub fn push_zsh_eval_context(label: &str) {
    if let Ok(mut ctx) = crate::ported::exec::zsh_eval_context.lock() {
        ctx.push(label.to_string());
        sync_zsh_eval_context_to_param(&ctx);
    }
}

/// Pop the most recently pushed label from the static and the
/// paramtab/scalar mirror. Pairs with `push_zsh_eval_context`.
pub fn pop_zsh_eval_context() {
    if let Ok(mut ctx) = crate::ported::exec::zsh_eval_context.lock() {
        ctx.pop();
        sync_zsh_eval_context_to_param(&ctx);
    }
}

/// Replace the shell-visible mirror with the current stack contents.
/// Writes the array entry directly (PM_READONLY bypass — same pattern
/// the binary's `-c` ZSH_EVAL_CONTEXT init uses at bins/zshrs.rs).
fn sync_zsh_eval_context_to_param(stack: &[String]) {
    let joined = stack.join(":");
    if let Ok(mut tab) = crate::ported::params::paramtab().write() {
        if let Some(pm) = tab.get_mut("zsh_eval_context") {
            pm.u_arr = Some(stack.to_vec());
            pm.node.flags &= !(crate::ported::zsh_h::PM_UNSET as i32);
        }
        if let Some(pm) = tab.get_mut("ZSH_EVAL_CONTEXT") {
            pm.u_str = Some(joined);
            pm.node.flags &= !(crate::ported::zsh_h::PM_UNSET as i32);
        }
    }
}

impl ShellExecutor {
    /// Execute the trap body for a signal name from the REPL signal
    /// loop (bins/zshrs.rs CtrlC/CtrlD dispatch). Thin passthru to
    /// `traps_table` lookup + `execute_script` — kept as a method
    /// because the REPL loop owns `&mut ShellExecutor` and needs a
    /// single call point. The async signal-handler dispatch path
    /// goes through `crate::ported::signals::dotrap` instead.
    pub fn run_trap(&mut self, signal: &str) {
        let action = crate::ported::builtin::traps_table()
            .lock()
            .ok()
            .and_then(|t| t.get(signal).cloned());
        if let Some(body) = action {
            if !body.is_empty() {
                let _ = self.execute_script(&body);
            }
        }
    }
}

impl ShellExecutor {
    pub(crate) fn apply_prompt_theme(&mut self, theme: &str, preview: bool) {
        let (ps1, rps1) = match theme {
            "minimal" => ("%# ", ""),
            "off" => ("$ ", ""),
            "adam1" => (
                "%B%F{cyan}%n@%m %F{blue}%~%f%b %# ",
                "%F{yellow}%D{%H:%M}%f",
            ),
            "redhat" => ("[%n@%m %~]$ ", ""),
            _ => ("%n@%m %~ %# ", ""),
        };
        if preview {
            println!("PS1={:?}", ps1);
            println!("RPS1={:?}", rps1);
        } else {
            self.set_scalar("PS1".to_string(), ps1.to_string());
            self.set_scalar("RPS1".to_string(), rps1.to_string());
            self.set_scalar("prompt_theme".to_string(), theme.to_string());
        }
    }
}
impl ShellExecutor {
    /// Expand glob pattern via canonical `glob_path` (port of
    /// `Src/glob.c::zglob`). Adds executor-side `current_command_glob_failed`
    /// cell so the dispatch layer skips the current command on NOMATCH +
    /// looks_like_glob instead of exiting the shell.
    pub fn expand_glob(&self, pattern: &str) -> Vec<String> {
        let expanded = glob_path(pattern);
        if !expanded.is_empty() {
            return expanded;
        }
        // No matches. Mirror zsh's `setopt nullglob` / `nomatch`
        // dispatch (Src/glob.c:1873-1886) here because glob_path
        // returns an empty Vec without knowing executor state.
        // c:Src/glob.c:1567-1569 `gf_nullglob` per-glob — the `(N)`
        // qualifier acts like `setopt nullglob` for this expression
        // alone. parse_qualifiers detects the suffix `(...)` block;
        // the resulting `qualifiers.nullglob` mirrors C's gf_nullglob
        // carrier.
        let per_glob_nullglob = crate::ported::glob::parse_qualifiers(pattern)
            .1
            .map(|q| q.nullglob)
            .unwrap_or(false);
        let nullglob = opt_state_get("nullglob").unwrap_or(false) || per_glob_nullglob;
        if nullglob {
            return Vec::new();
        }
        let nomatch = opt_state_get("nomatch").unwrap_or(true);
        // Use canonical `haswilds` (port of Src/pattern.c:4306-4376)
        // instead of the Rust-only `looks_like_glob`. C zsh's
        // `Src/glob.c:1876` NOMATCH branch fires whenever the input
        // tripped haswilds during the `zglob` entry check —
        // including patterns whose internal `(` / `)` form a group
        // or alternation but don't end with `)` (e.g. `abc(a)def`,
        // `(abc`). The previous `looks_like_glob` only caught
        // trailing-`(...)` qualifiers, leaving mid-word groups and
        // unclosed parens to fall through to the literal-passthrough
        // branch. #170 in docs/BUGS.md.
        let is_glob = crate::ported::pattern::haswilds(pattern);
        if nomatch && is_glob {
            // c:Src/glob.c:1876-1880 — `else if (isset(NOMATCH)) {`
            //   `zerr("no matches found: %s", ostr);`
            //   `zfree(matchbuf, 0);`
            //   `restore_globstate(saved);`
            //   `return;`
            // `}`
            // C aborts via ERRFLAG_ERROR set by zerr() at c:Src/utils.c
            // and the matchbuf/state cleanup. The Rust port mirrors
            // both: zerr() in utils.rs sets ERRFLAG_ERROR via
            // `errflag.fetch_or(ERRFLAG_ERROR, ...)` already; we then
            // re-set explicitly (defensive — historically this line
            // had `fetch_and(!ERRFLAG_ERROR)` which CLEARED the flag
            // immediately after zerr, making `echo /never/*` print
            // the literal and exit 0 instead of erroring like zsh —
            // parity bug #13).
            zerr(&format!("no matches found: {}", pattern)); // c:1877
            errflag.fetch_or(ERRFLAG_ERROR, Ordering::Relaxed); // c:1877 (zerr side-effect)
            self.current_command_glob_failed.set(true);
            return Vec::new(); // c:1880 return
        }
        // Pattern has no glob meta — pass through literally.
        vec![pattern.to_string()]
    }
    /// True iff the literal `pattern` actually contains a glob metachar
    /// in a position that would have triggered globbing. Used to avoid
    /// spurious "no matches" errors when expand_glob is called on a
    /// plain path that happened to route through this code (e.g. some
    /// fast paths bridge unconditionally).
    pub(crate) fn looks_like_glob(pattern: &str) -> bool {
        // A trailing `(qualifier)` is itself a glob trigger — e.g.
        // `path(L+10)` should be treated as a glob even when the
        // body has no `*`/`?`/`[...]`.
        let has_qual_suffix = if let Some(open) = pattern.rfind('(') {
            pattern.ends_with(')') && open + 1 < pattern.len() - 1
        } else {
            false
        };
        // Strip trailing `(...)` qualifier so we test the pattern body.
        let body = if let Some(open) = pattern.rfind('(') {
            if pattern.ends_with(')') {
                &pattern[..open]
            } else {
                pattern
            }
        } else {
            pattern
        };
        // Walk character-by-character so escaped metachars (`\*`, `\?`,
        // `\[`) are NOT counted as glob triggers. zsh: `echo \*` prints
        // a literal `*`; without the unescaped check, looks_like_glob
        // returned true on the bare `*` and the runtime glob expansion
        // aborted with NOMATCH.
        let chars: Vec<char> = body.chars().collect();
        let mut i = 0;
        let mut has_unescaped_star = false;
        let mut has_unescaped_question = false;
        let mut has_unescaped_bracket_open: Option<usize> = None;
        while i < chars.len() {
            let c = chars[i];
            if c == '\\' && i + 1 < chars.len() {
                // Escaped char — skip both.
                i += 2;
                continue;
            }
            match c {
                '*' => has_unescaped_star = true,
                '?' => has_unescaped_question = true,
                '[' if has_unescaped_bracket_open.is_none() => {
                    has_unescaped_bracket_open = Some(i);
                }
                _ => {}
            }
            i += 1;
        }
        // `[` only counts when there's a matching `]` after it.
        let has_bracket_class = has_unescaped_bracket_open
            .map(|i| body[i + 1..].contains(']'))
            .unwrap_or(false);
        // `<N-M>` numeric range glob is also a trigger — match shape
        // `<` + optional digits + `-` + optional digits + `>` outside
        // any bracket expression.
        let has_numeric_range =
            body.contains('<') && body.contains('>') && !extract_numeric_ranges(body).is_empty();
        has_unescaped_star
            || has_unescaped_question
            || has_bracket_class
            || has_qual_suffix
            || has_numeric_range
    }
}

impl ShellExecutor {
    pub(crate) fn copy_dir_recursive(src: &Path, dest: &Path) -> io::Result<()> {
        if !dest.exists() {
            fs::create_dir_all(dest)?;
        }
        for entry in fs::read_dir(src)? {
            let entry = entry?;
            let file_type = entry.file_type()?;
            let src_path = entry.path();
            let dest_path = dest.join(entry.file_name());

            if file_type.is_dir() {
                Self::copy_dir_recursive(&src_path, &dest_path)?;
            } else {
                fs::copy(&src_path, &dest_path)?;
            }
        }
        Ok(())
    }
}

// Magic-assoc scan-by-name aggregator. C's per-table getfn/scanfn
// pointers in paramdef[] (Src/Modules/parameter.c:825+) handle this
// indirectly via paramtab dispatch; this Rust-only helper exposes a
// single `partab_get` / `partab_scan_keys` entry that the bridge
// uses for name → keys lookup.
use std::cell::RefCell;
thread_local! {
    static SCAN_KEYS: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
}

/// Lookup helper for `${name[key]}` magic-assoc reads — dispatches
/// through canonical `PARTAB` (Src/Modules/parameter.c:2235 ports).
/// Returns `None` if name isn't a known magic-assoc.
pub fn partab_get(name: &str, key: &str) -> Option<String> {
    // c:Src/Modules/system.c:902,904 — `sysparams` and `errnos` are
    // bound by zsh/system's boot_/setup_ chain. Same for `mapfile`
    // from zsh/mapfile. Without explicit `zmodload`, these names
    // are unset in zsh; gate the PARTAB dispatch here so they
    // resolve via the empty-fallback path (matching ${sysparams[k]:-x}
    // taking the default). Bug #69 in docs/BUGS.md.
    if let Some(modname) = module_gated_partab_module(name) {
        if !crate::ported::module::MODULESTAB.lock().unwrap().is_loaded(modname) {
            return None;
        }
    }
    for entry in PARTAB.iter() {
        if entry.name == name {
            return (entry.getfn)(std::ptr::null_mut(), key).and_then(|p| p.u_str);
        }
    }
    None
}

/// Returns the owning module name for partab entries that are
/// bound by an explicit zmodload — `sysparams`/`errnos` from
/// zsh/system, `mapfile` from zsh/mapfile. Other partab entries
/// (aliases/commands/functions/...) are part of zsh/main and
/// always available.
fn module_gated_partab_module(name: &str) -> Option<&'static str> {
    match name {
        "sysparams" | "errnos" => Some("zsh/system"),
        "mapfile" => Some("zsh/mapfile"),
        _ => None,
    }
}

/// PM_ARRAY lookup for `${name}` / `${name[N]}` — walks
/// PARTAB_ARRAY and dispatches the whole-array getfn (Src/Modules/
/// parameter.c:2239-2291 ports). Returns `None` if name isn't a
/// known PM_ARRAY magic-assoc.
pub fn partab_array_get(name: &str) -> Option<Vec<String>> {
    // Bug #69 — gate module-bound PARTAB names on the owning
    // module's MOD_LINKED && !MOD_UNLOAD state.
    if let Some(modname) = module_gated_partab_module(name) {
        if !crate::ported::module::MODULESTAB.lock().unwrap().is_loaded(modname) {
            return None;
        }
    }
    for entry in PARTAB_ARRAY.iter() {
        if entry.name == name {
            return Some((entry.getfn)(std::ptr::null_mut()));
        }
    }
    None
}

/// Look up a PARTAB_ARRAY entry's flags, OR'd with the implicit
/// PM_SPECIAL | PM_HIDE | PM_HIDEVAL the C SPECIALPMDEF macro adds
/// (zsh.h:2123). Used by `${(t)name}` so reserved/special arrays
/// like `historywords` / `funcstack` report
/// `array-readonly-hide-hideval-special` matching zsh exactly.
pub fn partab_array_flags(name: &str) -> Option<u32> {
    for entry in PARTAB_ARRAY.iter() {
        if entry.name == name {
            let pm_special = crate::ported::zsh_h::PM_SPECIAL;
            let pm_hide = crate::ported::zsh_h::PM_HIDE;
            let pm_hideval = crate::ported::zsh_h::PM_HIDEVAL;
            return Some(entry.flags as u32 | pm_special | pm_hide | pm_hideval);
        }
    }
    None
}

/// Scan helper for `${(k)name}` — enumerates keys via canonical
/// scanfn, collected into Vec via SCAN_KEYS thread-local.
pub fn partab_scan_keys(name: &str) -> Option<Vec<String>> {
    // Bug #69 — gate module-bound PARTAB names on the owning
    // module's MOD_LINKED && !MOD_UNLOAD state.
    if let Some(modname) = module_gated_partab_module(name) {
        if !crate::ported::module::MODULESTAB.lock().unwrap().is_loaded(modname) {
            return None;
        }
    }
    for entry in PARTAB.iter() {
        if entry.name == name {
            SCAN_KEYS.with(|k| k.borrow_mut().clear());
            fn cb(node: &crate::ported::zsh_h::HashNode, _flags: i32) {
                SCAN_KEYS.with(|k| k.borrow_mut().push(node.nam.clone()));
            }
            (entry.scanfn)(std::ptr::null_mut(), Some(cb), 0);
            return Some(SCAN_KEYS.with(|k| k.borrow().clone()));
        }
    }
    None
}
/// Populate paramtab with PM_SPECIAL placeholder Params for every
/// PARTAB / PARTAB_ARRAY entry — Rust-only init helper, no direct
/// C counterpart (closest is `handlefeatures` walking `partab[]`
/// in `Src/Modules/parameter.c:2341` boot/enables chain).
///
/// Each magic-assoc name gets a Param with `entry.flags | PM_SPECIAL`.
/// Value reads still route through `partab_get` / `partab_array_get`;
/// having the Param in paramtab makes `paramtab.get(name)` return
/// Some(Param) so `${+name}` / `${(t)name}` / `typeset -p name` see
/// the entry. Without this, those reads returned empty for every
/// magic-assoc (aliases, commands, functions, etc.).
///
/// Called from ShellExecutor::new() since zshrs's bin entry skips
/// the canonical module-bootstrap chain.
pub fn init_partab_params() {
    use crate::ported::modules::parameter::{PARTAB, PARTAB_ARRAY};
    use crate::ported::zsh_h::{
        hashnode, param, Param, PM_HIDE, PM_HIDEVAL, PM_READONLY, PM_SPECIAL,
    };
    let mut tab = match paramtab().write() {
        Ok(t) => t,
        Err(_) => return,
    };
    // c:Src/zsh.h SPECIALPMDEF macro: `flags | PM_SPECIAL | PM_HIDE |
    // PM_HIDEVAL`. All magic-assoc/array params get HIDE+HIDEVAL added
    // by the macro itself.
    //
    // PM_READONLY is preserved on the stub for params that legitimately
    // need user-write protection (reswords, dis_reswords, patchars,
    // dis_patchars — all compute via getfn and have no legitimate
    // internal-write path). Other specials that DO have internal-write
    // paths (e.g. funcstack from function-call tracking) get the bit
    // stripped so the runtime can mutate their u_arr. Bug #374.
    let user_protected: &[&str] = &[
        "reswords",
        "dis_reswords",
        "patchars",
        "dis_patchars",
        "historywords",
        "errnos",
        "keymaps",
    ];
    let mk_pm = |name: &str, flags: i32| -> Param {
        let keep_readonly = user_protected.contains(&name);
        let pre_readonly_mask = if keep_readonly {
            !0i32
        } else {
            !(PM_READONLY as i32)
        };
        Box::new(param {
            node: hashnode {
                next: None,
                nam: name.to_string(),
                flags: (flags & pre_readonly_mask)
                    | PM_SPECIAL as i32
                    | PM_HIDE as i32
                    | PM_HIDEVAL as i32,
            },
            u_data: 0,
            u_arr: None,
            u_str: None,
            u_val: 0,
            u_dval: 0.0,
            u_hash: None,
            gsu_s: None,
            gsu_i: None,
            gsu_f: None,
            gsu_a: None,
            gsu_h: None,
            base: 0,
            width: 0,
            env: None,
            ename: None,
            old: None,
            level: 0,
        })
    };
    // c:Src/Modules/system.c:902,904 + Src/Modules/mapfile.c — these
    // params are provided by modules that real zsh requires explicit
    // `zmodload` for. Seeding them unconditionally makes
    // `${+sysparams}` return 1 by default (bug #69 in docs/BUGS.md),
    // diverging from zsh which returns 0 until the user runs
    // `zmodload zsh/system`. Skip here; `seed_partab_param` below adds
    // them on demand from the module's load path.
    let module_gated: &[&str] = &[
        "sysparams", // zsh/system
        "errnos",    // zsh/system
        "mapfile",   // zsh/mapfile
    ];
    for entry in PARTAB.iter() {
        if module_gated.contains(&entry.name) {
            continue;
        }
        tab.insert(entry.name.to_string(), mk_pm(entry.name, entry.flags));
    }
    for entry in PARTAB_ARRAY.iter() {
        if module_gated.contains(&entry.name) {
            continue;
        }
        tab.insert(entry.name.to_string(), mk_pm(entry.name, entry.flags));
    }
}

/// Insert a single PARTAB / PARTAB_ARRAY entry into paramtab. Called
/// from `zmodload <module>` once the module's boot completes, so that
/// `${+sysparams}` (etc.) flip from 0 → 1 only after explicit load.
/// No direct C counterpart — the C path runs through the module's
/// `setup_/boot_` chain which adds the SPECIALPMDEF entry via the
/// general hashtable machinery. Bug #69 in docs/BUGS.md.
pub fn seed_partab_param(name: &str) {
    use crate::ported::modules::parameter::{PARTAB, PARTAB_ARRAY};
    use crate::ported::zsh_h::{hashnode, param, PM_HIDE, PM_HIDEVAL, PM_READONLY, PM_SPECIAL};
    let mut tab = match crate::ported::params::paramtab().write() {
        Ok(t) => t,
        Err(_) => return,
    };
    if tab.contains_key(name) {
        return; // already seeded
    }
    let flags = PARTAB
        .iter()
        .find(|e| e.name == name)
        .map(|e| e.flags)
        .or_else(|| PARTAB_ARRAY.iter().find(|e| e.name == name).map(|e| e.flags));
    let Some(flags) = flags else {
        return;
    };
    let pm = Box::new(param {
        node: hashnode {
            next: None,
            nam: name.to_string(),
            flags: (flags & !(PM_READONLY as i32))
                | PM_SPECIAL as i32
                | PM_HIDE as i32
                | PM_HIDEVAL as i32,
        },
        u_data: 0,
        u_arr: None,
        u_str: None,
        u_val: 0,
        u_dval: 0.0,
        u_hash: None,
        gsu_s: None,
        gsu_i: None,
        gsu_f: None,
        gsu_a: None,
        gsu_h: None,
        base: 0,
        width: 0,
        env: None,
        ename: None,
        old: None,
        level: 0,
    });
    tab.insert(name.to_string(), pm);
}

/// Names provided by `zsh/system` / `zsh/mapfile` etc. that are
/// gated on explicit `zmodload`. Used by the bin_zmodload path to
/// re-seed paramtab after the module's boot completes.
pub fn module_gated_params_for(module: &str) -> &'static [&'static str] {
    match module {
        "zsh/system" => &["sysparams", "errnos"],
        "zsh/mapfile" => &["mapfile"],
        _ => &[],
    }
}
impl ShellExecutor {
    /// `enter_posix_mode` — see implementation.
    pub fn enter_posix_mode(&mut self) {
        self.posix_mode = true;
        self.plugin_cache = None;
        self.compsys_cache = None;
        self.compinit_pending = None;
        self.worker_pool = std::sync::Arc::new(crate::worker::WorkerPool::new(1));
        // Direct call to the canonical `emulate()` port
        // (Src/options.c:533) — `-R` semantics = fully=true.
        // bin_emulate goes through dispatch_builtin which needs an
        // ExecutorContext that isn't set up yet at apply_cli_flags
        // time; the underlying emulate() doesn't need one.
        crate::ported::options::emulate("sh", true);
    }
    /// `enter_ksh_mode` — see implementation.
    pub fn enter_ksh_mode(&mut self) {
        self.plugin_cache = None;
        self.compsys_cache = None;
        self.compinit_pending = None;
        self.worker_pool = std::sync::Arc::new(crate::worker::WorkerPool::new(1));
        crate::ported::options::emulate("ksh", true);
    }
}

/// Thin (text, pattern) → bool wrapper over the canonical
/// `patcompile()` + `pattry()` pair from `Src/pattern.c`. Argument
/// order is flipped so callers read naturally. Lives in vm_helper.rs
/// (non-port file) as the public convenience entry for extensions
/// and the VM bridge; `src/ported/*` files inline the compile+match
/// idiom directly to preserve PORT.md Rule 1 faithfulness.
pub fn glob_match_static(s: &str, pattern: &str) -> bool {
    let Some(prog) = patcompile(pattern, PAT_HEAPDUP as i32, None) else {
        return false;
    };
    // (#b) (GF_BACKREF) — capture-aware path. Use pattryrefs so the
    // per-group begin/end offsets surface, then write $match /
    // $mbegin / $mend (c:Src/pattern.c GF_BACKREF handling at
    // c:775 + c:2417). Falls through to the basic pattry path when
    // (#b) isn't on — that matches the previous behaviour exactly
    // and avoids the small extra cost (state clone + Vec<i32> alloc)
    // for the (#b)-free common case.
    let gf = prog.0.globflags;
    let has_backref = (gf & crate::ported::zsh_h::GF_BACKREF as i32) != 0;
    let matched;
    if has_backref {
        let mut nump: i32 = 0;
        let mut begp: Vec<i32> = Vec::new();
        let mut endp: Vec<i32> = Vec::new();
        matched = crate::ported::pattern::pattryrefs(
            &prog,
            s,
            s.len() as i32,
            -1,
            None,
            0,
            Some(&mut nump),
            Some(&mut begp),
            Some(&mut endp),
        );
        if matched {
            let n = (nump as usize).min(begp.len()).min(endp.len());
            let mut match_arr: Vec<String> = Vec::with_capacity(n);
            let mut begin_arr: Vec<String> = Vec::with_capacity(n);
            let mut end_arr: Vec<String> = Vec::with_capacity(n);
            // KSHARRAYS off → 1-based; on → 0-based. C path:
            // `setiparam("MBEGIN", patoffset + !isset(KSHARRAYS))`
            // — so the base offset added to each begin/end index.
            let ksharrays = crate::ported::zsh_h::isset(crate::ported::zsh_h::KSHARRAYS);
            let base = if ksharrays { 0 } else { 1 };
            for i in 0..n {
                let b = begp[i].max(0) as usize;
                let e = endp[i].max(0) as usize;
                let lo = b.min(s.len());
                let hi = e.min(s.len()).max(lo);
                match_arr.push(s[lo..hi].to_string());
                begin_arr.push((b + base).to_string());
                // mend is the INDEX of the last matched char (inclusive),
                // so end - 1 + base. For an empty span use the begin
                // offset (zsh's setiparam("MEND", mlen + patoffset + ...
                // - 1) shape from c:2444-2446).
                end_arr.push(((e + base).saturating_sub(1)).to_string());
            }
            crate::ported::params::setaparam("match", match_arr);
            crate::ported::params::setaparam("mbegin", begin_arr);
            crate::ported::params::setaparam("mend", end_arr);
        }
    } else {
        matched = pattry(&prog, s);
    }
    // c:Src/pattern.c GF_MATCHREF — `(#m)pat` writes the matched
    // substring to $MATCH on success. In `[[ str == pat ]]` cond
    // context the pattern matches the whole string, so on success
    // $MATCH = the input.
    if matched && pattern.contains("(#m)") {
        crate::ported::params::setsparam("MATCH", s);
        crate::ported::params::setiparam("MBEGIN", 1);
        crate::ported::params::setiparam("MEND", s.chars().count() as i64);
    }
    matched
}