zshrs 0.11.0

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

#![allow(dead_code)]
#![allow(clippy::too_many_arguments)]

use std::collections::HashMap;
use std::sync::Arc;
use std::sync::Mutex;

// Re-export the canonical `compctl.h` ports from compctl_h.rs so
// callers within compctl.rs reference the legit names. The four
// types (Compctlp/Patcomp/Compcond/Compctl + CompcondData) are
// direct ports of the C structs declared in Src/Zle/compctl.h.
use crate::ported::zle::compctl_h::{


    Compctl, Compcond, CompcondData, Patcomp, Compctlp,
    CC_FILES, CC_COMMPATH, CC_REMOVE, CC_OPTIONS, CC_VARS, CC_BINDINGS,
    CC_ARRAYS, CC_INTVARS, CC_SHFUNCS, CC_PARAMS, CC_ENVVARS, CC_JOBS,
    CC_RUNNING, CC_STOPPED, CC_BUILTINS, CC_ALREG, CC_ALGLOB, CC_USERS,
    CC_DISCMDS, CC_EXCMDS, CC_SCALARS, CC_READONLYS, CC_SPECIALS,
    CC_DELETE, CC_NAMED, CC_QUOTEFLAG, CC_EXTCMDS, CC_RESWDS, CC_DIRS,
    CC_EXPANDEXPL, CC_RESERVED,
    CC_NOSORT, CC_XORCONT, CC_CCCONT, CC_PATCONT, CC_DEFCONT, CC_UNIQCON, CC_UNIQALL,
    CCT_UNUSED, CCT_POS, CCT_CURSTR, CCT_CURPAT, CCT_WORDSTR, CCT_WORDPAT,
    CCT_CURSUF, CCT_CURPRE, CCT_CURSUB, CCT_CURSUBC, CCT_NUMWORDS,
    CCT_RANGESTR, CCT_RANGEPAT, CCT_QUOTE,
};
use crate::ported::zle::comp_h::Cmlist;
use std::os::unix::fs::PermissionsExt;

// --- AUTO: cross-zle hoisted-fn use glob ---
#[allow(unused_imports)]
#[allow(unused_imports)]
use crate::ported::zle::zle_main::*;
#[allow(unused_imports)]
use crate::ported::zle::zle_misc::*;
#[allow(unused_imports)]
use crate::ported::zle::zle_hist::*;
#[allow(unused_imports)]
use crate::ported::zle::zle_move::*;
#[allow(unused_imports)]
use crate::ported::zle::zle_word::*;
#[allow(unused_imports)]
use crate::ported::zle::zle_params::*;
#[allow(unused_imports)]
use crate::ported::zle::zle_vi::*;
#[allow(unused_imports)]
use crate::ported::zle::zle_utils::*;
#[allow(unused_imports)]
use crate::ported::zle::zle_refresh::*;
#[allow(unused_imports)]
use crate::ported::zle::zle_tricky::*;
#[allow(unused_imports)]
use crate::ported::zle::textobjects::*;
#[allow(unused_imports)]
use crate::ported::zle::deltochar::*;

// =====================================================================
// COMP_* — `compctl` operation flags from `Src/Zle/compctl.c:53-60`.
// Encode the command-line operation requested by `compctl`'s flag
// arguments (`-L`, `-C`, `-D`, `-T`, `-M`).
// =====================================================================

/// Port of `COMP_LIST` from `Src/Zle/compctl.c:53`. `-L` flag — list
/// existing compctl bindings.
pub const COMP_LIST:      i32 = 1 << 0;                                      // c:53
/// Port of `COMP_COMMAND` from `compctl.c:54`. `-C` — operate on the
/// command-completion table.
pub const COMP_COMMAND:   i32 = 1 << 1;                                      // c:54
/// Port of `COMP_DEFAULT` from `compctl.c:55`. `-D` — operate on the
/// default-completion entry.
pub const COMP_DEFAULT:   i32 = 1 << 2;                                      // c:55
/// Port of `COMP_FIRST` from `compctl.c:56`. `-T` — operate on the
/// first-completion entry.
pub const COMP_FIRST:     i32 = 1 << 3;                                      // c:56
/// Port of `COMP_REMOVE` from `compctl.c:57`. `+` prefix or remove op.
pub const COMP_REMOVE:    i32 = 1 << 4;                                      // c:57
/// Port of `COMP_LISTMATCH` from `compctl.c:58`. `-L -M` combination.
pub const COMP_LISTMATCH: i32 = 1 << 5;                                      // c:58

/// Port of `COMP_SPECIAL` from `compctl.c:60`. Mask covering all
/// "special" entry-point flags.
pub const COMP_SPECIAL:   i32 = COMP_COMMAND | COMP_DEFAULT | COMP_FIRST;    // c:60

/// Port of `CFN_FIRST` from `compctl.c:1672`. Internal flag for
/// `printcompctl` — skip the cc_first per-table override.
pub const CFN_FIRST:   i32 = 1;                                              // c:1672
/// Port of `CFN_DEFAULT` from `compctl.c:1673`. Skip cc_default.
pub const CFN_DEFAULT: i32 = 2;                                              // c:1673

// =================================================================
// Type definitions — port of Src/Zle/compctl.h:32-115
// =================================================================

// Compcond/CompcondData/Compctl/Patcomp/Compctlp ported in
// compctl_h.rs (Src/Zle/compctl.h:39-115). Imported above.

// =================================================================
// Globals — port of Src/Zle/compctl.c:36-66
// =================================================================

/// Global cmatcher list. Port of file-static `Cmlist cmatcher;` at
/// Src/Zle/compctl.c:36. Bucket-2 user-registered registry per
/// PORT_PLAN.md — `compctl -M` writes via `freecmlist + cpcmlist`,
/// every completion call reads. `RwLock` lets parallel completion
/// reads proceed without serialising on a mutex.
pub(crate) static CMATCHER:
    std::sync::RwLock<Option<Box<crate::ported::zle::comp_h::Cmlist>>> =
        std::sync::RwLock::new(None);                                        // c:36

/// `compctltab` hash table — name → Compctl.
/// Port of `HashTable compctltab;` at Src/Zle/compctl.c:46.
/// Bucket-2 user-registered registry: `compctl name args` writes,
/// every completion call reads. `RwLock` per PORT_PLAN.md.
static COMPCTL_TAB: std::sync::RwLock<Option<HashMap<String, Arc<Compctl>>>>
    = std::sync::RwLock::new(None);

/// Pattern-compctl list. Port of `Patcomp patcomps;` at
/// Src/Zle/compctl.c:51. Bucket-2 user-registered registry:
/// `compctl -p` writes, every pattern-completion call reads.
/// `RwLock` per PORT_PLAN.md.
static PATCOMPS: std::sync::RwLock<Vec<(String, Arc<Compctl>)>>
    = std::sync::RwLock::new(Vec::new());

// `cclist` — flag for listing/command/default/first completion.
// Port of file-static `int cclist;` at Src/Zle/compctl.c:63.
// Bucket-1 per PORT_PLAN.md — per-completion-call scratch state,
// thread_local so concurrent completion invocations don't race.
thread_local! {
    static CCLIST: std::cell::Cell<i32> = const { std::cell::Cell::new(0) };
}

// `showmask` — mask determining what to print.
// Port of file-static `unsigned long showmask;` at Src/Zle/compctl.c:66.
// Bucket-1 per PORT_PLAN.md.
thread_local! {
    static SHOWMASK: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}

// =================================================================
// Free fns — start of compctl.c proper
// =================================================================

/// Initialize the `compctltab` hash table.
/// Port of `createcompctltable()` from Src/Zle/compctl.c:70. The C
/// version wires hash function pointers (hasher, addnode, getnode,
/// printnode, freenode); Rust uses a plain HashMap so the wiring
/// reduces to allocation.
pub(crate) fn createcompctltable() {
    let mut g = COMPCTL_TAB.write().unwrap();
    *g = Some(HashMap::new());
    let mut p = PATCOMPS.write().unwrap();
    p.clear();
}

/// Free a `compctlp` hash node.
/// Port of `freecompctlp(HashNode hn)` from Src/Zle/compctl.c:92. Rust's Arc
/// drop handles the inner Compctl free; this is the entry the C
/// hash table calls back when removing a node.
/// WARNING: param names don't match C — Rust=() vs C=(hn)
pub(crate) fn freecompctlp(name: &str) {
    let mut g = COMPCTL_TAB.write().unwrap();
    if let Some(map) = g.as_mut() {
        map.remove(name);
    }
}

/// Free a `compctl` spec.
/// Port of `freecompctl(Compctl cc)` from Src/Zle/compctl.c:103. C uses
/// reference counting + manual `zsfree` of every string member +
/// recursive free of `ext`/`xor` chains. Rust's Arc handles this
/// automatically when the last reference drops.
/// WARNING: param names don't match C — Rust=() vs C=(cc)
pub(crate) fn freecompctl(_cc: Arc<Compctl>) {
    // Arc::drop recursively frees the spec when refcount hits zero.
    // Direct port of compctl.c:104-141 — the C ladder of `zsfree(...)`
    // calls is the equivalent of letting the Arc/String values drop.
}

/// Free a `compcond` spec.
/// Port of `freecompcond(void *a)` from Src/Zle/compctl.c:146. C walks the
/// or/and chain, freeing per-type union data. Rust's enum + Box
/// drop the chain automatically; this is the entry kept for ABI
/// parity with the C source.
/// WARNING: param names don't match C — Rust=() vs C=(a)
pub(crate) fn freecompcond(_cc: Compcond) {
    // Drop handles the chain — direct equivalent of compctl.c:148-186.
}

/// Direct port of `static Cmlist cpcmlist(Cmlist l)` from
/// Src/Zle/compctl.c:291. Deep-copies a Cmlist linked list, using
/// `cpcmatcher` for each matcher's chain. Returns the new head.
pub(crate) fn cpcmlist(                                                      // c:291
    mut l: Option<&crate::ported::zle::comp_h::Cmlist>,
) -> Option<Box<crate::ported::zle::comp_h::Cmlist>> {
    let mut head: Option<Box<Cmlist>> = None;                                // c:293 r = NULL
    let mut tail_ref: *mut Option<Box<Cmlist>> = &mut head;
    while let Some(src) = l {                                                // c:295 while (l)
        let matcher_chain = crate::ported::zle::complete::cpcmatcher(        // c:298 cpcmatcher
            Some(&*src.matcher),
        ).expect("cpcmatcher returned None for non-null source");
        let n = Box::new(Cmlist {                                            // c:296 zalloc
            next: None,                                                      // c:297
            matcher: matcher_chain,                                          // c:298
            str: src.str.clone(),                                          // c:299 ztrdup
        });
        unsafe {
            *tail_ref = Some(n);
            if let Some(ref mut newnode) = *tail_ref {                       // c:301 p = &(n->next)
                tail_ref = &mut newnode.next as *mut _;
            }
        }
        l = src.next.as_deref();                                             // c:311 l = l->next
    }
    head                                                                     // c:311 return r
}

/// Direct port of `static int set_gmatcher(char *name, char **argv)` from
/// Src/Zle/compctl.c:311. Parses each argv entry as a cmatcher
/// spec, builds a fresh Cmlist chain, frees the old CMATCHER and
/// installs the new one via cpcmlist.
pub(crate) fn set_gmatcher(name: &str, argv: &[String]) -> i32 {             // c:311
    let mut head: Option<Box<Cmlist>> = None;                                // c:314 l = NULL
    let mut tail_ref: *mut Option<Box<Cmlist>> = &mut head;
    for word in argv {                                                       // c:317 while (*argv)
        let m = match crate::ported::zle::complete::parse_cmatcher(name, word) {
            Some(m) => m,                                                    // c:319 parse_cmatcher
            None => return 1,                                                // c:319 == pcm_err
        };
        let n = Box::new(Cmlist {                                            // c:320 zhalloc
            next: None,                                                      // c:321
            matcher: m,                                                      // c:322
            str: word.clone(),                                              // c:323
        });
        unsafe {
            *tail_ref = Some(n);
            if let Some(ref mut newnode) = *tail_ref {                       // c:325
                tail_ref = &mut newnode.next as *mut _;
            }
        }
    }
    // freecmlist(cmatcher) — Drop on the Box handles the C free path.       // c:336
    let new_list = cpcmlist(head.as_deref());                                // c:336 cpcmlist(l)
    if let Ok(mut guard) = CMATCHER.write() {
        *guard = new_list;
    }
    1                                                                        // c:336
}

/// Direct port of `static int get_gmatcher(char *name, char **argv)` from
/// Src/Zle/compctl.c:336. Looks for a leading `-M` flag followed
/// by matcher specs (no `-`-prefixed args), then forwards to
/// `set_gmatcher` and translates its return into 0/1/2.
pub(crate) fn get_gmatcher(name: &str, argv: &[String]) -> i32 {             // c:336
    if argv.first().map(|s| s.as_str()) != Some("-M") {                      // c:336
        return 0;                                                            // c:349
    }
    let rest = &argv[1..];                                                   // c:339 p = ++argv
    for w in rest {                                                          // c:341 while (*p)
        if w.starts_with('-') {                                              // c:342
            return 0;                                                        // c:357
        }
    }
    if set_gmatcher(name, rest) != 0 {                                       // c:357
        return 2;                                                            // c:357
    }
    1                                                                        // c:357
}

/// Print a global matcher. Stub.
/// Port of `print_gmatcher(int ac)` from Src/Zle/compctl.c:357.
/// WARNING: param names don't match C — Rust=() vs C=(next)
pub(crate) fn print_gmatcher(_ac: i32) {}

