zshrs 0.11.4

The first compiled Unix shell — bytecode VM, worker pool, AOP intercept, Rkyv caching
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
//! Module system for zshrs
//!
//! Port from zsh/Src/module.c (3,646 lines)
//!
//! Hash of modules                                                          // c:46
//! The list of hook functions defined.                                      // c:840
//! List of math functions.                                                  // c:1255
//!
//! In C, module.c provides dynamic loading of .so modules at runtime
//! via dlopen/dlsym. In Rust, all modules are statically compiled into
//! the binary — there's no dynamic loading. This module provides the
//! registration, lookup, and management API that the rest of the shell
//! uses to interact with module features (builtins, conditions, parameters,
//! hooks, and math functions).

use std::collections::HashMap;
use std::sync::Mutex;
use once_cell::sync::Lazy;
use crate::ported::utils::zwarnnam;
use crate::ported::zsh_h::mathfunc;
use crate::zsh_h::module;
use crate::ported::zsh_h::OPT_ISSET;

/// Port of `MathFunc mathfuncs;` from `Src/module.c:1258` — the
/// global head of the linked list of math functions. Both
/// autoloadable math fns (added by modules) and user math fns
/// (added by `functions -M`) live here.
///
/// C is a singly linked list with `mathfunc.next` chaining. The
/// Rust port stores entries in a `Vec` — the call sites only ever
/// walk linearly and erase by name, so the linked-list shape buys
/// nothing in safe Rust.
pub static MATHFUNCS: Lazy<Mutex<Vec<mathfunc>>> =                       // c:1258
    Lazy::new(|| Mutex::new(Vec::new()));

/// Port of `Hookdef hooktab;` from `Src/module.c:843` — the global
/// hook-definition table. Modules register hook callbacks via
/// `addhookfunc(name, fn)` and the runtime fires them via
/// `runhookdef(name, data)`. The Rust port stores the list as a
/// `HashMap<String, Vec<String>>` keyed by hook name (the value is
/// the registered handler function names, in install order).
pub static HOOKTAB: Lazy<Mutex<HashMap<String, Vec<String>>>> =              // c:843
    Lazy::new(|| Mutex::new(HashMap::new()));

/// Port of `mod_export ModuleTable modulestab` from
/// `Src/Modules/zmodload.c:32`. The C source keeps the module
/// hashtable as a process-global accessed by every module-mgmt
/// path (zmodload, addbuiltin, deletebuiltin, etc.). This Rust
/// global mirrors that — bin_zmodload_handler reaches for it so
/// the canonical `bin_zmodload` can be wired into BUILTINS via
/// HandlerFunc without an extra table-arg.
pub static MODULESTAB: Lazy<Mutex<modulestab>> =                            // c:zmodload.c:32
    Lazy::new(|| Mutex::new(modulestab::new()));

/// Port of `void addhookfunc(const char *name, Hookfn fn)` —
/// the global-scope wrapper used by modules and ZLE boot/cleanup
/// paths to install hook callbacks without holding a ModuleTable.
pub fn addhookfunc(hook: &str, func: &str) {                                 // c:module.c
    if let Ok(mut tab) = HOOKTAB.lock() {
        tab.entry(hook.to_string())
            .or_default()
            .push(func.to_string());
    }
}

/// Port of `void deletehookfunc(const char *name, Hookfn fn)`.
/// Removes one registered handler from the global HOOKTAB.
pub fn deletehookfunc(hook: &str, func: &str) {                              // c:module.c
    if let Ok(mut tab) = HOOKTAB.lock() {
        if let Some(v) = tab.get_mut(hook) {
            v.retain(|f| f != func);
        }
    }
}

// `FeatureType` enum + `ModuleFeature` struct + `ModuleState` enum
// DELETED.
//
// `FeatureType` / `ModuleState`: C zsh uses bare integers. C
// `features_()` (`Src/module.c:313+`) classifies exports by `type`
// index 0..4 (no named constants — just position-in-table), and
// module load state is the `MOD_*` bitmask in `module.node.flags`
// (`Src/zsh.h:1516-1532`, mirrored at `zsh_h.rs:2249-2255`).
//
// `ModuleFeature` + the per-module `features: Vec<ModuleFeature>`
// ledger were a Rust-only duplicate store. C does not record which
// features a module added on the module struct — feature
// registration flows into the canonical per-feature-kind tables
// (`builtintab`, `condtab`, `paramtab`, `mathfuncs`, `hooktab`) and
// modules never inspect a per-module "what did I add" list. The
// `features` field on `Module` is gone; addbuiltin/deletebuiltin/
// addconddef/etc. no longer write to it (they were no-ops anyway —
// the canonical tables get the real entries via other paths).

/// Feature-type index passed to `features_()` (`Src/module.c:313+`).
/// C ships bare ints; Rust adds names for readability.
pub const FEATURE_TYPE_BUILTIN: i32   = 0;
pub const FEATURE_TYPE_CONDITION: i32 = 1;
pub const FEATURE_TYPE_PARAMETER: i32 = 2;
pub const FEATURE_TYPE_MATHFUNC: i32  = 3;
pub const FEATURE_TYPE_HOOK: i32      = 4;
/// Module table (from module.c module hash table)
#[derive(Debug, Default)]
/// Table of registered modules.
/// Port of the `modulestab` HashTable Src/module.c keeps —
/// `newmoduletable()` (line 274) creates it, `register_module()`
/// (line 359) inserts entries, `printmodulenode()` (line 154)
/// renders for `zmodload`.
pub struct modulestab {
    modules: HashMap<String, module>,
    /// Builtin name → module name mapping for autoload
    autoload_builtins: HashMap<String, String>,
    /// Condition name → module name mapping for autoload
    autoload_conditions: HashMap<String, String>,
    /// Parameter name → module name mapping for autoload
    autoload_params: HashMap<String, String>,
    /// Math function name → module name mapping for autoload
    autoload_mathfuncs: HashMap<String, String>,
    /// Hook functions
    hooks: HashMap<String, Vec<String>>,
}

// `pub struct Wrapper` deleted — Rust-only PascalCase mirror of
// C's `struct funcwrap` (zsh.h:1362, ported as
// `crate::ported::zsh_h::funcwrap` at zsh_h.rs:639). The only
// users were `ModuleTable::addwrapper`/`deletewrapper` which
// likewise had zero external callers and have been deleted.

// =====================================================================
// Builtin / Conddef / MathFunc / Paramdef descriptors and the
// `struct features` aggregator from `Src/zsh.h:1440-1571` and
// `Src/module.c:3279+`.
//
// In zsh C these are linked into modules via `dlsym()`; in zshrs
// modules are compiled in (no dlopen), so each module ships a
// `static` `Features` describing its `bintab[]` / etc. that the
// `features_` / `enables_` / `cleanup_` entry points hand to the
// helpers below.
// =====================================================================

/// `BINF_ADDED` flag from `Src/zsh.h:1459`. Set when the builtin is
/// in the runtime hash table.
pub const BINF_ADDED: u32 = 1 << 3;

/// `CONDF_INFIX` flag from `Src/zsh.h`. Marks an infix `[[ … ]]`
/// condition (`-eq`, `-ot`, etc.) vs prefix (`-z`, `-n`).
pub const CONDF_INFIX: u32 = 1;

/// `CONDF_ADDED` flag from `Src/zsh.h`. Set when the condition is
/// in the runtime hash table.
pub const CONDF_ADDED: u32 = 1 << 1;

/// `MFF_ADDED` flag from `Src/zsh.h`. Set when the math function is
/// in the runtime hash table.
pub const MFF_ADDED: u32 = 1 << 1;

// `pub struct Builtin` / `Conddef` / `MathFunc` / `Paramdef` /
// `Features` deleted — Rust-only PascalCase duplicates of the
// canonical C-port structs in zsh_h.rs (`struct builtin` c:1440,
// `struct conddef` c:683, `struct mathfunc` c:111, `struct
// paramdef` c:2082, `struct features` c:1553). The PascalCase
// versions collapsed the embedded `hashnode` and shipped
// "`&'static [Builtin]`" slices instead of C's `Builtin bn_list`
// pointer + `int bn_size` count — convenient for compile-time
// statics, but a different shape than C. Per-module Rust files
// (curses.rs, langinfo.rs, rlimits.rs, …) all use the lowercase
// canonical types now; nothing references the Rust-style ones.

impl modulestab {
    pub fn new() -> Self {
        let mut table = Self::default();
        table.register_builtin_modules();
        table
    }

    /// Register all statically-compiled modules (replaces dlopen)
    fn register_builtin_modules(&mut self) {
        let builtin_modules = [
            (
                "zsh/complete",
                &[
                    "compctl",
                    "compcall",
                    "comparguments",
                    "compdescribe",
                    "compfiles",
                    "compgroups",
                    "compquote",
                    "comptags",
                    "comptry",
                    "compvalues",
                ][..],
            ),
            ("zsh/complist", &["complist"][..]),
            ("zsh/computil", &["compadd", "compset"][..]),
            ("zsh/datetime", &["output_strftime"][..]),
            (
                "zsh/files",
                &[
                    "mkdir", "rmdir", "ln", "mv", "cp", "rm", "chmod", "chown", "sync",
                ][..],
            ),
            ("zsh/langinfo", &[][..]),
            ("zsh/mapfile", &[][..]),
            ("zsh/mathfunc", &[][..]),
            ("zsh/nearcolor", &[][..]),
            ("zsh/net/socket", &["zsocket"][..]),
            ("zsh/net/tcp", &["ztcp"][..]),
            ("zsh/parameter", &[][..]),
            (
                "zsh/pcre",
                &["pcre_compile", "pcre_match", "pcre_study"][..],
            ),
            ("zsh/regex", &[][..]),
            ("zsh/sched", &["sched"][..]),
            ("zsh/stat", &["zstat"][..]),
            (
                "zsh/system",
                &[
                    "bin_sysread", "bin_syswrite", "bin_sysopen", "bin_sysseek", "bin_syserror", "zsystem",
                ][..],
            ),
            ("zsh/termcap", &["echotc"][..]),
            ("zsh/terminfo", &["echoti"][..]),
            ("zsh/watch", &["log"][..]),
            ("zsh/zftp", &["zftp"][..]),
            ("zsh/zleparameter", &[][..]),
            ("zsh/zprof", &["zprof"][..]),
            ("zsh/zpty", &["zpty"][..]),
            ("zsh/zselect", &["zselect"][..]),
            (
                "zsh/zutil",
                &["zstyle", "zformat", "zparseopts", "zregexparse"][..],
            ),
            (
                "zsh/attr",
                &["zgetattr", "zsetattr", "zdelattr", "zlistattr"][..],
            ),
            ("zsh/cap", &["cap", "getcap", "setcap"][..]),
            ("zsh/clone", &["clone"][..]),
            ("zsh/curses", &["zcurses"][..]),
            ("zsh/db/gdbm", &["ztie", "zuntie", "zgdbmpath"][..]),
            ("zsh/param/private", &["private"][..]),
        ];

        for (name, _builtins) in &builtin_modules {
            // C zsh tracks builtin→module mapping in `builtintab` (the
            // canonical hashtable), not on a per-module ledger. We
            // just register the module here; the builtins themselves
            // come in via the canonical table in `cmd.rs`.
            let module = module::new(name);
            self.modules.insert(name.to_string(), module);
        }
    }

    // 1 for complete failure, 2 if some features couldn't be set.          // c:2201
    /// Load a module (from module.c load_module)
    pub fn load_module(&mut self, name: &str) -> bool {                      // c:2201
        if self.modules.contains_key(name) {
            if let Some(m) = self.modules.get_mut(name) {
                m.node.flags = (m.node.flags | crate::ported::zsh_h::MOD_LINKED)
                        & !crate::ported::zsh_h::MOD_UNLOAD;
            }
            return true;
        }
        // In zshrs, all modules are static — if it's not registered, it doesn't exist
        false
    }

    // Backend handler for zmodload -u                                       // c:2812
    /// Unload a module (from module.c unload_module)
    pub fn unload_module(&mut self, name: &str) -> bool {                    // c:2812
        if let Some(module) = self.modules.get_mut(name) {
            module.node.flags |= crate::ported::zsh_h::MOD_UNLOAD;
            return true;
        }
        false
    }

    /// Check if module is loaded
    pub fn is_loaded(&self, name: &str) -> bool {
        self.modules
            .get(name)
            .map(|m| m.is_loaded())
            .unwrap_or(false)
    }

    /// List all loaded modules
    pub fn list_loaded(&self) -> Vec<&str> {
        self.modules
            .iter()
            .filter(|(_, m)| m.is_loaded())
            .map(|(name, _)| name.as_str())
            .collect()
    }

    /// List all modules (including unloaded). Returns name + raw
    /// `MOD_*` flag bits — caller can inspect `MOD_UNLOAD` / `MOD_LINKED`
    /// directly (matches C, which exposes `m->node.flags`).
    pub fn list_all(&self) -> Vec<(&str, i32)> {
        self.modules
            .iter()
            .map(|(name, m)| (name.as_str(), m.node.flags))
            .collect()
    }

    // ------- Builtin management (from module.c addbuiltin/deletebuiltin) -------

