zshrs 0.11.18

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
//! 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::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::{options, MAX_OPS};
use crate::ported::zsh_h::{PM_ARRAY, PM_HASHED, PM_INTEGER, PM_READONLY};
use crate::ported::zsh_h::WC_SIMPLE;
use crate::compsys::cache::CompsysCache;
use crate::compsys::CompInitResult;
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>,
    pub paramtab_hashed_storage: HashMap<String, IndexMap<String, String>>,
    pub positional_params: Vec<String>,
    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>,
}

#[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>,
    pub jobs: JobTable,
    pub fpath: Vec<PathBuf>,
    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,
    pub profiling_enabled: bool,
    // compsys - completion system cache
    pub compsys_cache: Option<CompsysCache>,
    // Background compinit — receiver for async fpath scan result
    pub compinit_pending: Option<(
        std::sync::mpsc::Receiver<CompInitBgResult>,
        std::time::Instant,
    )>,
    // Plugin source cache — stores side effects of source/. in SQLite
    pub plugin_cache: Option<crate::plugin_cache::PluginCache>,
    // cdreplay - deferred compdef calls for zinit turbo mode
    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)>>,
    /// 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.
    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, 0));
        }
    }


    /// 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);
    }

    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 from the
        // vendored zsh source. build.rs parses Config/version.mk and
        // emits the constants in `zsh_version`.
        setsparam("ZSH_VERSION", zsh_version::ZSH_VERSION);
        setsparam("ZSH_PATCHLEVEL", zsh_version::ZSH_PATCHLEVEL);
        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, errors enabled.
        setsparam("OPTIND", "1");
        setsparam("OPTERR", "1");
        // 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:params.c:858-860 — standard non-special param defaults.
        setsparam("MAILCHECK", "60");
        setsparam("KEYTIMEOUT", "40");
        setsparam("LISTMAX", "100");
        // c:config.h:1004 — MAX_FUNCTION_DEPTH=500. Advisory cap;
        // dispatch_function_call enforces against this.
        setsparam("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(),
            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};
                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. Consequence: `(t)LINENO`
                    // etc. read `integer-special` instead of zsh's
                    // `integer-readonly-special` — a parity gap on
                    // introspection metadata; runtime behavior matches.
                    let safe_pm_flags =
                        entry.pm_flags & (PM_TIED | PM_DI);
                    let mut bits = safe_pm_flags | PM_SPECIAL;
                    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;
                    } 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,
                            base: 0,
                            width: 0,
                            env: None,
                            ename: None,
                            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::{PM_EXPORTED, PM_SCALAR};
                use crate::ported::zsh_h::hashnode as _hn;
                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/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 {
            return Err("parse error".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. Remove first to prevent infinite
        // recursion, then run. Reads from canonical traps_table —
        // `bin_trap` writes (`Src/builtin.c`).
        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);
        }

        let _ = status;
        Ok(self.last_status())
    }

    #[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.
    pub fn dispatch_function_call(&mut self, name: &str, args: &[String]) -> Option<i32> {
        // Autoload prelude: PM_UNDEFINED stub → loadautofn → wrap + eval.
        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() {
                    // 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);
                }
            }
        }
        let chunk = 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
        let funcnest_limit: usize = self
            .scalar("FUNCNEST")
            .and_then(|s| s.parse().ok())
            .unwrap_or(100);
        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).
        let mut synth_shf = crate::ported::zsh_h::shfunc {
            node: crate::ported::zsh_h::hashnode {
                next: None,
                nam: display_name.clone(),
                flags: 0,
            },
            filename: self.function_def_file.get(name).cloned().flatten(),
            lineno: self.function_line_base.get(name).copied().unwrap_or(0) as i64,
            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());

        crate::fusevm_disasm::maybe_print_stdout(&format!("function:{name}"), &chunk);
        let chunk_for_run = chunk.clone();
        // 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_runner = move || -> i32 {
            let mut vm = fusevm::VM::new(chunk_for_run.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");
        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) => {
                    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!("zshrs:1: no such file or directory: {}", cmd);
                        } else {
                            eprintln!("zshrs:1: command not found: {}", cmd);
                        }
                        Ok(127)
                    } else {
                        Err(format!("zshrs: {}: {}", cmd, e))
                    }
                }
            }
        } else {
            match command.status() {
                Ok(status) => Ok(status.code().unwrap_or(1)),
                Err(e) => {
                    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!("zshrs:1: no such file or directory: {}", cmd);
                        } else {
                            eprintln!("zshrs:1: command not found: {}", 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!("zshrs:1: permission denied: {}", cmd);
                        Ok(126)
                    } else {
                        Err(format!("zshrs: {}: {}", 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()
        }
    }


    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();
            // 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();
                }
            }
        }

        // 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();
        }
        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();
                let _ctx = ExecutorContext::enter(self);
                let _ = vm.run();
                cmd_status = Some(vm.last_status);
                // 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.
        if let Some(status) = cmd_status {
            self.set_last_status(status);
        } else {
            self.set_last_status(0);
        }

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

        // 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(i32), // Contains child PID
    Child,
}

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

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);
        if nomatch && Self::looks_like_glob(pattern) {
            // 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> {
    for entry in PARTAB.iter() {
        if entry.name == name {
            return (entry.getfn)(std::ptr::null_mut(), key).and_then(|p| p.u_str);
        }
    }
    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>> {
    for entry in PARTAB_ARRAY.iter() {
        if entry.name == name {
            return Some((entry.getfn)(std::ptr::null_mut()));
        }
    }
    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>> {
    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,
    };
    // Strip PM_READONLY when seeding stubs: read-only Params block
    // INTERNAL writes from the runtime's own function-call /
    // funcstack-push paths that go through setaparam. Real reads
    // route via PARTAB getfn callbacks, not these stub Params, so
    // the readonly flag's purpose (block userspace assignment) is
    // moot for the stub anyway.
    //
    // 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.
    let mk_pm = |name: &str, flags: i32| -> Param {
        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,
        })
    };
    for entry in PARTAB.iter() {
        tab.insert(entry.name.to_string(), mk_pm(entry.name, entry.flags));
    }
    for entry in PARTAB_ARRAY.iter() {
        tab.insert(entry.name.to_string(), mk_pm(entry.name, entry.flags));
    }
}
impl ShellExecutor {
    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);
    }
    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 matched = patcompile(pattern, PAT_HEAPDUP as i32, None)
        .map_or(false, |p| pattry(&p, 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. Capture-group (#b) is deferred; (#m) is
    // the high-traffic case (zinit plugin-name matching).
    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
}