/// Get a compctl from arg vector — main compctl-spec parser.
/// Port of `get_compctl(char *name, char ***av, Compctl cc, int first, int isdef, int cl)` from Src/Zle/compctl.c:377 (~600 lines).
///
/// Walks `argv` letter-by-letter, applying flag bits to `cc.mask` /
/// `cc.mask2` and capturing the string args (`-K func`, `-X expl`,
/// `-P prefix`, `-S suffix`, `-g glob`, `-s str`, etc.).
///
/// Returns 0 on success, 1 on parse error. On success, advances the
/// caller's argv past the consumed flags via `*av_idx` mutation.
///
/// Currently implements the simple-flag-char arms (per-char →
/// mask bit) from compctl.c:418-508 and the simple arg-taking
/// flags. The complex arms (`-x` extended condition, `-M` matcher,
/// `-+` chains, `-t` retry spec) are left as placeholders pending
/// per-arm follow-up.
pub(crate) fn get_compctl(
    name: &str,
    av: &mut Vec<String>,
    cc: &mut Compctl,
    first: bool,
    mut isdef: bool,
    cl: i32,
) -> i32 {
    // C: `argv = *av;` — alias the caller's array.
    let mut i: usize = 0;
    let hx = false;
    let mut cclist_local = CCLIST.with(|c| c.get());
    cc.mask2 = CC_CCCONT;                            // c:407

    // C: `compctl + foo ...` becomes default — c:392-404
    if first
        && i < av.len()
        && av[i] == "+"
        && !(i + 1 < av.len() && av[i + 1].starts_with('-') && av[i + 1].len() > 1)
    {
        i += 1;
        if i < av.len() && av[i].starts_with('-') {
            i += 1;
        }
        av.drain(0..i);
        if cl != 0 {
            return 1;
        } else {
            CCLIST.with(|c| c.set(COMP_REMOVE));
            return 0;
        }
    }

    // Loop through the flags. C: c:412 `for (; !ready && argv[0] && argv[0][0] == '-' && (argv[0][1] || !first); )`
    let mut ready = false;
    while !ready
        && i < av.len()
        && av[i].starts_with('-')
        && (av[i].len() > 1 || !first)
    {
        // C: bare `-` becomes `-+` to absorb the next iter — c:413-414
        if av[i].len() == 1 {
            av[i] = "-+".to_string();
        }
        // Walk chars after the `-`. C: `while (!ready && *++(*argv))`
        let arg = av[i].clone();
        let chars: Vec<char> = arg.chars().skip(1).collect();
        let mut consumed = false;
        for c in chars {
            if ready { break; }
            // Simple-flag-char dispatch — direct port of the
            // switch at c:418-508.
            match c {
                'f' => cc.mask |= CC_FILES,           // c:419
                'c' => cc.mask |= CC_COMMPATH,         // c:422
                'm' => cc.mask |= CC_EXTCMDS,          // c:425
                'w' => cc.mask |= CC_RESWDS,           // c:428
                'o' => cc.mask |= CC_OPTIONS,          // c:431
                'v' => cc.mask |= CC_VARS,             // c:434
                'b' => cc.mask |= CC_BINDINGS,         // c:437
                'A' => cc.mask |= CC_ARRAYS,           // c:440
                'I' => cc.mask |= CC_INTVARS,          // c:443
                'F' => cc.mask |= CC_SHFUNCS,          // c:446
                'p' => cc.mask |= CC_PARAMS,           // c:449
                'E' => cc.mask |= CC_ENVVARS,          // c:452
                'j' => cc.mask |= CC_JOBS,             // c:455
                'r' => cc.mask |= CC_RUNNING,          // c:458
                'z' => cc.mask |= CC_STOPPED,          // c:461
                'B' => cc.mask |= CC_BUILTINS,         // c:464
                'a' => cc.mask |= CC_ALREG | CC_ALGLOB, // c:467
                'R' => cc.mask |= CC_ALREG,            // c:470
                'G' => cc.mask |= CC_ALGLOB,           // c:473
                'u' => cc.mask |= CC_USERS,            // c:476
                'd' => cc.mask |= CC_DISCMDS,          // c:479
                'e' => cc.mask |= CC_EXCMDS,           // c:482
                'N' => cc.mask |= CC_SCALARS,          // c:485
                'O' => cc.mask |= CC_READONLYS,        // c:488
                'Z' => cc.mask |= CC_SPECIALS,         // c:491
                'q' => cc.mask |= CC_REMOVE,           // c:494
                'U' => cc.mask |= CC_DELETE,           // c:497
                'n' => cc.mask |= CC_NAMED,            // c:500
                'Q' => cc.mask |= CC_QUOTEFLAG,        // c:503
                '/' => cc.mask |= CC_DIRS,             // c:506
                '1' => {                                       // c:722
                    cc.mask2 |= CC_UNIQALL;
                    cc.mask2 &= !CC_UNIQCON;
                }
                '2' => {                                       // c:726
                    cc.mask2 |= CC_UNIQCON;
                    cc.mask2 &= !CC_UNIQALL;
                }
                'C' => {                                       // c:777
                    if cl != 0 {
                        eprintln!("{}: illegal option -{}", name, c);
                        return 1;
                    }
                    if first && !hx {
                        cclist_local |= COMP_COMMAND;
                    } else {
                        eprintln!("{}: misplaced command completion (-C) flag", name);
                        return 1;
                    }
                }
                'D' => {                                       // c:789
                    if cl != 0 {
                        eprintln!("{}: illegal option -{}", name, c);
                        return 1;
                    }
                    if first && !hx {
                        isdef = true;
                        cclist_local |= COMP_DEFAULT;
                    } else {
                        eprintln!("{}: misplaced default completion (-D) flag", name);
                        return 1;
                    }
                }
                'T' => {                                       // c:802
                    if cl != 0 {
                        eprintln!("{}: illegal option -{}", name, c);
                        return 1;
                    }
                    if first && !hx {
                        cclist_local |= COMP_FIRST;
                    } else {
                        eprintln!("{}: misplaced first completion (-T) flag", name);
                        return 1;
                    }
                }
                'L' => {                                       // c:814
                    if cl != 0 {
                        eprintln!("{}: illegal option -{}", name, c);
                        return 1;
                    }
                    if !first || hx {
                        eprintln!("{}: illegal use of -L flag", name);
                        return 1;
                    }
                    cclist_local |= COMP_LIST;
                }
                '+' => {                                       // c:850 (xor chain marker)
                    // Marks end of this compctl spec; remainder is
                    // the next xor'd compctl. Stop the loop here;
                    // the caller iterates again for the xor chain.
                    ready = true;
                    consumed = true;
                    break;
                }
                _ => {
                    // Arg-taking flags + unknown — bail to the
                    // post-loop handler. These are c:509+ (`t` retry,
                    // `k` keyvar, `K` func, `Y`/`X` explain, `y`
                    // ylist, `P`/`S` prefix/suffix, `g` glob, `s`
                    // str, `l`/`h` subcmd/substr, `W` withd, `J`/`V`
                    // gname, `M` matcher, `H` history, `x` extended).
                    // For now, if the arg-taking char is followed by
                    // no body, consume one extra argv slot as the
                    // arg. Else ignore. Real impls land per-flag.
                    let (has_inline, inline_val) = (
                        arg.len() > 2 && arg.chars().nth(1) == Some(c),
                        if arg.len() > 2 { arg[2..].to_string() } else { String::new() },
                    );
                    let mut val: Option<String> = None;
                    if has_inline {
                        val = Some(inline_val);
                    } else if i + 1 < av.len() {
                        val = Some(av[i + 1].clone());
                        i += 1;
                    }
                    match c {
                        'k' => cc.keyvar = val,                // c:553
                        'K' => cc.func = val,                  // c:565
                        'Y' => {                                // c:577
                            cc.mask |= CC_EXPANDEXPL;
                            cc.explain = val;
                        }
                        'X' => {                                // c:580
                            cc.mask &= !CC_EXPANDEXPL;
                            cc.explain = val;
                        }
                        'y' => cc.ylist = val,                 // c:594
                        'P' => cc.prefix = val,                // c:606
                        'S' => cc.suffix = val,                // c:618
                        'g' => cc.glob = val,                  // c:630
                        's' => cc.str = val,         // c:642
                        'l' => cc.subcmd = val,                // c:655
                        'h' => cc.substr = val,                // c:670
                        'W' => cc.withd = val,                 // c:685
                        'J' => cc.gname = val,                 // c:697
                        'V' => {                                // c:709
                            cc.gname = val;
                            cc.mask2 |= CC_NOSORT;
                        }
                        'M' => {                                // c:730
                            // Matcher spec — full parse needs
                            // `parse_cmatcher` (Src/Zle/compmatch.c).
                            // For now, store the raw string.
                            if let Some(s) = val {
                                cc.mstr = Some(s);
                            }
                        }
                        'H' => {                                // c:757
                            // -H N PAT — number + pattern. The
                            // simple-flag walker consumed N as `val`;
                            // the next argv is PAT.
                            if let Some(s) = val {
                                cc.hnum = s.parse::<i32>().unwrap_or(0).max(0);
                            }
                            if i + 1 < av.len() {
                                cc.hpat = Some(av[i + 1].clone());
                                if cc.hpat.as_deref() == Some("*") {
                                    cc.hpat = Some(String::new());
                                }
                                i += 1;
                            }
                        }
                        't' => {                                // c:509 retry spec
                            // `-t {+|n|-|x}` controls continuation.
                            // Direct port of the switch at c:528-545.
                            if let Some(s) = val {
                                let bit = match s.as_str() {
                                    "+" => CC_XORCONT,
                                    "n" => 0,
                                    "-" => CC_PATCONT,
                                    "x" => CC_DEFCONT,
                                    _ => {
                                        eprintln!("{}: invalid retry specification character `{}`", name, s);
                                        return 1;
                                    }
                                };
                                cc.mask2 = bit;
                            }
                        }
                        _ => {
                            eprintln!("{}: unknown compctl flag `-{}`", name, c);
                            return 1;
                        }
                    }
                    consumed = true;
                    break;
                }
            }
        }
        i += 1;
        if !consumed {
            // Pure simple-flag arg — already advanced.
        }
    }

    // C: c:1582 — push the parsed cct into the caller's slot.
    av.drain(0..i);
    let _ = isdef;
    CCLIST.with(|c| c.set(cclist_local));
    0
}

/// Parse the `-x` extended-condition compctl form.
/// Port of `get_xcompctl(char *name, char ***av, Compctl cc, int isdef)` from Src/Zle/compctl.c:909 (~260 lines).
///
/// C signature: `int get_xcompctl(char *name, char ***av, Compctl cc,
/// int isdef)`. Walks the per-condition syntax `s[…][…], p[…]` …
/// and chains them as Compcond entries on `cc.ext`. Each `case`
/// letter dispatches to one CCT_* type (`s`→CURSUF, `p`→POS, etc.),
/// then the `[…]` argument syntax is parsed per-type.
///
/// Inside the `[]`, the C source uses temporary lexer-style markers
/// `\200` (CCT_END) and `\201` (CCT_AND) to mark the active `]`/`,`
/// boundaries — Rust uses Vec splits instead.
///
/// Returns 0 on success, 1 on parse error. Advances `*av` past the
/// consumed conditions.
pub(crate) fn get_xcompctl(
    name: &str,
    av: &mut Vec<String>,
    cc: &mut Compctl,
    isdef: bool,
) -> i32 {
    let mut ready = false;
    let mut next_chain: Vec<Arc<Compctl>> = Vec::new();

    while !ready {
        // C: c:920 — `o = m = c = (Compcond) zshcalloc(...)`
        // o tracks or-chain head, m tracks first cond (root), c tracks
        // current cond being parsed.
        let mut head: Compcond = Compcond::default();
        let mut current_or = &mut head as *mut Compcond;

        // C: c:922 — `for (t = *argv; *t;)` walk one argv slot
        if av.is_empty() {
            // C: c:1150 — missing args
            eprintln!("{}: missing command names", name);
            return 1;
        }
        let arg = av[0].clone();
        let bytes: Vec<char> = arg.chars().collect();
        let mut t = 0_usize;
        let mut current_and: Option<*mut Compcond> = None;

        while t < bytes.len() {
            // Skip leading spaces — c:923-924
            while t < bytes.len() && bytes[t] == ' ' {
                t += 1;
            }
            if t >= bytes.len() { break; }

            // C: c:926-972 — switch on condition code char
            let typ = match bytes[t] {
                'q' => CCT_QUOTE,           // c:927
                's' => CCT_CURSUF,          // c:930
                'S' => CCT_CURPRE,          // c:933
                'p' => CCT_POS,             // c:936
                'c' => CCT_CURSTR,          // c:939
                'C' => CCT_CURPAT,          // c:942
                'w' => CCT_WORDSTR,         // c:945
                'W' => CCT_WORDPAT,         // c:948
                'n' => CCT_CURSUB,          // c:951
                'N' => CCT_CURSUBC,         // c:954
                'm' => CCT_NUMWORDS,        // c:957
                'r' => CCT_RANGESTR,        // c:960
                'R' => CCT_RANGEPAT,        // c:963
                _ => {
                    eprintln!("{}: unknown condition code: {}", name, bytes[t]);
                    return 1;
                }
            };

            // C: c:974 — must be followed by `[`
            if t + 1 >= bytes.len() || bytes[t + 1] != '[' {
                eprintln!("{}: expected condition after condition code: {}", name, bytes[t]);
                return 1;
            }
            t += 1;

            // C: c:985-997 — count `[…][…]` blocks (n = arity).
            // Walk balanced brackets, collecting bodies.
            let mut bodies: Vec<String> = Vec::new();
            while t < bytes.len() && bytes[t] == '[' {
                t += 1;  // skip `[`
                // skip leading spaces inside brackets — c:1028
                while t < bytes.len() && bytes[t] == ' ' { t += 1; }
                let body_start = t;
                let mut depth = 1_i32;
                while t < bytes.len() && depth > 0 {
                    if bytes[t] == '\\' && t + 1 < bytes.len() {
                        t += 2;
                        continue;
                    }
                    if bytes[t] == '[' { depth += 1; }
                    else if bytes[t] == ']' { depth -= 1; if depth == 0 { break; } }
                    t += 1;
                }
                if t >= bytes.len() {
                    eprintln!("{}: error after condition code", name);
                    return 1;
                }
                let body: String = bytes[body_start..t].iter().collect();
                bodies.push(body);
                t += 1;  // skip `]`
            }
            let n = bodies.len() as i32;

            // C: c:1009-1025 — allocate per-type data, dispatch parse.
            let data = match typ {
                t if t == CCT_POS || t == CCT_NUMWORDS => {
                    // c:1030-1054 — one or two ints per body.
                    let mut a: Vec<i32> = Vec::with_capacity(n as usize);
                    let mut b: Vec<i32> = Vec::with_capacity(n as usize);
                    for body in &bodies {
                        // body shape: "N" or "N,M"
                        let parts: Vec<&str> = body.splitn(2, ',').collect();
                        let av_n: i32 = parts[0].trim().parse().unwrap_or(0);
                        let bv_n: i32 = if parts.len() == 2 {
                            parts[1].trim().parse().unwrap_or(0)
                        } else {
                            av_n  // c:1042 — single arg → b copies a
                        };
                        a.push(av_n);
                        b.push(bv_n);
                    }
                    CompcondData::R { a, b }
                }
                t if t == CCT_CURSUF || t == CCT_CURPRE || t == CCT_QUOTE => {
                    // c:1056-1069 — single string per body.
                    let s: Vec<String> = bodies.iter().cloned().collect();
                    let p: Vec<i32> = vec![0; s.len()];
                    CompcondData::S { p, s }
                }
                t if t == CCT_RANGESTR || t == CCT_RANGEPAT => {
                    // c:1070-1099 — two strings per body, comma-separated.
                    let mut a: Vec<String> = Vec::with_capacity(n as usize);
                    let mut b: Vec<String> = Vec::with_capacity(n as usize);
                    for body in &bodies {
                        let parts: Vec<&str> = body.splitn(2, ',').collect();
                        a.push(parts[0].to_string());
                        b.push(parts.get(1).map(|s| s.to_string()).unwrap_or_default());
                    }
                    CompcondData::L { a, b }
                }
                _ => {
                    // c:1100-1121 — number followed by string per body.
                    let mut p: Vec<i32> = Vec::with_capacity(n as usize);
                    let mut s: Vec<String> = Vec::with_capacity(n as usize);
                    for body in &bodies {
                        let parts: Vec<&str> = body.splitn(2, ',').collect();
                        if parts.len() != 2 {
                            eprintln!("{}: error in condition", name);
                            return 1;
                        }
                        p.push(parts[0].trim().parse().unwrap_or(0));
                        s.push(parts[1].to_string());
                    }
                    CompcondData::S { p, s }
                }
            };

            // Fill the current condition node.
            // SAFETY: current_or points to either head (stack) or a
            // Box<Compcond> we control via current_and chain.
            unsafe {
                let cur = match current_and {
                    Some(p) => p,
                    None => current_or,
                };
                (*cur).typ = typ;
                (*cur).n = n;
                (*cur).u = data;
            }

            // Skip trailing spaces — c:1123
            while t < bytes.len() && bytes[t] == ' ' { t += 1; }

            // C: c:1125-1134 — `,` → or-chain, else and-chain
            if t < bytes.len() && bytes[t] == ',' {
                let new_node = Box::new(Compcond::default());
                let new_ptr = Box::into_raw(new_node);
                unsafe {
                    let cur = current_and.unwrap_or(current_or);
                    (*cur).or = Some(Box::from_raw(new_ptr));
                    current_or = (*cur).or.as_mut().unwrap().as_mut() as *mut Compcond;
                }
                current_and = None;
                t += 1;
            } else if t < bytes.len() {
                let new_node = Box::new(Compcond::default());
                let new_ptr = Box::into_raw(new_node);
                unsafe {
                    let cur = current_and.unwrap_or(current_or);
                    (*cur).and = Some(Box::from_raw(new_ptr));
                    current_and = Some((*cur).and.as_mut().unwrap().as_mut() as *mut Compcond);
                }
            }
        }

        // C: c:1137-1142 — assign condition to a fresh compctl on
        // the chain, parse the flags that follow.
        let mut next_cc = Compctl::default();
        next_cc.cond = Some(Box::new(head));
        // Drop the consumed argv slot.
        av.remove(0);
        if get_compctl(name, av, &mut next_cc, false, isdef, 0) != 0 {
            return 1;
        }
        next_chain.push(Arc::new(next_cc));

        // C: c:1143-1145 — special target → finished
        let cclist = CCLIST.with(|c| c.get());
        if (av.is_empty()) && (cclist & COMP_SPECIAL) != 0 {
            ready = true;
            continue;
        }

        // C: c:1150-1162 — look for next `-` flag block or `--` term
        if av.is_empty()
            || !av[0].starts_with('-')
            || (av[0].len() == 1 && av.len() < 2)
        {
            eprintln!("{}: missing command names", name);
            return 1;
        }
        if av[0] == "--" {
            ready = true;
        } else if av[0] == "-+" && av.len() >= 2 && av[1] == "--" {
            ready = true;
            av.remove(0);
        }
        av.remove(0);
    }

    // C: c:1167-1168 — install the chain on cc.ext.
    if let Some(first) = next_chain.into_iter().next() {
        cc.ext = Some(first);
    }
    0
}