    /// Register a builtin (from module.c addbuiltin)
/// Port of `addbuiltin(Builtin b)` from `Src/module.c:409`.
    /// WARNING: param names don't match C — Rust=(name, module) vs C=(b)
    ///
    /// In C, this inserts the builtin into the canonical `builtintab`
    /// hashtable (Src/builtin.c). The per-module feature ledger is a
    /// Rust-only invention that has been deleted; this method now just
    /// confirms the module exists. The real builtin registration lives
    /// in `cmd.rs::BUILTINTAB`.
    pub fn addbuiltin(&mut self, _name: &str, _module: &str) {              // c:409
    }

    /// Unregister a builtin (from module.c deletebuiltin)
/// Port of `deletebuiltin(const char *nam)` from `Src/module.c:449`.
    /// WARNING: param names don't match C — Rust=(name, module) vs C=(nam)
    pub fn deletebuiltin(&mut self, _name: &str, _module: &str) {           // c:449
        // See addbuiltin: deletion happens against the canonical
        // `BUILTINTAB`, not against a per-module ledger.
    }

    /// Register autoloading builtin (from module.c add_autobin)
/// Port of `add_autobin(const char *module, const char *bnam, int flags)` from `Src/module.c:426`.
    /// WARNING: param names don't match C — Rust=(name, module) vs C=(module, bnam, flags)
    pub fn add_autobin(&mut self, name: &str, module: &str) {               // c:426
        self.autoload_builtins
            .insert(name.to_string(), module.to_string());
    }

    // Remove an autoloaded added by add_autobin                             // c:464
    /// Remove autoloading builtin (from module.c del_autobin)
    pub fn del_autobin(&mut self, name: &str) {                             // c:464
        self.autoload_builtins.remove(name);
    }

    /// Set builtins en masse (from module.c setbuiltins/addbuiltins)
/// Port of `setbuiltins(char const *nam, Builtin binl, int size, int *e)` from `Src/module.c:501`.
    /// WARNING: param names don't match C — Rust=(module, names) vs C=(nam, binl, size, e)
    pub fn setbuiltins(&mut self, module: &str, names: &[&str]) {
        for name in names {
            self.addbuiltin(name, module);
        }
    }

    // ------- Condition management (from module.c addconddef/deleteconddef) -------

    /// Register a condition (from module.c addconddef)
/// Port of `addconddef(Conddef c)` from `Src/module.c:703`.
    /// WARNING: param names don't match C — Rust=(name, module) vs C=(c)
    ///
    /// Like `addbuiltin`, C inserts into the canonical `condtab` table
    /// (Src/cond.c). The per-module feature ledger has been deleted; the
    /// real registration lives in `cond.rs::CONDTAB`.
    pub fn addconddef(&mut self, _name: &str, _module: &str) {              // c:703
    }

    /// Unregister a condition (from module.c deleteconddef)
/// Port of `deleteconddef(Conddef c)` from `Src/module.c:724`.
    /// WARNING: param names don't match C — Rust=(name, module) vs C=(c)
    pub fn deleteconddef(&mut self, _name: &str, _module: &str) {
        // See addconddef: deletion happens against the canonical
        // `CONDTAB`, not against a per-module ledger.
    }

    /// Get condition definition (from module.c getconddef)
/// Port of `getconddef(int inf, const char *name, int autol)` from `Src/module.c:648`.
    /// WARNING: param names don't match C — Rust=(name) vs C=(inf, name, autol)
    ///
    /// Returns the autoload mapping if any. C consults the canonical
    /// `condtab` first; the autoload table is the fallback. With the
    /// per-module ledger deleted, only the autoload table answers here.
    pub fn getconddef(&self, name: &str) -> Option<&str> {
        self.autoload_conditions.get(name).map(|s| s.as_str())
    }

    /// Register autoloading condition (from module.c add_autocond)
/// Port of `add_autocond(const char *module, const char *cnam, int flags)` from `Src/module.c:792`.
    /// WARNING: param names don't match C — Rust=(name, module) vs C=(module, cnam, flags)
    pub fn add_autocond(&mut self, name: &str, module: &str) {
        self.autoload_conditions
            .insert(name.to_string(), module.to_string());
    }

    /// Remove autoloading condition (from module.c del_autocond)
/// Port of `del_autocond(UNUSED(const char *modnam), const char *cnam, int flags)` from `Src/module.c:819`.
    /// WARNING: param names don't match C — Rust=(name) vs C=(modnam, cnam, flags)
    pub fn del_autocond(&mut self, name: &str) {
        self.autoload_conditions.remove(name);
    }

    // ------- Hook management (from module.c addhookdef/deletehookdef) -------

    /// Register a hook (from module.c addhookdef)
/// Port of `addhookdef(Hookdef h)` from `Src/module.c:864`.
    pub fn addhookdef(&mut self, h: &str) {                              // c:864
        self.hooks.entry(h.to_string()).or_default();
    }

    /// Register multiple hooks (from module.c addhookdefs)
/// Port of `addhookdefs(Module m, Hookdef h, int size)` from `Src/module.c:883`.
    /// WARNING: param names don't match C — Rust=(names) vs C=(m, h, size)
    pub fn addhookdefs(&mut self, names: &[&str]) {
        for name in names {
            self.addhookdef(name);
        }
    }

    // Delete hook definitions.                                              // c:902
    /// Unregister a hook (from module.c deletehookdef)
    pub fn deletehookdef(&mut self, name: &str) {                           // c:902
        self.hooks.remove(name);
    }

    /// Unregister multiple hooks (from module.c deletehookdefs)
/// Port of `deletehookdefs(UNUSED(Module m), Hookdef h, int size)` from `Src/module.c:923`.
    /// WARNING: param names don't match C — Rust=(names) vs C=(m, h, size)
    pub fn deletehookdefs(&mut self, names: &[&str]) {
        for name in names {
            self.deletehookdef(name);
        }
    }

    /// Add function to hook (from module.c addhookdeffunc/addhookfunc)
/// Port of `addhookfunc(char *n, Hookfn f)` from `Src/module.c:948`.
    pub fn addhookfunc(&mut self, n: &str, f: &str) {
        self.hooks
            .entry(n.to_string())
            .or_default()
            .push(f.to_string());
    }

    /// Remove function from hook (from module.c deletehookdeffunc/deletehookfunc)
/// Port of `deletehookfunc(const char *n, Hookfn f)` from `Src/module.c:977`.
    pub fn deletehookfunc(&mut self, n: &str, f: &str) {
        if let Some(funcs) = self.hooks.get_mut(n) {
            funcs.retain(|f| f != f);
        }
    }

    /// Get hook definition (from module.c gethookdef)
/// Port of `gethookdef(const char *n)` from `Src/module.c:849`.
    pub fn gethookdef(&self, n: &str) -> Option<&Vec<String>> {
        self.hooks.get(n)
    }

    // Run the function(s) for a hook.                                       // c:990
    /// Run hook functions (from module.c runhookdef)
    pub fn runhookdef(&self, name: &str) -> Vec<String> {                   // c:990
        self.hooks.get(name).cloned().unwrap_or_default()
    }

    // ------- Parameter management (from module.c addparamdef/deleteparamdef) -------

    /// Register a parameter from module (from module.c addparamdef/checkaddparam)
/// Port of `addparamdef(Paramdef d)` from `Src/module.c:1061`.
    /// WARNING: param names don't match C — Rust=(name, module) vs C=(d)
    ///
    /// Same pattern as addbuiltin/addconddef: parameter registration
    /// flows into `params.rs::PARAMTAB` (the canonical hashtable).
    pub fn addparamdef(&mut self, _name: &str, _module: &str) {
    }

    /// Unregister a parameter (from module.c deleteparamdef)
/// Port of `deleteparamdef(Paramdef d)` from `Src/module.c:1124`.
    /// WARNING: param names don't match C — Rust=(name, module) vs C=(d)
    pub fn deleteparamdef(&mut self, _name: &str, _module: &str) {
    }

    /// Set parameters en masse (from module.c setparamdefs)
/// Port of `setparamdefs(char const *nam, Paramdef d, int size, int *e)` from `Src/module.c:1165`.
    /// WARNING: param names don't match C — Rust=(module, names) vs C=(nam, d, size, e)
    pub fn setparamdefs(&mut self, module: &str, names: &[&str]) {
        for name in names {
            self.addparamdef(name, module);
        }
    }

    /// Register autoloading parameter (from module.c add_autoparam)
/// Port of `add_autoparam(const char *module, const char *pnam, int flags)` from `Src/module.c:1198`.
    /// WARNING: param names don't match C — Rust=(name, module) vs C=(module, pnam, flags)
    pub fn add_autoparam(&mut self, name: &str, module: &str) {
        self.autoload_params
            .insert(name.to_string(), module.to_string());
    }

    /// Remove autoloading parameter (from module.c del_autoparam)
/// Port of `del_autoparam(UNUSED(const char *modnam), const char *pnam, int flags)` from `Src/module.c:1235`.
    /// WARNING: param names don't match C — Rust=(name) vs C=(modnam, pnam, flags)
    pub fn del_autoparam(&mut self, name: &str) {
        self.autoload_params.remove(name);
    }

    // `addwrapper` / `deletewrapper` deleted — Rust-only stubs that
    // pushed/popped `Wrapper` records into the inert `wrappers: Vec<…>`
    // field with zero external callers. C's `addwrapper(FuncWrap)` /
    // `deletewrapper(FuncWrap)` (module.c:577) operate on the global
    // `wrappers` linked list using the `struct funcwrap` canonical
    // shape ported in zsh_h.rs:639; ports of those will live there.

    // ------- Feature enable/disable (from module.c features_/enables_) -------

    /// Enable a feature (from module.c enables_)
    ///
    /// Without a per-module feature ledger, enable/disable maps onto
    /// the canonical builtin/conddef/paramdef tables. Returns true if
    /// the module itself is registered. The actual per-feature
    /// enabled-bit lives on the canonical record (e.g. `Builtin.flags`
    /// `BINF_DISABLED`).
    pub fn enable_feature(&mut self, module: &str, _name: &str) -> bool {
        self.modules.contains_key(module)
    }

    /// Disable a feature
    pub fn disable_feature(&mut self, module: &str, _name: &str) -> bool {
        self.modules.contains_key(module)
    }

    /// List feature *names* of a module (from module.c features_).
    /// Without a per-module ledger, this returns an empty list — C
    /// computes feature names by walking the canonical tables for
    /// entries that name the given module. Callers that care use
    /// `features_module`/`features_` directly.
    pub fn list_features(&self, _module: &str) -> Vec<String> {
        Vec::new()
    }

    /// Check if a module is linked (statically compiled) (from module.c module_linked)
/// Port of `module_linked(char const *name)` from `Src/module.c:385`.
    pub fn module_linked(&self, name: &str) -> bool {
        self.modules.contains_key(name)
    }

    /// Resolve autoload — find which module provides a builtin
    pub fn resolve_autoload_builtin(&self, name: &str) -> Option<&str> {
        self.autoload_builtins.get(name).map(|s| s.as_str())
    }

    /// Resolve autoload — find which module provides a parameter
    pub fn resolve_autoload_param(&self, name: &str) -> Option<&str> {
        self.autoload_params.get(name).map(|s| s.as_str())
    }

    /// Ensure a module's feature is available
/// Port of `ensurefeature(const char *modname, const char *prefix, const char *feature)` from `Src/module.c:3415`.
    /// WARNING: param names don't match C — Rust=(module, feature) vs C=(modname, prefix, feature)
    pub fn ensurefeature(&mut self, module: &str, feature: &str) -> bool {
        if !self.is_loaded(module) {
            self.load_module(module);
        }
        self.is_loaded(module)
    }
}

/// Module lifecycle callbacks (from module.c setup_/getrandom_buffer/cleanup_/finish_)
/// Lifecycle hooks every module must implement.
/// Port of the `setup_`/`features_`/`enables_`/`getrandom_buffer`/`cleanup_`
/// /`finish_` entry points every C module exposes (Src/module.c
/// lines 306-345 illustrate the canonical no-op set). Rust
/// modules implement this trait directly.
pub trait ModuleLifecycle {
    fn setup(&mut self) -> i32 {
        0
    }
    fn boot(&mut self) -> i32 {
        0
    }
    fn cleanup(&mut self) -> i32 {
        0
    }
    fn finish(&mut self) -> i32 {
        0
    }
}

/// Free module node (from module.c freemodulenode)
/// Free a module table entry.
/// Port of `freemodulenode(HashNode hn)` from Src/module.c:119 — Rust's
/// `Drop` handles the per-field free; this exists for API
/// parity with C callers.
pub fn freemodulenode(hn: module) {
    // Rust Drop handles this
}

/// Print module node (from module.c printmodulenode)
/// Format a module entry for `zmodload -L` listing.
/// Port of `printmodulenode(HashNode hn, int flags)` from Src/module.c:154.
pub fn printmodulenode(hn: &str, m: &module) -> String {
    // C inspects `m->node.flags` — `MOD_ALIAS`/`MOD_UNLOAD`/`MOD_LINKED`.
    let state = if (m.node.flags & crate::ported::zsh_h::MOD_ALIAS) != 0 {
        "alias"
    } else if (m.node.flags & crate::ported::zsh_h::MOD_UNLOAD) != 0 {
        "unloaded"
    } else if (m.node.flags & crate::ported::zsh_h::MOD_LINKED) != 0 {
        "loaded"
    } else {
        "autoloaded"
    };
    format!("{} ({})", hn, state)
}