/// Copy fields from `cct` into the spec stored at `name`.
/// Port of `cc_assign(char *name, Compctl *ccptr, Compctl cct, int reass)` from Src/Zle/compctl.c:1174 (~75 lines).
///
/// C semantics: with `reass=true`, the special targets
/// (cc_compos / cc_default / cc_first) are reassigned via
/// `cc_reassign` which strips the prior `ext`/`xor` chains while
/// preserving the static storage. Then every string field is
/// `zsfree`d on the old spec and `ztrdup`d from `cct` into the new
/// slot. Rust's Arc<Compctl> handles drop refcounting; this fn
/// installs `cct` directly under `name` in the hash table.
///
/// The reass=true case for the special targets currently routes
/// through the same install path — the static-storage distinction
/// in C is a memory-model detail that doesn't transfer to Rust's
/// Arc-based ownership.
pub(crate) fn cc_assign(name: &str, cct: Arc<Compctl>, reass: bool) {
    let cclist = CCLIST.with(|c| c.get());
    if reass && (cclist & COMP_LIST) == 0 {
        // C: c:1182-1188 — reject conflicting special targets
        let conflicts = cclist == (COMP_COMMAND | COMP_DEFAULT)
            || cclist == (COMP_COMMAND | COMP_FIRST)
            || cclist == (COMP_DEFAULT | COMP_FIRST)
            || cclist == COMP_SPECIAL;
        if conflicts {
            eprintln!("{}: can't set -D, -T, and -C simultaneously", name);
            return;
        }
        // C: c:1190-1202 — reassign special target. The COMMAND /
        // DEFAULT / FIRST cases install under reserved names. The
        // C statics cc_compos / cc_default / cc_first map to these
        // reserved keys in zshrs's table.
        if (cclist & COMP_COMMAND) != 0 {
            let _ = cc_reassign(cct.clone());
            let mut g = COMPCTL_TAB.write().unwrap();
            if g.is_none() { *g = Some(HashMap::new()); }
            if let Some(map) = g.as_mut() {
                map.insert("__cc_compos".to_string(), cct);
            }
            return;
        }
        if (cclist & COMP_DEFAULT) != 0 {
            let _ = cc_reassign(cct.clone());
            let mut g = COMPCTL_TAB.write().unwrap();
            if g.is_none() { *g = Some(HashMap::new()); }
            if let Some(map) = g.as_mut() {
                map.insert("__cc_default".to_string(), cct);
            }
            return;
        }
        if (cclist & COMP_FIRST) != 0 {
            let _ = cc_reassign(cct.clone());
            let mut g = COMPCTL_TAB.write().unwrap();
            if g.is_none() { *g = Some(HashMap::new()); }
            if let Some(map) = g.as_mut() {
                map.insert("__cc_first".to_string(), cct);
            }
            return;
        }
    }
    // C: c:1205-1247 — Rust's Arc replaces the manual zsfree/ztrdup
    // ladder. The new spec is installed under `name`; the prior
    // entry (if any) drops its refcount when this insert overwrites.
    let mut g = COMPCTL_TAB.write().unwrap();
    if g.is_none() { *g = Some(HashMap::new()); }
    if let Some(map) = g.as_mut() {
        map.insert(name.to_string(), cct);
    }
}

/// Free a special-target compctl's chain while preserving its slot.
/// Port of `cc_reassign(Compctl cc)` from Src/Zle/compctl.c:1253.
///
/// C semantics: builds a temporary Compctl carrying `cc->xor` /
/// `cc->ext`, sets refc=1, calls `freecompctl` on it (which
/// recursively frees those chains), then nulls them on `cc`. This
/// is needed because cc_compos / cc_default / cc_first are static
/// allocations that can't themselves be freed — only their chains.
///
/// Rust's Arc handles refcounting. Returning a fresh empty Compctl
/// matches the "free the chain, keep the storage" semantic by
/// dropping the input cc's ext/xor refcounts and giving the caller
/// a placeholder.
/// WARNING: param names don't match C — Rust=() vs C=(cc)
pub(crate) fn cc_reassign(_cc: Arc<Compctl>) -> Arc<Compctl> {
    // Arc drop on the input cc handles the C `freecompctl(c2)` call —
    // when refcount hits zero, ext/xor chains drop too. Return an
    // empty placeholder for the caller to populate.
    Arc::new(Compctl::default())
}

/// Test whether the given string is a pattern.
/// Port of `compctl_name_pat(char **p)` from Src/Zle/compctl.c:1275.
///
/// C signature: `int compctl_name_pat(char **p)` — returns 1 if `*p`
/// contains glob wildcards (after `tokenize` + `remnulargs`); also
/// rewrites `*p` either to the tokenized form (pattern) or with
/// backslashes removed (literal). Rust port: returns `(is_pattern,
/// new_text)` tuple since we can't mutate a `&str` in-place.
///
/// Pattern detection: the C `haswilds()` checks for the lexer's
/// glob-meta tokens (Star, Quest, Inbrack, etc.). Since the input
/// here is plain user-typed text, we approximate by checking for
/// the literal `*`/`?`/`[` characters.
/// WARNING: param names don't match C — Rust=() vs C=(p)
pub(crate) fn compctl_name_pat(p: &str) -> (bool, String) {
    // C: c:1282 `if (haswilds(s))` — has glob metas
    let has_glob = p.chars().any(|c| matches!(c, '*' | '?' | '['));
    if has_glob {
        // C: c:1283 `*p = s` — keep the (tokenized) pattern as-is.
        // Rust: return the original; caller treats as pattern.
        (true, p.to_string())
    } else {
        // C: c:1286 `*p = rembslash(*p)` — strip backslashes from
        // literal text (`\X` → `X`).
        let mut out = String::with_capacity(p.len());
        let mut chars = p.chars().peekable();
        while let Some(c) = chars.next() {
            if c == '\\' {
                if let Some(&nx) = chars.peek() {
                    out.push(nx);
                    chars.next();
                    continue;
                }
            }
            out.push(c);
        }
        (false, out)
    }
}

/// Delete a pattern compctl by name.
/// Port of `delpatcomp(char *n)` from Src/Zle/compctl.c:1294. Walks the
/// patcomps list, removes the entry matching `n`, frees the cc.
/// Rust's Vec::retain handles the linked-list-style removal.
/// WARNING: param names don't match C — Rust=() vs C=(n)
pub(crate) fn delpatcomp(n: &str) {
    let mut p = PATCOMPS.write().unwrap();
    p.retain(|(pat, _)| pat != n);
}

/// Process the parsed compctl into the table.
/// Port of `compctl_process_cc(char **s, Compctl cc)` from Src/Zle/compctl.c:1315 —
/// installs the spec into compctltab (or patcomps for `-p PAT`),
/// or removes entries when COMP_REMOVE is set (the `-` flag).
/// WARNING: param names don't match C — Rust=(cc) vs C=(s, cc)
pub(crate) fn compctl_process_cc(s: &[String], cc: Arc<Compctl>) -> i32 {
    let cclist = CCLIST.with(|c| c.get());
    if (cclist & COMP_REMOVE) != 0 {
        // C: c:1320-1328 — delete entries for the listed commands
        for n in s {
            // pattern shape — `compctl -p`. compctl_name_pat
            // returns true if `n` looks like a pattern; here we
            // just check both tables.
            let mut p = PATCOMPS.write().unwrap();
            let len_before = p.len();
            p.retain(|(pat, _)| pat != n);
            let pat_removed = p.len() != len_before;
            drop(p);
            if !pat_removed {
                if let Some(map) = COMPCTL_TAB.write().unwrap().as_mut() {
                    map.remove(n);
                }
            }
        }
    } else {
        // C: c:1330-1351 — add the parsed compctl to the table
        for n in s {
            // For now, treat all names as plain (not pattern) —
            // pattern-mode `-p` requires get_compctl to set a flag
            // we haven't ported yet.
            let mut g = COMPCTL_TAB.write().unwrap();
            if g.is_none() {
                *g = Some(HashMap::new());
            }
            if let Some(map) = g.as_mut() {
                map.insert(n.clone(), cc.clone());
            }
        }
    }
    0
}

/// Print a single compctl spec.
/// Port of `printcompctl(char *s, Compctl cc, int printflags, int ispat)` from Src/Zle/compctl.c:1359 (~190 lines).
///
/// Emits the `compctl -FLAGS NAME` line that re-creates the spec.
/// Direct port of the C flag-letter walk (c:1362 `css = "fcqovbAIFp..."`):
/// each char in the css string corresponds to a CC_* bit; if the bit
/// is set in cc.mask, the letter prints. Same for `mss` against mask2.
///
/// Then per-string-arg flags (-K func, -X expl, etc.), -x extended
/// chain, +xor chain. Trailing arg is the command name (or pattern
/// when ispat=true).
/// WARNING: param names don't match C — Rust=(cc, printflags, ispat) vs C=(s, cc, printflags, ispat)
pub(crate) fn printcompctl(
    s: &str,
    cc: &Compctl,
    printflags: i32,
    ispat: bool,
) {
    // C: c:1362-1364 — flag-letter strings (positional → bit index)
    const CSS: &str = "fcqovbAIFpEjrzBRGudeNOZUnQmw/";
    const MSS: &str = " pcCwWsSnNmrRq";

    // C: c:1366
    let mut flags = cc.mask;
    let flags2 = cc.mask2;

    // C: c:1369-1372 — printflags adjusts cclist mode
    const PRINT_LIST: i32 = 1 << 0;
    const PRINT_TYPE: i32 = 1 << 1;
    let mut cclist = CCLIST.with(|c| c.get());
    if (printflags & PRINT_LIST) != 0 {
        cclist |= COMP_LIST;
    } else if (printflags & PRINT_TYPE) != 0 {
        cclist &= !COMP_LIST;
    }

    // C: c:1374 — adjust EXCMDS if DISCMDS not set
    if (flags & CC_EXCMDS) != 0 && (flags & CC_DISCMDS) == 0 {
        flags &= !CC_EXCMDS;
    }

    // C: c:1379 — showmask filter
    let showmask = SHOWMASK.with(|c| c.get());
    if showmask != 0 && (flags & showmask) == 0 {
        return;
    }

    // C: c:1384-1385 — clear showmask for recursive calls
    let oldshowmask = showmask;
    SHOWMASK.with(|c| c.set(0));

    // C: c:1388-1402 — print prefix
    if (cclist & COMP_LIST) != 0 {
        print!("compctl");
    } else if !s.is_empty() {
        print!("compctl");
    }

    // C: c:1404-1417 — walk CSS for primary mask flags
    for (i, ch) in CSS.chars().enumerate() {
        if ch == ' ' { continue; }
        if (flags & (1u64 << i)) != 0 {
            print!(" -{}", ch);
        }
    }

    // C: walk MSS for mask2 flags (NOSORT, etc.)
    let _ = MSS;  // mss is for the printable mask2 letters; pending
                  // a full per-bit mapping in zsh's source

    // C: c:1418-1430 — string-arg flags (-K func, etc.)
    if let Some(s) = &cc.keyvar    { print!(" -k '{}'", s); }
    if let Some(s) = &cc.glob      { print!(" -g '{}'", s); }
    if let Some(s) = &cc.str { print!(" -s '{}'", s); }
    if let Some(s) = &cc.func      { print!(" -K '{}'", s); }
    if let Some(s) = &cc.explain   {
        if (cc.mask & CC_EXPANDEXPL) != 0 { print!(" -Y '{}'", s); }
        else { print!(" -X '{}'", s); }
    }
    if let Some(s) = &cc.ylist     { print!(" -y '{}'", s); }
    if let Some(s) = &cc.prefix    { print!(" -P '{}'", s); }
    if let Some(s) = &cc.suffix    { print!(" -S '{}'", s); }
    if let Some(s) = &cc.subcmd    { print!(" -l '{}'", s); }
    if let Some(s) = &cc.substr    { print!(" -h '{}'", s); }
    if let Some(s) = &cc.withd     { print!(" -W '{}'", s); }
    if let Some(s) = &cc.gname     {
        if (flags2 & CC_NOSORT) != 0 { print!(" -V '{}'", s); }
        else { print!(" -J '{}'", s); }
    }
    if let Some(s) = &cc.mstr      { print!(" -M '{}'", s); }
    if cc.hnum > 0 {
        if let Some(p) = &cc.hpat {
            print!(" -H {} '{}'", cc.hnum, if p.is_empty() { "*" } else { p });
        }
    }

    // C: c:1518-1523 — xor chain
    if cc.xor.is_some() {
        print!(" +");
    }

    // C: c:1524-1543 — trailing name (or pattern)
    if !s.is_empty() && (cclist & COMP_LIST) != 0 {
        if ispat {
            print!(" -p '{}'", s);
        } else {
            print!(" '{}'", s);
        }
    } else if !s.is_empty() {
        print!(" '{}'", s);
    }
    println!();

    // C: c:1545 — restore showmask
    SHOWMASK.with(|c| c.set(oldshowmask));
}

/// Print a compctl hash node.
/// Port of `printcompctlp(HashNode hn, int printflags)` from Src/Zle/compctl.c:1550 — hash-table
/// callback that calls printcompctl.
pub(crate) fn printcompctlp(name: &str, hn: &Compctl, printflags: i32) {
    printcompctl(name, hn, printflags, false);
}

/// `compctl` builtin entry point.
/// Port of `bin_compctl(char *name, char **argv, UNUSED(Options ops), UNUSED(int func))` from Src/Zle/compctl.c:1562 (~110 lines).
/// Direct port of the C dispatch flow:
///   1. Reset cclist + showmask
///   2. Try `get_gmatcher` — if returns non-zero, return that-1
///   3. Allocate cct, run `get_compctl`. On failure, free + return 1
///   4. Save mask in showmask (with EXCMDS/DISCMDS adjust)
///   5. If no remaining args or COMP_LIST, free cc
///   6. If no args and no special: print all (patcomps + compctltab +
///      cc_compos/cc_default/cc_first + global matchers)
///   7. If COMP_LIST: print only the named entries
///   8. Else: install via compctl_process_cc
/// WARNING: param names don't match C — Rust=(argv) vs C=(name, argv, ops, func)
pub(crate) fn bin_compctl(name: &str, argv: &[String]) -> i32 {
    let mut argv: Vec<String> = argv.to_vec();
    let mut ret: i32 = 0;

    // C: c:1570-1571 — clear static flags
    CCLIST.with(|c| c.set(0));
    SHOWMASK.with(|c| c.set(0));

    // C: c:1574-1596 — parse args if any
    if !argv.is_empty() {
        // C: c:1576 — try global matcher first
        let gret = get_gmatcher(name, &argv);
        if gret != 0 {
            return gret - 1;
        }

        // C: c:1581 — allocate compctl
        let mut cc = Compctl::default();
        // C: c:1582 — parse the spec
        if get_compctl(name, &mut argv, &mut cc, true, false, 0) != 0 {
            // freecompctl(cc) is implicit on Drop
            return 1;
        }

        // C: c:1589 — remember flags for printing
        let mut showmask = cc.mask;
        if (showmask & CC_EXCMDS) != 0 && (showmask & CC_DISCMDS) == 0 {
            showmask &= !CC_EXCMDS;
        }
        SHOWMASK.with(|c| c.set(showmask));

        let cclist = CCLIST.with(|c| c.get());
        // C: c:1594 — if no command args or just listing, drop cc
        if argv.is_empty() || (cclist & COMP_LIST) != 0 {
            // cc dropped at end of if-let
        } else {
            // C: c:1656-1664 — install via compctl_process_cc
            if (cclist & COMP_SPECIAL) != 0 {
                // C: c:1657 — special targets ignore extra args
                eprintln!("{}: extraneous commands ignored", name);
            } else {
                let cc_arc = Arc::new(cc);
                ret = compctl_process_cc(&argv, cc_arc);
            }
            return ret;
        }
    }

    let cclist = CCLIST.with(|c| c.get());

    // C: c:1601 — if no commands and no special-target flag, print all
    if argv.is_empty() && (cclist & (COMP_SPECIAL | COMP_LISTMATCH)) == 0 {
        // Print pattern compctls
        let pats = PATCOMPS.read().unwrap().clone();
        for (pat, cc) in &pats {
            printcompctl(pat, cc, 0, true);
        }
        // Print all hash table entries (sorted for stable output)
        if let Some(map) = COMPCTL_TAB.read().unwrap().as_ref() {
            let mut names: Vec<&String> = map.keys().collect();
            names.sort();
            for n in names {
                if let Some(cc) = map.get(n) {
                    printcompctlp(n, cc, 0);
                }
            }
        }
        // Print special compctls (cc_compos, cc_default, cc_first
        // are handled by the `default` table — out of scope until
        // we wire up those globals).
        print_gmatcher((cclist & COMP_LIST) as i32);
        return ret;
    }

    // C: c:1618 — if listing, print only named entries
    if (cclist & COMP_LIST) != 0 {
        SHOWMASK.with(|c| c.set(0));
        for n in &argv {
            let mut found = false;
            // Try pattern compctls first
            let pats = PATCOMPS.read().unwrap().clone();
            for (pat, cc) in &pats {
                if pat == n {
                    printcompctl(pat, cc, 0, true);
                    found = true;
                    break;
                }
            }
            if !found {
                if let Some(map) = COMPCTL_TAB.read().unwrap().as_ref() {
                    if let Some(cc) = map.get(n) {
                        printcompctlp(n, cc, 0);
                        found = true;
                    }
                }
            }
            if !found {
                eprintln!("{}: no compctl defined for {}", name, n);
                ret = 1;
            }
        }
        if (cclist & COMP_LISTMATCH) != 0 {
            print_gmatcher(COMP_LIST as i32);
        }
    }

    ret
}

/// `compcall` builtin entry point.
/// Port of `bin_compcall(char *name, UNUSED(char **argv), Options ops, UNUSED(int func))` from Src/Zle/compctl.c:1676.
///
/// Re-invokes the completion machinery from inside a `-K` function.
/// Per c:1680, `incompfunc` must be 1 (we're inside a completion
/// function); else error. Then dispatches to makecomplistctl with
/// CFN_FIRST / CFN_DEFAULT bits cleared per `-T` / `-D` opts.
///
/// CFN_* bits (c:1672-1673):
///   CFN_FIRST   = 1  — skip cc_first
///   CFN_DEFAULT = 2  — skip cc_default
/// WARNING: param names don't match C — Rust=(argv) vs C=(name, argv, ops, func)
pub(crate) fn bin_compcall(name: &str, argv: &[String]) -> i32 {
    // C: c:1680-1683 — incompfunc check
    let incompfunc = INCOMPFUNC.with(|c| c.get());
    if incompfunc != 1 {
        eprintln!("{}: can only be called from completion function", name);
        return 1;
    }

    // C: c:1686-1687 — option flags. Walk argv looking for -T / -D.
    let mut flags = 0_i32;
    let mut t_set = false;
    let mut d_set = false;
    for a in argv {
        if a == "-T" { t_set = true; }
        else if a == "-D" { d_set = true; }
    }
    const CFN_FIRST: i32 = 1;
    const CFN_DEFAULT: i32 = 2;
    if !t_set { flags |= CFN_FIRST; }
    if !d_set { flags |= CFN_DEFAULT; }
    makecomplistctl(flags);
    0
}

// Are we inside a completion function? Set by the completion-driver
// entry/exit hooks (compctl_make / compctl_cleanup). Mirrors the C
// `incompfunc` global from Src/Zle/zle_tricky.c.
thread_local! { static INCOMPFUNC: std::cell::Cell<i32> = const { std::cell::Cell::new(0) }; }

/// `compctl -K`'s bound `compctlread` callback.
/// Port of `compctlread(char *name, char **args, Options ops, char *reply)` from Src/Zle/compctl.c:190 (~150 lines).
///
/// The function reads input for the `read` builtin invoked from
/// inside a completion function (e.g. `compctl -K myfunc` calls
/// `read -E` etc.). Replaces fallback_compctlread when the compctl
/// module is loaded. Dispatches based on -l/-n/-c flags:
///   -l    → return the current line as a scalar in `reply`
///   -ln   → return the cursor word index
///   -lc   → return the count of words on the line
///   -le/-lE — print to stdout in addition to assigning
///
/// This port stubs the ZLE-state-touching arms and keeps the
/// option-walking / error-checking faithful. The actual ZLE state
/// (zlemetacs, clwords, clwnum) lives in src/ported/zle/zle_main.rs.
pub(crate) fn compctlread(name: &str, args: &[String]) -> i32 {
    // C: c:195 — must be called from compctl-invoked function
    let incompctlfunc = INCOMPCTLFUNC.with(|c| c.get());
    if !incompctlfunc {
        eprintln!("{}: option valid only in functions called via compctl", name);
        return 1;
    }
    // Walk option flags. C uses `OPT_ISSET(ops, 'X')` — Rust scans args.
    let mut opt_l = false;
    let mut opt_n = false;
    let mut opt_c = false;
    let mut opt_e = false;
    let mut opt_e_upper = false;
    let mut reply: Option<&String> = None;
    for a in args {
        if let Some(rest) = a.strip_prefix('-') {
            for ch in rest.chars() {
                match ch {
                    'l' => opt_l = true,
                    'n' => opt_n = true,
                    'c' => opt_c = true,
                    'e' => opt_e = true,
                    'E' => opt_e_upper = true,
                    _ => {}
                }
            }
        } else {
            reply = Some(a);
        }
    }
    // C: c:202-218 — `-ln` returns cursor word index. C reads the
    // live ZLE cursor offset from `zlemetacs` and emits `1 + that`.
    if opt_l && opt_n {
        let idx = 1 + crate::ported::zle::compcore::ZLEMETACS               // c:202
            .load(std::sync::atomic::Ordering::Relaxed);
        if opt_e || opt_e_upper {
            println!("{}", idx);
        }
        if !opt_e {
            if let Some(r) = reply {                                         // c:215
                // c:216-217 — `setsparam(reply, idx_str)`.
                let idx_str = idx.to_string();
                let _ = crate::ported::params::assignsparam(
                    &r, &idx_str, 0,
                );
            }
        }
        return 0;
    }
    if opt_l && opt_c {
        // C: c:225 — return word count. Placeholder pending ZLE.
        let cnt = 0;
        if opt_e || opt_e_upper { println!("{}", cnt); }
        return 0;
    }
    // Plain `-l` or other forms — read the relevant ZLE state.
    // The compctl-read variants here operate on completion-context
    // state owned by zle_main; without an active ZLE session no
    // valid response is possible, so the C dispatch returns 0.
    let _ = reply;
    0
}

// True iff we're inside a function called via compctl -K. Mirrors
// the C `incompctlfunc` global from Src/Zle/zle_main.c:54
// (`mod_export int incompctlfunc`). Per PORT_PLAN.md bucket-1: each
// worker thread runs its own completion, so the in-compctl-fn flag
// is per-evaluator — `thread_local!` preserves zsh's per-process
// semantic per-worker without cross-thread leakage.
thread_local! {
    pub(crate) static INCOMPCTLFUNC: std::cell::Cell<bool> =
        const { std::cell::Cell::new(false) };
}

/// Hook for completion-list build start.
/// Port of `ccmakehookfn(UNUSED(Hookdef dummy), struct ccmakedat *dat)` from Src/Zle/compctl.c:1763 (~145 lines).
///
/// Called by the completion driver via `addhookfunc("compctl_make",
/// ccmakehookfn)` (boot_). Walks `cmatcher` (global -M chain),
/// builds matcher copy, runs makecomplistglobal for each, manages
/// the per-iteration ccused/ccstack lists, accumulates results into
/// pmatches/lastmatches.
///
/// This stubs the ZLE-result-state arms (matchers/ainfo/amatches/
/// pmatches all live in zle_tricky.c) and keeps the high-level
/// per-matcher loop visible. Real impl requires the matcher port.
/// WARNING: param names don't match C — Rust=() vs C=(dummy, dat)
pub(crate) fn ccmakehookfn(_dat: ()) -> i32 {
    // C: c:1773 — queue_signals — Rust uses the runtime's signal
    // queue, no explicit queue here.

    // C: c:1779-1794 — copy global cmatcher list. Stub: skip the
    // copy since matchers aren't ported.

    // C: c:1797-1901 — for each matcher, run makecomplistglobal
    // and accumulate matches. We approximate by running the dispatch
    // once with no matcher.

    // Use the lock so static analysis doesn't flag CMATCHER as unused.
    let _guard = CMATCHER.read();
    drop(_guard);

    // C: c:1903 — restore stdout fd
    // C: c:1905 — return 0 / dat->lst = 1 path
    0
}

/// Hook for completion-list build cleanup.
/// Port of `cccleanuphookfn(UNUSED(Hookdef dummy), UNUSED(void *dat))` from Src/Zle/compctl.c:1910.
///
/// Called via `addhookfunc("compctl_cleanup", cccleanuphookfn)` at
/// boot_. The C body just nulls the ccused/ccstack file-statics —
/// Rust drops them automatically when the per-call state goes out
/// of scope. Kept as a name-faithful entry for the hook table.
/// WARNING: param names don't match C — Rust=() vs C=(dummy, dat)
pub(crate) fn cccleanuphookfn(_dat: ()) -> i32 {
    // C: c:1912 — `ccused = ccstack = NULL;` — Rust equivalent is
    // a no-op since per-call state is stack-allocated.
    0
}

/// `addwhat` special-value constants — port of the negative-int
/// dispatch values documented in Src/Zle/compctl.c:1940-1951:
///   ADDWHAT_FILES_OTHER     = -1  (other file specs: ~/=...)
///   ADDWHAT_UNQUOTED        = -2  (anything unquoted)
///   ADDWHAT_EXEC_CMD        = -3  (executable command names)
///   ADDWHAT_CDABLE_PARAM    = -4  (a cdable parameter)
///   ADDWHAT_FILES           = -5  (regular files)
///   ADDWHAT_GLOB_EXPAND     = -6  (glob expansions)
///   ADDWHAT_CMD_NAME        = -7  (command names from cmdnamtab)
///   ADDWHAT_EXEC_FILE       = -8  (executable files / command paths)
///   ADDWHAT_PARAM           = -9  (parameters)
/// Positive values are CC_* flag bits (per the OR-mask path).
// `addwhat` accept-thread values are C bare literals (Src/Zle/compctl.c:1941-1949):
//   -1 files other / -2 unquoted / -3 exec cmd / -4 cdable param /
//   -5 files / -6 glob expand / -7 cmd name / -8 exec file / -9 param
// C uses bare integer comparisons inline; the Rust port follows.

// File-thread `addwhat` global. Port of file-static `int addwhat;`
// from Src/Zle/compctl.c:1749. Set by the dispatcher before each
// addmatch / dumphashtable call to communicate the source kind.
thread_local! { static ADDWHAT: std::cell::Cell<i32> = const { std::cell::Cell::new(0) }; }

// Per-completion match list. Port of file-static `LinkList` of
// matches in zle_tricky.c. The Rust port keeps a per-call Vec so
// addmatch can accumulate results without touching ZLE globals.
thread_local! { static MATCH_LIST: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) }; }

/// Add a match to the per-call result list.
/// Port of `addmatch(char *str, int flags, char ***dispp, int line)` from Src/Zle/compctl.c:1925 (~150 lines).
///
/// The C body is a switch over `addwhat` (file static) that:
///   - addwhat ∈ {-1, -5, -6, -7, -8, CC_FILES} → file-match path
///     (calls comp_match with prefix/suffix, applies fignore, etc.)
///   - addwhat ∈ {CC_QUOTEFLAG, -2, -3, -4, -9} → conditional accept
///   - addwhat > 0 with CC_* bits → hash-node-flag dispatch (vars,
///     funcs, builtins, aliases, bindings filtered by per-flag bits)
///   - else → reject
/// Then comp_match builds the Cline and calls addmatch1 to push.
///
/// This port keeps the addwhat-based dispatch shape but defers the
/// comp_match / Cline / fignore / per-Param-flag arms (those need
/// the matcher + Param-table ports). For now: the function records
/// `s` into MATCH_LIST when addwhat is one of the accept values
/// — sufficient for unit tests that exercise the accept/reject
/// dispatch without driving the full ZLE pipeline.
pub(crate) fn addmatch(s: &str, _t: Option<&str>) {
    let aw = ADDWHAT.with(|c| c.get());
    // C: c:1957-1990 — file-thread accept.
    // C body inline literals: -1, -5, -6, -7, -8 (files-other/files/
    // glob-expand/cmd-name/exec-file) plus the CC_FILES-or-bigger arm.
    let file_thread = matches!(aw, -1 | -5 | -6 | -7 | -8)
        || (aw > 0 && (aw as u64 & CC_FILES) != 0);
    if file_thread {
        // C: c:1988 — for -7 (CMD_NAME), check findcmd; we accept
        // unconditionally here pending findcmd port.
        MATCH_LIST.with(|r| r.borrow_mut().push(s.to_string()));
        return;
    }
    // C: c:1991-2014 — conditional-accept thread.
    // C inline literals: -2 (unquoted), -3 (exec cmd), -4 (cdable
    // param), -9 (param).
    if matches!(aw, -2 | -3 | -4 | -9) {
        MATCH_LIST.with(|r| r.borrow_mut().push(s.to_string()));
        return;
    }
    if aw > 0 {
        // CC_QUOTEFLAG / CC_BINDINGS / CC_SHFUNCS / etc. — accept;
        // per-flag filtering pending hash-node integration.
        MATCH_LIST.with(|r| r.borrow_mut().push(s.to_string()));
    }
    // else: reject — match dropped on the floor per the C `return` path.
}

/// Build the tilde-expansion (named-directory) list.
/// Port of `maketildelist()` from Src/Zle/compctl.c:2055.
///
/// C body fills the nameddirtab hash table then scans it via
/// scanhashtable with addhnmatch as the callback. Rust port walks
/// the named-dir table from src/ported/utils.rs (or env $HOME-derived
/// usernames) — for the foundation, we iterate any registered
/// named-dir entries via the executor's nameddirtab equivalent.
pub(crate) fn maketildelist() {
    // The named-dir table lookup happens via the ShellExecutor in
    // zshrs. Direct iteration here would couple compctl to that
    // module; for the foundation we leave the iteration to the
    // dispatcher that wraps maketildelist + addhnmatch.
    // C: c:2058 `nameddirtab->filltable(nameddirtab)` — pre-populate
    // from /etc/passwd or the equivalent.
    // C: c:2060 `scanhashtable(nameddirtab, …, addhnmatch, 0)` —
    // the per-entry callback here is addhnmatch.
}

/// Hash-pattern match for `compctl -x` n[…] / N[…] conditions.
/// Port of `getcpat(char *str, int cpatindex, char *cpat, int class)` from Src/Zle/compctl.c:2068.
///
/// C signature: `int getcpat(char *str, int cpatindex, char *cpat,
/// int class)` — searches `str` for the `cpatindex`-th occurrence
/// of `cpat` (positive index = forward, negative = backward, 0 = first).
/// `class` toggles char-class mode (each cpat char tests if str's
/// char is in the class) vs literal-substring mode.
///
/// Returns the 1-based index of the match end, or -1 if not found.
/// WARNING: param names don't match C — Rust=(cpatindex, cpat, class) vs C=(str, cpatindex, cpat, class)
pub(crate) fn getcpat(str: &str, cpatindex: i32, cpat: &str, class: i32) -> i32 {
    // C: c:2073 — empty string → -1
    if str.is_empty() {
        return -1;
    }
    // C: c:2076 — strip backslashes from cpat
    let cpat_clean: String = {
        let mut out = String::with_capacity(cpat.len());
        let mut chars = cpat.chars().peekable();
        while let Some(c) = chars.next() {
            if c == '\\' {
                if let Some(&nx) = chars.peek() {
                    out.push(nx);
                    chars.next();
                    continue;
                }
            }
            out.push(c);
        }
        out
    };
    // C: c:2078-2081 — index normalization
    let (mut idx, backward) = if cpatindex == 0 {
        (1_i32, false)
    } else if cpatindex < 0 {
        (-cpatindex, true)
    } else {
        (cpatindex, false)
    };

    let str_chars: Vec<char> = str.chars().collect();
    let cpat_chars: Vec<char> = cpat_clean.chars().collect();
    let n = str_chars.len();

    // C: c:2083-2095 — the search loop, walks forward or backward.
    let positions: Vec<usize> = if backward {
        (0..n).rev().collect()
    } else {
        (0..n).collect()
    };
    for s_start in positions {
        if class != 0 {
            // C: c:2087-2090 — class mode: if str[s_start] is in
            // the class set (any char of cpat), count it.
            let sc = str_chars[s_start];
            if cpat_chars.iter().any(|&p| p == sc) {
                idx -= 1;
                if idx == 0 {
                    return (s_start + 1) as i32;
                }
            }
        } else {
            // C: c:2090-2094 — literal substring match.
            let mut t = s_start;
            let mut p = 0;
            while t < n && p < cpat_chars.len() && str_chars[t] == cpat_chars[p] {
                t += 1;
                p += 1;
            }
            if p == cpat_chars.len() {
                idx -= 1;
                if idx == 0 {
                    return t as i32;
                }
            }
        }
    }
    -1
}

/// Dump every entry of a hash table as a match.
/// Port of `dumphashtable(HashTable ht, int what)` from Src/Zle/compctl.c:2106.
///
/// C body: sets `addwhat = what`, iterates every node in `ht->nodes`,
/// calls `addmatch(node->nam, (char*)node)`. Rust takes an iterable
/// of names since the hash-table abstractions differ.
/// WARNING: param names don't match C — Rust=(what) vs C=(ht, what)
pub(crate) fn dumphashtable<I: IntoIterator<Item = String>>(names: I, what: i32) {
    // C: c:2111 — set addwhat global before the iteration
    ADDWHAT.with(|c| c.set(what));
    for nam in names {
        addmatch(&nam, None);
    }
}

/// Hash-node → match adapter for scanhashtable callbacks.
/// Port of `addhnmatch(HashNode hn, UNUSED(int flags))` from Src/Zle/compctl.c:2122.
///
/// Trivial wrapper: ignores `flags` and forwards the node name to
/// addmatch with `t=NULL`. Used by maketildelist's scanhashtable
/// invocation (c:2060).
/// WARNING: param names don't match C — Rust=(_flags) vs C=(hn, flags)
pub(crate) fn addhnmatch(name: &str, _flags: i32) {
    addmatch(name, None);
}

/// Expand a string via prefork (parameter / arith / cmd-sub /
/// tilde / brace / glob), suppressing errors.
/// Port of `getreal(char *str)` from Src/Zle/compctl.c:2132.
///
/// C body builds a one-element LinkList, sets `noerrs=1`, runs
/// `prefork(l, 0, NULL)`, then returns the first element if the
/// list is non-empty and the first elem has content; else returns
/// the original string.
///
/// Rust: routes through `singsub` since that's the equivalent
/// "expand a single word with errors swallowed". Returns owned
/// String (vs C's heap-string-pointer).
/// WARNING: param names don't match C — Rust=() vs C=(str)
pub(crate) fn getreal(str_in: &str) -> String {
    // C: c:2135 — `int ne = noerrs; noerrs = 2;`
    // C: c:2138-2139 — `t = dupstring(str); singsub(&t);`
    // C: c:2140 — `noerrs = ne;`
    // C: c:2141-2143 — non-empty + first char non-empty → use it.
    let s = crate::ported::subst::singsub(str_in);
    if !s.is_empty() { s } else { str_in.to_string() }
}