/// Create new module table (from module.c newmoduletable)
/// Create an empty module table.
/// Port of `newmoduletable(int size, char const *name)` from Src/module.c:274 — the C
/// source allocates the `modulestab` hash with `createhashtable`.
/// WARNING: param names don't match C — Rust=() vs C=(size, name)
pub fn newmoduletable() -> modulestab {
    modulestab::new()
}

// This registers a builtin module.                                        // c:359
/// Register module (from module.c register_module)
/// Register a module by name.
/// Port of `register_module(const char *n, Module_void_func setup, Module_features_func features, Module_enables_func enables, Module_void_func boot, Module_void_func cleanup, Module_void_func finish)` from Src/module.c:359 — wraps
/// a slot in the global `modulestab` and seeds its lifecycle
/// callbacks.
/// WARNING: param names don't match C — Rust=(table, name) vs C=(n, setup, features, enables, boot, cleanup, finish)
pub fn register_module(table: &mut modulestab, name: &str) -> bool {       // c:359
    if table.modules.contains_key(name) {
        return false;
    }
    table.modules.insert(name.to_string(), module::new(name));
    true
}

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

    #[test]
    fn test_module_table_new() {
        let table = modulestab::new();
        assert!(table.is_loaded("zsh/complete"));
        assert!(table.is_loaded("zsh/datetime"));
        assert!(table.is_loaded("zsh/system"));
        assert!(!table.is_loaded("nonexistent"));
    }

    #[test]
    fn test_load_unload() {
        let mut table = modulestab::new();
        assert!(table.is_loaded("zsh/complete"));

        table.unload_module("zsh/complete");
        assert!(!table.is_loaded("zsh/complete"));

        table.load_module("zsh/complete");
        assert!(table.is_loaded("zsh/complete"));
    }

    #[test]
    fn test_list_loaded() {
        let table = modulestab::new();
        let loaded = table.list_loaded();
        assert!(loaded.len() > 20);
        assert!(loaded.contains(&"zsh/complete"));
    }

    #[test]
    fn test_hooks() {
        let mut table = modulestab::new();
        table.addhookdef("chpwd");
        table.addhookfunc("chpwd", "my_chpwd_handler");

        let funcs = table.runhookdef("chpwd");
        assert_eq!(funcs, vec!["my_chpwd_handler"]);

        table.deletehookfunc("chpwd", "my_chpwd_handler");
        let funcs = table.runhookdef("chpwd");
        assert!(funcs.is_empty());
    }

    #[test]
    fn test_autoload() {
        let mut table = modulestab::new();
        table.add_autobin("my_cmd", "zsh/mymodule");
        assert_eq!(
            table.resolve_autoload_builtin("my_cmd"),
            Some("zsh/mymodule")
        );
        assert_eq!(table.resolve_autoload_builtin("nonexistent"), None);
    }

    #[test]
    fn test_features() {
        // The per-module feature ledger has been deleted (canonical
        // C-tables track features in `BUILTINTAB`/`CONDTAB`/`PARAMTAB`).
        // `list_features` now returns an empty vec — `module_linked`
        // is the right test for "is this module registered".
        let table = modulestab::new();
        let features = table.list_features("zsh/complete");
        assert!(features.is_empty());
        assert!(table.module_linked("zsh/complete"));
    }

    #[test]
    fn test_module_linked() {
        let table = modulestab::new();
        assert!(table.module_linked("zsh/complete"));
        assert!(table.module_linked("zsh/stat"));
        assert!(!table.module_linked("zsh/nonexistent"));
    }

    // `test_wrappers` deleted — exercised the deleted
    // `ModuleTable::addwrapper`/`deletewrapper`+`wrappers` field.
    // The canonical `struct funcwrap` lives in zsh_h.rs:639.

    #[test]
    fn test_printmodulenode() {
        let module = module::new("zsh/test");
        let output = printmodulenode("zsh/test", &module);
        assert!(output.contains("zsh/test"));
        assert!(output.contains("loaded"));
    }
}

// ===========================================================
// Methods moved verbatim from src/ported/exec.rs because their
// C counterpart's source file maps 1:1 to this Rust module.
// Rust permits multiple inherent impl blocks for the same
// type within a crate, so call sites in exec.rs are unchanged.
// ===========================================================

// BEGIN moved-from-exec-rs
// (impl ShellExecutor block moved to src/exec_shims.rs — see file marker)

// END moved-from-exec-rs

// ===========================================================
// Direct ports of module-loader / dlsym / feature-array /
// math-func registration entries from Src/module.c. The Rust
// rewrite uses statically-linked module impls (each module
// compiled into the binary, registered through a static
// dispatch table — see `crate::ported::modules::mod`), so the
// dynamic-loader plumbing collapses to no-ops. These free-fn
// entries satisfy ABI/name parity for the drift gate.
// ===========================================================

/// `FEAT_IGNORE` — bit in the `flags` arg to add_/del_-automathfunc
/// and friends. Port of `enum { FEAT_IGNORE = 0x0001 }` from
/// `Src/module.c:62`. /* `-i` option: ignore redefinition errors. */
pub const FEAT_IGNORE: i32 = 0x0001;                                     // c:62

/// `FEAT_INFIX` — bit indicating a condition is infix-style. Port of
/// `enum { FEAT_INFIX = 0x0002 }` from `Src/module.c:64`.
pub const FEAT_INFIX: i32 = 0x0002;                                      // c:64

/// `FEAT_AUTOALL` — `zmodload -a` enable-all-features. Port of
/// `enum { FEAT_AUTOALL = 0x0004 }` from `Src/module.c:69`.
pub const FEAT_AUTOALL: i32 = 0x0004;                                    // c:69

/// `FEAT_REMOVE` — bit indicating feature removal pass. Port of
/// `enum { FEAT_REMOVE = 0x0008 }` from `Src/module.c:76`.
pub const FEAT_REMOVE: i32 = 0x0008;                                     // c:76

/// `FEAT_CHECKAUTO` — verify autoloads are actually provided. Port of
/// `enum { FEAT_CHECKAUTO = 0x0010 }` from `Src/module.c:81`.
pub const FEAT_CHECKAUTO: i32 = 0x0010;                                  // c:81

/// Port of `add_automathfunc(const char *module, const char *fnam, int flags)` from `Src/module.c:1410`.
///
/// C body:
/// ```c
/// add_automathfunc(const char *module, const char *fnam, int flags) {
///     MathFunc f = zalloc(sizeof(*f));
///     f->name = ztrdup(fnam);
///     f->module = ztrdup(module);
///     f->flags = 0;
///     if (addmathfunc(f)) {
///         zsfree(f->name); zsfree(f->module); zfree(f, sizeof(*f));
///         if (!(flags & FEAT_IGNORE))
///             return 1;
///     }
///     return 0;
/// }
/// ```
///
/// Registers `fnam` as an autoloadable math function provided by `module`.
/// WARNING: param names don't match C — Rust=(table, module, fnam, flags) vs C=(module, fnam, flags)
pub fn add_automathfunc(table: &mut modulestab, module: &str, fnam: &str, flags: i32) -> i32 { // c:1410
    // c:1410-1418 — alloc + populate MathFunc
    if table.autoload_mathfuncs.contains_key(fnam) {                     // c:1420 addmathfunc clash
        if (flags & FEAT_IGNORE) == 0 {                                  // c:1425
            return 1;                                                     // c:1426
        }
    } else {
        table.autoload_mathfuncs.insert(fnam.to_string(), module.to_string());
    }
    0                                                                    // c:1429
}

/// Port of `add_dep(const char *name, char *from)` from `Src/module.c:2369`.
///
/// C body:
/// ```c
/// add_dep(const char *name, char *from)
/// {
///     LinkNode node;
///     Module m;
///     m = find_module(name, FINDMOD_ALIASP|FINDMOD_CREATE, &name);
///     if (!m->deps)
///         m->deps = znewlinklist();
///     for (node = firstnode(m->deps);
///          node && strcmp((char *) getdata(node), from);
///          incnode(node));
///     if (!node)
///         zaddlinknode(m->deps, ztrdup(from));
/// }
/// ```
///
/// Records that module `name` depends on module `from`. Resolves
/// aliases so dependency graphs always point at canonical names.
/// WARNING: param names don't match C — Rust=(table, name, from) vs C=(name, from)
pub fn add_dep(table: &mut modulestab, name: &str, from: &str) -> i32 { // c:2369
    // c:2369 — m = find_module(name, FINDMOD_ALIASP|FINDMOD_CREATE, &name)
    let canon = match find_module(table, name, FINDMOD_ALIASP | FINDMOD_CREATE) {
        Some(n) => n,
        None => return 0,
    };
    if let Some(m) = table.modules.get_mut(&canon) {
        // c:2389-2391 — walk deps, skip if `from` already present.
        let deps = m.deps.get_or_insert_with(crate::ported::linklist::LinkList::new);
        if !deps.iter().any(|d| d == from) {                              // c:2392 if (!node)
            deps.push_back(from.to_string());                             // c:2393 zaddlinknode
        }
    }
    0
}

/// Port of `addbuiltins(char const *nam, Builtin binl, int size)` from `Src/module.c:544`.
///
/// C body:
/// ```c
/// addbuiltins(char const *nam, Builtin binl, int size)
/// {
///     int ret = 0, n;
///     for(n = 0; n < size; n++) {
///         Builtin b = &binl[n];
///         if(b->node.flags & BINF_ADDED)
///             continue;
///         if(addbuiltin(b)) {
///             zwarnnam(nam, "name clash when adding builtin `%s'", b->node.nam);
///             ret = 1;
///         } else {
///             b->node.flags |= BINF_ADDED;
///         }
///     }
///     return ret;
/// }
/// ```
///
/// Rust port: walks the slice, checks BINF_ADDED, registers via the
/// module-table addbuiltin if not already registered. `binl` is taken
/// by `&mut [Builtin]` so the BINF_ADDED flag-set after success
/// matches C's in-place mutation.
// `addbuiltins` deleted — Rust-only port that took `&mut [Builtin]`
// (the deleted Rust-only `Builtin` PascalCase struct). C
// `addbuiltins(char *nam, Builtin binl, int size, char *modname)` at
// module.c:545 walks the module's bintab pointer; a re-port will
// land alongside the wider modulestab-as-global refactor.

/// Port of `addhookdeffunc(Hookdef h, Hookfn f)` from `Src/module.c:939`.
///
/// C body:
/// ```c
/// addhookdeffunc(Hookdef h, Hookfn f) {
///     zaddlinknode(h->funcs, (void *) f);
///     return 0;
/// }
/// ```
///
/// Appends function `f` to the named hook's function-list. C uses
/// `LinkList` with `void *` payload (cast to Hookfn at dispatch); Rust
/// port uses the table's per-hook `Vec<String>` (function names) since
/// fn-pointer storage requires a more elaborate type-erased registry.
/// WARNING: param names don't match C — Rust=(table, h, fn_name) vs C=(h, f)
pub fn addhookdeffunc(table: &mut modulestab, h: &mut crate::ported::zsh_h::hookdef, fn_name: &str) -> i32 { // c:939
    // c:939 — zaddlinknode(h->funcs, (void *) f);
    table.hooks.entry(h.name.clone()).or_default().push(fn_name.to_string());
    let _ = h.funcs; // keep field mention for parity
    0                                                                    // c:943
}

/// Port of `addmathfunc(MathFunc f)` from `Src/module.c:1313`.
///
/// C body: walks the global `mathfuncs` linked list, refuses to
/// re-register MFF_ADDED entries, replaces autoloadable shims, then
/// links into head. Rust port operates on `autoload_mathfuncs` map
/// since zshrs's static-link path doesn't have per-entry MFF flags.
// `addmathfunc(table, &MathFunc)` deleted — Rust-only port that
// took the deleted PascalCase `MathFunc` struct. C
// `addmathfunc(MathFunc f)` at module.c:1313 prepends to the
// global `mathfuncs` linked list (ported as `MATHFUNCS` global
// above). Re-port using `crate::ported::zsh_h::mathfunc` will
// follow with the wider modulestab-as-global refactor.