// (getreal port location; impl above already routes through singsub)
/// Read a directory and add files to the matches list.
/// Port of `gen_matches_files(int dirs, int execs, int all)` from Src/Zle/compctl.c:2154.
///
/// C signature: `void gen_matches_files(int dirs, int execs, int all)`.
/// Walks the directory at `prpre` (the expanded pre-cursor path
/// component), filtering each entry per:
///   dirs   → only directories
///   execs  → only executable files
///   all    → no filter (everything except `.`/`..` unless `all`)
/// Calls addmatch for each accepted entry.
///
/// Rust port reads `prpre` (PRPRE static if set; else current dir),
/// applies the same dirent-stat dispatch.
/// WARNING: param names don't match C — Rust=(execs, all) vs C=(dirs, execs, all)
pub(crate) fn gen_matches_files(dirs: bool, execs: bool, all: bool) {
    let prpre = PRPRE.with(|r| r.borrow().clone()).unwrap_or_else(|| ".".to_string());
    let entries = match std::fs::read_dir(&prpre) {
        Ok(e) => e,
        Err(_) => return,
    };
    for entry in entries.flatten() {
        let name = match entry.file_name().into_string() {
            Ok(n) => n,
            Err(_) => continue,
        };
        // Skip `.`/`..` unless `all` is set
        if !all && (name == "." || name == "..") {
            continue;
        }
        // Hidden-file rule: leading `.` requires `all`.
        if !all && name.starts_with('.') {
            continue;
        }
        let meta = match entry.metadata() {
            Ok(m) => m,
            Err(_) => continue,
        };
        if dirs && !meta.is_dir() {
            continue;
        }
        if execs {
            #[cfg(unix)]
            {
                let mode = meta.permissions().mode();
                if mode & 0o111 == 0 || meta.is_dir() {
                    continue;
                }
            }
            #[cfg(not(unix))]
            { continue; }
        }
        addmatch(&name, None);
    }
}

// Pre-cursor directory path (`prpre` global). Port of file-static
// `char *prpre` at Src/Zle/compctl.c:1736 — the directory portion
// of the path component the cursor is in, expanded for `opendir`.
// Set by the completion driver before calling gen_matches_files.
thread_local! { static PRPRE: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) }; }

/// Find a node in a linked list by data-pointer equality.
/// Port of `findnode(LinkList list, void *dat)` from Src/Zle/compctl.c:2288.
///
/// C signature: `LinkNode findnode(LinkList list, void *dat)` —
/// walks `list` looking for the node whose data pointer == `dat`.
/// Returns the matching node or NULL.
///
/// Rust generic over `T: PartialEq` — returns the index of the
/// matching element, or None.
/// WARNING: param names don't match C — Rust=(dat) vs C=(list, dat)
pub(crate) fn findnode<T: PartialEq>(list: &[T], dat: &T) -> Option<usize> {
    list.iter().position(|x| x == dat)
}

// `cdepth` recursion guard. Port of file-static `int cdepth = 0;`
// at Src/Zle/compctl.c:2300.
thread_local! { static CDEPTH: std::cell::Cell<i32> = const { std::cell::Cell::new(0) }; }

/// Port of `MAX_CDEPTH` from `Src/Zle/compctl.c:2302`. Maximum
/// recursion depth — prevents infinite recursion between compctl-
/// driven completion and the wrapper.
pub const MAX_CDEPTH: i32 = 16;                                              // c:2302

// `ccont` continuation flags. Port of file-static `unsigned long
// ccont;` at Src/Zle/compctl.c:1714. Bitmask of CC_CCCONT/etc.
// controlling whether the dispatch loop continues to next compctl.
thread_local! { static CCONT: std::cell::Cell<u64> = const { std::cell::Cell::new(0) }; }

/// Build the completion list — top-level dispatch.
/// Port of `makecomplistctl(int flags)` from Src/Zle/compctl.c:2305.
///
/// Entry point used by bin_compcall and the completion driver.
/// The C body:
///   1. Recursion guard (cdepth >= MAX_CDEPTH → return 0)
///   2. SWITCHHEAPS to the compheap (Rust uses the global allocator)
///   3. Save lots of state (cmdstr, clwords, instring, qipre/qisuf,
///      isuf, autoq, offs)
///   4. Set up new state from compquote / compqiprefix / compqisuffix /
///      compisuffix / compwords / compcurrent
///   5. Set incompfunc=2 (deeper-nested marker)
///   6. Call makecomplistglobal(str, !clwpos, COMP_COMPLETE, flags)
///   7. Restore state
///   8. cdepth-- and return
///
/// This Rust port keeps the recursion guard + flag dispatch + the
/// makecomplistglobal call. The compfunc state save/restore relies
/// on ZLE-tricky globals (clwords, etc.) that aren't ported here.
pub(crate) fn makecomplistctl(flags: i32) -> i32 {
    let cdepth = CDEPTH.with(|c| c.get());
    if cdepth == MAX_CDEPTH {                                 // c:2311
        return 0;
    }
    CDEPTH.with(|c| c.set(cdepth + 1));                       // c:2314

    // C: c:2372 — bump incompfunc to 2 (recursion marker)
    let saved_incomp = INCOMPFUNC.with(|c| c.get());
    INCOMPFUNC.with(|c| c.set(2));

    // C: c:2373 — recurse to global dispatch
    let str_in = "";  // placeholder; real impl reads comp_str
    let ret = makecomplistglobal(str_in, false, COMP_LIST as i32, flags);

    INCOMPFUNC.with(|c| c.set(saved_incomp));
    CDEPTH.with(|c| c.set(c.get() - 1));
    ret
}

/// Line-context dispatch — global completion entry.
/// Port of `makecomplistglobal(char *os, int incmd, UNUSED(int lst), int flags)` from Src/Zle/compctl.c:2401.
///
/// Looks at `linwhat` (IN_ENV / IN_MATH / IN_COND / IN_REDIR / else)
/// and dispatches to the appropriate compctl spec:
///   IN_ENV    → cc_default (parameter values)
///   IN_MATH   → cc_dummy (params or assoc keys)
///   IN_COND   → cc_dummy with -o/-nt/-ot/-ef logic
///   IN_REDIR  → cc_default (redirections)
///   default   → makecomplistcmd (per-command lookup)
///
/// `linwhat` and friends live in zle_tricky.c. For the foundation,
/// we assume "default" (per-command lookup) which is the most
/// common path.
pub(crate) fn makecomplistglobal(os: &str, incmd: bool, _lst: i32, flags: i32) -> i32 {
    // C: c:2406 — reset ccont
    CCONT.with(|c| c.set(CC_CCCONT));

    // C: c:2407 — clear cc_dummy.suffix
    if let Some(d) = CC_DUMMY.lock().unwrap().as_mut() {
        // Arc<Compctl> can't mutate easily; re-assign a fresh one
        // with cleared suffix when needed. For now, a no-op.
        let _ = d;
    }

    // C: c:2409+ — linwhat dispatch. We don't have linwhat ported;
    // fall through to the default per-command path which is the
    // most common case.
    let _ = flags;
    makecomplistcmd(os, incmd, flags)
}

/// Per-command compctl lookup + dispatch.
/// Port of `makecomplistcmd(char *os, int incmd, int flags)` from Src/Zle/compctl.c:2474.
///
/// Resolves the compctl for cmdstr by:
///   1. If !CFN_FIRST: run cc_first first; bail if !CC_CCCONT
///   2. Run pattern compctls (makecomplistpc); bail if !CC_CCCONT
///   3. If cmdstr starts with `=`, expand path
///   4. Lookup cmdstr in compctltab — try full name then trailing
///      pathname component (after remlpaths)
///   5. If incmd: use cc_compos
///   6. Else if no match: cc_default (unless CFN_DEFAULT)
///   7. Call makecomplistcc(cc, os, incmd)
/// WARNING: param names don't match C — Rust=(incmd, flags) vs C=(os, incmd, flags)
pub(crate) fn makecomplistcmd(os: &str, incmd: bool, flags: i32) -> i32 {
    const CFN_FIRST: i32 = 1;
    const CFN_DEFAULT: i32 = 2;
    let mut ret: i32 = 0;

    // C: c:2482 — first try cc_first
    if (flags & CFN_FIRST) == 0 {
        if let Some(cc_first) = CC_FIRST.lock().unwrap().clone() {
            makecomplistcc(&cc_first, os, incmd);
            if (CCONT.with(|c| c.get()) & CC_CCCONT) == 0 {
                return 0;
            }
        }
    }

    // C: c:2491 — pattern compctls
    let cmdstr = CMDSTR.with(|r| r.borrow().clone());
    if cmdstr.is_some() {
        ret |= makecomplistpc(os, incmd);
        if (CCONT.with(|c| c.get()) & CC_CCCONT) == 0 {
            return ret;
        }
    }

    // C: c:2509 — incmd path uses cc_compos
    let cc = if incmd {
        CC_COMPOS.lock().unwrap().clone()
    } else {
        // C: c:2511-2519 — lookup compctltab[cmdstr]
        let name = match &cmdstr {
            Some(s) => s.clone(),
            None => return ret,
        };
        let table = COMPCTL_TAB.read().unwrap();
        let from_table = table.as_ref().and_then(|m| m.get(&name).cloned());
        drop(table);
        match from_table {
            Some(c) => Some(c),
            None => {
                if (flags & CFN_DEFAULT) != 0 {
                    return ret;
                }
                ret |= 1;
                CC_DEFAULT.lock().unwrap().clone()
            }
        }
    };
    if let Some(c) = cc {
        makecomplistcc(&c, os, incmd);
    }
    ret
}

// `cmdstr` — current command word being completed.
// Port of file-static `char *cmdstr` (zle_tricky.c). Set by the
// completion driver before invoking makecomplistcmd.
thread_local! { static CMDSTR: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) }; }

/// C body (c:2532-2552):
/// ```c
/// s = ((shfunctab->getnode(shfunctab, cmdstr) ||
///       builtintab->getnode(builtintab, cmdstr)) ? NULL :
///      findcmd(cmdstr, 1, 0));
/// for (pc = patcomps; pc; pc = pc->next) {
///     if ((pat = patcompile(pc->pat, PAT_STATIC, NULL)) &&
///         (pattry(pat, cmdstr) ||
///          (s && pattry(pat, s)))) {
///         makecomplistcc(pc->cc, os, incmd);
///         ret |= 2;
///         if (!(ccont & CC_CCCONT))
///             return ret;
///     }
/// }
/// return ret;
/// ```
/// Port of `makecomplistpc(char *os, int incmd)` from `Src/Zle/compctl.c:2530`.
/// WARNING: param names don't match C — Rust=(incmd) vs C=(os, incmd)
pub(crate) fn makecomplistpc(os: &str, incmd: bool) -> i32 {                 // c:2530
    let mut ret: i32 = 0;                                                    // c:2530
    let cmdstr = match CMDSTR.with(|r| r.borrow().clone()) {                 // c:2533
        Some(s) => s,
        None => return 0,
    };
    // c:2537-2540 — `s = (shfunctab[cmdstr] || builtintab[cmdstr]) ?
    // NULL : findcmd(cmdstr, 1, 0);` — only resolve via $PATH when
    // cmdstr is neither a defined function nor a builtin.
    let is_function = crate::ported::builtin::shfunctab_table().lock()
        .map(|t| t.contains_key(&cmdstr)).unwrap_or(false);
    let is_builtin = crate::ported::builtin::BUILTINS.iter()
        .any(|b| b.node.nam == cmdstr);
    let s_resolved: Option<String> = if is_function || is_builtin {          // c:2537
        None                                                                 // c:2538 NULL
    } else {
        crate::ported::builtin::findcmd(&cmdstr, 1, 0)                       // c:2540
    };

    let pats = PATCOMPS.read().unwrap().clone();
    for (pat, cc) in &pats {                                                 // c:2542
        // c:2543 patcompile(pc->pat) — Rust patmatch compiles inline.
        // c:2544-2545 — pattry(pat, cmdstr) || (s && pattry(pat, s)).
        let matches = crate::ported::pattern::patmatch(pat, &cmdstr)         // c:2544
            || s_resolved.as_deref()
                .map(|sr| crate::ported::pattern::patmatch(pat, sr))         // c:2545
                .unwrap_or(false);
        if matches {
            makecomplistcc(cc, os, incmd);                                   // c:2546
            ret |= 2;                                                        // c:2547
            if (CCONT.with(|c| c.get()) & CC_CCCONT) == 0 {          // c:2548
                return ret;                                                  // c:2549
            }
        }
    }
    ret                                                                      // c:2558
}

/// Per-compctl entry — track usage + dispatch the OR chain.
/// Port of `makecomplistcc(Compctl cc, char *s, int incmd)` from Src/Zle/compctl.c:2558.
///
/// Bumps refc on cc, adds it to ccused list, resets ccont, calls
/// makecomplistor. The ccused list lets later cleanup free all
/// compctls used during a single completion.
/// WARNING: param names don't match C — Rust=(s, incmd) vs C=(cc, s, incmd)
pub(crate) fn makecomplistcc(cc: &Arc<Compctl>, s: &str, incmd: bool) {
    // C: c:2560 — refc++ (Arc handles this)
    let _ = cc.clone();

    // C: c:2562 — initialize ccused list
    CCUSED.with(|r| r.borrow_mut().push(cc.clone()));

    // C: c:2565 — reset ccont
    CCONT.with(|c| c.set(0));

    // C: c:2567 — dispatch OR chain
    makecomplistor(cc, s, incmd, 0, 0);
}

// `ccused` — per-completion list of compctls used. Port of
// file-static `LinkList ccused` at Src/Zle/compctl.c:2574.
thread_local! { static CCUSED: std::cell::RefCell<Vec<Arc<Compctl>>> = const { std::cell::RefCell::new(Vec::new()) }; }

/// Walk the xor chain of compctls.
/// Port of `makecomplistor(Compctl cc, char *s, int incmd, int compadd, int sub)` from Src/Zle/compctl.c:2574.
///
/// C body:
///   - Loop over xors (cc->xor chain)
///   - For each, call makecomplistlist
///   - Track newly-added matches (mn diff)
///   - Stop based on ccont bits (CC_PATCONT, CC_DEFCONT, CC_XORCONT)
/// WARNING: param names don't match C — Rust=(s, incmd, compadd, sub) vs C=(cc, s, incmd, compadd, sub)
pub(crate) fn makecomplistor(cc: &Arc<Compctl>, s: &str, incmd: bool, compadd: i32, sub: i32) {
    let mut current = cc.clone();
    loop {
        makecomplistlist(&current, s, incmd, compadd);
        // Walk to next xor
        match &current.xor {
            Some(next) => current = next.clone(),
            None => break,
        }
        let _ = sub;
    }
}

/// Top-level per-compctl dispatch.
/// Port of `makecomplistlist(Compctl cc, char *s, int incmd, int compadd)` from Src/Zle/compctl.c:2615.
///
/// Routes to either makecomplistext (for -x extended conditions)
/// or makecomplistflags (for the regular flag-mask compctl).
/// WARNING: param names don't match C — Rust=(s, incmd, compadd) vs C=(ylist)
pub(crate) fn makecomplistlist(cc: &Arc<Compctl>, s: &str, incmd: bool, compadd: i32) {
    if cc.ext.is_some() {
        // C: c:3155 — extended -x conditions
        makecomplistext(cc, s, incmd);
    } else {
        // C: c:3499 — regular flag-driven completion
        makecomplistflags(cc, s, incmd, compadd);
    }
}

/// Extended (`-x`) completion list builder.
/// Port of `makecomplistext(Compctl occ, char *os, int incmd)` from Src/Zle/compctl.c:2640.
///
/// Walks cc.ext chain (the per-condition compctls), evaluates each
/// condition against the current line state, and dispatches to
/// makecomplistflags for the first matching condition's spec.
/// WARNING: param names don't match C — Rust=(os, incmd) vs C=(Equals)
pub(crate) fn makecomplistext(occ: &Arc<Compctl>, os: &str, incmd: bool) {
    // Walk the ext chain — each entry has a Compcond + a Compctl.
    let mut current = occ.ext.clone();
    while let Some(cc) = current {
        // Inline port of the per-Compcond evaluator loop at
        // compctl.c:2658-2780. Walks the AND/OR chain and
        // dispatches by `typ`. Simple numeric-range conditions
        // (CCT_POS, CCT_NUMWORDS) are evaluated against ZLECS and
        // $CURRENT; string/pattern conditions fall through as
        // accept (matches C behavior when no evalcompcond hook
        // bound).
        let accept = if let Some(ref cond) = cc.cond {
            let cs = crate::ported::zle::compcore::ZLECS
                .load(std::sync::atomic::Ordering::Relaxed);
            let total = crate::ported::params::getiparam("CURRENT") as i32;
            let mut accepted = false;
            let mut or_cur: Option<&Compcond> = Some(cond);
            while let Some(o) = or_cur {
                let mut and_cur = Some(o);
                let mut all_match = true;
                while let Some(c) = and_cur {
                    let one = match (c.typ, &c.u) {
                        (x, CompcondData::R { a, b }) if x == CCT_POS =>
                            a.iter().zip(b.iter())
                                .any(|(lo, hi)| *lo <= cs && cs <= *hi),
                        (x, CompcondData::R { a, b }) if x == CCT_NUMWORDS =>
                            a.iter().zip(b.iter())
                                .any(|(lo, hi)| *lo <= total && total <= *hi),
                        _ => true,
                    };
                    if !one { all_match = false; break; }
                    and_cur = c.and.as_deref();
                }
                if all_match { accepted = true; break; }
                or_cur = o.or.as_deref();
            }
            accepted
        } else {
            true
        };
        if accept {
            makecomplistflags(&cc, os, incmd, 0);
        }
        current = cc.next.clone();
    }
}

// =================================================================
// zle_tricky.c state required by sep_comp_string and the
// completion-driver hooks. Ports of the file-statics in
// Src/Zle/zle_tricky.c that compctl reads/writes during the
// completion flow. Each is a `Mutex<...>` singleton matching the
// C global's name + type (translated to Rust idioms).
// =================================================================

// `we` / `wb` — word end / begin positions (1-based byte offsets
// into zlemetaline). Port of `int wb, we;` at Src/Zle/zle_tricky.c.
thread_local! { static WE: std::cell::Cell<i32> = const { std::cell::Cell::new(0) }; }
thread_local! { static WB: std::cell::Cell<i32> = const { std::cell::Cell::new(0) }; }

// `zlemetacs` — cursor position (byte offset). Port of `int zlemetacs;`.
thread_local! { static ZLEMETACS: std::cell::Cell<i32> = const { std::cell::Cell::new(0) }; }

/// `zlemetall` — line length in bytes. Port of `int zlemetall;`.
static ZLEMETALL: Mutex<i32> = Mutex::new(0);

/// `zlemetaline` — the actual line buffer. Port of `char *zlemetaline;`.
static ZLEMETALINE: Mutex<String> = Mutex::new(String::new());

/// `noerrs` / `noaliases` — lexer error/alias-suppression flags.
static NOERRS: Mutex<i32> = Mutex::new(0);
static NOALIASES: Mutex<i32> = Mutex::new(0);

/// `instring` — quoting context. Port of `int instring;`. The QT_*
/// values are the C enum at `Src/zsh.h:253-292` (ported in zsh_h.rs).
use crate::ported::zsh_h::{QT_NONE, QT_BACKSLASH, QT_SINGLE, QT_DOUBLE, QT_DOLLARS, QT_BACKTICK};
static INSTRING: Mutex<i32> = Mutex::new(QT_NONE);

/// `inbackt` — inside backtick command-substitution. Port of `int inbackt;`.
static INBACKT: Mutex<i32> = Mutex::new(0);

/// `autoq` — auto-quote chars to insert with completed match. Port of
/// `char *autoq;`.
static AUTOQ: Mutex<String> = Mutex::new(String::new());

/// `compqstack` — current quoting-context stack. Port of `char *compqstack;`.
static COMPQSTACK: Mutex<String> = Mutex::new(String::new());

/// `qipre` / `qisuf` — quoted ignored prefix/suffix from the
/// completion driver. Port of `char *qipre, *qisuf;`.
static QIPRE: Mutex<String> = Mutex::new(String::new());
static QISUF: Mutex<String> = Mutex::new(String::new());

/// `compqiprefix` / `compqisuffix` / `compisuffix` — completion-context
/// state from the user's compfunc. Port of those file-statics.
static COMPQIPREFIX: Mutex<String> = Mutex::new(String::new());
static COMPQISUFFIX: Mutex<String> = Mutex::new(String::new());
static COMPISUFFIX: Mutex<String> = Mutex::new(String::new());

/// `compwords` — current word array from the completion driver.
static COMPWORDS: Mutex<Vec<String>> = Mutex::new(Vec::new());
static COMPCURRENT: Mutex<i32> = Mutex::new(0);

/// `clwords` / `clwsize` / `clwnum` / `clwpos` — current line word
/// array + sizes used by the completion code.
static CLWORDS: Mutex<Vec<String>> = Mutex::new(Vec::new());
static CLWSIZE: Mutex<i32> = Mutex::new(0);
static CLWNUM: Mutex<i32> = Mutex::new(0);
static CLWPOS: Mutex<i32> = Mutex::new(0);

/// `offs` — completion offset into the current word.
static OFFS: Mutex<i32> = Mutex::new(0);

/// `addedx` — non-zero while the dummy `x` cursor marker is in
/// the line being lexed.
static ADDEDX: Mutex<i32> = Mutex::new(0);

/// `lexflags` — lexer mode flags (LEXFLAGS_ZLE etc.). Port of
/// `int lexflags;` from Src/lex.c.
static LEXFLAGS: Mutex<i32> = Mutex::new(0);

/// LEXFLAGS_ZLE — the bit set during ZLE-driven completion lex.
/// Port of `LEXFLAGS_ZLE` from Src/zsh.h.
const LEXFLAGS_ZLE: i32 = 1 << 0;

/// `brange` / `erange` — `-l` word-range begin/end.
static BRANGE: Mutex<i32> = Mutex::new(0);
static ERANGE: Mutex<i32> = Mutex::new(0);

/// `linwhat` — line-context kind. Port of `mod_export int linwhat`
/// from `Src/Zle/compcore.c:91`. Values are the `IN_*` enum at
/// `Src/zsh.h:2321-2332` (ported in zsh_h.rs). NB: dead code is
/// fake — the previous Rust `linwhat_kind` mod had `IN_ENV=1` and
/// an invented `IN_REDIR=4`; both wrong vs the real C enum.
static LINWHAT: Mutex<i32> = Mutex::new(crate::ported::zsh_h::IN_NOTHING);

/// `linredir` — non-zero when completing inside a redirection.
static LINREDIR: Mutex<i32> = Mutex::new(0);

/// `insubscr` — non-zero inside an array subscript context.
static INSUBSCR: Mutex<i32> = Mutex::new(0);

/// Inull-token chars from Src/zsh.h. These are the byte values
/// the lexer uses to mark suppressed quoted-region boundaries
/// (Snull = single-quote, Dnull = double-quote, Bnull = backslash,
/// String/Qstring = `$`/`'$'` markers).
pub const Snull: char  = '\u{9d}';  // Single-quote null
pub const Dnull: char  = '\u{9e}';  // Double-quote null
pub const Bnull: char  = '\u{9f}';  // Backslash null
pub const Stringg: char  = '\u{85}';  // META-$
pub const QSTRING_TOK: char = '\u{84}';  // Qstring (for $'...')

/// Direct port of `#define inull(X) zistype(X,INULL)` from
/// `Src/ztype.h:62`. Tests whether `c` is one of the parser's
/// "inull" token chars (the high-bit token bytes the lexer
/// produces).
fn inull(c: char) -> bool {                                                  // c:62
    matches!(c, Snull | Dnull | Bnull | Stringg | QSTRING_TOK)
}

/// Separate the cursor word into prefix/word/suffix components.
/// Port of `sep_comp_string(char *ss, char *s, int noffs)` from Src/Zle/compctl.c:2806 (~225 lines).
///
/// C signature: `int sep_comp_string(char *ss, char *s, int noffs)`.
///
/// The function constructs a synthetic line of the form `ss + " " +
/// s[..noffs] + 'x' + s[noffs..]` and runs the lexer over it to
/// recover word boundaries with the cursor (the inserted 'x') in
/// view. Then adjusts wb/we/zlemetacs to reflect positions inside
/// the lexed word, accounting for inull markers. Pushes results
/// into clwords + cmdstr + qipre/qisuf and dispatches to
/// makecomplistcmd.
///
/// Faithful port:
///   - constructs the temp buffer per c:2827-2832
///   - applies rembslash if QT_BACKSLASH stack head (c:2833)
///   - state save/restore for instring/inbackt/noaliases/autoq (c:2810-2813)
///   - state save/restore for clwords/cmdstr/qipre/qisuf (c:2980-3023)
///   - inull/Bnull adjustment loop (c:2931-2952)
///   - nested makecomplistcmd dispatch (c:3006)
///
/// The actual `ctxtlex()` driver is replaced by the lex.rs module
/// — for this port we approximate by
/// splitting the temp string on whitespace + tracking the cursor
/// word. Full lexer-token reconstruction (LEXERR/STRING/ENDINPUT
/// handling for unbalanced quotes per c:2842-2855) is the
/// remaining gap; the foundation here handles plain-token cases
/// which cover the most common compctl flows.
pub(crate) fn sep_comp_string(ss: &str, s: &str, noffs: i32) -> i32 {
    // C: c:2810-2813 — save state to restore on exit
    let owe = WE.with(|c| c.get());
    let owb = WB.with(|c| c.get());
    let ocs = ZLEMETACS.with(|c| c.get());
    let oll = *ZLEMETALL.lock().unwrap();
    let ois = *INSTRING.lock().unwrap();
    let oib = *INBACKT.lock().unwrap();
    let ona = *NOALIASES.lock().unwrap();
    let ne = *NOERRS.lock().unwrap();
    let ol = ZLEMETALINE.lock().unwrap().clone();
    let oaq = AUTOQ.lock().unwrap().clone();

    let sl = ss.len() as i32;
    let mut got = false;
    let mut i = 0_i32;
    let mut cur: i32 = -1;
    let mut swb = 0_i32;
    let mut swe = 0_i32;
    let mut soffs = 0_i32;
    let mut ns: String = String::new();
    let mut foo: Vec<String> = Vec::new();

    // C: c:2823-2832 — build the temp buffer with cursor `x` marker.
    // tmp = ss + " " + s[..noffs] + 'x' + s[noffs..]
    *ADDEDX.lock().unwrap() = 1;
    *NOERRS.lock().unwrap() = 1;
    *LEXFLAGS.lock().unwrap() = LEXFLAGS_ZLE;
    let mut tmp = String::with_capacity(ss.len() + 3 + s.len());
    tmp.push_str(ss);
    tmp.push(' ');
    let s_chars: Vec<char> = s.chars().collect();
    let noffs_u = (noffs as usize).min(s_chars.len());
    let s_pre: String = s_chars[..noffs_u].iter().collect();
    let s_post: String = s_chars[noffs_u..].iter().collect();
    tmp.push_str(&s_pre);
    let scs_initial = sl + 1 + noffs;
    ZLEMETACS.with(|c| c.set(scs_initial));
    let mut scs = scs_initial;
    tmp.push('x');
    tmp.push_str(&s_post);
    let tl = tmp.len() as i32;

    // C: c:2833 — apply rembslash if QT_BACKSLASH stack head
    let qstack_head = COMPQSTACK.lock().unwrap().chars().next().unwrap_or(QT_NONE as u8 as char);
    let remq = qstack_head as i32 == QT_BACKSLASH;
    if remq {
        // rembslash — strip backslashes
        let mut stripped = String::with_capacity(tmp.len());
        let mut chars = tmp.chars().peekable();
        while let Some(c) = chars.next() {
            if c == '\\' {
                if let Some(&_nx) = chars.peek() {
                    // Skip backslash, keep next char
                    continue;
                }
            }
            stripped.push(c);
        }
        tmp = stripped;
    }

    // C: c:2835-2839 — push input, set zlemetaline
    *ZLEMETALINE.lock().unwrap() = tmp.clone();
    *ZLEMETALL.lock().unwrap() = tl - 1;
    *NOALIASES.lock().unwrap() = 1;

    // C: c:2840-2873 — lex loop. We approximate ctxtlex() with a
    // whitespace-tokenize + cursor-word detection. Real lexer
    // integration requires lex.rs wired with
    // ZLE input-stack semantics.
    {
        let chars: Vec<char> = tmp.chars().collect();
        let mut t_start = 0_usize;
        let mut idx = 0_usize;
        let mut word_idx = 0_i32;
        while idx <= chars.len() {
            let at_end = idx == chars.len();
            let is_sep = !at_end && chars[idx] == ' ';
            if at_end || is_sep {
                if idx > t_start {
                    let token: String = chars[t_start..idx].iter().collect();
                    let abs_start = t_start as i32;
                    let abs_end = idx as i32;
                    foo.push(token.clone());
                    // C: c:2862-2871 — first time scs falls inside
                    // a token, that's the cursor word.
                    if !got && scs >= abs_start && scs <= abs_end {
                        got = true;
                        cur = word_idx;
                        swb = abs_start;
                        swe = abs_end;
                        soffs = scs - swb;
                        // C: chuck(p + soffs) — remove the dummy 'x'
                        let mut t = token.clone();
                        if (soffs as usize) < t.len() {
                            t.remove(soffs as usize);
                        }
                        ns = t;
                    }
                    word_idx += 1;
                }
                t_start = idx + 1;
            }
            if at_end { break; }
            idx += 1;
        }
        i = word_idx;
    }

    *NOALIASES.lock().unwrap() = ona;
    *NOERRS.lock().unwrap() = ne;
    WB.with(|c| c.set(owb));
    WE.with(|c| c.set(owe));
    ZLEMETACS.with(|c| c.set(ocs));
    *ZLEMETALINE.lock().unwrap() = ol;
    *ZLEMETALL.lock().unwrap() = oll;

    // C: c:2885 — bail if no cursor word found
    if cur < 0 || i < 1 {
        return 1;
    }

    // C: c:2887-2896 — check_param dispatch (params + Snull/Dnull
    // marker conversion). Skipped pending check_param port.

    // C: c:2898-2929 — quote-prefix detection. Examine ns[0] for
    // Snull/Dnull/Stringg/QSTRING_TOK and adjust instring + autoq.
    let ts = ns.clone();
    let _ = ts.clone();
    let first_char = ns.chars().next();
    let is_quoted_open = matches!(
        first_char,
        Some(Snull) | Some(Dnull)
    ) || (matches!(first_char, Some(Stringg) | Some(QSTRING_TOK))
        && ns.chars().nth(1) == Some(Snull));

    if is_quoted_open {
        let new_instring = match first_char {
            Some(Snull) => QT_SINGLE,
            Some(Dnull) => QT_DOUBLE,
            _ => QT_DOLLARS,
        };
        *INSTRING.lock().unwrap() = new_instring;
        *INBACKT.lock().unwrap() = 0;
        swb += 1;
        // C: c:2921 — if the closing quote-marker matches at end, swe--
        if let (Some(first), Some(last)) = (ns.chars().next(), ns.chars().last()) {
            if first == last && ns.len() >= 2 {
                swe -= 1;
            }
        }
        // C: c:2925 — autoq from compqstack[1] and multiquote
        let qstack = COMPQSTACK.lock().unwrap().clone();
        if qstack.len() >= 2 {
            *AUTOQ.lock().unwrap() = String::new();
        } else {
            *AUTOQ.lock().unwrap() = ts.clone();
        }
    } else {
        *INSTRING.lock().unwrap() = QT_NONE;
        *AUTOQ.lock().unwrap() = String::new();
    }

    // C: c:2931-2952 — inull walk: drop inull markers from ns,
    // adjusting scs/soffs/swb as we go.
    let mut ns_chars: Vec<char> = ns.chars().collect();
    let mut p_idx = 0_usize;
    let mut walk_i = swb;
    while p_idx < ns_chars.len() {
        let c = ns_chars[p_idx];
        if inull(c) {
            if walk_i < scs {
                soffs -= 1;
                if remq && c == Bnull && p_idx + 1 < ns_chars.len() {
                    swb -= 2;
                }
            }
            let next = ns_chars.get(p_idx + 1).copied();
            if next.is_some() || c != Bnull {
                if c == Bnull {
                    if scs == walk_i + 1 {
                        scs += 1;
                        soffs += 1;
                    }
                } else if scs > walk_i {
                    scs -= 1;
                    walk_i -= 1;  // C: `scs > i--`
                }
            } else if scs == swe {
                scs -= 1;
            }
            ns_chars.remove(p_idx);
            // Don't advance p_idx — re-check the new char at p_idx
            // (matches C's `chuck(p--); p++;` next-iter increment).
            walk_i -= 1;
        } else {
            p_idx += 1;
            walk_i += 1;
        }
    }
    ns = ns_chars.iter().collect();

    // C: c:2961-2974 — build qp/qs from ss + qipre/qisuf
    let qipre_val = QIPRE.lock().unwrap().clone();
    let qisuf_val = QISUF.lock().unwrap().clone();
    let qp = format!("{}{}", qipre_val, &s[..((swb - sl - 1).max(0) as usize).min(s.len())]);
    if swe < swb {
        swe = swb;
    }
    swe -= sl + 1;
    let s_len = s.len() as i32;
    if swe > s_len {
        swe = s_len;
        if (ns.len() as i32) > swe - swb + 1 {
            ns.truncate((swe - swb + 1) as usize);
        }
    }
    let qs_start = (swe.max(0) as usize).min(s.len());
    let qs = format!("{}{}", &s[qs_start..], qisuf_val);
    let s_chars_len = ns.len() as i32;
    if soffs > s_chars_len {
        soffs = s_chars_len;
    }

    // C: c:2980-3023 — state save/restore + nested makecomplistcmd
    let ow = CLWORDS.lock().unwrap().clone();
    let os = CMDSTR.with(|r| r.borrow().clone());
    let oqp = QIPRE.lock().unwrap().clone();
    let oqs = QISUF.lock().unwrap().clone();
    let oqst = COMPQSTACK.lock().unwrap().clone();
    let olws = *CLWSIZE.lock().unwrap();
    let olwn = *CLWNUM.lock().unwrap();
    let olwp = *CLWPOS.lock().unwrap();
    let obr = *BRANGE.lock().unwrap();
    let oer = *ERANGE.lock().unwrap();
    let oof = *OFFS.lock().unwrap();
    let occ = CCONT.with(|c| c.get());

    // C: c:2986-2989 — push current quote char onto compqstack
    let new_quote_char = if *INSTRING.lock().unwrap() != QT_NONE {
        char::from_u32(*INSTRING.lock().unwrap() as u32).unwrap_or('\\')
    } else {
        char::from_u32(QT_BACKSLASH as u32).unwrap_or('\\')
    };
    let mut new_compqstack = String::new();
    new_compqstack.push(new_quote_char);
    new_compqstack.push_str(&oqst);
    *COMPQSTACK.lock().unwrap() = new_compqstack;

    // C: c:2991-2997 — install foo into clwords
    *CLWSIZE.lock().unwrap() = foo.len() as i32;
    *CLWNUM.lock().unwrap() = foo.len() as i32;
    *CLWORDS.lock().unwrap() = foo.clone();
    *CLWPOS.lock().unwrap() = cur;
    CMDSTR.with(|r| *r.borrow_mut() = foo.first().cloned());
    *BRANGE.lock().unwrap() = 0;
    *ERANGE.lock().unwrap() = (foo.len() as i32) - 1;
    *QIPRE.lock().unwrap() = qp;
    *QISUF.lock().unwrap() = qs;
    *OFFS.lock().unwrap() = soffs;
    CCONT.with(|c| c.set(CC_CCCONT));

    // C: c:3006 — nested dispatch
    const CFN_FIRST: i32 = 1;
    let _ = makecomplistcmd(&ns, cur == 0, CFN_FIRST);

    CCONT.with(|c| c.set(occ));
    *OFFS.lock().unwrap() = oof;
    CMDSTR.with(|r| *r.borrow_mut() = os);
    *CLWORDS.lock().unwrap() = ow;
    *CLWSIZE.lock().unwrap() = olws;
    *CLWNUM.lock().unwrap() = olwn;
    *CLWPOS.lock().unwrap() = olwp;
    *BRANGE.lock().unwrap() = obr;
    *ERANGE.lock().unwrap() = oer;
    *QIPRE.lock().unwrap() = oqp;
    *QISUF.lock().unwrap() = oqs;
    *COMPQSTACK.lock().unwrap() = oqst;

    *AUTOQ.lock().unwrap() = oaq;
    *INSTRING.lock().unwrap() = ois;
    *INBACKT.lock().unwrap() = oib;

    0
}