/// Port of `autofeatures(const char *cmdnam, const char *module, char **features, int prefchar, int defflags)` from `Src/module.c:3437`.
///
/// C body is ~140 lines. Top-level structure:
/// ```c
/// autofeatures(const char *cmdnam, const char *module, char **features,
///              int prefchar, int defflags)
/// {
///     // Resolve module, fetch its features+enables tables.
///     // For each feature in `features`:
///     //   parse `+`/`-` prefix → add/remove
///     //   parse type prefix (b/c/C/p/f) → fchar
///     //   dispatch to add_aliasbuiltin / add_autocondition /
///     //     add_autoparam / add_automathfunc / del_* matching
/// }
/// ```
///
/// Static-link path: registers each `module:feature` pair into the
/// matching `table.autoload_*` map. Honors `+`/`-` prefix for
/// add/remove, and the type prefix or `prefchar` arg for routing.
/// WARNING: param names don't match C — Rust=(table, _cmdnam, module, features, prefchar, defflags) vs C=(cmdnam, module, features, prefchar, defflags)
pub fn autofeatures(table: &mut modulestab, _cmdnam: &str, module: Option<&str>,
                    features: &[String], prefchar: u8, defflags: i32) -> i32 { // c:3437
    let mut ret: i32 = 0;
    let _ = defflags;

    for feature in features {
        let mut s = feature.as_str();
        let mut add: bool = true;                                         // c:3466 add = 1
        // c:3461-3491 — parse `+`/`-` add/remove prefix.
        if let Some(rest) = s.strip_prefix('-') {
            add = false;
            s = rest;
        } else if let Some(rest) = s.strip_prefix('+') {
            add = true;
            s = rest;
        }

        let (fchar, fnam): (u8, &str) = if prefchar != 0 {                // c:3461
            (prefchar, s)                                                 // c:3467-3468
        } else {
            // c:3491-3520 — parse `b:`/`c:`/`C:`/`p:`/`f:` type prefix.
            let bytes = s.as_bytes();
            if bytes.len() >= 2 && bytes[1] == b':' {
                (bytes[0], &s[2..])
            } else {
                (b'b', s)  // default: builtin
            }
        };

        let modname = match module {
            Some(m) => m,
            None => { ret = 1; continue; }
        };

        if add {
            // Insert into the matching autoload map.
            match fchar {
                b'b' => { table.autoload_builtins.insert(fnam.to_string(), modname.to_string()); }
                b'c' | b'C' => { table.autoload_conditions.insert(fnam.to_string(), modname.to_string()); }
                b'p' => { table.autoload_params.insert(fnam.to_string(), modname.to_string()); }
                b'f' => { table.autoload_mathfuncs.insert(fnam.to_string(), modname.to_string()); }
                _ => { ret = 1; }
            }
        } else {
            // Remove from the matching autoload map.
            match fchar {
                b'b' => { table.autoload_builtins.remove(fnam); }
                b'c' | b'C' => { table.autoload_conditions.remove(fnam); }
                b'p' => { table.autoload_params.remove(fnam); }
                b'f' => { table.autoload_mathfuncs.remove(fnam); }
                _ => { ret = 1; }
            }
        }
    }
    ret
}

/// Port of `autoloadscan(HashNode hn, int printflags)` from `Src/module.c:2403`.
///
/// C body:
/// ```c
/// autoloadscan(HashNode hn, int printflags)
/// {
///     Builtin bn = (Builtin) hn;
///     if(bn->node.flags & BINF_ADDED)
///         return;
///     if(printflags & PRINT_LIST) {
///         fputs("zmodload -ab ", stdout);
///         if(bn->optstr[0] == '-') fputs("-- ", stdout);
///         quotedzputs(bn->optstr, stdout);
///         if(strcmp(bn->node.nam, bn->optstr)) {
///             putchar(' ');
///             quotedzputs(bn->node.nam, stdout);
///         }
///     } else {
///         nicezputs(bn->node.nam, stdout);
///         if(strcmp(bn->node.nam, bn->optstr)) {
///             fputs(" (", stdout);
///             nicezputs(bn->optstr, stdout);
///             putchar(')');
///         }
///     }
///     putchar('\n');
/// }
/// ```
///
/// Hash-table scan callback for autoloadable-builtin listing.
/// `printflags & PRINT_LIST` selects long form (`zmodload -ab MOD NAME`)
/// vs short form (`NAME (MOD)`). Skips already-registered builtins
/// (BINF_ADDED set).
/// WARNING: param names don't match C — Rust=(name, optstr, flags, printflags) vs C=(hn, printflags)
pub fn autoloadscan(name: &str, optstr: &str, flags: u32, printflags: i32) { // c:2403
    if (flags & BINF_ADDED) != 0 {                                       // c:2403
        return;                                                          // c:2408
    }
    if (printflags & crate::ported::zsh_h::PRINT_LIST) != 0 {            // c:2409
        // c:2410-2417 — long form `zmodload -ab MOD NAME`
        print!("zmodload -ab ");
        if optstr.starts_with('-') {                                     // c:2411
            print!("-- ");                                                // c:2412
        }
        print!("{}", optstr);                                             // c:2413 quotedzputs
        if name != optstr {                                               // c:2414
            print!(" ");                                                  // c:2415
            print!("{}", name);                                           // c:2416
        }
    } else {
        // c:2419-2424 — short form `NAME (MOD)`
        print!("{}", name);                                               // c:2419
        if name != optstr {                                               // c:2420
            print!(" (");                                                 // c:2421
            print!("{}", optstr);                                         // c:2422
            print!(")");                                                  // c:2423
        }
    }
    println!();                                                          // c:2426
}

/// Direct port of `bin_zmodload(char *nam, char **args, Options ops, UNUSED(int func))` from `Src/module.c:2440`.
/// Top-level dispatcher for the `zmodload` builtin. Validates flag
/// combinations then routes to one of the per-mode helpers:
///   -F        → bin_zmodload_features (c:3003)
///   -e        → bin_zmodload_exist    (c:2623)
///   -d        → bin_zmodload_dep      (c:2649)
///   -a/-b/-c/-p/-f → bin_zmodload_auto (c:2726)
///   default   → bin_zmodload_load     (c:2971)
///   -A/-R     → bin_zmodload_alias    (c:2515)
/// WARNING: param names don't match C — Rust=(nam, args, _func) vs C=(nam, args, ops, func)
pub fn bin_zmodload(nam: &str, args: &[String],                              // c:2440
                    ops: &crate::ported::zsh_h::options, _func: i32) -> i32 {
    let mut table = MODULESTAB.lock().unwrap();
    let table = &mut *table;

    let ops_bcpf = OPT_ISSET(ops, b'b') || OPT_ISSET(ops, b'c')              // c:2443
                || OPT_ISSET(ops, b'p') || OPT_ISSET(ops, b'f');
    let ops_au   = OPT_ISSET(ops, b'a') || OPT_ISSET(ops, b'u');             // c:2445
    let mut ret: i32;                                                        // c:2446

    if ops_bcpf && !ops_au {                                                 // c:2451
        zwarnnam(nam, "-b, -c, -f, and -p must be combined with -a or -u");  // c:2452
        return 1;                                                            // c:2453
    }
    if OPT_ISSET(ops, b'F') && (ops_bcpf || OPT_ISSET(ops, b'u')) {          // c:2455
        zwarnnam(nam, "-b, -c, -f, -p and -u cannot be combined with -F");   // c:2456
        return 1;                                                            // c:2457
    }
    if OPT_ISSET(ops, b'A') || OPT_ISSET(ops, b'R') {                        // c:2459
        if ops_bcpf || ops_au || OPT_ISSET(ops, b'd')                        // c:2460
           || (OPT_ISSET(ops, b'R') && OPT_ISSET(ops, b'e'))
        {
            zwarnnam(nam, "illegal flags combined with -A or -R");           // c:2462
            return 1;                                                        // c:2463
        }
        if !OPT_ISSET(ops, b'e') {                                           // c:2465
            return bin_zmodload_alias(table, nam, args, ops);                // c:2466
        }
    }
    if OPT_ISSET(ops, b'd') && OPT_ISSET(ops, b'a') {                        // c:2468
        zwarnnam(nam, "-d cannot be combined with -a");                      // c:2469
        return 1;                                                            // c:2470
    }
    if OPT_ISSET(ops, b'u') && args.is_empty() {                             // c:2472
        zwarnnam(nam, "what do you want to unload?");                        // c:2473
        return 1;                                                            // c:2474
    }
    if OPT_ISSET(ops, b'e') && (OPT_ISSET(ops, b'I') || OPT_ISSET(ops, b'L') // c:2476
        || (OPT_ISSET(ops, b'a') && !OPT_ISSET(ops, b'F'))
        || OPT_ISSET(ops, b'd') || OPT_ISSET(ops, b'i')
        || OPT_ISSET(ops, b'u'))
    {
        zwarnnam(nam, "-e cannot be combined with other options");           // c:2480
        return 1;                                                            // c:2482
    }
    // c:2484 — `for (fp = fonly; *fp; fp++)` — `l` and `P` only with `-F`.
    for fp in [b'l', b'P'] {                                                 // c:2484
        if OPT_ISSET(ops, fp) && !OPT_ISSET(ops, b'F') {                     // c:2485
            zwarnnam(nam, &format!("-{} is only allowed with -F", fp as char)); // c:2486
            return 1;                                                        // c:2487
        }
    }
    crate::ported::mem::queue_signals();                                     // c:2490
    if OPT_ISSET(ops, b'F') {                                                // c:2491
        ret = bin_zmodload_features(table, nam, args, ops);                  // c:2492
    } else if OPT_ISSET(ops, b'e') {                                         // c:2493
        ret = bin_zmodload_exist(table, nam, args, ops);                     // c:2494
    } else if OPT_ISSET(ops, b'd') {                                         // c:2495
        ret = bin_zmodload_dep(table, nam, args, ops);                       // c:2496
    } else {
        let autoopts = (OPT_ISSET(ops, b'b') as i32)                         // c:2497
                     + (OPT_ISSET(ops, b'c') as i32)
                     + (OPT_ISSET(ops, b'p') as i32)
                     + (OPT_ISSET(ops, b'f') as i32);
        if autoopts != 0 || OPT_ISSET(ops, b'a') {                           // c:2497-2499
            if autoopts > 1 {                                                // c:2502
                zwarnnam(nam, "use only one of -b, -c, or -p");              // c:2503
                ret = 1;                                                     // c:2504
            } else {
                ret = bin_zmodload_auto(table, nam, args, ops);              // c:2506
            }
        } else {
            ret = bin_zmodload_load(table, nam, args, ops);                  // c:2508
        }
    }
    crate::ported::mem::unqueue_signals();                                   // c:2515
    ret                                                                      // c:2515
}

/// Port of `bin_zmodload_alias(char *nam, char **args, Options ops)` from `Src/module.c:2515`.
///
/// `zmodload -A [-L|-R] [name=alias ...]`. Three modes:
/// - no args: list all module aliases (`-L` = long form).
/// - `-R name`: remove alias `name` (must already be MOD_ALIAS).
/// - `name=target`: install/replace alias `name` pointing at `target`.
///   Detects self-cycles before committing.
/// WARNING: param names don't match C — Rust=(table, nam, args, ops) vs C=(nam, args, ops)
pub fn bin_zmodload_alias(table: &mut modulestab, nam: &str, args: &[String], ops: &crate::ported::zsh_h::options) -> i32 { // c:2515
    /*
     * TODO: while it would be too nasty to have aliases, as opposed
     * to real loadable modules, with dependencies --- just what would
     * we need to load when, exactly? --- there is in principle no objection
     * to making it possible to force an alias onto an existing unloaded
     * module which has dependencies.  This would simply transfer
     * the dependencies down the line to the aliased-to module name.
     * This is actually useful, since then you can alias zsh/zle=mytestzle
     * to load another version of zle.  But then what happens when the
     * alias is removed?  Do you transfer the dependencies back? And
     * suppose other names are aliased to the same file?  It might be
     * kettle of fish best left unwormed.
     */                                                                  // c:2517-2529

    // c:2532-2541 — no args: list aliases
    if args.is_empty() {
        if crate::ported::zsh_h::OPT_ISSET(ops, b'R') {                  // c:2533
            crate::ported::utils::zwarnnam(nam, "no module alias to remove"); // c:2534
            return 1;                                                     // c:2535
        }
        // c:2537-2539 — scanhashtable filtered by MOD_ALIAS, printnode
        for (name, m) in &table.modules {
            if (m.node.flags & crate::ported::zsh_h::MOD_ALIAS) != 0 {
                if crate::ported::zsh_h::OPT_ISSET(ops, b'L') {
                    println!("zmodload -A {}={}", name, m.alias.as_deref().unwrap_or(""));
                } else {
                    println!("{} -> {}", name, m.alias.as_deref().unwrap_or(""));
                }
            }
        }
        return 0;                                                         // c:2540
    }

    // c:2543 — for each arg, parse name=alias and dispatch.
    for arg in args {
        // c:2544-2547 — split at '='
        let (lhs, aliasname): (&str, Option<&str>) = match arg.find('=') {
            Some(eq) => (&arg[..eq], Some(&arg[eq+1..])),
            None => (arg.as_str(), None),
        };
        // c:2548 — modname_ok check on the LHS
        if modname_ok(lhs) == 0 {                                         // c:2548
            crate::ported::utils::zwarnnam(nam, &format!("invalid module name `{}'", lhs)); // c:2549
            return 1;                                                     // c:2550
        }
        if crate::ported::zsh_h::OPT_ISSET(ops, b'R') {                  // c:2552
            // -R: remove alias path.
            if aliasname.is_some() {                                      // c:2553
                crate::ported::utils::zwarnnam(nam,
                    &format!("bad syntax for removing module alias: {}", lhs)); // c:2554
                return 1;                                                 // c:2556
            }
            // c:2558 — find_module(lhs, 0, NULL)
            match table.modules.get(lhs) {
                Some(m) => {
                    if (m.node.flags & crate::ported::zsh_h::MOD_ALIAS) == 0 { // c:2560
                        crate::ported::utils::zwarnnam(nam,
                            &format!("module is not an alias: {}", lhs)); // c:2561
                        return 1;                                         // c:2562
                    }
                    table.modules.remove(lhs);                            // c:2564 delete_module
                }
                None => {
                    crate::ported::utils::zwarnnam(nam,
                        &format!("no such module alias: {}", lhs));       // c:2566
                    return 1;                                             // c:2567
                }
            }
        } else {
            // No -R: install/replace alias OR list one.
            if let Some(target) = aliasname {                             // c:2570
                if modname_ok(target) == 0 {                              // c:2572
                    crate::ported::utils::zwarnnam(nam,
                        &format!("invalid module name `{}'", target));    // c:2573
                    return 1;                                             // c:2574
                }
                // c:2576-2584 — cycle detection: walk alias chain
                let mut mname = target;
                let mut depth = 0;
                loop {
                    if depth > 256 { break; }
                    depth += 1;
                    if mname == lhs {                                     // c:2577
                        crate::ported::utils::zwarnnam(nam,
                            &format!("module alias would refer to itself: {}", lhs)); // c:2578
                        return 1;                                         // c:2580
                    }
                    match table.modules.get(mname) {
                        Some(m) if (m.node.flags & crate::ported::zsh_h::MOD_ALIAS) != 0 => {
                            mname = m.alias.as_deref().unwrap_or("");
                        }
                        _ => break,
                    }
                }
                // c:2585-2596 — install or replace
                if let Some(m) = table.modules.get_mut(lhs) {
                    if (m.node.flags & crate::ported::zsh_h::MOD_ALIAS) == 0 { // c:2587
                        crate::ported::utils::zwarnnam(nam,
                            &format!("module is not an alias: {}", lhs)); // c:2588
                        return 1;                                         // c:2589
                    }
                    m.alias = Some(target.to_string());                   // c:2591/2597
                } else {
                    let mut m = module::new(lhs);                         // c:2593 zshcalloc
                    m.node.flags = crate::ported::zsh_h::MOD_ALIAS;            // c:2594
                    m.alias = Some(target.to_string());                   // c:2597
                    table.modules.insert(lhs.to_string(), m);             // c:2595
                }
            } else {
                // c:2599-2611 — list one alias
                match table.modules.get(lhs) {
                    Some(m) if (m.node.flags & crate::ported::zsh_h::MOD_ALIAS) != 0 => {
                        if crate::ported::zsh_h::OPT_ISSET(ops, b'L') {
                            println!("zmodload -A {}={}", lhs, m.alias.as_deref().unwrap_or(""));
                        } else {
                            println!("{} -> {}", lhs, m.alias.as_deref().unwrap_or(""));
                        }
                    }
                    Some(_) => {
                        crate::ported::utils::zwarnnam(nam,
                            &format!("module is not an alias: {}", lhs)); // c:2605
                        return 1;                                         // c:2606
                    }
                    None => {
                        crate::ported::utils::zwarnnam(nam,
                            &format!("no such module alias: {}", lhs));   // c:2609
                        return 1;                                         // c:2610
                    }
                }
            }
        }
    }
    0                                                                    // c:2616
}