/// The flag-driven completion-list builder — workhorse fn.
/// Port of `makecomplistflags(Compctl cc, char *s, int incmd, int compadd)` from Src/Zle/compctl.c:3499 (~500 lines).
///
/// Walks the bits of cc.mask and cc.mask2, dispatching per CC_* bit
/// to the matching generator:
///   CC_FILES     → gen_matches_files (regular files)
///   CC_DIRS      → gen_matches_files(dirs=true)
///   CC_COMMPATH  → command-path completion
///   CC_OPTIONS   → option completion
///   CC_VARS      → dumphashtable(paramtab, CC_VARS)
///   CC_BINDINGS  → bindings (zle widgets)
///   CC_ARRAYS    → param table filtered to PM_ARRAY
///   CC_INTVARS   → param table filtered to PM_INTEGER
///   CC_SHFUNCS   → shfunctab
///   CC_PARAMS    → paramtab non-exported
///   CC_ENVVARS   → paramtab PM_EXPORTED
///   CC_JOBS / CC_RUNNING / CC_STOPPED → job table filters
///   CC_BUILTINS  → builtintab
///   CC_USERS     → /etc/passwd users (or named-dir filltable)
///   CC_DISCMDS / CC_EXCMDS → cmdnamtab filtered by DISABLED bit
///   CC_RESWDS    → reserved-word table
///   CC_NAMED     → named-directory table
///   CC_DIRS      → directory matches
///   ... and more
///
/// Plus arg-taking flags:
///   cc.glob   → globlist expansion
///   cc.str → string-arg expansion via singsub
///   cc.func   → call user function (compctl -K)
///   cc.keyvar → read array variable for matches
///   cc.hpat   → history-pattern matches
///
/// This stub records the dispatch entry so call sites can wire to
/// it; per-bit generators land per-bit in follow-ups.
pub(crate) fn makecomplistflags(cc: &Arc<Compctl>, s: &str, _incmd: bool, _compadd: i32) {
    let _ = (cc, s);
    // Set ccont per cc.mask2 — c:3499 loop init reads CC_CCCONT
    // from mask2 to determine dispatch continuation.
    CCONT.with(|c| c.set(cc.mask2));

    // CC_FILES — c:3650+ in real impl
    if (cc.mask & CC_FILES) != 0 {
        ADDWHAT.with(|c| c.set(-5));
        gen_matches_files(false, false, false);
    }
    // CC_DIRS — c:3680
    if (cc.mask & CC_DIRS) != 0 {
        ADDWHAT.with(|c| c.set(-5));
        gen_matches_files(true, false, false);
    }
    // CC_NAMED — c:3742
    if (cc.mask & CC_NAMED) != 0 {
        ADDWHAT.with(|c| c.set(-1));
        maketildelist();
    }
    // Per-CC_* arms beyond these (CC_VARS, CC_SHFUNCS, …) iterate
    // hashtables. The canonical paramtab/cmdnamtab/shfunctab live in
    // `crate::ported::params` / `crate::ported::utils`; arms expand
    // their entries with `scanhashtable(table, …)` equivalents.

    // cc.func (compctl -K) — call user function for matches.
    // Skipped pending function-dispatch wiring.

    // cc.glob — globlist expansion. Skipped pending glob-port use.

    // cc.str (-s) — call singsub on the string.
    if let Some(s) = &cc.str {
        let expanded = getreal(s);
        // Push as a single match with addwhat=GLOB_EXPAND
        ADDWHAT.with(|c| c.set(-6));
        addmatch(&expanded, None);
    }
}

// =================================================================
// Module boot/cleanup hooks — port of compctl.c:4000+
// =================================================================

/// Storage for the special compctl targets — `cc_compos` (command
/// completion), `cc_default` (default completion), `cc_first`
/// (first completion). Port of the file-static C declarations at
/// Src/Zle/compctl.c:41 — `struct compctl cc_compos, cc_default,
/// cc_first, cc_dummy;`. setup_ initializes the masks; tests +
/// real-completion paths read them.
pub(crate) static CC_COMPOS: Mutex<Option<Arc<Compctl>>> = Mutex::new(None);
pub(crate) static CC_DEFAULT: Mutex<Option<Arc<Compctl>>> = Mutex::new(None);
pub(crate) static CC_FIRST: Mutex<Option<Arc<Compctl>>> = Mutex::new(None);
pub(crate) static CC_DUMMY: Mutex<Option<Arc<Compctl>>> = Mutex::new(None);

/// Last-used compctl tracking list. Port of `LinkList lastccused`
/// at Src/Zle/compctl.c:1702. setup_ initializes to empty; finish_
/// frees its contents.
static LASTCCUSED: Mutex<Vec<Arc<Compctl>>> = Mutex::new(Vec::new());

/// Pointer to compctlread (vs fallback_compctlread). Port of the
/// `CompctlReadFn compctlreadptr` indirect dispatch at
/// Src/Modules/zle/compctl.c:4016. setup_ installs this; finish_
/// restores the fallback.
static COMPCTLREAD_INSTALLED: Mutex<bool> = Mutex::new(false);

/// Setup hook — port of `setup_(UNUSED(Module m))` from Src/Zle/compctl.c:4014.
///
/// Wires `compctlreadptr` to compctlread, creates the compctltab,
/// initializes the special targets:
///   cc_compos.mask  = CC_COMMPATH
///   cc_default.refc = 10000  (sentinel "never free")
///   cc_default.mask = CC_FILES
///   cc_first.refc   = 10000
///   cc_first.mask2  = CC_CCCONT
/// Clears lastccused.
pub(crate) fn setup_() -> i32 {
    *COMPCTLREAD_INSTALLED.lock().unwrap() = true;
    createcompctltable();
    *CC_COMPOS.lock().unwrap() = Some(Arc::new(Compctl {
        mask: CC_COMMPATH,                            // c:4018
        ..Default::default()
    }));
    *CC_DEFAULT.lock().unwrap() = Some(Arc::new(Compctl {
        refc: 10000,                                          // c:4020
        mask: CC_FILES,                                // c:4021
        ..Default::default()
    }));
    *CC_FIRST.lock().unwrap() = Some(Arc::new(Compctl {
        refc: 10000,                                          // c:4023
        mask2: CC_CCCONT,                             // c:4025
        ..Default::default()
    }));
    *LASTCCUSED.lock().unwrap() = Vec::new();                 // c:4034
    0
}

/// Features hook — port of `features_(UNUSED(Module m), UNUSED(char ***features))` from Src/Zle/compctl.c:4034.
///
/// Returns the list of feature strings the module exposes. zsh C
/// uses `featuresarray(m, &module_features)` which reads
/// `module_features.bn_size` (line 4005 — 2 builtins: compctl,
/// compcall). Rust returns the explicit list.
pub(crate) fn features_() -> Vec<String> {
    vec!["b:compctl".to_string(), "b:compcall".to_string()]
}

/// Enables hook — port of `enables_(UNUSED(Module m), UNUSED(int **enables))` from Src/Zle/compctl.c:4042.
///
/// C delegates to `handlefeatures(m, &module_features, enables)`
/// which writes the per-feature enable bits to `*enables`. Rust
/// returns a per-feature bool vector — entries currently default
/// to enabled (1). Wiring to the module-load runtime is a separate
/// concern.
pub(crate) fn enables_() -> Vec<i32> {
    vec![1, 1]
}

/// Boot hook — port of `boot_(UNUSED(Module m))` from Src/Zle/compctl.c:4049.
///
/// Registers the two completion-driver hooks via
/// `addhookfunc("compctl_make", ccmakehookfn)` and
/// `addhookfunc("compctl_cleanup", cccleanuphookfn)`. Rust hooks
/// dispatch via the same names; the actual hook registry is in
/// src/ported/module.rs.
pub(crate) fn boot_() -> i32 {
    // C: c:4051-4052 — addhookfunc calls. zshrs's hook registry
    // would be wired via crate::ported::module — for the C-source
    // faithful port we keep the names + intent visible here.
    0
}

/// Cleanup hook — port of `cleanup_(UNUSED(Module m))` from Src/Zle/compctl.c:4058.
///
/// Reverses boot_: removes the two hooks, then disables features
/// via `setfeatureenables(m, &module_features, NULL)`.
pub(crate) fn cleanup_() -> i32 {
    // C: c:4060-4062 — deletehookfunc + setfeatureenables.
    0
}

/// Finish hook — port of `finish_(UNUSED(Module m))` from Src/Zle/compctl.c:4067.
///
/// Tears down the compctltab hash table, frees lastccused, restores
/// `compctlreadptr` to the fallback. Rust drops the table on Mutex
/// reset; lastccused frees via Vec::clear; compctlreadptr is the
/// COMPCTLREAD_INSTALLED bool.
pub(crate) fn finish_() -> i32 {
    *COMPCTL_TAB.write().unwrap() = None;                       // c:4067 deletehashtable
    LASTCCUSED.lock().unwrap().clear();                       // c:4071-4072 freelinklist
    *COMPCTLREAD_INSTALLED.lock().unwrap() = false;           // c:4074
    0
}

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

    /// Serialize tests that touch the singleton state — `cargo test`
    /// runs tests in parallel and the static `COMPCTL_TAB` / `CCLIST`
    /// would interleave. The parking_lot variant would deadlock-free
    /// across panics; std::sync::Mutex is fine since each test runs
    /// quickly and panics propagate.
    static TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    #[test]
    fn createcompctltable_initializes_table() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        createcompctltable();
        let g = COMPCTL_TAB.read().unwrap();
        assert!(g.is_some());
        assert_eq!(g.as_ref().unwrap().len(), 0);
    }

    #[test]
    fn cc_assign_inserts_into_table() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        createcompctltable();
        let cc = Arc::new(Compctl {
            mask: CC_FILES,
            ..Default::default()
        });
        cc_assign("ls", cc, false);
        let g = COMPCTL_TAB.read().unwrap();
        assert!(g.as_ref().unwrap().contains_key("ls"));
    }

    #[test]
    fn freecompctlp_removes_entry() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        createcompctltable();
        cc_assign("rm", Arc::new(Compctl::default()), false);
        freecompctlp("rm");
        let g = COMPCTL_TAB.read().unwrap();
        assert!(!g.as_ref().unwrap().contains_key("rm"));
    }

    #[test]
    fn cc_flags_bit_layout_matches_c_compctlh() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // Spot-check that the bit values match the C constants.
        assert_eq!(CC_FILES, 1);
        assert_eq!(CC_COMMPATH, 2);
        assert_eq!(CC_OPTIONS, 8);
        assert_eq!(CC_JOBS, 1 << 11);
    }

    #[test]
    fn cct_constants_match_c_compctlh() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        assert_eq!(CCT_POS, 1);
        assert_eq!(CCT_CURPAT, 3);
        assert_eq!(CCT_QUOTE, 13);
    }

    #[test]
    fn comp_op_special_combines_command_default_first() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        assert_eq!(
            COMP_SPECIAL,
            COMP_COMMAND | COMP_DEFAULT | COMP_FIRST
        );
    }

    #[test]
    fn cc_flags2_constants_match_c_compctlh() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        assert_eq!(CC_NOSORT, 1);
        assert_eq!(CC_CCCONT, 4);
        assert_eq!(CC_UNIQALL, 1 << 6);
    }

    #[test]
    fn get_compctl_simple_flag_chars_set_mask() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // `compctl -fcv ls` — files + commpath + vars
        let mut argv = vec!["-fcv".to_string(), "ls".to_string()];
        let mut cc = Compctl::default();
        let r = get_compctl("compctl", &mut argv, &mut cc, true, false, 0);
        assert_eq!(r, 0);
        assert_ne!(cc.mask & CC_FILES, 0);
        assert_ne!(cc.mask & CC_COMMPATH, 0);
        assert_ne!(cc.mask & CC_VARS, 0);
        // `ls` should remain in argv
        assert_eq!(argv, vec!["ls".to_string()]);
    }

    #[test]
    fn get_compctl_combined_a_sets_alreg_and_alglob() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let mut argv = vec!["-a".to_string(), "ls".to_string()];
        let mut cc = Compctl::default();
        get_compctl("compctl", &mut argv, &mut cc, true, false, 0);
        assert_ne!(cc.mask & CC_ALREG, 0);
        assert_ne!(cc.mask & CC_ALGLOB, 0);
    }

    #[test]
    fn get_compctl_arg_taking_K_captures_function_name() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let mut argv = vec!["-K".to_string(), "_my_completer".to_string(), "myfunc".to_string()];
        let mut cc = Compctl::default();
        get_compctl("compctl", &mut argv, &mut cc, true, false, 0);
        assert_eq!(cc.func.as_deref(), Some("_my_completer"));
        assert_eq!(argv, vec!["myfunc".to_string()]);
    }

    #[test]
    fn get_compctl_inline_arg_K_captures_function_name() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // `-K_my_func`  → the K flag char with inline arg
        let mut argv = vec!["-K_my_func".to_string(), "myfunc".to_string()];
        let mut cc = Compctl::default();
        get_compctl("compctl", &mut argv, &mut cc, true, false, 0);
        assert_eq!(cc.func.as_deref(), Some("_my_func"));
    }

    #[test]
    fn get_compctl_P_S_capture_prefix_suffix() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let mut argv = vec![
            "-P".to_string(), "before-".to_string(),
            "-S".to_string(), "-after".to_string(),
            "cmd".to_string()
        ];
        let mut cc = Compctl::default();
        get_compctl("compctl", &mut argv, &mut cc, true, false, 0);
        assert_eq!(cc.prefix.as_deref(), Some("before-"));
        assert_eq!(cc.suffix.as_deref(), Some("-after"));
    }

    #[test]
    fn get_compctl_1_2_set_uniq_flags() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let mut argv = vec!["-1".to_string(), "ls".to_string()];
        let mut cc = Compctl::default();
        get_compctl("compctl", &mut argv, &mut cc, true, false, 0);
        assert_ne!(cc.mask2 & CC_UNIQALL, 0);
        assert_eq!(cc.mask2 & CC_UNIQCON, 0);
    }

    #[test]
    fn get_compctl_V_implies_NOSORT() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let mut argv = vec!["-V".to_string(), "mygroup".to_string(), "cmd".to_string()];
        let mut cc = Compctl::default();
        get_compctl("compctl", &mut argv, &mut cc, true, false, 0);
        assert_eq!(cc.gname.as_deref(), Some("mygroup"));
        assert_ne!(cc.mask2 & CC_NOSORT, 0);
    }

    #[test]
    fn bin_compctl_install_then_lookup_via_table() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        createcompctltable();
        let r = bin_compctl("compctl", &["-f".to_string(), "mycmd".to_string()]);
        assert_eq!(r, 0);
        let g = COMPCTL_TAB.read().unwrap();
        assert!(g.as_ref().unwrap().contains_key("mycmd"));
        let cc = g.as_ref().unwrap().get("mycmd").unwrap();
        assert_ne!(cc.mask & CC_FILES, 0);
    }

    #[test]
    fn compctl_name_pat_detects_glob_wildcards() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // Glob-meta chars present → pattern.
        let (is_pat, _) = compctl_name_pat("ls*");
        assert!(is_pat);
        let (is_pat, _) = compctl_name_pat("foo?bar");
        assert!(is_pat);
        let (is_pat, _) = compctl_name_pat("[abc]");
        assert!(is_pat);
    }

    #[test]
    fn compctl_name_pat_strips_backslashes_from_literal() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let (is_pat, out) = compctl_name_pat("\\$home");
        assert!(!is_pat);
        // Backslash dropped, `$` kept.
        assert_eq!(out, "$home");
    }

    #[test]
    fn delpatcomp_removes_matching_pattern() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let mut p = PATCOMPS.write().unwrap();
        p.push(("foo*".to_string(), Arc::new(Compctl::default())));
        p.push(("bar*".to_string(), Arc::new(Compctl::default())));
        drop(p);
        delpatcomp("foo*");
        let p = PATCOMPS.read().unwrap();
        assert_eq!(p.len(), 1);
        assert_eq!(p[0].0, "bar*");
    }

    #[test]
    fn cc_assign_with_reass_command_target_uses_special_key() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        createcompctltable();
        CCLIST.with(|c| c.set(COMP_COMMAND));
        cc_assign("compctl", Arc::new(Compctl {
            mask: CC_FILES,
            ..Default::default()
        }), true);
        let g = COMPCTL_TAB.read().unwrap();
        assert!(g.as_ref().unwrap().contains_key("__cc_compos"));
        // Reset for other tests.
        drop(g);
        CCLIST.with(|c| c.set(0));
    }

    #[test]
    fn cc_assign_with_reass_default_target_uses_special_key() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        createcompctltable();
        CCLIST.with(|c| c.set(COMP_DEFAULT));
        cc_assign("compctl", Arc::new(Compctl::default()), true);
        let g = COMPCTL_TAB.read().unwrap();
        assert!(g.as_ref().unwrap().contains_key("__cc_default"));
        drop(g);
        CCLIST.with(|c| c.set(0));
    }

    #[test]
    fn setup_initializes_special_targets_and_table() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        setup_();
        // cc_compos has CC_COMMPATH set
        let cc_compos = CC_COMPOS.lock().unwrap().clone();
        assert!(cc_compos.is_some());
        assert_eq!(cc_compos.unwrap().mask, CC_COMMPATH);
        // cc_default has CC_FILES + refc=10000 sentinel
        let cc_default = CC_DEFAULT.lock().unwrap().clone();
        assert!(cc_default.is_some());
        let cc_default = cc_default.unwrap();
        assert_eq!(cc_default.mask, CC_FILES);
        assert_eq!(cc_default.refc, 10000);
        // cc_first has CC_CCCONT in mask2
        let cc_first = CC_FIRST.lock().unwrap().clone();
        assert!(cc_first.is_some());
        assert_eq!(cc_first.unwrap().mask2, CC_CCCONT);
        // table exists
        assert!(COMPCTL_TAB.read().unwrap().is_some());
        // compctlread installed
        assert!(*COMPCTLREAD_INSTALLED.lock().unwrap());
    }

    #[test]
    fn finish_tears_down_state() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        setup_();
        finish_();
        // Table cleared
        assert!(COMPCTL_TAB.read().unwrap().is_none());
        // compctlread restored
        assert!(!*COMPCTLREAD_INSTALLED.lock().unwrap());
        // lastccused cleared
        assert_eq!(LASTCCUSED.lock().unwrap().len(), 0);
    }

    #[test]
    fn features_returns_two_builtins() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let f = features_();
        assert_eq!(f, vec!["b:compctl".to_string(), "b:compcall".to_string()]);
    }

    #[test]
    fn enables_returns_two_enabled_bits() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let e = enables_();
        assert_eq!(e, vec![1, 1]);
    }

    #[test]
    fn bin_compcall_outside_compfunc_errors() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        INCOMPFUNC.with(|c| c.set(0));
        let r = bin_compcall("compcall", &[]);
        assert_eq!(r, 1);
    }

    #[test]
    fn bin_compcall_inside_compfunc_succeeds() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        INCOMPFUNC.with(|c| c.set(1));
        let r = bin_compcall("compcall", &["-T".to_string()]);
        assert_eq!(r, 0);
        // Reset
        INCOMPFUNC.with(|c| c.set(0));
    }

    #[test]
    fn compctlread_outside_compctl_func_errors() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        INCOMPCTLFUNC.with(|c| c.set(false));
        let r = compctlread("compctlread", &[]);
        assert_eq!(r, 1);
    }

    #[test]
    fn cccleanuphookfn_returns_zero() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // Trivial — no state to verify, just that it doesn't panic.
        assert_eq!(cccleanuphookfn(()), 0);
    }

    #[test]
    fn addmatch_rejects_unset_addwhat() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // C: c:2015 — `else` arm in addmatch falls through to drop the
        // match when addwhat is 0 (neither file-thread nor
        // conditional-accept set).
        let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        MATCH_LIST.with(|r| r.borrow_mut().clear());
        ADDWHAT.with(|c| c.set(0));
        addmatch("dropped", None);
        let captured = MATCH_LIST.with(|r| r.borrow().clone());
        assert!(captured.is_empty(), "addwhat=0 should drop matches");
    }

    #[test]
    fn addmatch_accepts_files_kind() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        MATCH_LIST.with(|r| r.borrow_mut().clear());
        ADDWHAT.with(|c| c.set(-5));
        addmatch("foo.txt", None);
        addmatch("bar.txt", None);
        let m = MATCH_LIST.with(|r| r.borrow().clone());
        assert_eq!(m.len(), 2);
        assert_eq!(m[0], "foo.txt");
    }

    #[test]
    fn addmatch_accepts_param_kind() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        MATCH_LIST.with(|r| r.borrow_mut().clear());
        ADDWHAT.with(|c| c.set(-9));
        addmatch("HOME", None);
        let m = MATCH_LIST.with(|r| r.borrow().clone());
        assert_eq!(m.len(), 1);
        assert_eq!(m[0], "HOME");
    }

    #[test]
    fn addmatch_accepts_cc_files_positive_mask() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        MATCH_LIST.with(|r| r.borrow_mut().clear());
        ADDWHAT.with(|c| c.set(CC_FILES as i32));
        addmatch("foo", None);
        let m = MATCH_LIST.with(|r| r.borrow().clone());
        assert_eq!(m.len(), 1);
    }

    #[test]
    fn getcpat_finds_first_substring() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // Search "abcabc" for "bc" first occurrence → position 3
        // (1-based, points past the matched substring).
        let r = getcpat("abcabc", 1, "bc", 0);
        assert_eq!(r, 3);
    }

    #[test]
    fn getcpat_finds_second_substring() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // Search "abcabc" for the 2nd "bc" → position 6.
        let r = getcpat("abcabc", 2, "bc", 0);
        assert_eq!(r, 6);
    }

    #[test]
    fn getcpat_negative_index_searches_backward() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // Backward search "abcabc" for last "bc" → position 5.
        let r = getcpat("abcabc", -1, "bc", 0);
        assert!(r >= 0, "should find match (got {})", r);
    }

    #[test]
    fn getcpat_class_mode_matches_any_char_in_set() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // Search "abcdef" for any of {b, d, f} — class mode.
        // First match at index 1 (b).
        let r = getcpat("abcdef", 1, "bdf", 1);
        assert_eq!(r, 2);  // 1-based position of 'b'
    }

    #[test]
    fn getcpat_not_found_returns_negative_one() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let r = getcpat("hello", 1, "xyz", 0);
        assert_eq!(r, -1);
    }

    #[test]
    fn getcpat_strips_backslashes_in_pattern() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // `\$` in pattern should be treated as literal `$`.
        let r = getcpat("foo$bar", 1, "\\$", 0);
        assert_eq!(r, 4);  // 1-based pos right after the `$`
    }

    #[test]
    fn dumphashtable_calls_addmatch_per_entry() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        MATCH_LIST.with(|r| r.borrow_mut().clear());
        let entries = vec!["alpha".to_string(), "beta".to_string(), "gamma".to_string()];
        dumphashtable(entries, -5);
        let m = MATCH_LIST.with(|r| r.borrow().clone());
        assert_eq!(m.len(), 3);
    }

    #[test]
    fn addhnmatch_forwards_to_addmatch() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        MATCH_LIST.with(|r| r.borrow_mut().clear());
        ADDWHAT.with(|c| c.set(-5));
        addhnmatch("xyz", 0);
        let m = MATCH_LIST.with(|r| r.borrow().clone());
        assert_eq!(m.len(), 1);
        assert_eq!(m[0], "xyz");
    }

    #[test]
    fn makecomplistctl_recursion_guard() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        // Force depth to MAX
        CDEPTH.with(|c| c.set(MAX_CDEPTH));
        let r = makecomplistctl(0);
        assert_eq!(r, 0);
        // Reset for other tests.
        CDEPTH.with(|c| c.set(0));
    }

    #[test]
    fn makecomplistflags_cc_files_invokes_gen_matches() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        MATCH_LIST.with(|r| r.borrow_mut().clear());
        // Set prpre to a known dir we can read.
        PRPRE.with(|r| *r.borrow_mut() = Some(".".to_string()));
        let cc = Arc::new(Compctl {
            mask: CC_FILES,
            ..Default::default()
        });
        makecomplistflags(&cc, "", false, 0);
        // Should have at least picked up Cargo.toml or similar from pwd.
        let m = MATCH_LIST.with(|r| r.borrow().clone());
        assert!(!m.is_empty(), "expected file matches in pwd");
    }

    #[test]
    fn makecomplistflags_cc_str_expansion_emits_one_match() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        MATCH_LIST.with(|r| r.borrow_mut().clear());
        let cc = Arc::new(Compctl {
            str: Some("hardcoded".to_string()),
            ..Default::default()
        });
        makecomplistflags(&cc, "", false, 0);
        let m = MATCH_LIST.with(|r| r.borrow().clone());
        assert_eq!(m.len(), 1);
        assert_eq!(m[0], "hardcoded");
    }

    #[test]
    fn makecomplistor_walks_xor_chain() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        MATCH_LIST.with(|r| r.borrow_mut().clear());
        // Build cc1 with str "first", xor → cc2 with str "second"
        let cc2 = Arc::new(Compctl {
            str: Some("second".to_string()),
            ..Default::default()
        });
        let cc1 = Arc::new(Compctl {
            str: Some("first".to_string()),
            xor: Some(cc2),
            ..Default::default()
        });
        makecomplistor(&cc1, "", false, 0, 0);
        let m = MATCH_LIST.with(|r| r.borrow().clone());
        assert_eq!(m.len(), 2);
        assert_eq!(m[0], "first");
        assert_eq!(m[1], "second");
    }

    #[test]
    fn makecomplistcc_pushes_to_ccused() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        CCUSED.with(|r| r.borrow_mut().clear());
        let cc = Arc::new(Compctl::default());
        makecomplistcc(&cc, "", false);
        let used = CCUSED.with(|r| r.borrow().clone());
        assert_eq!(used.len(), 1);
    }

    #[test]
    fn makecomplistpc_iterates_patcomps() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        // Verify makecomplistpc returns 0 when cmdstr is unset
        // (its early-bail path) — full pattern-match test requires
        // VM context for glob_match_static.
        CMDSTR.with(|r| *r.borrow_mut() = None);
        let r = makecomplistpc("", false);
        assert_eq!(r, 0);
    }

    #[test]
    fn findnode_returns_index_of_match() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let list = vec!["a".to_string(), "b".to_string(), "c".to_string()];
        assert_eq!(findnode(&list, &"b".to_string()), Some(1));
        assert_eq!(findnode(&list, &"z".to_string()), None);
    }

    #[test]
    fn cc_assign_rejects_conflicting_special_targets() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        createcompctltable();
        CCLIST.with(|c| c.set(COMP_COMMAND | COMP_DEFAULT));
        cc_assign("compctl", Arc::new(Compctl::default()), true);
        let g = COMPCTL_TAB.read().unwrap();
        // Should have been rejected — neither key installed.
        assert!(!g.as_ref().unwrap().contains_key("__cc_compos"));
        assert!(!g.as_ref().unwrap().contains_key("__cc_default"));
        drop(g);
        CCLIST.with(|c| c.set(0));
    }

    #[test]
    fn compctl_process_cc_remove_deletes_named_entries() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        createcompctltable();
        cc_assign("foo", Arc::new(Compctl::default()), false);
        cc_assign("bar", Arc::new(Compctl::default()), false);
        CCLIST.with(|c| c.set(COMP_REMOVE));
        compctl_process_cc(&["foo".to_string()], Arc::new(Compctl::default()));
        let g = COMPCTL_TAB.read().unwrap();
        let map = g.as_ref().unwrap();
        assert!(!map.contains_key("foo"));
        assert!(map.contains_key("bar"));
        // Reset cclist for other tests.
        CCLIST.with(|c| c.set(0));
    }

    #[test]
    fn sep_comp_string_returns_zero_or_one() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        // C compctl.c:2806-3030 contract — sep_comp_string only returns
        // 0 (success / dispatched) or 1 (bail, no cursor word).
        let r = sep_comp_string("", "", 0);
        assert!(r == 0 || r == 1, "expected 0 or 1, got {}", r);
    }

    #[test]
    fn sep_comp_string_round_trips_zle_state() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        // Pre-set zle_tricky.c globals; sep_comp_string must restore them
        // on exit (C compctl.c:2810-2813 save / 2941-2950 restore).
        WE.with(|c| c.set(42));
        WB.with(|c| c.set(7));
        ZLEMETACS.with(|c| c.set(11));
        *ZLEMETALL.lock().unwrap() = 99;
        *INSTRING.lock().unwrap() = QT_DOUBLE;
        *INBACKT.lock().unwrap() = 1;
        *NOALIASES.lock().unwrap() = 1;
        *NOERRS.lock().unwrap() = 0;
        *ZLEMETALINE.lock().unwrap() = "hello".to_string();
        *AUTOQ.lock().unwrap() = "Q".to_string();

        let _ = sep_comp_string("", "x", 0);

        assert_eq!(WE.with(|c| c.get()), 42);
        assert_eq!(WB.with(|c| c.get()), 7);
        assert_eq!(ZLEMETACS.with(|c| c.get()), 11);
        assert_eq!(*ZLEMETALL.lock().unwrap(), 99);
        assert_eq!(*INSTRING.lock().unwrap(), QT_DOUBLE);
        assert_eq!(*INBACKT.lock().unwrap(), 1);
        assert_eq!(*NOALIASES.lock().unwrap(), 1);
        assert_eq!(*NOERRS.lock().unwrap(), 0);
        assert_eq!(*ZLEMETALINE.lock().unwrap(), "hello");
        assert_eq!(*AUTOQ.lock().unwrap(), "Q");
    }

    #[test]
    fn inull_recognises_marker_chars() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // C compctl.c:2917 — INULL macro recognises Snull/Dnull/Bnull
        // plus String/Qstring tokens for inull-walk.
        assert!(inull(Snull));
        assert!(inull(Dnull));
        assert!(inull(Bnull));
        assert!(inull(Stringg));
        assert!(inull(QSTRING_TOK));
        assert!(!inull('a'));
        assert!(!inull(' '));
    }

    #[test]
    fn qt_constants_match_c_zsh_h() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // C: enum at Src/zsh.h:253-292 — QT_NONE / QT_BACKSLASH /
        // QT_SINGLE / QT_DOUBLE / QT_DOLLARS / QT_BACKTICK in that
        // declaration order, so values are 0..5.
        assert_eq!(QT_NONE, 0);
        assert_eq!(QT_BACKSLASH, 1);
        assert_eq!(QT_SINGLE, 2);
        assert_eq!(QT_DOUBLE, 3);
        assert_eq!(QT_DOLLARS, 4);
        assert_eq!(QT_BACKTICK, 5);
    }
}