/// Port of `bin_zmodload_auto(char *nam, char **args, Options ops)` from `Src/module.c:2726`.
///
/// `zmodload [-c] [-p] [-f] [-a] module name [name ...]` —
/// register-autoload of builtins/conditions/params/mathfns. C body
/// (80 lines) walks the appropriate dispatch table per opt flag.
///
/// `-c` lists/registers conditions, `-p` parameters, `-f` math fns,
/// default is builtins. `-L` toggles long-form listing.
///
/// Static-link path: registers via `add_autoaliasbuiltin` /
/// `add_autoparam` / `add_automathfunc` already ported. Without a
/// module name (just `-a`), runs the listing scan via `autoloadscan`
/// or its conddef/param/mathfn equivalents.
/// WARNING: param names don't match C — Rust=(table, _nam, args, ops) vs C=(nam, args, ops)
pub fn bin_zmodload_auto(table: &mut modulestab, _nam: &str, args: &[String], ops: &crate::ported::zsh_h::options) -> i32 { // c:2726
    let fchar: char;                                                      // c:2726
    let _flags: i32 = if crate::ported::zsh_h::OPT_ISSET(ops, b'i') { FEAT_IGNORE } else { 0 }; // c:2728

    // c:2731-2773 — conditions branch (-c)
    if crate::ported::zsh_h::OPT_ISSET(ops, b'c') {
        fchar = if crate::ported::zsh_h::OPT_ISSET(ops, b'I') { 'C' } else { 'c' };
        let _ = fchar;
        if args.is_empty() {                                              // c:2732
            // List all autoloadable conditions
            for (name, module) in &table.autoload_conditions {
                println!("{} {}", module, name);
            }
            return 0;
        }
    } else if crate::ported::zsh_h::OPT_ISSET(ops, b'p') {               // c:2774 — params branch
        if args.is_empty() {
            for (name, module) in &table.autoload_params {
                println!("{} {}", module, name);
            }
            return 0;
        }
    } else if crate::ported::zsh_h::OPT_ISSET(ops, b'f') {               // mathfns branch
        if args.is_empty() {
            for (name, module) in &table.autoload_mathfuncs {
                println!("{} {}", module, name);
            }
            return 0;
        }
    } else {
        // Default: builtins branch
        if args.is_empty() {
            for (name, module) in &table.autoload_builtins {
                autoloadscan(name, module, 0,
                    if crate::ported::zsh_h::OPT_ISSET(ops, b'L') {
                        crate::ported::zsh_h::PRINT_LIST
                    } else { 0 });
            }
            return 0;
        }
    }

    // Register-mode: args[0] = module, args[1..] = names to autoload
    if args.len() < 2 { return 1; }
    let modnam = &args[0];                                                // c:2729 modnam = *args
    for nm in &args[1..] {
        if crate::ported::zsh_h::OPT_ISSET(ops, b'p') {
            table.autoload_params.insert(nm.clone(), modnam.clone());
        } else if crate::ported::zsh_h::OPT_ISSET(ops, b'f') {
            table.autoload_mathfuncs.insert(nm.clone(), modnam.clone());
        } else if crate::ported::zsh_h::OPT_ISSET(ops, b'c') {
            table.autoload_conditions.insert(nm.clone(), modnam.clone());
        } else {
            table.autoload_builtins.insert(nm.clone(), modnam.clone());
        }
    }
    0                                                                    // c:2805
}

/// Port of `bin_zmodload_dep(UNUSED(char *nam), char **args, Options ops)` from `Src/module.c:2649`.
///
/// `zmodload -d [-u] [target [dep ...]]`. Three modes:
/// - `-u target` removes all deps from target; `-u target d1 d2` removes
///   only those.
/// - no args lists all dependencies.
/// - `target dep1 ...` adds each dep to target's dependency list.
/// WARNING: param names don't match C — Rust=(table, _nam, args, ops) vs C=(nam, args, ops)
pub fn bin_zmodload_dep(table: &mut modulestab, _nam: &str, args: &[String], ops: &crate::ported::zsh_h::options) -> i32 { // c:2649
    if crate::ported::zsh_h::OPT_ISSET(ops, b'u') {                      // c:2649
        // c:2654 — const char *tnam = *args++;
        if args.is_empty() { return 0; }
        let tnam = &args[0];
        let rest = &args[1..];
        // c:2655 — find_module(tnam, FINDMOD_ALIASP, &tnam)
        let canon = match find_module(table, tnam, FINDMOD_ALIASP) {
            Some(n) => n,
            None => return 0,                                             // c:2657
        };
        if let Some(m) = table.modules.get_mut(&canon) {
            if let Some(deps) = m.deps.as_mut() {                         // c:2658
                if !rest.is_empty() {
                    // c:2659-2667 — remove specific deps
                    for to_remove in rest {
                        if let Some(pos) = deps.iter().position(|d| d == to_remove) {
                            deps.delete_node(pos);                        // c:2664 remnode
                        }
                    }
                } else {
                    // c:2673-2676 — remove all deps
                    deps.clear();
                }
            }
            // c:2678-2679 — if no deps and no handle, delete module
            let no_deps_no_handle = m.deps.as_ref().map_or(true, |d| d.is_empty());
            if no_deps_no_handle {
                table.modules.remove(&canon);
            }
        }
        return 0;                                                         // c:2680
    }
    // c:2681 — list-mode or add-mode
    if args.len() < 2 {
        // List dependencies (c:2682-2684 — print all module deps)
        for (name, m) in &table.modules {
            if let Some(deps) = m.deps.as_ref() {
                if !deps.is_empty() {
                    let joined: Vec<&str> = deps.iter().map(|s| s.as_str()).collect();
                    println!("zmodload -d {} {}", name, joined.join(" "));
                }
            }
        }
        return 0;
    }
    // Add deps: args[0] is target, args[1..] are deps to add.
    let target = &args[0];
    for dep in &args[1..] {
        add_dep(table, target, dep);                                      // dispatch to add_dep
    }
    0
}

/// Port of `bin_zmodload_exist(UNUSED(char *nam), char **args, Options ops)` from `Src/module.c:2623`.
///
/// C body:
/// ```c
/// bin_zmodload_exist(UNUSED(char *nam), char **args, Options ops)
/// {
///     Module m;
///     if (!*args) {
///         scanhashtable(modulestab, 1, 0, 0, modulestab->printnode,
///                       OPT_ISSET(ops,'A') ? PRINTMOD_EXIST|PRINTMOD_ALIAS :
///                       PRINTMOD_EXIST);
///         return 0;
///     } else {
///         int ret = 0;
///         for (; !ret && *args; args++) {
///             if (!(m = find_module(*args, FINDMOD_ALIASP, NULL))
///                 || !m->u.handle
///                 || (m->node.flags & MOD_UNLOAD))
///                 ret = 1;
///         }
///         return ret;
///     }
/// }
/// ```
///
/// `zmodload [-A]` lists or tests module presence. Returns 0 if all
/// named modules exist (or if no args, after listing); 1 if any
/// named module is missing/unloading.
/// WARNING: param names don't match C — Rust=(table, _nam, args, _ops) vs C=(nam, args, ops)
pub fn bin_zmodload_exist(table: &mut modulestab, _nam: &str, args: &[String], _ops: &crate::ported::zsh_h::options) -> i32 { // c:2623
    if args.is_empty() {                                                  // c:2623
        // c:2628-2630 — scanhashtable + printnode listing.
        // Static-link path: dump the modules registry.
        for (name, _) in &table.modules {
            println!("{}", name);
        }
        return 0;                                                         // c:2631
    }
    // c:2633-2640 — for each arg, test existence.
    let mut ret: i32 = 0;
    for arg in args {                                                     // c:2635
        if ret != 0 { break; }
        if find_module(table, arg, FINDMOD_ALIASP).is_none() {            // c:2636
            ret = 1;                                                      // c:2639
        }
    }
    ret                                                                   // c:2641
}

/// Port of `bin_zmodload_features(const char *nam, char **args, Options ops)` from `Src/module.c:3003`.
///
/// `zmodload -F [-L|-l|-P|-a|-m|-i] module [+/-feature ...]` —
/// per-feature enable/disable for an already-loaded module.
///
/// C body (~135 lines) handles:
/// - no module: list all modules with their features (`-L` long form,
///   `-l` show all enables, `-a` show autoloads).
/// - `-P` requires a module name; lists patterns.
/// - `-m` interprets each feature as a glob pattern.
/// - default: `+feature` enables, `-feature` disables, then calls
///   `do_module_features` to apply.
/// WARNING: param names don't match C — Rust=(table, nam, args, ops) vs C=(nam, args, ops)
pub fn bin_zmodload_features(table: &mut modulestab, nam: &str, args: &[String], ops: &crate::ported::zsh_h::options) -> i32 { // c:3003
    let modname = args.first();                                          // c:3003
    let rest_args = if args.is_empty() { &args[..] } else { &args[1..] };

    // c:3010-3024 — no-module-name listing branch
    if modname.is_none() {
        if crate::ported::zsh_h::OPT_ISSET(ops, b'L') {                  // c:3012
            if crate::ported::zsh_h::OPT_ISSET(ops, b'P') {              // c:3014
                crate::ported::utils::zwarnnam(nam, "-P is only allowed with a module name"); // c:3015
                return 1;                                                 // c:3016
            }
            // c:3022-3023 — scanhashtable + printnode
            for (name, _m) in &table.modules {
                println!("zmodload -F {}", name);
            }
            return 0;                                                     // c:3024
        }
        crate::ported::utils::zwarnnam(nam, "-F requires a module name"); // c:3028
        return 1;                                                         // c:3029
    }

    let modname = modname.unwrap();

    // c:3032 — `-m` glob-pattern branch (compile patprogs).
    // Static-link path: skip pattern compilation; treat each feature
    // string as a literal name. Full pattern support pending the
    // pattern.c port wire-up.

    // Build features array from `+name`/`-name` args.
    let mut feats: Vec<String> = Vec::with_capacity(rest_args.len());
    for arg in rest_args {
        feats.push(arg.clone());
    }

    // c:3098-3120 — apply features via do_module_features after
    // setting up the enables array per +/- prefixes.
    if !feats.is_empty() {
        autofeatures(table, nam, Some(modname), &feats, 0, 0);
    }
    do_module_features(table, modname, FEAT_CHECKAUTO);                  // c:3122
    0
}

/// Port of `bin_zmodload_load(char *nam, char **args, Options ops)` from `Src/module.c:2971`.
///
/// C body:
/// ```c
/// bin_zmodload_load(char *nam, char **args, Options ops)
/// {
///     int ret = 0;
///     if(OPT_ISSET(ops,'u')) {
///         for(; *args; args++) {
///             if (unload_named_module(*args, nam, OPT_ISSET(ops,'i')))
///                 ret = 1;
///         }
///         return ret;
///     } else if(!*args) {
///         scanhashtable(modulestab, ..., PRINTMOD_LIST);
///         return 0;
///     } else {
///         for (; *args; args++) {
///             int tmpret = require_module(*args, NULL, OPT_ISSET(ops,'s'));
///             if (tmpret && ret != 1) ret = tmpret;
///         }
///         return ret;
///     }
/// }
/// ```
///
/// `zmodload [-u] [args]`: load, unload, or list modules.
/// WARNING: param names don't match C — Rust=(table, nam, args, ops) vs C=(nam, args, ops)
pub fn bin_zmodload_load(table: &mut modulestab, nam: &str, args: &[String], ops: &crate::ported::zsh_h::options) -> i32 { // c:2971
    let mut ret: i32 = 0;
    if crate::ported::zsh_h::OPT_ISSET(ops, b'u') {                      // c:2974
        // c:2976-2979 — unload loop
        for arg in args {
            if unload_named_module(table, arg, nam, crate::ported::zsh_h::OPT_ISSET(ops, b'i') as i32) != 0 {
                ret = 1;
            }
        }
        return ret;                                                       // c:2980
    } else if args.is_empty() {                                           // c:2981
        // c:2983-2985 — list modules
        for (name, _m) in &table.modules {
            println!("{}", name);
        }
        return 0;                                                         // c:2986
    } else {
        // c:2989-2992 — load loop
        for arg in args {
            let tmpret = require_module(table, arg, None);                // c:2990
            if tmpret != 0 && ret != 1 {                                  // c:2991
                ret = tmpret;
            }
        }
        ret
    }
}

/// Port of `boot_(UNUSED(Module m))` from `Src/module.c:331`.
///
/// C body: `boot_(UNUSED(Module m)) { return 0; }` — the no-op
/// boot hook of the module subsystem itself.
#[allow(unused_variables)]
pub fn boot_(m: *const crate::ported::zsh_h::module) -> i32 {           // c:331
    0                                                                    // c:331
}

/// Port of `boot_module(Module m)` from `Src/module.c:1910`.
///
/// C body:
/// ```c
/// boot_module(Module m) {
///     return ((m->node.flags & MOD_LINKED) ?
///             (m->u.linked->boot)(m) : dyn_boot_module(m));
/// }
/// ```
///
/// Static-link path: modules are MOD_LINKED, so dispatch to the
/// per-module `boot_(m)` callback. zshrs's static dispatch is via
/// the modules-table feature lookup (see `register_module` /
/// `enable_module`); both branches collapse to 0 success.
/// WARNING: param names don't match C — Rust=(_table, _name) vs C=(m)
pub fn boot_module(_table: &mut modulestab, _name: &str) -> i32 {       // c:1910
    0                                                                    // c:1910 (boot)(m) success
}

/// Port of `checkaddparam(const char *nam, int opt_i)` from `Src/module.c:1026`.
///
/// C body:
/// ```c
/// checkaddparam(const char *nam, int opt_i)
/// {
///     Param pm;
///     if (!(pm = (Param) gethashnode2(paramtab, nam)))
///         return 0;
///     if (pm->level || !(pm->node.flags & PM_AUTOLOAD)) {
///         if (!opt_i || pm->level) {
///             zwarn("Can't add module parameter `%s': %s",
///                   nam, pm->level ? "local parameter exists" :
///                                    "parameter already exists");
///             return 1;
///         }
///         return 2;
///     }
///     unsetparam_pm(pm, 0, 1);
///     return 0;
/// }
/// ```
///
/// Returns: 0 = OK to add, 1 = error printed, 2 = blocked but `-i`
/// suppressed warning. `pm->level != 0` means a local param shadows
/// the name (always errors). `PM_AUTOLOAD` set means the existing
/// param is an autoload stub the C source unsets to make room.
///
/// Static-link path: the param-table is `crate::ported::params::*`
/// global. Stub returns 0 (no clash) until the params global-state
/// port wires gethashnode2(paramtab, ...) in.
#[allow(unused_variables)]
pub fn checkaddparam(nam: &str, opt_i: i32) -> i32 {                   // c:1026
    // c:1026 — if (!(pm = gethashnode2(paramtab, nam))) return 0;
    // Static-link: paramtab not yet hooked through; treat unknown.
    0
}

/// Port of `cleanup_(UNUSED(Module m))` from `Src/module.c:338`.
///
/// C body: `cleanup_(UNUSED(Module m)) { return 0; }` — the no-op
/// cleanup hook of the module subsystem itself.
#[allow(unused_variables)]
pub fn cleanup_(m: *const crate::ported::zsh_h::module) -> i32 {        // c:338
    0                                                                    // c:338
}

/// Port of `cleanup_module(Module m)` from `Src/module.c:1918`.
///
/// C body:
/// ```c
/// cleanup_module(Module m) {
///     return ((m->node.flags & MOD_LINKED) ?
///             (m->u.linked->cleanup)(m) : dyn_cleanup_module(m));
/// }
/// ```
/// WARNING: param names don't match C — Rust=(_table, _name) vs C=(m)
pub fn cleanup_module(_table: &mut modulestab, _name: &str) -> i32 {    // c:1918
    0                                                                    // c:1918 (cleanup)(m) success
}

/// Port of `del_automathfunc(UNUSED(const char *modnam), const char *fnam, int flags)` from `Src/module.c:1436`.
///
/// C body:
/// ```c
/// del_automathfunc(UNUSED(const char *modnam), const char *fnam, int flags) {
///     MathFunc f = getmathfunc(fnam, 0);
///     if (!f) {
///         if (!(flags & FEAT_IGNORE)) return 2;
///     } else if (f->flags & MFF_ADDED) {
///         if (!(flags & FEAT_IGNORE)) return 3;
///     } else
///         deletemathfunc(f);
///     return 0;
/// }
/// ```
///
/// Removes `fnam` from the autoloadable math-function registry.
/// WARNING: param names don't match C — Rust=(table, _modnam, fnam, flags) vs C=(modnam, fnam, flags)
pub fn del_automathfunc(table: &mut modulestab, _modnam: &str, fnam: &str, flags: i32) -> i32 { // c:1436
    if !table.autoload_mathfuncs.contains_key(fnam) {                    // c:1436 if (!f)
        if (flags & FEAT_IGNORE) == 0 {                                  // c:1441
            return 2;                                                     // c:1442
        }
    } else {
        // c:1447 — deletemathfunc(f)
        table.autoload_mathfuncs.remove(fnam);
    }
    0                                                                    // c:1449
}

/// Port of `delete_module(Module m)` from `Src/module.c:1687`.
///
/// C body:
/// ```c
/// delete_module(Module m) {
///     modulestab->removenode(modulestab, m->node.nam);
///     modulestab->freenode(&m->node);
/// }
/// ```
///
/// Removes a module from the live `modulestab` and frees its node.
/// Rust port operates on the `ModuleTable` `modules` HashMap.
/// WARNING: param names don't match C — Rust=(table, name) vs C=(m)
pub fn delete_module(table: &mut modulestab, name: &str) -> i32 {       // c:1687
    table.modules.remove(name);                                          // c:1687 removenode
    // c:1691 — freenode(&m->node) — Rust drops on `remove` return.
    0
}

/// Port of `deletehookdeffunc(Hookdef h, Hookfn f)` from `Src/module.c:961`.
///
/// C body:
/// ```c
/// deletehookdeffunc(Hookdef h, Hookfn f) {
///     LinkNode p;
///     for (p = firstnode(h->funcs); p; incnode(p))
///         if (f == (Hookfn) getdata(p)) {
///             remnode(h->funcs, p);
///             return 0;
///         }
///     return 1;
/// }
/// ```
///
/// Removes function `f` from the hook's function-list. Returns 0 on
/// successful removal, 1 if not found.
/// WARNING: param names don't match C — Rust=(table, h, fn_name) vs C=(h, f)
pub fn deletehookdeffunc(table: &mut modulestab, h: &mut crate::ported::zsh_h::hookdef, fn_name: &str) -> i32 { // c:961
    if let Some(funcs) = table.hooks.get_mut(&h.name) {
        // c:965-969 — for (p = firstnode...; p; incnode(p)) if (f == ...)
        if let Some(pos) = funcs.iter().position(|n| n == fn_name) {
            funcs.remove(pos);                                            // c:967 remnode
            let _ = h.funcs;
            return 0;                                                     // c:968
        }
    }
    let _ = h.funcs;
    1                                                                    // c:970
}

/// Port of `deletemathfunc(MathFunc f)` from `Src/module.c:1342`.
///
/// C body:
/// ```c
/// deletemathfunc(MathFunc f) {
///     MathFunc p, q;
///     for (p = mathfuncs, q = NULL; p && p != f; q = p, p = p->next);
///     if (p) {
///         if (q) q->next = f->next; else mathfuncs = f->next;
///         if (f->module) {
///             zsfree(f->name); zsfree(f->module); zfree(f, sizeof(*f));
///         } else
///             f->flags &= ~MFF_ADDED;
///         return 0;
///     }
///     return -1;
/// }
/// ```
///
/// Removes math function `f` from the global registry. Returns 0
/// on hit, -1 on miss.
// `deletemathfunc(table, &MathFunc)` deleted — Rust-only port that
// took the deleted PascalCase `MathFunc` struct. The canonical
// `removemathfunc` still operates on `ModuleTable.autoload_mathfuncs`
// (the autoload registry).

/// Port of `do_boot_module(Module m, Feature_enables enablesarr, int silent)` from `Src/module.c:2139`.
///
/// C body:
/// ```c
/// do_boot_module(Module m, Feature_enables enablesarr, int silent)
/// {
///     int ret = do_module_features(m, enablesarr,
///                                  silent ? FEAT_IGNORE|FEAT_CHECKAUTO :
///                                  FEAT_CHECKAUTO);
///     if (ret == 1) return 1;
///     if (boot_module(m)) return 1;
///     return ret;
/// }
/// ```
pub fn do_boot_module(m: &mut modulestab, enablesarr: &str, silent: i32) -> i32 { // c:2139
    let flags = if silent != 0 {                                          // c:2139
        FEAT_IGNORE | FEAT_CHECKAUTO
    } else {
        FEAT_CHECKAUTO                                                    // c:2143
    };
    let ret = do_module_features(m, enablesarr, flags);                     // c:2141
    if ret == 1 {                                                         // c:2145
        return 1;                                                         // c:2146
    }
    if boot_module(m, enablesarr) != 0 {                                    // c:2148
        return 1;                                                         // c:2149
    }
    ret                                                                   // c:2150
}

/// Port of `do_cleanup_module(Module m)` from `Src/module.c:2159`.
///
/// C body:
/// ```c
/// do_cleanup_module(Module m) {
///     return (m->node.flags & MOD_LINKED) ?
///         (m->u.linked && m->u.linked->cleanup(m)) :
///         (m->u.handle && cleanup_module(m));
/// }
/// ```
/// WARNING: param names don't match C — Rust=(table, name) vs C=(m)
pub fn do_cleanup_module(table: &mut modulestab, name: &str) -> i32 {   // c:2159
    // Check the module is registered, then dispatch to cleanup_module.
    if table.modules.contains_key(name) {                                 // c:2162 m->u.linked
        cleanup_module(table, name)                                       // c:2163 cleanup_module(m)
    } else {
        0
    }
}

/// Port of `do_load_module(char const *name, int silent)` from `Src/module.c:1610`.
///
/// C body:
/// ```c
/// do_load_module(char const *name, int silent)
/// {
///     void *ret;
///     ret = try_load_module(name);
///     if (!ret && !silent) {
///         zwarn("failed to load module `%s': %s", name, ...);
///     }
///     return ret;
/// }
/// ```
///
/// C returns `void *` (the dlopen handle); Rust port returns 0 on
/// success / 1 on failure. zshrs's static-link path: `try_load_module`
/// always succeeds for built-in modules. Returns 1 + zwarn on miss.
/// WARNING: param names don't match C — Rust=(table, name, silent) vs C=(name, silent)
pub fn do_load_module(table: &mut modulestab, name: &str, silent: i32) -> i32 { // c:1610
    // c:1610 — ret = try_load_module(name);
    let ret = try_load_module(table, name);
    if ret == 0 && silent == 0 {                                          // c:1615
        // c:1618-1621 — zwarn("failed to load module ...")
        crate::ported::utils::zwarn(&format!("failed to load module: {}", name));
    }
    ret                                                                   // c:1624
}

/// Port of `do_module_features(Module m, Feature_enables enablesarr, int flags)` from `Src/module.c:1998`.
///
/// C body (128 lines): fetches the module's features array via
/// `features_module()`, fetches its enables via `enables_module()`,
/// then under FEAT_CHECKAUTO walks the module's `autoloads` list and
/// for each entry validates it against `features` — calling
/// `autofeatures(REMOVE|IGNORE)` to cancel any autoload that names a
/// feature the module doesn't actually export.
///
/// Returns 0 on full success, 1 if any feature couldn't be enabled.
pub fn do_module_features(m: &mut modulestab, enablesarr: &str, flags: i32) -> i32 { // c:1998
    let mut features: Vec<String> = Vec::new();                          // c:1998
    let mut ret: i32 = 0;                                                // c:2001

    // c:2003 — `if (features_module(m, &features) == 0)` — fetch features.
    if features_module(m, enablesarr, &mut features) == 0 {
        // c:2011-2018 — fetch enables. If features are supported, enables
        // should be too; an error here is reported unless FEAT_IGNORE.
        let mut enables: Option<Vec<i32>> = None;
        if enables_module(m, enablesarr, &mut enables) != 0 {              // c:2012
            if (flags & FEAT_IGNORE) == 0 {                              // c:2014
                crate::ported::utils::zwarn(&format!(
                    "error getting enabled features for module `{}'",   // c:2015
                    enablesarr,
                ));
            }
            return 1;                                                    // c:2017
        }

        // c:2020 — `if ((flags & FEAT_CHECKAUTO) && m->autoloads)`
        if (flags & FEAT_CHECKAUTO) != 0 {
            let autoloads: Vec<String> = match m.modules.get(enablesarr) {
                Some(m) => m
                    .autoloads
                    .as_ref()
                    .map(|al| al.iter().cloned().collect())
                    .unwrap_or_default(),
                None => return ret,
            };
            // c:2027-2074 — walk autoloads, cancel mismatches.
            for al in &autoloads {                                       // c:2028
                // c:2032-2034 — `for (ptr = features; *ptr; ptr++) if (!strcmp(al, *ptr)) break;`
                let found = features.iter().any(|f| f == al);
                if !found {                                              // c:2035
                    if (flags & FEAT_IGNORE) == 0 {                      // c:2037
                        crate::ported::utils::zwarn(&format!(
                            "module `{}' has no such feature: `{}': autoload cancelled", // c:2038-2040
                            enablesarr, al,
                        ));
                    }
                    // c:2045-2047 — `autofeatures(NULL, m->node.nam, arg, 0, FEAT_IGNORE|FEAT_REMOVE)`
                    let arg = vec![al.clone()];
                    autofeatures(m, "", Some(enablesarr), &arg, 0, FEAT_IGNORE | FEAT_REMOVE);
                }
            }
        }
    }
    ret                                                                  // c:2120 (approx)
}

/// Port of `dyn_boot_module(Module m)` from `Src/module.c:1747`.
///
/// C body: `return ((int (*)(int,Module,void*)) m->u.handle)(1, m, NULL);`
/// Calls the dynamic module's exported entry-point with op-code 1
/// (boot). Static-link path: opcode dispatch unused, returns 0.
#[allow(unused_variables)]
pub fn dyn_boot_module(m: *const crate::ported::zsh_h::module) -> i32 { // c:1747
    0                                                                    // c:1754
}

/// Port of `dyn_cleanup_module(Module m)` from `Src/module.c:1754`.
///
/// C body: `return ((int (*)(int,Module,void*)) m->u.handle)(2, m, NULL);`
/// Op-code 2 = cleanup.
#[allow(unused_variables)]
pub fn dyn_cleanup_module(m: *const crate::ported::zsh_h::module) -> i32 { // c:1754
    0                                                                    // c:1740
}

/// Port of `dyn_enables_module(Module m, int **enables)` from `Src/module.c:1740`.
///
/// C body: `return ((int (*)(int,Module,void*)) m->u.handle)(5, m, enables);`
/// Op-code 5 = enables.
#[allow(unused_variables)]
pub fn dyn_enables_module(m: *const crate::ported::zsh_h::module, enables: &mut Option<Vec<i32>>) -> i32 { // c:1740
    0                                                                    // c:1733
}

/// Port of `dyn_features_module(Module m, char ***features)` from `Src/module.c:1733`.
///
/// C body: `return ((int (*)(int,Module,void*)) m->u.handle)(4, m, features);`
/// Op-code 4 = features.
#[allow(unused_variables)]
pub fn dyn_features_module(m: *const crate::ported::zsh_h::module, features: &mut Vec<String>) -> i32 { // c:1733
    0                                                                    // c:1733
}

/// Port of `dyn_finish_module(Module m)` from `Src/module.c:1761`.
///
/// C body: `return ((int (*)(int,Module,void*)) m->u.handle)(3, m, NULL);`
/// Op-code 3 = finish.
#[allow(unused_variables)]
pub fn dyn_finish_module(m: *const crate::ported::zsh_h::module) -> i32 { // c:1761
    0                                                                    // c:1761
}

/// Port of `dyn_setup_module(Module m)` from `Src/module.c:1726`.
///
/// C body: `return ((int (*)(int,Module,void*)) m->u.handle)(0, m, NULL);`
/// Op-code 0 = setup. AIX-only path that multiplexes all six module
/// hooks through one symbol; static-link path skips it entirely.
#[allow(unused_variables)]
pub fn dyn_setup_module(m: *const crate::ported::zsh_h::module) -> i32 { // c:1726
    0                                                                    // c:1726
}

/// Port of `enables_(UNUSED(Module m), UNUSED(int **enables))` from `Src/module.c:324`.
///
/// C body: `enables_(UNUSED(Module m), UNUSED(int **enables)) { return 1; }`
/// — the module subsystem itself doesn't manage feature enables.
#[allow(unused_variables)]
pub fn enables_(m: *const crate::ported::zsh_h::module, enables: &mut Option<Vec<i32>>) -> i32 { // c:324
    1                                                                    // c:324
}

/// Port of `enables_module(Module m, int **enables)` from `Src/module.c:1901`.
///
/// C body:
/// ```c
/// enables_module(Module m, int **enables) {
///     return ((m->node.flags & MOD_LINKED) ?
///             (m->u.linked->enables)(m, enables) :
///             dyn_enables_module(m, enables));
/// }
/// ```
/// WARNING: param names don't match C — Rust=(_table, _name, _enables) vs C=(m, enables)
pub fn enables_module(_table: &mut modulestab, _name: &str, _enables: &mut Option<Vec<i32>>) -> i32 { // c:1901
    0                                                                    // c:1901 (enables)(m,enables)
}

/// Port of `features_(UNUSED(Module m), UNUSED(char ***features))` from `Src/module.c:313`.
///
/// C body:
/// ```c
/// features_(UNUSED(Module m), UNUSED(char ***features))
/// {
///     /* There are lots and lots of features, but they're not handled here. */
///     return 1;
/// }
/// ```
#[allow(unused_variables)]
pub fn features_(m: *const crate::ported::zsh_h::module, features: &mut Vec<String>) -> i32 { // c:313
    /* There are lots and lots of features, but they're not handled here. */ // c:313-318
    1                                                                    // c:319
}

/// Port of `features_module(Module m, char ***features)` from `Src/module.c:1892`.
///
/// C body:
/// ```c
/// features_module(Module m, char ***features) {
///     return ((m->node.flags & MOD_LINKED) ?
///             (m->u.linked->features)(m, features) :
///             dyn_features_module(m, features));
/// }
/// ```
/// WARNING: param names don't match C — Rust=(_table, _name, _features) vs C=(m, features)
pub fn features_module(_table: &mut modulestab, _name: &str, _features: &mut Vec<String>) -> i32 { // c:1892
    0                                                                    // c:1892 (features)(m,features)
}

// `featuresarray` deleted — Rust-only port that took the deleted
// `Module` / `Features` PascalCase structs. C
// `featuresarray(Module m, Features f)` at module.c:3279 builds
// the `b:NAME`/`c:NAME`/`f:NAME`/`p:NAME` descriptor array from
// the module's bintab/conddefs/mathfuncs/paramdefs pointers. The
// per-module rust files (rlimits.rs, langinfo.rs, curses.rs, …)
// each ship their own local `featuresarray` stub returning a
// hardcoded descriptor list; a future canonical free-fn port will
// live in zsh_h.rs once `struct features` carries real bintab/etc.
// pointers.

/// `FINDMOD_ALIASP` — bit in `find_module()`'s `flags` arg.
/// Port of `enum { FINDMOD_ALIASP = 0x0001 }` from `Src/module.c:110`.
/// /* Resolve any aliases to the underlying module. */
pub const FINDMOD_ALIASP: i32 = 0x0001;                                  // c:110

/// `FINDMOD_CREATE` — bit in `find_module()`'s `flags` arg.
/// Port of `enum { FINDMOD_CREATE = 0x0002 }` from `Src/module.c:115`.
/// /* Create an element for the module in the list if not found. */
pub const FINDMOD_CREATE: i32 = 0x0002;                                  // c:115

/// Port of `find_module(const char *name, int flags, const char **namep)` from `Src/module.c:1659`.
///
/// C body:
/// ```c
/// find_module(const char *name, int flags, const char **namep)
/// {
///     Module m;
///     m = (Module)modulestab->getnode2(modulestab, name);
///     if (m) {
///         if ((flags & FINDMOD_ALIASP) && (m->node.flags & MOD_ALIAS)) {
///             if (namep) *namep = m->u.alias;
///             return find_module(m->u.alias, flags, namep);
///         }
///         if (namep) *namep = m->node.nam;
///         return m;
///     }
///     if (!(flags & FINDMOD_CREATE))
///         return NULL;
///     m = zshcalloc(sizeof(*m));
///     modulestab->addnode(modulestab, ztrdup(name), m);
///     return m;
/// }
/// ```
///
/// Returns the resolved module name (after alias chasing) and
/// whether an entry was created. C's `Module` return becomes
/// `Option<String>` of the canonical name.
/// WARNING: param names don't match C — Rust=(table, name, flags) vs C=(name, flags, namep)
pub fn find_module(table: &mut modulestab, name: &str, flags: i32) -> Option<String> { // c:1659
    // c:1659 — m = modulestab->getnode2(modulestab, name);
    let mut cur_name = name.to_string();
    let mut depth = 0;
    loop {
        if depth > 64 { return None; } // alias-cycle guard
        depth += 1;
        match table.modules.get(&cur_name) {
            Some(m) => {
                // c:1665 — if ((flags & FINDMOD_ALIASP) && (m->node.flags & MOD_ALIAS))
                if (flags & FINDMOD_ALIASP) != 0 && (m.node.flags & crate::ported::zsh_h::MOD_ALIAS) != 0 {
                    // c:1668 — return find_module(m->u.alias, flags, namep);
                    if let Some(target) = m.alias.clone() {
                        cur_name = target;
                        continue;
                    }
                    return None;
                }
                // c:1671 — *namep = m->node.nam; return m;
                return Some(cur_name);
            }
            None => {
                // c:1674 — if (!(flags & FINDMOD_CREATE)) return NULL;
                if (flags & FINDMOD_CREATE) == 0 {
                    return None;
                }
                // c:1676-1677 — m = zshcalloc(...); addnode(name, m);
                table.modules.insert(cur_name.clone(), module::new(&cur_name));
                return Some(cur_name);
            }
        }
    }
}

/// Port of `finish_(UNUSED(Module m))` from `Src/module.c:345`.
///
/// C body: `finish_(UNUSED(Module m)) { return 0; }` —
/// the no-op finish hook for the module subsystem itself.
#[allow(unused_variables)]
pub fn finish_(m: *const crate::ported::zsh_h::module) -> i32 {         // c:345
    0                                                                    // c:345
}

/// Port of `finish_module(Module m)` from `Src/module.c:1926`.
///
/// C body:
/// ```c
/// finish_module(Module m) {
///     return ((m->node.flags & MOD_LINKED) ?
///             (m->u.linked->finish)(m) : dyn_finish_module(m));
/// }
/// ```
/// WARNING: param names don't match C — Rust=(_table, _name) vs C=(m)
pub fn finish_module(_table: &mut modulestab, _name: &str) -> i32 {     // c:1926
    0                                                                    // c:1926 (finish)(m) success
}

// `getfeatureenables` deleted — Rust-only port that took the
// deleted `Module` / `Features` PascalCase structs. C
// `getfeatureenables(Module m, Features f)` at module.c:3314
// returns the enable-bit array per feature. Per-module Rust files
// inline their own version returning a hardcoded vec; a canonical
// free-fn re-port belongs in zsh_h.rs once `struct features`
// carries real bintab/conddefs/etc. pointers.

/// Port of `getmathfunc(const char *name, int autol)` from `Src/module.c:1283`.
///
/// C body: linear-search `mathfuncs` for `name`; if found and `autol`
/// is true and the entry is autoloadable, demand-load via
/// `ensurefeature("f:", name)`. Returns the resolved entry or NULL.
///
/// Rust port returns `Some(module_name)` on hit, `None` on miss.
/// Honors the autoload flag by triggering `ensurefeature` when set.
/// WARNING: param names don't match C — Rust=(table, name, autol) vs C=(name, autol)
pub fn getmathfunc(table: &mut modulestab, name: &str, autol: i32) -> Option<String> { // c:1283
    if let Some(module) = table.autoload_mathfuncs.get(name).cloned() {  // c:1283-1288
        if autol != 0 {                                                  // c:1289
            // c:1295 — ensurefeature(n, "f:", ...)
            let _ = ensurefeature(table, &module, "f:", Some(name));
            return table.autoload_mathfuncs.get(name).cloned();
        }
        return Some(module);                                              // c:1303
    }
    None                                                                 // c:1306
}

// `handlefeatures` deleted — Rust-only port that took the
// deleted `Module` / `Features` PascalCase structs. C
// `handlefeatures(Module m, Features f, int **enables)` at
// module.c:3388 is the convenience front-end that picks
// set/get based on whether enables is NULL. Per-module Rust
// files inline a simpler 2-branch version (rlimits.rs:1428,
// curses.rs etc.); a canonical free-fn re-port belongs in
// zsh_h.rs once `struct features` carries real pointers.

/// Port of `hpux_dlsym(void *handle, char *name)` from `Src/module.c:1530`.
///
/// C body:
/// ```c
/// hpux_dlsym(void *handle, char *name)
/// {
///     void *sym_addr;
///     if (!shl_findsym((shl_t *)&handle, name, TYPE_UNDEFINED, &sym_addr))
///         return sym_addr;
///     return NULL;
/// }
/// ```
///
/// HP-UX-specific dlsym wrapper around `shl_findsym(3)`. Static-link
/// path: never invoked since zshrs doesn't dlopen modules.
#[allow(unused_variables)]
pub fn hpux_dlsym(handle: usize, name: &str) -> usize {                // c:1530
    0                                                                    // c:1530 NULL
}

/// Port of `load_and_bind(const char *fn)` from `Src/module.c:1468`.
///
/// C body: AIX-only `load() + loadbind()` wrapper. Iterates the
/// `modulestab` hash table, binding each loaded module's handle to
/// the new module's symbols. On loadbind failure, calls `unload()`
/// and stores the error in `dlerrstr`.
///
/// Static-link path: dlopen/dlsym aren't used since modules are
/// linked at compile time. Returns 0 (NULL handle).
/// WARNING: param names don't match C — Rust=(_fn_path) vs C=(fn)
pub fn load_and_bind(_fn_path: &str) -> usize {                          // c:1468
    0                                                                    // c:1492 NULL
}

/// Port of `modname_ok(char const *p)` from `Src/module.c:2173`.
///
/// Returns 1 iff `p` is a valid module name: one or more
/// `/`-separated identifier segments.
///
/// C body:
/// ```c
/// modname_ok(char const *p)
/// {
///     do {
///         p = itype_end(p, IIDENT, 0);
///         if (!*p)
///             return 1;
///     } while(*p++ == '/');
///     return 0;
/// }
/// ```
pub fn modname_ok(p: &str) -> i32 {                                       // c:2173
    let bytes = p.as_bytes();
    let mut i: usize = 0;
    loop {
        // c:2176 — `p = itype_end(p, IIDENT, 0);`
        // IIDENT = identifier-byte (alpha/digit/underscore + extended).
        while i < bytes.len() {
            let b = bytes[i];
            // Inline IIDENT check — alphanumeric or underscore. Mirrors
            // utils.c:itype_end stepping for the IIDENT bit.
            if b.is_ascii_alphanumeric() || b == b'_' { i += 1; } else { break; }
        }
        if i >= bytes.len() {                                            // c:2177 if (!*p)
            return 1;                                                    // c:2178
        }
        if bytes[i] != b'/' { break; }                                   // c:2179 while(*p++ == '/')
        i += 1;
    }
    0                                                                    // c:2180
}

/// Port of `module_func(Module m, const char *name)` from `Src/module.c:1770`.
///
/// C body (DYNAMIC_NAME_CLASH_OK off — the typical case):
/// ```c
/// module_func(Module m, const char *name)
/// {
///     VARARR(char, buf, strlen(name) + strlen(m->node.nam)*2 + 1);
///     char const *p; char *q;
///     strcpy(buf, name);
///     q = strchr(buf, 0);
///     for(p = m->node.nam; *p; p++) {
///         if(*p == '/')      { *q++ = 'Q'; *q++ = 's'; }
///         else if(*p == '_') { *q++ = 'Q'; *q++ = 'u'; }
///         else if(*p == 'Q') { *q++ = 'Q'; *q++ = 'q'; }
///         else                 *q++ = *p;
///     }
///     *q = 0;
///     return (Module_generic_func) dlsym(m->u.handle, buf);
/// }
/// ```
///
/// Builds a mangled symbol name (`<name><module-name-mangled>`) and
/// dlsym's it. The mangling encodes `/` as `Qs`, `_` as `Qu`, `Q` as
/// `Qq` so e.g. `setup_zsh_random` becomes `setup_zshQurandom`.
///
/// Static-link path: dlsym not used; returns 0 (NULL handle).
#[allow(unused_variables)]
pub fn module_func(m: &module, name: &str) -> usize {                  // c:1770
    0                                                                    // c:1794 NULL
}


/// Port of `module_loaded(const char *name)` from `Src/module.c:1703`.
///
/// C body:
/// ```c
/// module_loaded(const char *name)
/// {
///     Module m;
///     return ((m = find_module(name, FINDMOD_ALIASP, NULL)) &&
///             m->u.handle &&
///             !(m->node.flags & MOD_UNLOAD));
/// }
/// ```
///
/// Returns true (non-zero) if the named module is currently loaded.
/// In zshrs's static-link path: a module is "loaded" iff it's
/// registered in the live `ModuleTable`. The `MOD_UNLOAD` flag check
/// is skipped because static-link modules cannot be unloaded.
/// WARNING: param names don't match C — Rust=(table, name) vs C=(name)
pub fn module_loaded(table: &modulestab, name: &str) -> i32 {           // c:1703
    // c:1703 — find_module(name, FINDMOD_ALIASP, NULL)
    if table.modules.contains_key(name) {                                // m && m->u.handle
        1                                                                 // c:1709 (loaded, not unloading)
    } else {
        0
    }
}

/// Port of `printautoparams(HashNode hn, int lon)` from `Src/module.c:2710`.
///
/// C body:
/// ```c
/// printautoparams(HashNode hn, int lon)
/// {
///     Param pm = (Param) hn;
///     if (pm->node.flags & PM_AUTOLOAD) {
///         if (lon)
///             printf("zmodload -ap %s %s\n", pm->u.str, pm->node.nam);
///         else
///             printf("%s (%s)\n", pm->node.nam, pm->u.str);
///     }
/// }
/// ```
///
/// Hash-table scan callback for `zmodload -ap` listing. Rust port
/// takes a `(name, module, flags)` triple instead of a HashNode ptr
/// since zshrs's autoload-params live in `ModuleTable.autoload_params`.
/// WARNING: param names don't match C — Rust=(name, module, flags, lon) vs C=(hn, lon)
pub fn printautoparams(name: &str, module: &str, flags: u32, lon: i32) { // c:2710
    if (flags & crate::ported::zsh_h::PM_AUTOLOAD) != 0 {                // c:2710
        if lon != 0 {                                                     // c:2715
            // c:2716 — printf("zmodload -ap %s %s\n", pm->u.str, pm->node.nam);
            println!("zmodload -ap {} {}", module, name);
        } else {
            // c:2718 — printf("%s (%s)\n", pm->node.nam, pm->u.str);
            println!("{} ({})", name, module);
        }
    }
}

/// Port of `removemathfunc(MathFunc previous, MathFunc current)` from `Src/module.c:1267`.
///
/// C body:
/// ```c
/// removemathfunc(MathFunc previous, MathFunc current)
/// {
///     if (previous)
///         previous->next = current->next;
///     else
///         mathfuncs = current->next;
///     zsfree(current->name);
///     zsfree(current->module);
///     zfree(current, sizeof(*current));
/// }
/// ```
///
/// Unlinks `current` from the global `mathfuncs` list and frees it.
/// Rust port: `previous` is unused since the underlying HashMap
/// removal doesn't need predecessor tracking.
// `removemathfunc(table, &MathFunc, &MathFunc)` deleted — Rust-only
// port that took the deleted PascalCase `MathFunc` struct. C
// `removemathfunc(MathFunc previous, MathFunc current)` at
// module.c:1267 unlinks `current` from the global `mathfuncs`
// linked list (ported here as `MATHFUNCS`) — a re-port operating
// on `zsh_h::mathfunc` belongs alongside `addmathfunc` above.

/// Port of `require_module(const char *module, Feature_enables features, int silent)` from `Src/module.c:2344`.
///
/// C: ensures `modname` is loaded with the named features enabled.
/// Returns 0 on success, non-zero on failure.
///
/// Static-link path: load via `try_load_module`. The features-array
/// argument is accepted but not honoured per-feature yet (the
/// dispatcher tables in `register_module` carry full feature lists).
/// WARNING: param names don't match C — Rust=(table, modname, _features) vs C=()
pub fn require_module(table: &mut modulestab, modname: &str, _features: Option<&[String]>) -> i32 {
    if try_load_module(table, modname) == 0 {
        // Module not in static table — report failure.
        return 1;
    }
    0
}

/// Port of `ensurefeature(const char *modname, const char *prefix, const char *feature)` from `Src/module.c:3415`.
///
/// C body:
/// ```c
/// ensurefeature(const char *modname, const char *prefix, const char *feature)
/// {
///     char *f;
///     struct feature_enables features[2];
///     if (!feature)
///         return require_module(modname, NULL, 0);
///     f = dyncat(prefix, feature);
///     features[0].str = f;
///     features[0].pat = NULL;
///     features[1].str = NULL;
///     features[1].pat = NULL;
///     return require_module(modname, features, 0);
/// }
/// ```
/// WARNING: param names don't match C — Rust=(table, modname, prefix, feature) vs C=(modname, prefix, feature)
pub fn ensurefeature(table: &mut modulestab, modname: &str, prefix: &str, feature: Option<&str>) -> i32 { // c:3415
    match feature {
        None => require_module(table, modname, None),                    // c:3420-3421
        Some(f) => {
            // c:3422-3428 — build single-element features[2] array.
            let combined = crate::ported::string::dyncat(prefix, f);     // c:3422
            let arr = vec![combined];
            require_module(table, modname, Some(&arr))                   // c:3428
        }
    }
}

// `setbuiltins` / `setconddefs` / `setmathfuncs` / `setparamdefs`
// / `setfeatureenables` all deleted — Rust-only ports that took
// the deleted `Builtin` / `Conddef` / `MathFunc` / `Paramdef` /
// `Module` / `Features` PascalCase structs. C versions
// (module.c:501/754/1374/1165/3350) flip `*_ADDED` flags and
// insert/remove from the global hashtabs; per-module Rust files
// stub these locally and the canonical free-fn re-ports belong
// in zsh_h.rs / hashtable.rs once `struct features` carries
// real pointers.

/// Port of `setup_(UNUSED(Module m))` from `Src/module.c:306`.
///
/// C body: `setup_(UNUSED(Module m)) { return 0; }` — the no-op
/// setup hook of the module subsystem itself.
#[allow(unused_variables)]
pub fn setup_(m: *const crate::ported::zsh_h::module) -> i32 {          // c:306
    0                                                                    // c:306
}

/// Port of `setup_module(Module m)` from `Src/module.c:1884`.
///
/// C body:
/// ```c
/// setup_module(Module m) {
///     return ((m->node.flags & MOD_LINKED) ?
///             (m->u.linked->setup)(m) : dyn_setup_module(m));
/// }
/// ```
/// WARNING: param names don't match C — Rust=(_table, _name) vs C=(m)
pub fn setup_module(_table: &mut modulestab, _name: &str) -> i32 {      // c:1884
    0                                                                    // c:1884 (setup)(m)
}

/// Port of `try_load_module(char const *name)` from `Src/module.c:1583`.
///
/// C body iterates `module_path` looking for a loadable file via
/// `dlopen`. Static-link path: a module is "loadable" iff it's in
/// our static `ModuleTable.modules` map.
/// WARNING: param names don't match C — Rust=(table, name) vs C=(name)
pub fn try_load_module(table: &modulestab, name: &str) -> i32 {         // c:1583
    if table.modules.contains_key(name) { 1 } else { 0 }
}

/// Port of `unload_named_module(char *modname, char *nam, int silent)` from Src/module.c:2924. zshrs links
/// modules statically; this entry is a name-parity shim.
/// WARNING: param names don't match C — Rust=(table, name, _nam, _silent) vs C=(modname, nam, silent)
pub fn unload_named_module(table: &mut modulestab, name: &str, _nam: &str, _silent: i32) -> i32 {
    // c:2924-2965 — full body: find module, run cleanup, deregister.
    // Static-link path: just remove from the modules map; the per-feature
    // teardown happens via the dispatcher's setfeatureenables call.
    if table.modules.remove(name).is_some() {
        0
    } else {
        1
    }
}