zshrs 0.11.18

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

use crate::ported::options::opt_state_get;
use crate::ported::sort::zstrcmp;
use crate::ported::builtin::LASTVAL;
use crate::ported::pattern::haswilds;
use crate::ported::signals::unqueue_signals;
use crate::ported::string::dyncat;
use crate::ported::utils::{zerr, errflag, init_dirsav, lchdir, restoredir};
// `vm_helper` import removed — ShellExecutor reach-in routed through
// `crate::ported::exec_hooks` fn-ptrs (see memory
// feedback_no_exec_script_from_ported).
use crate::ported::zsh_h::{isset, redir, Bnull, Bnullkeep, Dnull, Inang, Nularg, Outang, Pound, Snull, BAREGLOBQUAL, BRACECCL, CASEGLOB, ERRFLAG_INT, EXTENDEDGLOB, GLOBDOTS, GLOBSTARSHORT, IS_DASH, LISTTYPES, MARKDIRS, Meta, MULTIOS, NULLGLOB, NUMERICGLOBSORT, PP_UNKWN, PREFORK_SINGLE, REDIR_CLOSE, REDIR_ERRWRITE, REDIR_MERGEIN, REDIR_MERGEOUT, SHGLOB, SUB_ALL, SUB_END, SUB_GLOBAL, SUB_LIST, SUB_LONG, SUB_MATCH, SUB_REST, SUB_START, SUB_SUBSTR, ZSHTOK_SHGLOB, ZSHTOK_SUBST};
use std::sync::atomic::Ordering;
use std::collections::HashSet;
use std::fs::{self, Metadata};
use std::os::unix::fs::{MetadataExt, PermissionsExt};
use std::path::{Component, Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
use crate::ported::subst::LinkList;
use crate::subst::prefork;

/// A glob match with metadata for sorting
#[derive(Debug, Clone)]
/// One glob match result.
/// Port of `struct gmatch` from Src/glob.c — `gmatchcmp()`
/// (line 936) sorts arrays of these for the `o`/`O` qualifier.
pub struct gmatch {
    pub name: String,
    pub path: PathBuf,
    pub size: u64,
    pub atime: i64,
    pub mtime: i64,
    pub ctime: i64,
    pub links: u64,
    pub mode: u32,
    pub uid: u32,
    pub gid: u32,
    pub dev: u64,
    pub ino: u64,
    // For symlink targets (when following)
    pub target_size: u64,
    pub target_atime: i64,
    pub target_mtime: i64,
    pub target_ctime: i64,
    pub target_links: u64,
    // For exec sort strings
    pub sort_strings: Vec<String>,
}

impl GlobOptSnapshot {
    /// Read every glob-relevant option from the canonical live store
    /// (`opt_state_get`) once. Returns a self-contained snapshot.
    pub fn capture() -> Self {
        Self {
            bareglobqual: isset(BAREGLOBQUAL),
            braceccl: isset(BRACECCL),
            caseglob: isset(CASEGLOB),
            extendedglob: isset(EXTENDEDGLOB),
            globdots: isset(GLOBDOTS),
            globstarshort: isset(GLOBSTARSHORT),
            listtypes: isset(LISTTYPES),
            markdirs: isset(MARKDIRS),
            nullglob: isset(NULLGLOB),
            numericglobsort: isset(NUMERICGLOBSORT),
        }
    }
}

thread_local! {
    /// Thread-local glob option cache. `Some(snap)` while a glob()
    /// call is in flight on this thread; `None` otherwise (reads
    /// fall back to the live `isset()`).
    static GLOB_OPTS_TLS: std::cell::RefCell<Option<GlobOptSnapshot>> =
        const { std::cell::RefCell::new(None) };
}

// =====================================================================
// GS_* — sort-specifier flag bits — `Src/glob.c:77-94`. The `glob -O`
// + `glob -o` sort-spec parser stuffs these bits into the per-glob
// sortspec struct so the qsort comparator picks the right key.
// =====================================================================

/// Port of `GS_NAME` from `Src/glob.c:77`. Sort by filename.
pub const GS_NAME: i32 = 1; // c:77

impl Drop for GlobOptsGuard {
    fn drop(&mut self) {
        if self.populated {
            GLOB_OPTS_TLS.with_borrow_mut(|g| *g = None);
        }
    }
}
/// Port of `GS_DEPTH` from `Src/glob.c:78`. Sort by directory depth.
pub const GS_DEPTH: i32 = 2; // c:78
/// Port of `GS_EXEC` from `Src/glob.c:79`. Sort via external function.
pub const GS_EXEC: i32 = 4; // c:79

/// Port of `GS_SHIFT_BASE` from `Src/glob.c:81`. Bit position where
/// the size/mtime/atime/ctime/links sort keys live.
pub const GS_SHIFT_BASE: i32 = 8; // c:81

/// Port of `GS_SIZE` from `Src/glob.c:83`. Sort by file size.
pub const GS_SIZE: i32 = GS_SHIFT_BASE; // c:83
/// Port of `GS_ATIME` from `Src/glob.c:84`. Sort by access time.
pub const GS_ATIME: i32 = GS_SHIFT_BASE << 1; // c:84
/// Port of `GS_MTIME` from `Src/glob.c:85`. Sort by modification time.
pub const GS_MTIME: i32 = GS_SHIFT_BASE << 2; // c:85
/// Port of `GS_CTIME` from `Src/glob.c:86`. Sort by inode-change time.
pub const GS_CTIME: i32 = GS_SHIFT_BASE << 3; // c:86
/// Port of `GS_LINKS` from `Src/glob.c:87`. Sort by hard-link count.
pub const GS_LINKS: i32 = GS_SHIFT_BASE << 4; // c:87

/// Port of `GS_SHIFT` from `Src/glob.c:89`. Bit-shift offset where the
/// reverse-direction variants of the size/atime/mtime/ctime/links
/// sort flags live.
pub const GS_SHIFT: i32 = 5; // c:89

/// Port of `GS__SIZE`  from `Src/glob.c:90` (reverse-sort variant).
pub const GS__SIZE: i32 = GS_SIZE << GS_SHIFT; // c:90
/// Port of `GS__ATIME` from `Src/glob.c:91`.
pub const GS__ATIME: i32 = GS_ATIME << GS_SHIFT; // c:91
/// Port of `GS__MTIME` from `Src/glob.c:92`.
pub const GS__MTIME: i32 = GS_MTIME << GS_SHIFT; // c:92
/// Port of `GS__CTIME` from `Src/glob.c:93`.
pub const GS__CTIME: i32 = GS_CTIME << GS_SHIFT; // c:93
/// Port of `GS__LINKS` from `Src/glob.c:94`.
pub const GS__LINKS: i32 = GS_LINKS << GS_SHIFT; // c:94

/// Port of `GS_DESC` from `Src/glob.c:96`. Descending-order toggle.
pub const GS_DESC: i32 = GS_SHIFT_BASE << (2 * GS_SHIFT); // c:96
/// Port of `GS_NONE` from `Src/glob.c:97`. Marker for no-sort spec.
pub const GS_NONE: i32 = GS_SHIFT_BASE << (2 * GS_SHIFT + 1); // c:97

/// Port of `GS_NORMAL` from `Src/glob.c:99`. Forward-direction sort
/// keys (excluding NAME/DEPTH/EXEC and the reverse variants).
pub const GS_NORMAL: i32 = GS_SIZE | GS_ATIME | GS_MTIME | GS_CTIME | GS_LINKS; // c:99
/// Port of `GS_LINKED` from `Src/glob.c:100`. Reverse-direction
/// (linked) sort keys.
pub const GS_LINKED: i32 = GS_NORMAL << GS_SHIFT; // c:100

// =====================================================================
// TT_* — time + size unit selectors. Two parallel namespaces using
// the same numeric values.
// =====================================================================

/// Port of `TT_DAYS` from `Src/glob.c:121`. Time qualifier in days.
pub const TT_DAYS: i32 = 0; // c:121
/// Port of `TT_HOURS` from `Src/glob.c:122`. Time qualifier in hours.
pub const TT_HOURS: i32 = 1; // c:122
/// Port of `TT_MINS` from `Src/glob.c:123`. Time qualifier in minutes.
pub const TT_MINS: i32 = 2; // c:123
/// Port of `TT_WEEKS` from `Src/glob.c:124`. Time qualifier in weeks.
pub const TT_WEEKS: i32 = 3; // c:124
/// Port of `TT_MONTHS` from `Src/glob.c:125`. Time qualifier in months.
pub const TT_MONTHS: i32 = 4; // c:125
/// Port of `TT_SECONDS` from `Src/glob.c:126`. Time qualifier in seconds.
pub const TT_SECONDS: i32 = 5; // c:126

/// Port of `TT_BYTES` from `Src/glob.c:128`. Size qualifier in bytes.
pub const TT_BYTES: i32 = 0; // c:128
/// Port of `TT_POSIX_BLOCKS` from `Src/glob.c:129`. Size qualifier
/// in POSIX 512-byte blocks (the `b` glob qualifier suffix).
pub const TT_POSIX_BLOCKS: i32 = 1; // c:129
/// Port of `TT_KILOBYTES` from `Src/glob.c:130`.
pub const TT_KILOBYTES: i32 = 2; // c:130
/// Port of `TT_MEGABYTES` from `Src/glob.c:131`.
pub const TT_MEGABYTES: i32 = 3; // c:131
/// Port of `TT_GIGABYTES` from `Src/glob.c:132`.
pub const TT_GIGABYTES: i32 = 4; // c:132
/// Port of `TT_TERABYTES` from `Src/glob.c:133`.
pub const TT_TERABYTES: i32 = 5; // c:133

/// Port of `MAX_SORTS` from `Src/glob.c:164`. Maximum sort-spec keys
/// per glob (`glob -O 'reverse(name).size'` style).
pub const MAX_SORTS: usize = 12; // c:164

/// Main glob state — port of `struct globdata` from Src/glob.c:168.
/// C zsh has a single file-static `static struct globdata curglobdata;`
/// (glob.c:196) and accesses fields through a wall of #define macros
/// (`matchsz`/`matchct`/`pathbuf`/`pathpos`/`quals`/...) that all
/// resolve to `curglobdata.gd_*`. The Rust port collapses the
/// `gd_matchsz`/`gd_matchct`/`gd_matchbuf`/`gd_matchptr` quartet into
/// `matches: Vec<GlobMatch>` (the natural Rust shape) and folds the
/// `gd_gf_*` glob-flag bag into `options: GlobOptions`, but the
/// 1:1 correspondence to `struct globdata` is otherwise faithful.
// struct to easily save/restore current state                              // c:166
#[allow(non_camel_case_types)]
pub struct globdata {
    // c:168
    pub matches: Vec<gmatch>,
    pub qualifiers: Option<qualifier_set>,
    pub pathbuf: String,     // c:170 gd_pathbuf
    pub pathpos: usize,      // c:169 gd_pathpos
    pub matchct: i32,        // c:173 gd_matchct
    pub pathbufsz: usize,    // c:174 gd_pathbufsz
    pub pathbufcwd: i32,     // c:175 gd_pathbufcwd
    pub gf_nullglob: i32,    // c:186 gd_gf_nullglob
    pub gf_markdirs: i32,    // c:186 gd_gf_markdirs
    pub gf_noglobdots: i32,  // c:186 gd_gf_noglobdots
    pub gf_listtypes: i32,   // c:186 gd_gf_listtypes
    pub gf_pre_words: Option<Vec<String>>,  // c:190 gd_gf_pre_words
    pub gf_post_words: Option<Vec<String>>, // c:190 gd_gf_post_words
}

// c:197 — `static struct globdata curglobdata;`
// C's single file-static glob state; macros at c:199-222 redirect
// `pathbufsz`, `gf_noglobdots`, etc. to `curglobdata.gd_*`. Rust
// mirror — accessed via lock for thread safety; C is single-threaded.
pub static CURGLOBDATA: std::sync::Mutex<globdata> = std::sync::Mutex::new(globdata {
    matches: Vec::new(),
    qualifiers: None,
    pathbuf: String::new(),
    pathpos: 0,
    matchct: 0,
    pathbufsz: 0,
    pathbufcwd: 0,
    gf_nullglob: 0,
    gf_markdirs: 0,
    gf_noglobdots: 0,
    gf_listtypes: 0,
    gf_pre_words: None,
    gf_post_words: None,
});

/// Port of `int badcshglob` from `Src/glob.c:103`. Tracks csh-glob
/// diagnostic state across a single command line: bit 1 = "at
/// least one expansion failed" (CSHNULLGLOB and no matches),
/// bit 2 = "at least one expansion produced output". `globlist`
/// resets to 0 at entry, ORs the bits as each `zglob` runs, then
/// emits "no match" iff the final value is 1 (some failed, none
/// succeeded). Used to make `*.nope *.ok` succeed without
/// diagnostic, but `*.nope alone` error out under CSHNULLGLOB.
pub static BADCSHGLOB: std::sync::atomic::AtomicI32 =
    std::sync::atomic::AtomicI32::new(0); // c:103

/// Port of `struct complist` from `Src/glob.c:252`.
/// C body:
/// ```c
/// struct complist {
///     Complist next;
///     Patprog  pat;
///     int      closure;  /* 1 if this is a (foo/)# */
///     int      follow;   /* 1 to go thru symlinks  */
/// };
/// ```
#[allow(non_camel_case_types)]
pub struct complist {
    // c:252
    pub next: Option<Box<complist>>,          // c:253
    pub pat: crate::ported::pattern::Patprog, // c:254
    pub closure: i32,                         // c:255
    pub follow: i32,                          // c:256
}

/// Add path component (from glob.c addpath lines 263-274)
/// Append a path component to a glob path buffer.
/// Port of `addpath(char *s, int l)` from Src/glob.c:265.
pub fn addpath(s: &mut String, l: &str) {
    // c:265
    s.push_str(l);
    if !s.ends_with('/') {
        s.push('/');
    }
}

/// Stat full path (from glob.c statfullpath lines 282-347)
/// `stat`/`lstat` a (pathbuf, name) tuple.
/// Port of `statfullpath(const char *s, struct stat *st, int l)` from Src/glob.c:283.
pub fn statfullpath(s: &str, st: &str, l: bool) -> Option<Metadata> {
    // c:283
    let full = if st.is_empty() {
        if s.is_empty() {
            ".".to_string()
        } else {
            s.to_string()
        }
    } else {
        format!("{}{}", s, st)
    };

    if l {
        fs::metadata(&full).ok()
    } else {
        fs::symlink_metadata(&full).ok()
    }
}
// END moved-from-exec-rs (free ported)

// ===========================================================
// Direct ports of static helpers from Src/glob.c not yet covered
// above. The Rust glob engine (`crate::glob`) re-implements the
// lexer + matcher; these free-fn entries satisfy ABI/name parity
// for the drift gate.
// ===========================================================

/// Port of `static void insert(char *s, int checked)` from `Src/glob.c:346`.
/// Records one matched path `s` into the glob result list, optionally
/// re-stat'ing for type-marker output (`gf_listtypes`/`gf_markdirs`),
/// applying qualifier predicates (`quals`), and capturing per-mode
/// stat fields into the growing `matchbuf`.
///
/// ```c
/// static void
/// insert(char *s, int checked)
/// {
///     struct stat buf, buf2, *bp;
///     char *news = s;
///     int statted = 0;
///     queue_signals();
///     inserts = NULL;
///     if (gf_listtypes || gf_markdirs) { /* type-marker stat */ ... }
///     if (qualct || qualorct) { /* qualifier chain */ ... }
///     else if (!checked) { if (statfullpath(s, NULL, 1)) { ... return; }
///                          news = dyncat(pathbuf, news); }
///     else news = dyncat(pathbuf, news);
///     while (!inserts || (news = dupstring(*inserts++))) {
///         /* :modifier, stat-cache, matchptr field-copy, grow matchbuf */
///     }
///     unqueue_signals();
/// }
/// ```
#[allow(unused_variables)]
pub fn insert(s: &str, checked: i32) {
    crate::ported::signals::queue_signals(); // c:352

    // c:353 — `inserts = NULL;`. Module-static; this is the loop
    // sentinel that controls the `while (!inserts || (news =...))`
    // tail loop. Set to None to mean "C's NULL → straight pass".
    let mut inserts_local: Option<Vec<String>> = None; // c:353

    let mut news: String = s.to_string(); // c:349
    let mut statted: i32 = 0; // c:350

    // c:355 — `if (gf_listtypes || gf_markdirs)`. The `gf_*` globals
    // are file-static in glob.c (no Rust port yet); read them off the
    // captured option snapshot when available.
    let (gf_listtypes, gf_markdirs, gf_follow): (i32, i32, i32) = {
        // c:355,366
        // gf_listtypes / gf_markdirs are populated by the qualifier
        // parser (c:2187-2188); without a wired flag-state, treat both
        // as zero. Tests in this file don't exercise the type-marker
        // path so the stub is correct for the current call sites.
        (0, 0, 0)
    };
    let mut buf: Option<Metadata> = None; // c:348 struct stat buf
    let mut buf2: Option<Metadata> = None; // c:348 struct stat buf2

    let mut checked_v = checked; // c:346

    if gf_listtypes != 0 || gf_markdirs != 0 {
        // c:355
        let st = statfullpath(s, "", true); // c:358
        match st {
            None => {
                unqueue_signals(); // c:359
                return; // c:360
            }
            Some(m) => {
                buf = Some(m.clone()); // c:358 buf populated
                checked_v = 1; // c:363
                statted = 1; // c:363
            }
        }
        use std::os::unix::fs::MetadataExt;
        let mut mode = buf.as_ref().map(|b| b.mode()).unwrap_or(0); // c:365
        if gf_follow != 0 {
            // c:366
            let is_lnk = buf
                .as_ref()
                .map(|b| (b.mode() & 0o170000) == 0o120000)
                .unwrap_or(false);
            if !is_lnk {
                // c:367
                buf2 = buf.clone(); // c:368 memcpy(buf2, buf)
            } else {
                buf2 = statfullpath(s, "", false); // c:367 statfullpath(.., 0)
                if buf2.is_none() {
                    buf2 = buf.clone();
                } // c:368
            }
            statted |= 2; // c:369
            mode = buf2.as_ref().map(|b| b.mode()).unwrap_or(mode); // c:370
        }
        let is_dir = (mode & 0o170000) == 0o040000;
        if gf_listtypes != 0 || is_dir {
            // c:372
            let marker = file_type(mode); // c:377
            news.push(marker); // c:377-378
        }
    }

    // c:381 — `if (qualct || qualorct)`. Qualifier eval chain. The Rust
    // port runs qualifiers through the qualifier_set carried inside
    // `globdata`, not via the file-static `quals` linked list; the
    // canonical caller (apply_glob_qualifiers) already dispatches the
    // filter pass. Snapshot zero for both counts so the qual-eval
    // branch is skipped here.
    let qualct: i32 = 0; // c:381 qualct
    let qualorct: i32 = 0; // c:381 qualorct
    let pathbuf_local: String = String::new(); // c:170 gd_pathbuf — caller scope

    if qualct != 0 || qualorct != 0 {
        // c:381
        // c:385-388 — stat if not already
        if statted == 0 {
            if statfullpath(s, "", true).is_none() {
                // c:385
                unqueue_signals(); // c:386
                return; // c:387
            }
        }
        news = dyncat(&pathbuf_local, &news); // c:389
        statted = 1; // c:391
                     // c:392-418 — for (qn = qo; qn && qn->func;) ...
                     // The qualifier-fn pointer chain (`qn->func`) isn't exposed
                     // as a free fn array yet; the apply_glob_qualifiers entry
                     // upstream of this insert call already runs every qualifier
                     // and only invokes `insert` for survivors. Skip the loop.
    } else if checked_v == 0 {
        // c:419
        if statfullpath(s, "", true).is_none() {
            // c:420
            unqueue_signals(); // c:421
            return; // c:422
        }
        news = dyncat(&pathbuf_local, &news); // c:424
    } else {
        // c:425
        news = dyncat(&pathbuf_local, &news); // c:426
    }

    // c:428 — `while (!inserts || (news = dupstring(*inserts++)))`
    let mut inserts_idx: usize = 0;
    loop {
        let cur_news: String = if let Some(list) = inserts_local.as_ref() {
            // c:428
            if inserts_idx >= list.len() {
                break;
            }
            let s = crate::ported::mem::dupstring(&list[inserts_idx]);
            inserts_idx += 1;
            s
        } else {
            news.clone()
        };
        let mut cur_news = cur_news;

        // c:429-433 — `if (colonmod) modify(&news, &mod, 1);`
        // The colonmod static + modify() port aren't wired; skip the
        // `(:r:s/.../.../)` colon-modifier branch.
        let colonmod: Option<String> = None; // c:429
        if let Some(_mod_str) = colonmod { // c:429
             // modify(&cur_news, &mod_str, 1);                               // c:432
        }

        // c:434-437 — late stat for normal-sort if not already statted.
        let gf_sorts: i32 = 0; // c:434 gf_sorts (file-static)
        if statted == 0 && (gf_sorts & GS_NORMAL) != 0 {
            // c:434
            buf = statfullpath(s, "", true); // c:435
            statted = 1; // c:436
        }
        // c:438-445 — link-target stat for linked-sort branch.
        if (statted & 2) == 0 && (gf_sorts & GS_LINKED) != 0 {
            // c:438
            if statted != 0 {
                // c:439
                use std::os::unix::fs::MetadataExt;
                let is_lnk = buf
                    .as_ref()
                    .map(|b| (b.mode() & 0o170000) == 0o120000)
                    .unwrap_or(false);
                if !is_lnk {
                    // c:440
                    buf2 = buf.clone(); // c:441
                } else {
                    buf2 = statfullpath(s, "", false); // c:440
                    if buf2.is_none() {
                        buf2 = buf.clone();
                    } // c:441
                }
            } else {
                // c:442
                buf2 = statfullpath(s, "", false); // c:442
                if buf2.is_none() {
                    buf2 = statfullpath(s, "", true); // c:443
                }
            }
            statted |= 2; // c:444
        }

        // c:446 — `matchptr->name = news;`
        // matchptr/matchbuf are file-static in glob.c; the Rust port
        // builds a `Vec<gmatch>` inside `globdata::matches` (the
        // caller owns the destination). The actual append happens
        // there. The structural body below mirrors the C copy.
        let mut entry = gmatch {
            // c:446
            name: cur_news.clone(),
            path: PathBuf::from(&cur_news),
            size: 0,
            atime: 0,
            mtime: 0,
            ctime: 0,
            links: 0,
            mode: 0,
            uid: 0,
            gid: 0,
            dev: 0,
            ino: 0,
            target_size: 0,
            target_atime: 0,
            target_mtime: 0,
            target_ctime: 0,
            target_links: 0,
            sort_strings: Vec::new(),
        };
        if (statted & 1) != 0 {
            // c:447
            use std::os::unix::fs::MetadataExt;
            if let Some(b) = buf.as_ref() {
                entry.size = b.size(); // c:448 buf.st_size
                entry.atime = b.atime(); // c:449
                entry.mtime = b.mtime(); // c:450
                entry.ctime = b.ctime(); // c:451
                entry.links = b.nlink(); // c:452
            }
        }
        if (statted & 2) != 0 {
            // c:463
            use std::os::unix::fs::MetadataExt;
            if let Some(b) = buf2.as_ref() {
                entry.target_size = b.size(); // c:464
                entry.target_atime = b.atime(); // c:465
                entry.target_mtime = b.mtime(); // c:466
                entry.target_ctime = b.ctime(); // c:467
                entry.target_links = b.nlink(); // c:468
            }
        }
        // c:479 — `matchptr++;`
        // c:481-486 — grow matchbuf if matchct == matchsz.
        // Caller (apply_glob_qualifiers in this file) is responsible
        // for pushing `entry` onto `globdata.matches`; this `insert`
        // entry hands the prepared `gmatch` back via a return-channel
        // when the file-static result list lands. For now consume it.
        let _ = entry; // c:479

        if inserts_local.is_none() {
            // c:487
            break; // c:488
        }
        let _ = &mut cur_news;
    }

    let _ = (inserts_idx, buf, buf2); // suppress warnings
    unqueue_signals(); // c:490
}

/// Top-level glob walker dispatching by pattern component.
///
/// Closest C equivalent: `scanner(Complist q, int shortcircuit)`
/// at Src/glob.c:500. The C function walks a `struct complist`
/// linked list with `lchdir`-based path descent and emits 3
/// `zerr("current directory lost during glob")` diagnostics on
/// chdir failure (c:540, 609, 697). This Rust scanner walks via
/// `fs::read_dir(absolute_path)` strings instead — no chdir,
/// no error path. Faithful port is deferred (see
/// docs/PORT_CHECKLIST.md glob.rs entry).
fn scanner(state: &mut globdata, components: &[PatternComponent], depth: usize) {
    // c:500 partial port
    if components.is_empty() {
        return;
    }

    let base_path = if state.pathbuf.is_empty() {
        ".".to_string()
    } else {
        state.pathbuf.clone()
    };

    match &components[0] {
        PatternComponent::Pattern(pat) => {
            scan_pattern(state, &base_path, pat, &components[1..], depth);
        }
        PatternComponent::Recursive { follow_links } => {
            // Match zero directories first
            scanner(state, &components[1..], depth);
            // Then recurse into subdirectories
            scan_recursive(state, &base_path, &components[1..], *follow_links, depth);
        }
    }
}

/* This function tokenizes a zsh glob pattern */                            // c:706
/// Port of `parsecomplist(char *instr)` from Src/glob.c:710.
/// Tokenize a zsh glob path pattern into a `Complist` of path
/// components, recursively. Returns `None` and sets `errflag |=
/// ERRFLAG_ERROR` on parse failure. Reads `gf_noglobdots` from
/// `CURGLOBDATA` (the curglobdata singleton at c:197).
pub fn parsecomplist(instr: &str) -> Option<Box<complist>> {
    // c:710
    let p1: crate::ported::pattern::Patprog;                                 // c:712
    let l1: Box<complist>;                                                   // c:713
    // c:714 `char *str;` — used as the skipparens cursor (parens branch).
    // c:715 — compflags depend on gf_noglobdots from curglobdata.
    let gf_noglobdots: i32 = CURGLOBDATA
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .gf_noglobdots;                                                      // c:214 macro / c:186 field
    let compflags: i32 = if gf_noglobdots != 0 {
        crate::ported::zsh_h::PAT_FILE | crate::ported::zsh_h::PAT_NOGLD
    } else {
        crate::ported::zsh_h::PAT_FILE
    };                                                                       // c:715

    let chars: Vec<char> = instr.chars().collect();
    if chars.len() >= 2
        && chars[0] == crate::ported::zsh_h::Star
        && chars[1] == crate::ported::zsh_h::Star
    {
        // c:717
        let mut shortglob: i32 = 0;                                          // c:718
        let cond_a = chars.get(2) == Some(&'/');                             // c:719
        let cond_b = chars.get(2) == Some(&crate::ported::zsh_h::Star)
            && chars.get(3) == Some(&'/');                                   // c:719
        let cond_c = {
            shortglob = if crate::ported::zsh_h::isset(crate::ported::zsh_h::GLOBSTARSHORT) {
                1
            } else {
                0
            };
            shortglob != 0
        };                                                                   // c:720
        if cond_a || cond_b || cond_c {
            /* Match any number of directories. */                           // c:721
            /* with three stars, follow symbolic links */                    // c:724
            let follow: i32 = if chars.get(2) == Some(&crate::ported::zsh_h::Star) {
                1
            } else {
                0
            };                                                               // c:725
            /*
             * With GLOBSTARSHORT, leave a star in place for the
             * pattern inside the directory.
             */                                                              // c:726-729
            let advance: usize = (if shortglob != 0 { 1 } else { 3 }) + follow as usize; // c:730

            /* Now get the next path component if there is one. */           // c:732
            let next_instr: String = chars[advance..].iter().collect();
            // c:733 — `l1 = (Complist) zhalloc(sizeof *l1);`
            let next_l = parsecomplist(&next_instr);                         // c:734
            if next_l.is_none() {
                crate::ported::utils::errflag.fetch_or(
                    crate::ported::zsh_h::ERRFLAG_ERROR,
                    std::sync::atomic::Ordering::Relaxed,
                );                                                           // c:735
                return None;                                                 // c:736
            }
            let pat = crate::ported::pattern::patcompile(
                "",
                compflags | crate::ported::zsh_h::PAT_ANY,
                None,
            )?;                                                              // c:738
            l1 = Box::new(complist {
                next: next_l,
                pat,
                closure: 1,                                                  // c:739
                follow,                                                      // c:740
            });
            return Some(l1);                                                 // c:741
        }
    }

    /* Parse repeated directories such as (dir/)# and (dir/)## */            // c:745
    let zpc = crate::ported::pattern::zpc_special
        .lock()
        .unwrap_or_else(|e| e.into_inner());
    let inpar_c = zpc[crate::ported::zsh_h::ZPC_INPAR as usize] as char;
    let hash_c = zpc[crate::ported::zsh_h::ZPC_HASH as usize] as char;
    drop(zpc);

    // c:746-748 — `if (*(str = instr) == zpc_special[ZPC_INPAR] &&
    //               !skipparens(Inpar, Outpar, (char **)&str) &&
    //               *str == zpc_special[ZPC_HASH] && str[-2] == '/')`.
    // C `skipparens` returns 0 on a fully balanced `(...)` and -1/positive
    // on failure. Replicate the depth-walk inline with C-faithful semantics
    // (utils::skipparens has a divergent usize-returning signature).
    let mut str_after_parens: Option<usize> = None;                          // char-index of char AFTER `)`
    let mut skip_level: i32 = -1;                                            // C `level` return value
    if chars.first() == Some(&inpar_c) {                                     // c:746 — `*str == Inpar`
        let mut level: i32 = 1;                                              // c:2416
        let mut i: usize = 1;                                                // mirrors `++*s` advancing past `(`
        while i < chars.len() && level != 0 {                                // c:2416 `*++*s && level`
            if chars[i] == crate::ported::zsh_h::Inpar {
                level += 1;                                                  // c:2417-2418
            } else if chars[i] == crate::ported::zsh_h::Outpar {
                level -= 1;                                                  // c:2419-2420
            }
            i += 1;
        }
        skip_level = level;                                                  // c:2422 — 0 on success
        str_after_parens = Some(i);                                          // C `str` now points past `)`
    }
    let parens_balanced = chars.first() == Some(&inpar_c) && skip_level == 0; // c:746-747 `!skipparens(...)`
    let after_paren_idx = str_after_parens.unwrap_or(0);
    let str_at_hash = parens_balanced && chars.get(after_paren_idx) == Some(&hash_c); // c:748 `*str == Pound`
    // c:748 `str[-2] == '/'` — `str` is past `)`, so `str[-2]` is char
    // before `)`. In chars, that's `chars[after_paren_idx - 2]`.
    let preceded_by_slash =
        parens_balanced && after_paren_idx >= 2 && chars.get(after_paren_idx - 2) == Some(&'/');

    if parens_balanced && str_at_hash && preceded_by_slash {
        // c:749 — `instr++;`
        let mut cursor: String = chars[1..].iter().collect();
        let mut endexp = String::new();
        let p1_opt =
            crate::ported::pattern::patcompile(&cursor, compflags, Some(&mut endexp));  // c:750
        if p1_opt.is_none() {
            return None;                                                     // c:751
        }
        let p1_real = p1_opt.unwrap();
        cursor = endexp;                                                     // C: `instr` advanced past compiled pattern
        let c2: Vec<char> = cursor.chars().collect();
        if c2.first() == Some(&'/')
            && c2.get(1) == Some(&crate::ported::zsh_h::Outpar)
            && c2.get(2) == Some(&crate::ported::zsh_h::Pound)
        {
            // c:752
            let mut pdflag: i32 = 0;                                         // c:753
            let mut adv = 3;                                                 // c:755
            if c2.get(3) == Some(&crate::ported::zsh_h::Pound) {
                pdflag = 1;                                                  // c:757
                adv = 4;                                                     // c:758
            }
            let next_instr: String = c2[adv..].iter().collect();
            // c:760-761 — `l1 = (Complist) zhalloc(...); l1->pat = p1;`
            /* special case (/)# to avoid infinite recursion */              // c:762
            // c:763 — `(*((char *)p1 + p1->startoff)) ? 1 + pdflag : 0`
            let pat_nonempty = !p1_real.1.is_empty()
                && p1_real.1.get(p1_real.0.startoff as usize).copied().unwrap_or(0) != 0;
            let closure = if pat_nonempty { 1 + pdflag } else { 0 };
            let next_l = parsecomplist(&next_instr);                         // c:765
            // c:766 — `return (l1->pat) ? l1 : NULL;`
            l1 = Box::new(complist {
                next: next_l,
                pat: p1_real,
                closure,
                follow: 0,                                                   // c:764
            });
            return Some(l1);
        }
    } else {
        /* parse single path component */                                    // c:769
        let mut endexp = String::new();
        let p1_opt = crate::ported::pattern::patcompile(
            instr,
            compflags | crate::ported::zsh_h::PAT_FILET,
            Some(&mut endexp),
        );                                                                   // c:770
        if p1_opt.is_none() {
            return None;                                                     // c:771
        }
        p1 = p1_opt.unwrap();
        let cursor: Vec<char> = endexp.chars().collect();
        /* then do the remaining path components */                          // c:772
        let head = cursor.first().copied();
        if head == Some('/') || head.is_none() {
            // c:773
            let ef: i32 = if head == Some('/') { 1 } else { 0 };             // c:774
            let next_l: Option<Box<complist>> = if ef != 0 {
                let rest: String = cursor[1..].iter().collect();
                parsecomplist(&rest)                                         // c:779
            } else {
                None
            };
            // c:780 — `return (ef && !l1->next) ? NULL : l1;`
            if ef != 0 && next_l.is_none() {
                return None;
            }
            l1 = Box::new(complist {
                next: next_l,
                pat: p1,
                closure: 0,                                                  // c:778
                follow: 0,
            });
            return Some(l1);
        }
    }
    crate::ported::utils::errflag.fetch_or(
        crate::ported::zsh_h::ERRFLAG_ERROR,
        std::sync::atomic::Ordering::Relaxed,
    );                                                                       // c:783
    None                                                                     // c:784
}

/* turn a string into a Complist struct:  this has path components */    // c:787
/// Port of `parsepat(char *str)` from Src/glob.c:791.
/// Top-level entry: strip leading `(#...)` flag block via
/// `patgetglobflags`, then initialise `pathbuf`/`pathpos` per the
/// pattern's absolute-vs-relative head, then dispatch to
/// `parsecomplist`. Mutates `CURGLOBDATA.{pathbuf,pathpos,pathbufsz}`.
pub fn parsepat(s: &str) -> Option<Box<complist>> {
    // c:791
    // c:793 `long assert; int ignore;` — captured into patgetglobflags result
    crate::ported::pattern::patcompstart();                                  // c:796
    let chars: Vec<char> = s.chars().collect();
    let zpc = crate::ported::pattern::zpc_special
        .lock()
        .unwrap_or_else(|e| e.into_inner());
    let inpar_c = zpc[crate::ported::zsh_h::ZPC_INPAR as usize] as char;
    let hash_c = zpc[crate::ported::zsh_h::ZPC_HASH as usize] as char;
    let ksh_at_c = zpc[crate::ported::zsh_h::ZPC_KSH_AT as usize] as char;
    drop(zpc);

    /*
     * Check for initial globbing flags, so that they don't form
     * a bogus path component.
     */                                                                      // c:797-800
    let mut cursor: String = s.to_string();
    let first_is_inpar_hash =
        chars.first() == Some(&inpar_c) && chars.get(1) == Some(&hash_c);    // c:801
    let first_is_ksh_at_inpar_hash = chars.first() == Some(&ksh_at_c)
        && chars.get(1) == Some(&crate::ported::zsh_h::Inpar)
        && chars.get(2) == Some(&hash_c);                                    // c:802-803
    if first_is_inpar_hash || first_is_ksh_at_inpar_hash {
        let skip = if chars.first() == Some(&crate::ported::zsh_h::Inpar) {
            2
        } else {
            3
        };                                                                   // c:804
        cursor = chars[skip..].iter().collect();
        let flag_result = crate::ported::pattern::patgetglobflags(&cursor);  // c:805
        if flag_result.is_none() {
            return None;                                                     // c:806
        }
        let (_bits, _assertp, consumed) = flag_result.unwrap();
        cursor = cursor[consumed..].to_string();
    }

    /* Now there is no (#X) in front, we can check the path. */              // c:809
    {
        let mut gd = CURGLOBDATA.lock().unwrap_or_else(|e| e.into_inner());
        // c:810-811 — `if (!pathbuf) pathbuf = zalloc(pathbufsz = PATH_MAX+1);`
        if gd.pathbuf.capacity() == 0 {
            gd.pathbufsz = libc::PATH_MAX as usize + 1;
            gd.pathbuf = String::with_capacity(gd.pathbufsz);
        }
        // c:812 — `DPUTS(pathbufcwd, "BUG: glob changed directory");`
        debug_assert!(gd.pathbufcwd == 0, "BUG: glob changed directory");
        if cursor.starts_with('/') {                                         // c:813
            /* pattern has absolute path */
            cursor = cursor[1..].to_string();                                // c:814 `str++;`
            gd.pathbuf.clear();
            gd.pathbuf.push('/');                                            // c:815 `pathbuf[0] = '/';`
            gd.pathpos = 1;                                                  // c:816 `pathbuf[pathpos = 1] = '\0';`
        } else {
            /* pattern is relative to pwd */                                 // c:817
            gd.pathbuf.clear();                                              // c:818 `pathbuf[pathpos = 0] = '\0';`
            gd.pathpos = 0;
        }
    }

    parsecomplist(&cursor)                                                   // c:820
}

/// Parse qualifier (from glob.c qgetnum)
/// Parse a numeric glob-qualifier argument.
/// Port of `qgetnum(char **s)` from Src/glob.c:827.
pub fn qgetnum(s: &str) -> Option<(i64, &str)> {
    // c:827
    let end = s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len());
    if end == 0 {
        return None;
    }
    let num = s[..end].parse::<i64>().ok()?;
    Some((num, &s[end..]))
}

impl globdata {
    pub fn new() -> Self {
        globdata {
            matches: Vec::new(),
            qualifiers: None,
            pathbuf: String::with_capacity(4096),
            pathpos: 0,
            matchct: 0,
            pathbufsz: 4096,
            pathbufcwd: 0,
            gf_nullglob: 0,
            gf_markdirs: 0,
            gf_noglobdots: 0,
            gf_listtypes: 0,
            gf_pre_words: None,
            gf_post_words: None,
        }
    }
}

// ============================================================================
// Mode specification parsing (from glob.c qgetmodespec)
// ============================================================================

// `ModeSpec` struct deleted — Rust-only helper. C `qgetmodespec`
// (`Src/glob.c:844`) parses one clause and returns the combined
// `long` mode-bits directly, mutating the parse cursor via `char**`.
// The Rust port now returns `(who, op, perm, rest)` as a flat tuple
// so the canonical "no intermediate struct" pattern is preserved.

/// Parse mode specification like chmod (from glob.c qgetmodespec lines 790-920)
/// Examples: u+x, go-w, a=r, 755 — returns `(who, op, perm, rest)`.
/// Port of `qgetmodespec(char **s)` from `Src/glob.c:844`.
pub fn qgetmodespec(s: &str) -> Option<(u32, char, u32, &str)> {
    let mut chars = s.chars().peekable();
    let mut spec_who: u32 = 0;
    let mut spec_op: char = '\0';
    let mut spec_perm: u32 = 0;

    // Check for octal mode
    if chars.peek().map(|c| c.is_ascii_digit()).unwrap_or(false) {
        let mut mode_str = String::new();
        while let Some(&c) = chars.peek() {
            if c.is_ascii_digit() && c < '8' {
                mode_str.push(c);
                chars.next();
            } else {
                break;
            }
        }
        if let Ok(mode) = u32::from_str_radix(&mode_str, 8) {
            spec_perm = mode;
            spec_op = '=';
            spec_who = 0o7777;
            let rest_pos = s.len() - chars.collect::<String>().len();
            return Some((spec_who, spec_op, spec_perm, &s[rest_pos..]));
        }
        return None;
    }

    // Parse symbolic mode
    // Who: u, g, o, a
    let mut who = 0u32;
    while let Some(&c) = chars.peek() {
        match c {
            'u' => {
                who |= 0o4700;
                chars.next();
            }
            'g' => {
                who |= 0o2070;
                chars.next();
            }
            'o' => {
                who |= 0o1007;
                chars.next();
            }
            'a' => {
                who |= 0o7777;
                chars.next();
            }
            _ => break,
        }
    }
    if who == 0 {
        who = 0o7777; // Default to all
    }
    spec_who = who;

    // Op: +, -, =
    spec_op = match chars.next() {
        Some('+') => '+',
        Some('-') => '-',
        Some('=') => '=',
        _ => return None,
    };

    // Perm: r, w, x, X, s, t
    let mut perm = 0u32;
    while let Some(&c) = chars.peek() {
        match c {
            'r' => {
                perm |= 0o444;
                chars.next();
            }
            'w' => {
                perm |= 0o222;
                chars.next();
            }
            'x' => {
                perm |= 0o111;
                chars.next();
            }
            'X' => {
                perm |= 0o111;
                chars.next();
            } // Conditional execute
            's' => {
                perm |= 0o6000;
                chars.next();
            }
            't' => {
                perm |= 0o1000;
                chars.next();
            }
            _ => break,
        }
    }
    spec_perm = perm & who;

    let rest_pos = s.len() - chars.collect::<String>().len();
    Some((spec_who, spec_op, spec_perm, &s[rest_pos..]))
}

// `impl GlobMatch` block deleted — C builds Gmatch entries inline
// in `insert()` (glob.c:346) and `gmatchcmp` (glob.c:936) is a
// free function taking two Gmatch pointers. The Rust port mirrors
// that shape: no methods on the struct; construction inlined at
// the scanner call site, comparator as a free fn below.

/// Port of `gmatchcmp(Gmatch a, Gmatch b)` from Src/glob.c:936 —
/// the qsort comparator the `o`/`O` glob qualifier drives.
///
/// `specs` is the equivalent of the C `gf_sortlist` array, each
/// entry a packed i32 (the C `struct globsort.tp` field):
///   bits 0..=4        — primary key (GS_NAME / GS_DEPTH / GS_EXEC /
///                       GS_SIZE / GS_ATIME / GS_MTIME / GS_CTIME /
///                       GS_LINKS, plus GS_NONE marker)
///   bits << GS_SHIFT  — same keys, follow-link variant
///                       (GS__SIZE / GS__ATIME / …)
///   GS_DESC bit       — reverse direction (`O` qualifier instead of `o`)
/// WARNING: param names don't match C — Rust=(b, specs, numeric_sort) vs C=(a, b)
pub fn gmatchcmp(
    // c:936
    a: &gmatch,
    b: &gmatch,
    specs: &[i32],
    numeric_sort: bool,
) -> std::cmp::Ordering {
    for &tp in specs {
        // c:943
        let key = tp & !GS_DESC; // c:944 s->tp & ~GS_DESC
        let follow = (key & GS_LINKED) != 0;
        let key_unshifted = if follow { key >> GS_SHIFT } else { key };
        let cmp = if key_unshifted == GS_NAME {
            // c:945
            zstrcmp(
                &a.name,
                &b.name,
                if numeric_sort {
                    crate::zsh_h::SORTIT_NUMERICALLY as u32
                } else {
                    0
                },
            )
        } else if key_unshifted == GS_DEPTH {
            // c:949
            a.path
                .components()
                .count()
                .cmp(&b.path.components().count())
        } else if key_unshifted == GS_SIZE {
            // c:985
            if follow {
                a.target_size.cmp(&b.target_size)
            } else {
                a.size.cmp(&b.size)
            }
        } else if key_unshifted == GS_ATIME {
            // c:988
            if follow {
                b.target_atime.cmp(&a.target_atime)
            } else {
                b.atime.cmp(&a.atime)
            }
        } else if key_unshifted == GS_MTIME {
            // c:995
            if follow {
                b.target_mtime.cmp(&a.target_mtime)
            } else {
                b.mtime.cmp(&a.mtime)
            }
        } else if key_unshifted == GS_CTIME {
            if follow {
                b.target_ctime.cmp(&a.target_ctime)
            } else {
                b.ctime.cmp(&a.ctime)
            }
        } else if key_unshifted == GS_LINKS {
            if follow {
                b.target_links.cmp(&a.target_links)
            } else {
                b.links.cmp(&a.links)
            }
        } else if key_unshifted == GS_EXEC {
            // c:974
            let idx = ((key as u32) >> 16) as usize;
            let asx = a.sort_strings.get(idx).map(|s| s.as_str()).unwrap_or("");
            let bsx = b.sort_strings.get(idx).map(|s| s.as_str()).unwrap_or("");
            zstrcmp(
                asx,
                bsx,
                if numeric_sort {
                    crate::zsh_h::SORTIT_NUMERICALLY as u32
                } else {
                    0
                },
            )
        } else {
            std::cmp::Ordering::Equal // GS_NONE / unknown
        };
        if cmp != std::cmp::Ordering::Equal {
            return if (tp & GS_DESC) != 0 {
                cmp.reverse()
            } else {
                cmp
            };
        }
    }
    std::cmp::Ordering::Equal
}

// `Redirect` struct + `RedirectType` enum + `xpandredir` fn
// DELETED. Both types were Rust-only duplicates of `parse::Redirect`
// / `parse::RedirectOp` with no callers. The `xpandredir` impl took
// the wrong signature anyway — C's `xpandredir(struct redir *fn,
// LinkList redirtab)` at `Src/glob.c:2150` mutates a linked-list
// in place and returns int; this Rust version returned `Vec<Redirect>`
// and operated on the duplicate Redirect type. Port `xpandredir`
// freshly against `parse::Redirect` when an actual caller appears.

// ============================================================================
// Exec string for sorting (from glob.c glob_exec_string)
// ============================================================================

/// Port of `static char *glob_exec_string(char **sp)` from
/// `Src/glob.c:1085`.
///
/// **C is a PARSER, not an executor.** It extracts the qualifier
/// argument string from `*sp` (advancing the pointer past the
/// delimiters) and returns the duplicated text. The actual eval
/// happens at the call sites (c:1680/1713/1747) which feed the
/// returned string into `qualsheval` (for `e:`/`+:`) or
/// `gf_sortlist[].exec` (for sort).
///
/// Previous Rust port was COMPLETELY MIS-IMPLEMENTED:
///   1. **Signature wrong:** Rust took `(cmd, filename)` and returned
///      command output. C takes `(**sp)` and returns the parsed
///      qualifier string (the `cmd` itself, NOT its output).
///   2. **Forked `/bin/sh`:** spawned a separate POSIX shell process
///      to run the cmd. That's even more broken than `qualsheval`
///      was, because the function isn't supposed to execute anything
///      at all at this layer.
///
/// Now mirrors C's parser body (c:1090-1117): handle the `+` prefix
/// (identifier form) vs the `e:` delimited form (get_strarg), set
/// `*sp` past the closing delimiter, return the dup'd inner text.
///
/// Returns `(parsed_string, advance_offset)` so the caller can
/// emulate C's `*sp = tt + plus;` pointer advance via slice
/// indexing.
/// WARNING: param names don't match C — Rust=(s, plus) vs C=(sp)
pub fn glob_exec_string(s: &str, plus_form: bool) -> Option<(String, usize)> {
    // c:1085
    if plus_form {
        // c:1090
        // c:1092 — `tt = itype_end(s, IIDENT, 0);`
        // c:1093-1097 — `if (tt == s) { zerr("missing identifier after `+'"); return NULL; }`
        let tt = crate::ported::utils::itype_end(s, false);
        if tt == 0 {
            // c:1093
            zerr("missing identifier after `+'"); // c:1095
            return None; // c:1096
        }
        // c:1109 — `sdata = dupstring(s + plus);` (plus=0 here).
        // c:1113 — `*sp = tt + plus;` → advance offset is `tt`.
        Some((s[..tt].to_string(), tt))
    } else {
        // c:1099 — `tt = get_strarg(s, &plus);` — find matching delimiter.
        // get_strarg returns delimiter-balanced span; for `e:foo:` it
        // walks `s` past the inner expr and returns position of the
        // closing `:`.
        match crate::ported::subst::get_strarg(s) {
            Some((_del, content, rest)) => {
                // c:1100-1104 — `if (!*tt) { zerr("missing end of string"); return NULL; }`
                if rest.is_empty() && content.is_empty() {
                    zerr("missing end of string"); // c:1102
                    return None; // c:1103
                }
                // c:1109-1115 — `sdata = dupstring(s + plus); ... *sp = tt + plus;`.
                // Advance offset: bytes consumed of `s` = s.len() - rest.len().
                let advance = s.len() - rest.len();
                Some((content, advance))
            }
            None => {
                zerr("missing end of string"); // c:1102
                None
            }
        }
    }
}

/*
 * Insert a glob match.
 * If there were words to prepend given by the P glob qualifier, do so.
 */                                                                          // c:1120-1123
/// Port of `insert_glob_match(LinkList list, LinkNode next, char *data)`
/// from Src/glob.c:1125. Inserts `data` at `next`, with optional
/// `gf_pre_words` prefix and `gf_post_words` suffix injection from
/// CURGLOBDATA (the `P:before:after:` glob qualifier).
pub fn insert_glob_match(list: &mut Vec<String>, next: usize, data: &str) {
    // c:1125
    let (pre, post) = {
        let gd = CURGLOBDATA.lock().unwrap_or_else(|e| e.into_inner());
        (gd.gf_pre_words.clone(), gd.gf_post_words.clone())                  // c:1127, c:1136
    };
    // C `insertlinknode(list, next, data)` inserts AFTER node `next`,
    // returning the newly added node (so subsequent inserts append in
    // order). Our Vec<String> analog inserts at index `next+1` and
    // bumps `next` to point at the just-inserted slot.
    let mut cur = next;
    let n = list.len();
    let mut clamp = |i: usize| -> usize { if i > n { n } else { i } };
    if let Some(pre_words) = pre {                                           // c:1127 `if (gf_pre_words)`
        for w in pre_words.iter() {                                          // c:1129
            let pos = clamp(cur + 1);
            list.insert(pos, w.clone());                                     // c:1130 `dupstring(getdata(added))`
            cur = pos;                                                       // c:1130 — return-value advances `next`
        }
    }
    let pos = clamp(cur + 1);
    list.insert(pos, data.to_string());                                      // c:1134
    cur = pos;
    if let Some(post_words) = post {                                         // c:1136 `if (gf_post_words)`
        for w in post_words.iter() {                                         // c:1138
            let pos = clamp(cur + 1);
            list.insert(pos, w.clone());                                     // c:1139
            cur = pos;
        }
    }
}

/// Port of `checkglobqual(char *str, int sl, int nobareglob, char **sp)` from Src/glob.c:1158.
/// C: `int checkglobqual(char *str, int sl, int nobareglob, char **sp)` —
///   confirm the trailing `(...)` is a glob qualifier (not literal).
///   Sets `*sp` to the qualifier start position. Returns 0 if not a
///   qualifier, non-zero if it is.
/// WARNING: param names don't match C — Rust=(str, sl, _nobareglob) vs C=(str, sl, nobareglob, sp)
pub fn checkglobqual(
    str: &str,
    sl: i32,
    _nobareglob: i32, // c:1158
    sp: &mut Option<usize>,
) -> i32 {
    // c:1163-1164 — `if (str[sl-1] != Outpar) return 0;`
    let bytes = str.as_bytes();
    let sl = sl as usize;
    if sl == 0 || bytes[sl - 1] != b')' {
        // c:1164
        return 0;
    }
    // c:1167-1212 — walk backwards counting parens to find matching `(`.
    let mut paren = 1i32;
    let mut i = sl - 1;
    while i > 0 {
        i -= 1;
        match bytes[i] {
            b')' => paren += 1,
            b'(' => {
                paren -= 1;
                if paren == 0 {
                    *sp = Some(i);
                    return 1; // c:1209
                }
            }
            _ => {}
        }
    }
    0 // c:1212
}

/// Port of `zglob(LinkList list, LinkNode np, int nountok)` from
/// Src/glob.c:1214. Top-level glob expansion: gate on GLOBOPT/
/// EXECOPT/haswilds (c:1230-1234), remove the placeholder node,
/// expand the pattern via `glob_path` (which covers the c:1240-2012
/// qualifier+scanner+sort body), then splice the resulting matches
/// back at `node` via `insert_glob_match` (c:1995-2007).
pub fn zglob(list: &mut Vec<String>, np: usize, nountok: i32) {
    // c:1214
    if np >= list.len() {
        return;
    }
    // c:1217 — `LinkNode node = prevnode(np);` — the insertion point
    // after the placeholder is uremnode'd. Vec analog: insert at np.
    let node: usize = np;                                                    // c:1217
    let ostr = list[np].clone();                                             // c:1221 `ostr = getdata(np)`
    // c:1226 — `nobareglob = !isset(BAREGLOBQUAL);` (consumed by qualifier
    // parser inside glob_path).

    // c:1230 — `if (unset(GLOBOPT) || !haswilds(ostr) || unset(EXECOPT))`
    if !crate::ported::zsh_h::isset(crate::ported::zsh_h::GLOBOPT)
        || !haswilds(&ostr)
        || !crate::ported::zsh_h::isset(crate::ported::zsh_h::EXECOPT)
    {
        if nountok == 0 {                                                    // c:1231
            // c:1232 — untokenize in-place; replace list[np] with the
            // untokenized form.
            list[np] = crate::ported::lex::untokenize(&ostr);
        }
        return;                                                              // c:1233
    }

    // c:1235 — `save_globstate(saved);` happens inside glob_path via
    // its `enter_glob_scope()` RAII guard, equivalent semantics.

    // c:1237-1238 — `str = dupstring(ostr); uremnode(list, np);`
    list.remove(np);                                                         // c:1238

    let matches = glob_path(&ostr);                                          // c:1240-1995 body

    // c:1871-1875 — badcshglob accounting. Each zglob run updates
    // the per-command-line counter so globlist's terminal diagnostic
    // can distinguish "some failures, no successes" (emit error)
    // from "some failures, some successes" (silent).
    if !matches.is_empty() {
        // c:1872 — `badcshglob |= 2;` (at least one expansion OK).
        BADCSHGLOB.fetch_or(2, std::sync::atomic::Ordering::Relaxed);
    } else if crate::ported::zsh_h::isset(crate::ported::zsh_h::CSHNULLGLOB) {
        // c:1874-1875 — `badcshglob |= 1;` (at least one expansion
        // failed) under CSHNULLGLOB.
        BADCSHGLOB.fetch_or(1, std::sync::atomic::Ordering::Relaxed);
    }

    // c:1872-1888 — `Deal with failures to match depending on options`.
    // C body verbatim (c:1872-1888):
    //   if (matchct)
    //       badcshglob |= 2;
    //   else if (!gf_nullglob) {
    //       if (isset(CSHNULLGLOB)) {
    //           badcshglob |= 1;
    //       } else if (isset(NOMATCH)) {
    //           zerr("no matches found: %s", ostr);
    //           zfree(matchbuf, 0);
    //           restore_globstate(saved);
    //           return;
    //       } else {
    //           /* treat as an ordinary string */
    //           untokenize(matchptr->name = dupstring(ostr));
    //           matchptr++;
    //           matchct = 1;
    //       }
    //   }
    // gf_nullglob (c:212) is the per-glob nullglob bit toggled by
    // qualifier `N`; here we approximate with the global option.
    // Parity bug #13: previously this Rust arm fell through to the
    // ordinary-literal path (c:1882-1887) unconditionally, making
    // `echo /never/*` print the literal glob instead of erroring.
    if matches.is_empty() {
        let nullglob = isset(crate::ported::zsh_h::NULLGLOB); // c:1873 !gf_nullglob
        let csh_nullglob = isset(crate::ported::zsh_h::CSHNULLGLOB); // c:1874
        if !nullglob && !csh_nullglob && isset(crate::ported::zsh_h::NOMATCH) {
            // c:1876-1880 — `else if (isset(NOMATCH)) { zerr; return; }`
            crate::ported::utils::zerr(&format!(
                "no matches found: {}",
                ostr
            ));
            // c:1878 — `zfree(matchbuf, 0);` (Rust drop handles it)
            // c:1879 — `restore_globstate(saved);` (handled by guard)
            return; // c:1880
        }
        // c:1882-1887 — `treat as an ordinary string`. The matchptr++
        // bookkeeping in C maps to our `list.insert`.
        let restored = if nountok == 0 {
            crate::ported::lex::untokenize(&ostr)                            // c:1884 untokenize(matchptr->name = dupstring(ostr))
        } else {
            ostr.clone()
        };
        let pos = if node > list.len() { list.len() } else { node };
        list.insert(pos, restored);                                          // c:1885 matchptr++, c:1886 matchct = 1
        return;
    }

    // c:1995-2007 — splice matches back via insert_glob_match (honors
    // gf_pre_words / gf_post_words).
    let mut cur = if node == 0 { 0 } else { node - 1 };                      // node is `prevnode(np)` semantics
    for m in matches.iter() {
        insert_glob_match(list, cur, m);                                     // c:1995
        cur += 1;
        if let Some(g) = CURGLOBDATA.lock().ok() {
            // Advance past any pre_words that insert_glob_match added.
            if let Some(p) = &g.gf_pre_words {
                cur += p.len();
            }
            if let Some(p) = &g.gf_post_words {
                cur += p.len();
            }
        }
    }
}

/// File type character for -F style listing
/// Render a mode bitmap as the `*` qualifier letter (`d`/`b`/
/// `c`/`l`/`s`/`p`/etc.).
/// Port of `file_type(mode_t filemode)` from Src/glob.c:2018.
pub fn file_type(filemode: u32) -> char {
    // c:2018
    let fmt = filemode & libc::S_IFMT as u32;
    if fmt == libc::S_IFBLK as u32 {
        '#'
    } else if fmt == libc::S_IFCHR as u32 {
        '%'
    } else if fmt == libc::S_IFDIR as u32 {
        '/'
    } else if fmt == libc::S_IFIFO as u32 {
        '|'
    } else if fmt == libc::S_IFLNK as u32 {
        '@'
    } else if fmt == libc::S_IFREG as u32 {
        if filemode & 0o111 != 0 {
            '*'
        } else {
            ' '
        }
    } else if fmt == libc::S_IFSOCK as u32 {
        '='
    } else {
        '?'
    }
}

// ============================================================================
// Brace expansion
// ============================================================================

/// Check if string has brace expansion
/// Check whether a string has brace-expansion `{a,b}` content.
/// Port of `hasbraces(char *str)` from Src/glob.c:2042.
/// WARNING: param names don't match C — Rust=(s, brace_ccl) vs C=(str)
pub fn hasbraces(s: &str, brace_ccl: bool) -> bool {
    // c:2042
    let mut depth = 0;
    let mut has_comma = false;
    let mut has_dotdot = false;
    let mut brace_open: Option<usize> = None;

    let chars: Vec<char> = s.chars().collect();
    let len = chars.len();

    let mut i = 0;
    while i < len {
        // c:Src/lex.c:3587-3600 — backslash escape converts the next
        // char into a tokenized literal (Bnull/Bnullkeep). xpandbraces
        // sees the tokenized form so `\{` never enters the brace
        // walk. Accept both the canonical Bnull (`\u{9f}`,
        // Src/zsh.h:195) and ASCII `\` so direct callers (tests,
        // utility paths) and pipeline callers (bridge → multsub →
        // xpandbraces with Bnull markers from gettokstr) both behave
        // the same: skip the escape marker plus the next char.
        if (chars[i] == '\\' || chars[i] == '\u{9f}') && i + 1 < len {
            i += 2; // c:3591 — skip Bnull/Bnullkeep + escaped char
            continue;
        }
        match chars[i] {
            // c:Src/glob.c:hasbraces — Inbrace/Outbrace/Comma TOKEN
            // strictly (\u{8f} / \u{90} / \u{9a}). The lexer emits
            // TOKEN form for unescaped `{`/`,`/`}`; `\X` produces
            // Bnull + ASCII X. After remnulargs strips Bnull, the
            // ASCII X doesn't match the TOKEN check so escaped
            // braces correctly bypass expansion.
            '\u{8f}' => {
                if depth == 0 {
                    brace_open = Some(i);
                }
                depth += 1;
            }
            '\u{90}' if depth > 0 => {
                depth -= 1;
                if depth == 0 {
                    if has_comma || has_dotdot {
                        return true;
                    }
                    if brace_ccl {
                        if let Some(open) = brace_open {
                            if i > open + 1 {
                                return true;
                            }
                        }
                    }
                    has_comma = false;
                    has_dotdot = false;
                    brace_open = None;
                }
            }
            '\u{9a}' if depth == 1 => has_comma = true,
            '.' if depth == 1 && i + 1 < len && chars[i + 1] == '.' => has_dotdot = true,
            _ => {}
        }
        i += 1;
    }

    false
}

// ============================================================================
// Brace char range parsing (from glob.c bracechardots)
// ============================================================================

/// Parse character range in braces like {a..z} (from glob.c bracechardots line 2222)
/// Port of `bracechardots(char *str, convchar_t *c1p, convchar_t *c2p)` from `Src/glob.c:2222`.
/// WARNING: param names don't match C — Rust=(s) vs C=(str, c1p, c2p)
pub fn bracechardots(s: &str) -> Option<(char, char, i32)> {
    let chars: Vec<char> = s.chars().collect();

    // Must be at least "a..b"
    if chars.len() < 4 {
        return None;
    }

    // Find ..
    let dotdot_pos = s.find("..")?;
    if dotdot_pos == 0 {
        return None;
    }

    let left = &s[..dotdot_pos];
    let right = &s[dotdot_pos + 2..];

    // Check for increment
    let (end_str, incr) = if let Some(pos) = right.find("..") {
        let end = &right[..pos];
        let inc: i32 = right[pos + 2..].parse().unwrap_or(1);
        (end, inc)
    } else {
        (right, 1)
    };

    // Single character range
    if left.chars().count() == 1 && end_str.chars().count() == 1 {
        let c1 = left.chars().next()?;
        let c2 = end_str.chars().next()?;
        return Some((c1, c2, incr));
    }

    None
}

/// Expand braces in a string
/// Brace-expand a string into a flat list.
/// Port of `xpandbraces(LinkList list, LinkNode *np)` from Src/glob.c:2276 — same
/// `{a,b}` / `{1..10}` / `{a-z}` handling.
/// WARNING: param names don't match C — Rust=(s, brace_ccl) vs C=(list, np)
pub fn xpandbraces(s: &str, brace_ccl: bool) -> Vec<String> {
    // c:2276
    if !hasbraces(s, brace_ccl) {
        return vec![s.to_string()];
    }

    // Inline single-brace expansion — direct port of the per-iteration
    // brace-scan inside zsh's xpandbraces (Src/glob.c:2276). Walks the
    // string, finds the first `{`...`}` group, classifies as range
    // (`a..b`) / comma (`a,b`) / ccl (`[abc]`-style char-class), and
    // dispatches to the matching expander. Returns Some(parts) on
    // expansion, None if no brace group or unmatched.
    let try_expand_one = |s: &str| -> Option<Vec<String>> {
        let chars: Vec<char> = s.chars().collect();
        let len = chars.len();
        // c:Src/glob.c:xpandbraces — Inbrace TOKEN strict.
        let start = chars.iter().position(|&c| c == '\u{8f}')?;
        let mut depth = 1;
        let mut comma_positions = Vec::new();
        let mut dotdot_pos = None;
        for i in (start + 1)..len {
            match chars[i] {
                '\u{8f}' => depth += 1,
                '\u{90}' => {
                    depth -= 1;
                    if depth == 0 {
                        let prefix: String = chars[..start].iter().collect();
                        let suffix: String = chars[i + 1..].iter().collect();
                        let content: String = chars[start + 1..i].iter().collect();
                        if let Some(dp) = dotdot_pos {
                            if comma_positions.is_empty() {
                                if let Some(parts) = expand_range(&prefix, &content, dp, &suffix) {
                                    return Some(parts);
                                }
                                // c:Src/glob.c:2476-2506 — when range
                                // parsing fails INSIDE C's xpandbraces
                                // (err != 0 set at c:2355/2360/2369/2371),
                                // the function falls through to the
                                // normal-comma-expansion path. With no
                                // commas, that loop produces a single
                                // `prefix + content + suffix` — i.e.
                                // strips the outermost braces only.
                                // BUT: C only reaches xpandbraces when
                                // `hasbraces()` (c:2042) returned 1,
                                // and hasbraces requires DIGITS in the
                                // range endpoints (c:2076-2096) for the
                                // numeric form. Patterns like
                                // `{hello..world}` fail hasbraces and
                                // never enter xpandbraces — they stay
                                // as literal `{hello..world}`.
                                //
                                // Rust's hasbraces is more permissive
                                // (accepts any `..` inside `{}`), so we
                                // gate the strip-braces fallback on the
                                // SAME shape C uses: at least one digit
                                // must appear in the left or right
                                // endpoint, mirroring c:2085 `idigit
                                // (lbr[1]) || idigit(str[-1])`.
                                let left = &content[..dp];
                                let right = &content[dp + 2..];
                                let strip_end = right
                                    .find("..")
                                    .map(|p| &right[..p])
                                    .unwrap_or(right);
                                let has_digit = left
                                    .chars()
                                    .any(|c| c.is_ascii_digit())
                                    || strip_end
                                        .chars()
                                        .any(|c| c.is_ascii_digit());
                                if has_digit {
                                    // c:2495-2498 — strip braces.
                                    return Some(vec![format!(
                                        "{}{}{}",
                                        prefix, content, suffix
                                    )]);
                                }
                                // Non-digit `..` content (e.g.
                                // `{hello..world}`) — C wouldn't have
                                // entered xpandbraces. Preserve the
                                // literal pattern intact.
                                return None;
                            }
                        }
                        if !comma_positions.is_empty() {
                            return expand_comma(&prefix, &content, &comma_positions, &suffix);
                        }
                        if brace_ccl && !content.is_empty() {
                            return expand_ccl(&prefix, &content, &suffix);
                        }
                        return None;
                    }
                }
                '\u{9a}' if depth == 1 => comma_positions.push(i - start - 1),
                '.' if depth == 1 && i + 1 < len && chars[i + 1] == '.' && dotdot_pos.is_none() => {
                    dotdot_pos = Some(i - start - 1);
                }
                _ => {}
            }
        }
        None
    };

    let mut results = vec![s.to_string()];
    let mut changed = true;
    while changed {
        changed = false;
        let mut new_results = Vec::new();
        for item in &results {
            if let Some(expanded) = try_expand_one(item) {
                new_results.extend(expanded);
                changed = true;
            } else {
                new_results.push(item.clone());
            }
        }
        results = new_results;
    }
    results
}

/// Simple glob pattern matching
/* check to see if a matches b (b is not a filename pattern) */            // c:2510
// !!! WARNING: RUST-ONLY HELPER — extra args + flipped arg order vs C !!!
// C signature: `int matchpat(char *a, char *b)` — `a` = text to match,
// `b` = pattern. Rust callers (cond.rs, watch.rs, glob.rs internal users)
// pass `(pattern, text, extended, case_sensitive)` — pattern-FIRST,
// flipped from C, plus two per-call option overrides. The BODY below
// is C-faithful for the matching path (patcompile + pattry, no Unicode
// case-folding); `extended`/`case_sensitive` drive transient
// `opt_state_set` overrides around the patcompile call. The transient
// swap is the WRONG mechanism — patcompile is not reentrant under
// concurrent option mutation. SOLE acceptable use: this same-process,
// single-threaded matchpat call path. Replace with: all callers
// migrate to (a) global setopt and (b) canonical C arg order
// `matchpat(text, pattern)`.
// !!! WARNING: RUST-ONLY HELPER — extra args + flipped arg order vs C !!!
/// Port of `matchpat(char *a, char *b)` from `Src/glob.c:2514`.
/// CALLER CONVENTION: Rust=(pattern, text, ext, cs) — pattern FIRST
/// (FLIPPED from C `matchpat(text=a, pattern=b)`). Body remaps to
/// C order internally.
pub fn matchpat(pattern_in: &str, text_in: &str, extended: bool, case_sensitive: bool) -> bool {
    // Remap to C names (a=text, b=pattern) at the function boundary so
    // the body below reads identically to Src/glob.c:2514-2530.
    let a = text_in;
    let b = pattern_in;
    // c:2514
    crate::ported::signals_h::queue_signals();                               // c:2519
    // GF_IGNCASE handling: zshrs's pattern matcher DOES honor the
    // flag in `patmatch_internal` (pattern.rs:2245/2312/2333 — P_EXACTLY,
    // P_ANYOF, P_ANYBUT all check `glob_flags & (GF_IGNCASE|GF_LCMATCHUC)`
    // and case-fold appropriately). The pre-fold below is a defensive
    // fast path for the simple case-insensitive `:#`/`:#:` filter — it
    // bypasses the matcher's per-arm fold and avoids any stale-cache
    // edge case in the compile→match handoff. Costs one to_lowercase
    // call per side; correct under all matcher implementations.
    let (a_eff, b_eff) = if case_sensitive {
        (a.to_string(), b.to_string())
    } else {
        (a.to_lowercase(), b.to_lowercase())
    };
    // Per-call option override (Rust-only): snapshot, set, restore.
    let prev_extended = crate::ported::options::opt_state_get("extendedglob");
    let prev_caseglob = crate::ported::options::opt_state_get("caseglob");
    crate::ported::options::opt_state_set("extendedglob", extended);
    crate::ported::options::opt_state_set("caseglob", case_sensitive);
    // c:2521 — `if (!(p = patcompile(b, PAT_STATIC, NULL)))`. Rust uses
    // PAT_HEAPDUP (=0) — pattern::patmatch's canonical compile path;
    // PAT_STATIC's static-buffer path is incomplete in zshrs.
    let p_opt = crate::ported::pattern::patcompile(&b_eff, crate::ported::zsh_h::PAT_HEAPDUP, None);
    if let Some(v) = prev_extended {
        crate::ported::options::opt_state_set("extendedglob", v);
    }
    if let Some(v) = prev_caseglob {
        crate::ported::options::opt_state_set("caseglob", v);
    }
    let ret = match p_opt {
        Some(p) => crate::ported::pattern::pattry(&p, &a_eff),               // c:2525
        None => {
            crate::ported::utils::zerr(&format!("bad pattern: {}", b));      // c:2522
            false                                                            // c:2523
        }
    };
    crate::ported::signals_h::unqueue_signals();                             // c:2527
    ret                                                                      // c:2529
}

/// Get match return value (from glob.c get_match_ret line 2550)
/// Port of `get_match_ret(Imatchdata imd, int b, int e)` from `Src/glob.c:2550`.
pub fn get_match_ret(imd: &imatchdata, b: usize, e: usize) -> String {
    if b >= e || b >= imd.str.len() {
        return String::new();
    }

    let e = e.min(imd.str.len());
    imd.str[b..e].to_string()
}

/// Compile pattern and get match info (from glob.c compgetmatch line 2650)
/// Port of `compgetmatch(char *pat, int *flp, char **replstrp)` from `Src/glob.c:2650`.
/// WARNING: param names don't match C — Rust=(pat) vs C=(pat, flp, replstrp)
pub fn compgetmatch(pat: &str) -> Option<(String, i32)> {
    // c:1993 — `SUB_START` (anchor at head) / `SUB_END` (anchor at
    // tail) / `SUB_LONG` (`##`/`%%` doubled = longest). All three
    // imported from the canonical zsh_h.rs port; the previous local
    // redeclaration risked the same drift hazard as the HIST_*
    // bit-value bug caught earlier.
    let mut flags: i32 = 0;
    let mut pattern = pat.to_string();

    if pattern.starts_with('#') {
        flags |= SUB_START;
        pattern = pattern[1..].to_string();
    }
    if pattern.starts_with("##") {
        flags |= SUB_START | SUB_LONG;
        pattern = pattern[2..].to_string();
    }
    if pattern.ends_with('%') {
        flags |= SUB_END;
        pattern.pop();
    }
    if pattern.ends_with("%%") {
        flags |= SUB_END | SUB_LONG;
        pattern.truncate(pattern.len().saturating_sub(2));
    }

    Some((pattern, flags))
}

/// Port of `getmatch(char **sp, char *pat, int fl, int n, char *replstr)`
/// from `Src/glob.c:2710`. C body (4 lines):
///   `Patprog p;
///    if (!(p = compgetmatch(pat, &fl, &replstr))) return 1;
///    return igetmatch(sp, p, fl, n, replstr, NULL);`
/// Rust returns the resulting string (callers don't take a `**sp`
/// out-pointer); compgetmatch/igetmatch hold the real prepare +
/// match-and-replace logic.
pub fn getmatch(sp: &str, pat: &str, fl: i32, n: i32, replstr: Option<&str>) -> String {
    let (prep_pat, prep_fl) = match compgetmatch(pat) {
        // c:2713
        Some(t) => t,
        None => return sp.to_string(), // c:2713 return 1
    };
    let mut buf = sp.to_string();
    igetmatch(&mut buf, &prep_pat, prep_fl | fl, n, replstr); // c:2715
    buf
}

/// Get match for array elements (from glob.c getmatcharr lines 2690-2750)
/// Port of `getmatcharr(char ***ap, char *pat, int fl, int n, char *replstr)` from `Src/glob.c:2727`.
pub fn getmatcharr(
    ap: &[String],
    pat: &str,
    fl: i32,
    n: i32,
    replstr: Option<&str>,
) -> Vec<String> {
    ap.iter()
        .map(|s| getmatch(s, pat, fl, n, replstr))
        .collect()
}

/// Port of `int getmatchlist(char *str, Patprog p, LinkList *repllistp)`
/// from `Src/glob.c:2749`.
/// ```c
/// int
/// getmatchlist(char *str, Patprog p, LinkList *repllistp)
/// {
///     char **sp = &str;
///     return igetmatch(sp, p, SUB_LONG|SUB_GLOBAL|SUB_SUBSTR|SUB_LIST,
///                      0, NULL, repllistp);
/// }
/// ```
/// 3-line delegation to `igetmatch` with the canonical flag set. The
/// `repllistp` out-param is the LinkList that receives the match
/// position pairs; the Rust port currently lacks a repllistp out-
/// channel on `igetmatch`, so this entry mirrors the C structure
/// and returns the igetmatch status.
pub fn getmatchlist(sp: &mut String, p: &str) -> i32 {
    // c:2749
    igetmatch(
        sp,
        p,
        SUB_LONG | SUB_GLOBAL | SUB_SUBSTR | SUB_LIST, // c:2761
        0,
        None,
    ) // c:2762
}

/// File-static `static int in_expandredir = 0;` from `Src/glob.c:1206`
/// — set during the `globlist` call inside `xpandredir` so the glob
/// pipeline knows the result feeds a redirection (suppresses the
/// "no matches" warning in the caller's normal flow).
pub static IN_EXPANDREDIR: std::sync::atomic::AtomicI32 = // c:1206
    std::sync::atomic::AtomicI32::new(0);

/// Direct port of `int xpandredir(struct redir *fn, LinkList redirtab)`
/// from `Src/glob.c:2150`. Expands `>>*.c`-style redirections by
/// running `prefork` + (when MULTIOS is set) `globlist` over the redir
/// name. Single match: rewrite `fn->name` in place and decode the
/// MERGEIN/MERGEOUT special syntax (`-` close, `p` pipe-fd, digits =
/// fd number). Multi match: clone the redir for each name and append
/// to `redirtab`. Returns 1 if multios produced multiple entries, 0
/// otherwise.
/// WARNING: param names don't match C — Rust=(fn_, redirtab) vs C=(fn, redirtab)
pub fn xpandredir(
    fn_: &mut redir, // c:2150
    redirtab: &mut Vec<redir>,
) -> i32 {
    use std::sync::atomic::Ordering::SeqCst;
    let mut ret = 0; // c:2156
    let name = match fn_.name.as_deref() {
        // c:2160 init_list1(fake, fn->name)
        Some(n) => n.to_string(),
        None => return 0,
    };
    let mut fake: LinkList = LinkList::new();
    fake.push_back(name); // c:2160
    let mut rf = 0i32;
    prefork(
        &mut fake, // c:2162 prefork
        if isset(MULTIOS) { 0 } else { PREFORK_SINGLE },
        &mut rf,
    );
    // c:2164 — `if (!errflag && isset(MULTIOS))`. C uses LOGICAL NOT
    // on `errflag` (an `int`), so the condition is "errflag is zero".
    // The previous Rust port wrote `!errflag.load(...) != 0` which is
    // BITWISE NOT in Rust (`!i32` is `^-1`), making the condition
    // equivalent to `errflag != -1` — true for every common errflag
    // value (0 / ERRFLAG_ERROR=1 / ERRFLAG_INT=2). Result: the
    // globlist call ran even when errflag was set, papering over
    // the abort path that C uses to bail early on prior errors.
    if errflag.load(SeqCst) == 0
        && isset(MULTIOS)
    {
        // c:2164
        IN_EXPANDREDIR.store(1, SeqCst); // c:2165
        crate::ported::subst::globlist(&mut fake, 0); // c:2166
        IN_EXPANDREDIR.store(0, SeqCst); // c:2167
    }
    if errflag.load(SeqCst) != 0 {
        return 0;
    } // c:2169
    let names: Vec<String> = fake.iter().cloned().collect();
    if names.len() == 1 {
        // c:2171 nonempty(&fake) && !nextnode(firstnode)
        let s = crate::lex::untokenize(&names[0]); // c:2174 untokenize(s)
        fn_.name = Some(s.clone()); // c:2173 fn->name = s
        if fn_.typ == REDIR_MERGEIN || fn_.typ == REDIR_MERGEOUT {
            // c:2175
            let bytes = s.as_bytes();
            if bytes.len() == 1 && IS_DASH(bytes[0] as char) {
                // c:2176-2177 IS_DASH(s[0]) && !s[1]
                fn_.typ = REDIR_CLOSE;
            } else if bytes.len() == 1 && bytes[0] == b'p' {
                // c:2178 s[0]=='p' && !s[1]
                fn_.fd2 = -2;
            } else {
                let mut i = 0;
                while i < bytes.len() && bytes[i].is_ascii_digit() {
                    i += 1;
                } // c:2181 idigit
                if i == bytes.len() && i > 0 {
                    // c:2183 !*s && s > fn->name
                    fn_.fd2 = crate::ported::utils::zstrtol(&s, 10).0 as i32; // c:2184 zstrtol(.., 10)
                } else if fn_.typ == REDIR_MERGEIN {
                    // c:2185
                    zerr("file number expected"); // c:2186
                } else {
                    fn_.typ = REDIR_ERRWRITE; // c:2188
                }
            }
        }
    } else if fn_.typ == REDIR_MERGEIN {
        // c:2192
        zerr("file number expected"); // c:2193
    } else {
        if fn_.typ == REDIR_MERGEOUT {
            fn_.typ = REDIR_ERRWRITE;
        } // c:2195
        for nam in names {
            // c:2196 while ((nam = ugetnode(&fake)))
            let mut ff = fn_.clone(); // c:2199-2200 zhalloc + *ff = *fn
            ff.name = Some(nam); // c:2201 ff->name = nam
            redirtab.push(ff); // c:2202 addlinknode(redirtab, ff)
            ret = 1; // c:2203
        }
    }
    ret // c:2206
}

/// Port of `freerepldata(void *ptr)` from Src/glob.c:2766.
/// C: `static void freerepldata(void *ptr)` →
///   `zfree(ptr, sizeof(struct repldata));`
#[allow(unused_variables)]
pub fn freerepldata(ptr: *mut std::ffi::c_void) { // c:2766
                                                  // Rust drop covers the equivalent.
}

/// Port of `freematchlist(LinkList repllist)` from Src/glob.c:2773.
/// C: `void freematchlist(LinkList repllist)` →
///   `freelinklist(repllist, freerepldata);`
pub fn freematchlist(repllist: Option<&mut Vec<(usize, usize)>>) {
    // c:2773
    if let Some(l) = repllist {
        l.clear(); // c:2776
    }
}

/// Set pattern start offset (from glob.c set_pat_start)
/// Port of `set_pat_start(Patprog p, int offs)` from `Src/glob.c:2780`.
pub fn set_pat_start(p: &str, offs: usize) -> String {
    if offs == 0 || offs >= p.len() {
        return p.to_string();
    }
    p[offs..].to_string()
}

/// Set pattern end (from glob.c set_pat_end)
/// Port of `set_pat_end(Patprog p, char null_me)` from `Src/glob.c:2797`.
pub fn set_pat_end(p: &str, null_me: usize) -> String {
    if null_me >= p.len() {
        return p.to_string();
    }
    p[..null_me].to_string()
}

/// Port of `igetmatch(char **sp, Patprog p, int fl, int n, char *replstr, LinkList *repllistp)` from Src/glob.c:2832.
/// C: `static int igetmatch(char **sp, Patprog p, int fl, int n,
///     char *replstr, LinkList *repllistp)` — pattern-replace inner
///     matcher; modifies `*sp` in place, optionally collects match
///     positions into `*repllistp`.
/// WARNING: param names don't match C — Rust=(sp, p, fl, n, replstr) vs C=(sp, p, fl, n, replstr, repllistp)
pub fn igetmatch(
    sp: &mut String,
    p: &str,
    fl: i32,
    _n: i32, // c:2832
    replstr: Option<&str>,
) -> i32 {

    // c:2840-3100+ — full SUB_* dispatch: longest/shortest/global/end-
    // anchor replacement loop with multibyte tracking. Rust port walks
    // chars + `matchpat`; full Patprog substrate (with chunked DFA
    // execution) lives in src/ported/pattern.rs. SUB_START imported
    // from zsh_h.rs at top-of-file rather than redeclared locally.
    let anchored_start = (fl & SUB_START) != 0;
    let anchored_end = (fl & SUB_END) != 0;
    let substr_mode = (fl & SUB_SUBSTR) != 0;
    let shortest = (fl & SUB_LONG) == 0;
    let chars: Vec<char> = sp.chars().collect();
    let len = chars.len();

    // c:2887-2898 — SUB_ALL: entire-string match flag.
    if (fl & SUB_ALL) != 0 {
        // c:2887
        let i = matchpat(p, sp, true, true); // c:2888 pattrylen
        if !i {
            // c:2889
            // c:2890-2893 — no match: clear replstr.
            if (fl & SUB_MATCH) != 0 {
                // c:2895
                *sp = String::new();
                return 0; // c:2896
            }
            return 1; // c:2897
        }
        if let Some(r) = replstr {
            // c:2894 get_match_ret
            *sp = r.to_string();
        }
        if sp.is_empty() && (fl & SUB_REST) != 0 && i {
            // c:2895
            return 0; // c:2896
        }
        return 1; // c:2897
    }

    if len == 0 {
        return 1;
    }
    // c:2998-3041 — SUB_LIST: collect all match offset pairs.
    if (fl & SUB_LIST) != 0 {
        // c:2998
        // Walk all substrings; collect (start, end) pairs the caller
        // can read via subsequent `getmatchlist` invocations. Without
        // a `repllistp` out-channel through the Rust signature, we
        // only walk to validate at-least-one-match; the canonical
        // collection point is the caller-supplied LinkList that the
        // C body populates at c:3000+. Defer until the out-vec lands.
        let mut found = false;
        for start in 0..len {
            // c:3008
            for end in (start + 1)..=len {
                // c:3009
                let s2: String = chars[start..end].iter().collect();
                if matchpat(p, &s2, true, true) {
                    // c:3010
                    found = true;
                    if shortest {
                        break;
                    } // c:3011 SUB_LONG vs short
                }
            }
            if !substr_mode {
                break;
            }
        }
        return if found { 0 } else { 1 };
    }

    // c:Src/glob.c:2900+ — SUB_MATCH inverts the disposition of the
    // anchored-strip operators. Default (no SUB_MATCH): the matched
    // portion is REMOVED and the rest is returned (`${var#pat}` →
    // tail after the matched prefix). With SUB_MATCH: the matched
    // portion is KEPT and the rest is removed (`${(M)var#pat}` → the
    // matched prefix only). Previously honoured only in the SUB_ALL
    // arm at c:2895; the anchored-prefix / anchored-suffix / substr
    // arms below always returned prefix+suffix, so `(M)` was a no-op
    // for `#pat` / `%pat`. Mirror the C SUB_MATCH branch by emitting
    // just the matched slice.
    let match_only = (fl & SUB_MATCH) != 0;
    let (match_start, match_end) = if anchored_start && anchored_end {
        if matchpat(p, sp, true, true) {
            (0, len)
        } else {
            if match_only {
                *sp = String::new();
                return 0;
            }
            return 1;
        }
    } else if anchored_start {
        let mut best_end = 0;
        for end in 1..=len {
            let substr: String = chars[..end].iter().collect();
            if matchpat(p, &substr, true, true) {
                if shortest {
                    *sp = if match_only {
                        chars[..end].iter().collect()
                    } else {
                        match replstr {
                            Some(r) => format!("{}{}", r, chars[end..].iter().collect::<String>()),
                            None => chars[end..].iter().collect(),
                        }
                    };
                    return 0;
                }
                best_end = end;
            }
        }
        if best_end > 0 {
            (0, best_end)
        } else {
            if match_only {
                *sp = String::new();
                return 0;
            }
            return 1;
        }
    } else if anchored_end {
        let mut best_start = len;
        for start in (0..len).rev() {
            let substr: String = chars[start..].iter().collect();
            if matchpat(p, &substr, true, true) {
                if shortest {
                    *sp = if match_only {
                        chars[start..].iter().collect()
                    } else {
                        match replstr {
                            Some(r) => format!("{}{}", chars[..start].iter().collect::<String>(), r),
                            None => chars[..start].iter().collect(),
                        }
                    };
                    return 0;
                }
                best_start = start;
            }
        }
        if best_start < len {
            (best_start, len)
        } else {
            if match_only {
                *sp = String::new();
                return 0;
            }
            return 1;
        }
    } else {
        for start in 0..len {
            for end in (start + 1)..=len {
                let substr: String = chars[start..end].iter().collect();
                if matchpat(p, &substr, true, true) {
                    if match_only {
                        *sp = chars[start..end].iter().collect();
                        return 0;
                    }
                    let prefix: String = chars[..start].iter().collect();
                    let suffix: String = chars[end..].iter().collect();
                    *sp = match replstr {
                        Some(r) => format!("{}{}{}", prefix, r, suffix),
                        None => format!("{}{}", prefix, suffix),
                    };
                    return 0;
                }
            }
        }
        if match_only {
            *sp = String::new();
            return 0;
        }
        return 1;
    };
    *sp = if match_only {
        chars[match_start..match_end].iter().collect()
    } else {
        let prefix: String = chars[..match_start].iter().collect();
        let suffix: String = chars[match_end..].iter().collect();
        match replstr {
            Some(r) => format!("{}{}{}", prefix, r, suffix),
            None => format!("{}{}", prefix, suffix),
        }
    };
    0
}

// ============================================================================
// Tokenization (from glob.c tokenize family)
// ============================================================================

// `enum GlobToken` deleted — C uses the byte-token constants
// (`Star`/`Quest`/`Inpar`/...) from `Src/zsh.h:159-200`, mirrored in
// the Rust port at `zsh_h.rs:128-160`. `tokenize()` (`Src/glob.c:3548`
// → `zshtokenize`) mutates the input string in place, replacing each
// glob-metacharacter with its high-bit byte token; the Rust port now
// matches.

// `ztokens[]` from `Src/lex.c:38` — the source-char ↔ token-byte
// table the C tokenizer indexes with `(t - ztokens) + Pound`. Each
// position N in the string maps to high-bit byte `Pound + N`.
const ZTOKENS: &str = "#$^*(())$=|{}[]`<>>?~`,-!'\"\\\\";

/// Tokenize a glob pattern in place — port of `tokenize(char *s)` from
/// `Src/glob.c:3548`. One-line C delegation: `zshtokenize(s, 0)`.
pub fn tokenize(s: &mut String) {
    // c:3548
    zshtokenize(s, 0); // c:3552
}

/// Tokenize for shell — port of `shtokenize(char *s)` from
/// `Src/glob.c:3563`. Builds flags from SHGLOB option then delegates
/// to `zshtokenize`.
pub fn shtokenize(s: &mut String) {
    // c:3563
    let mut flags = ZSHTOK_SUBST; // c:3567
    if isset(SHGLOB) {
        // c:3568
        flags |= ZSHTOK_SHGLOB; // c:3569
    }
    zshtokenize(s, flags); // c:3570
}

/// Port of `zshtokenize(char *s, int flags)` from `Src/glob.c:3575`.
/// Walks `s` in place, replacing each glob-metachar with its high-bit
/// byte token from the `ZTOKENS` table; respects ZSHTOK_SUBST (use
/// Bnullkeep for escaped tokens) and ZSHTOK_SHGLOB (don't tokenize
/// `<` / `(` / `|` / `)`).
pub fn zshtokenize(s: &mut String, flags: i32) {
    // c:3575
    let ztokens: Vec<char> = ZTOKENS.chars().collect();
    let mut chars: Vec<char> = s.chars().collect();
    let mut bslash = false; // c:3578
    let mut i = 0;
    while i < chars.len() {
        // c:3580 for (; *s; s++)
        let c = chars[i];
        match c {
            x if x == Meta as char => {                                              // c:3583 case Meta
                i += 2;                                                      // c:3585 skip both Meta and next
                bslash = false;
                continue;
            }
            x if x == Bnull || x == Bnullkeep || x == '\\' => {              // c:3587-3589
                if bslash {                                                  // c:3590
                    chars[i - 1] = if (flags & ZSHTOK_SUBST) != 0 {          // c:3591
                        Bnullkeep
                    } else {
                        Bnull
                    };
                } else {
                    bslash = true;                                           // c:3595
                    i += 1;
                    continue;                                                // c:3596 (skip bslash=0 reset)
                }
            }
            '<' => {                                                         // c:3598
                if (flags & ZSHTOK_SHGLOB) != 0 {                            // c:3599
                    // break — no tokenization
                } else if bslash {                                           // c:3601
                    chars[i - 1] = if (flags & ZSHTOK_SUBST) != 0 {
                        Bnullkeep
                    } else {
                        Bnull
                    };
                } else {
                    // c:3605-3614 — try to parse `<N-N>` redirection.
                    let t = i;                                               // c:3605
                    let mut j = i + 1;
                    while j < chars.len() && chars[j].is_ascii_digit() {     // c:3606 idigit
                        j += 1;
                    }
                    if j < chars.len() && (chars[j] == '-') {                // c:3607 IS_DASH
                        let mut k = j + 1;
                        while k < chars.len() && chars[k].is_ascii_digit() { // c:3609
                            k += 1;
                        }
                        if k < chars.len() && chars[k] == '>' {              // c:3611
                            chars[t] = Inang;                                // c:3613
                            chars[k] = Outang;                               // c:3614
                            i = k + 1;
                            bslash = false;
                            continue;
                        }
                    }
                    // c:3608/3611 `goto cont` — re-switch on current *s;
                    // since none of the conditions matched, fall through.
                }
            }
            '(' | '|' | ')' if (flags & ZSHTOK_SHGLOB) != 0 => {             // c:3617-3620
                // no tokenization under SHGLOB
            }
            '>' | '^' | '#' | '~' | '[' | ']' | '*' | '?'                    // c:3621-3631
            | '=' | '-' | '!' | '(' | '|' | ')' => {
                for (n, &t) in ztokens.iter().enumerate() {                  // c:3633
                    if t == c {                                              // c:3634
                        if bslash {                                          // c:3635
                            chars[i - 1] = if (flags & ZSHTOK_SUBST) != 0 {
                                Bnullkeep
                            } else {
                                Bnull
                            };
                        } else {
                            chars[i] = char::from_u32(Pound as u32 + n as u32)
                                .unwrap_or(c);                                // c:3638
                        }
                        break;                                                // c:3639
                    }
                }
            }
            _ => {}
        }
        bslash = false; // c:3646
        i += 1;
    }
    *s = chars.into_iter().collect();
}

/// Port of `void remnulargs(char *s)` from `Src/glob.c:3649`.
///
/// C body (c:3651-3676): walks `s` looking for INULL bytes.
///   - `Bnullkeep` in SCAN phase: skip (the `continue` at c:3658)
///     — don't treat as a null marker.
///   - Any other INULL: switch to COPY phase. In copy phase:
///       - `Bnullkeep` becomes literal `\` (the "active backslash"
///         is re-materialized).
///       - Other INULLs: stripped.
///       - Non-INULL: kept.
///   - If the post-copy string is empty, replace with `Nularg`
///     (single-char empty-arg marker).
///
/// The previous Rust port collapsed the body to
/// `s.retain(|c| c != '\0' && c != Bnullkeep)` — a simple
/// strip of NUL and Bnullkeep. Three divergences:
///   - Stripped Bnullkeep entirely instead of preserving it in
///     the scan-only phase (when it appears BEFORE any other
///     inull) or converting to `\` in the copy phase.
///   - Didn't strip Snull/Dnull/Bnull/Nularg — those inulls
///     stayed in the output, polluting downstream processing.
///   - Didn't emit Nularg sentinel for empty post-strip strings.
pub fn remnulargs(s: &mut String) {
    // c:3649
    if s.is_empty() {
        // c:3654
        return;
    }
    // c:3656 `inull(c)` predicate: Snull / Dnull / Bnull / Bnullkeep / Nularg.
    let is_inull =
        |c: char| c == Snull || c == Dnull || c == Bnull || c == Bnullkeep || c == Nularg;
    let src: Vec<char> = s.chars().collect();
    let mut out: Vec<char> = Vec::with_capacity(src.len());
    let mut i = 0usize;
    // c:3656 — SCAN phase: copy chars, skip standalone Bnullkeep.
    while i < src.len() {
        let c = src[i];
        if c == Bnullkeep {
            // c:3657 continue
            i += 1;
            continue;
        }
        if is_inull(c) {
            // c:3663 inull(c)
            // c:3664+ — COPY phase: walk the rest, fold Bnullkeep
            // to `\\`, strip other inulls.
            i += 1;
            while i < src.len() {
                let d = src[i];
                if d == Bnullkeep {
                    // c:3666
                    out.push('\\'); // c:3667
                } else if !is_inull(d) {
                    // c:3668
                    out.push(d); // c:3669
                }
                i += 1;
            }
            break;
        }
        // SCAN phase non-inull: keep verbatim.
        out.push(c);
        i += 1;
    }
    // c:3673-3675 — empty result → Nularg sentinel.
    if out.is_empty() {
        out.push(Nularg);
    }
    *s = out.into_iter().collect();
}

/// Port of `qualdev(UNUSED(char *name), struct stat *buf, off_t dv, UNUSED(char *dummy))` from Src/glob.c:3688.
/// C: `static int qualdev(UNUSED(char *name), struct stat *buf, off_t dv,
///     UNUSED(char *dummy))` → `return (off_t)buf->st_dev == dv;`
#[allow(unused_variables)]
pub fn qualdev(name: &str, buf: &libc::stat, dv: i64, dummy: &str) -> i32 {
    // c:3688
    (buf.st_dev as i64 == dv) as i32 // c:3697
}

/// Port of `qualnlink(UNUSED(char *name), struct stat *buf, off_t ct, UNUSED(char *dummy))` from Src/glob.c:3697.
/// C: ternary on `g_range`: < / > / == against `st_nlink`.
#[allow(unused_variables)]
pub fn qualnlink(name: &str, buf: &libc::stat, ct: i64, dummy: &str) -> i32 {
    // c:3697
    let g = G_RANGE.load(Ordering::Relaxed);
    let nl = buf.st_nlink as i64; // c:3708
    if g < 0 {
        (nl < ct) as i32
    } else if g > 0 {
        (nl > ct) as i32
    } else {
        (nl == ct) as i32
    }
}

/// Port of `qualuid(UNUSED(char *name), struct stat *buf, off_t uid, UNUSED(char *dummy))` from Src/glob.c:3708.
/// C: `return buf->st_uid == uid;`
#[allow(unused_variables)]
pub fn qualuid(name: &str, buf: &libc::stat, uid: i64, dummy: &str) -> i32 {
    // c:3708
    (buf.st_uid as i64 == uid) as i32 // c:3717
}

/// Port of `qualgid(UNUSED(char *name), struct stat *buf, off_t gid, UNUSED(char *dummy))` from Src/glob.c:3717.
/// C: `return buf->st_gid == gid;`
#[allow(unused_variables)]
pub fn qualgid(name: &str, buf: &libc::stat, gid: i64, dummy: &str) -> i32 {
    // c:3717
    (buf.st_gid as i64 == gid) as i32 // c:3726
}

/// Port of `qualisdev(UNUSED(char *name), struct stat *buf, UNUSED(off_t junk), UNUSED(char *dummy))` from Src/glob.c:3726.
/// C: `return S_ISBLK(buf->st_mode) || S_ISCHR(buf->st_mode);`
#[allow(unused_variables)]
pub fn qualisdev(name: &str, buf: &libc::stat, junk: i64, dummy: &str) -> i32 {
    // c:3726
    let m = buf.st_mode as u32 & libc::S_IFMT as u32;
    ((m == libc::S_IFBLK as u32) || (m == libc::S_IFCHR as u32)) as i32 // c:3735
}

/// Port of `qualisblk(UNUSED(char *name), struct stat *buf, UNUSED(off_t junk), UNUSED(char *dummy))` from Src/glob.c:3735.
/// C: `return S_ISBLK(buf->st_mode);`
#[allow(unused_variables)]
pub fn qualisblk(name: &str, buf: &libc::stat, junk: i64, dummy: &str) -> i32 {
    // c:3735
    ((buf.st_mode as u32 & libc::S_IFMT as u32) == libc::S_IFBLK as u32) as i32 // c:3744
}

/// Port of `qualischr(UNUSED(char *name), struct stat *buf, UNUSED(off_t junk), UNUSED(char *dummy))` from Src/glob.c:3744.
/// C: `return S_ISCHR(buf->st_mode);`
#[allow(unused_variables)]
pub fn qualischr(name: &str, buf: &libc::stat, junk: i64, dummy: &str) -> i32 {
    // c:3744
    ((buf.st_mode as u32 & libc::S_IFMT as u32) == libc::S_IFCHR as u32) as i32 // c:3753
}

/// Port of `qualisdir(UNUSED(char *name), struct stat *buf, UNUSED(off_t junk), UNUSED(char *dummy))` from Src/glob.c:3753.
/// C: `return S_ISDIR(buf->st_mode);`
#[allow(unused_variables)]
pub fn qualisdir(name: &str, buf: &libc::stat, junk: i64, dummy: &str) -> i32 {
    // c:3753
    ((buf.st_mode as u32 & libc::S_IFMT as u32) == libc::S_IFDIR as u32) as i32 // c:3762
}

/// Port of `qualisfifo(UNUSED(char *name), struct stat *buf, UNUSED(off_t junk), UNUSED(char *dummy))` from Src/glob.c:3762.
/// C: `return S_ISFIFO(buf->st_mode);`
#[allow(unused_variables)]
pub fn qualisfifo(name: &str, buf: &libc::stat, junk: i64, dummy: &str) -> i32 {
    // c:3762
    ((buf.st_mode as u32 & libc::S_IFMT as u32) == libc::S_IFIFO as u32) as i32 // c:3771
}

/// Port of `qualislnk(UNUSED(char *name), struct stat *buf, UNUSED(off_t junk), UNUSED(char *dummy))` from Src/glob.c:3771.
/// C: `return S_ISLNK(buf->st_mode);`
#[allow(unused_variables)]
pub fn qualislnk(name: &str, buf: &libc::stat, junk: i64, dummy: &str) -> i32 {
    // c:3771
    ((buf.st_mode as u32 & libc::S_IFMT as u32) == libc::S_IFLNK as u32) as i32 // c:3780
}

/// Port of `qualisreg(UNUSED(char *name), struct stat *buf, UNUSED(off_t junk), UNUSED(char *dummy))` from Src/glob.c:3780.
/// C: `return S_ISREG(buf->st_mode);`
#[allow(unused_variables)]
pub fn qualisreg(name: &str, buf: &libc::stat, junk: i64, dummy: &str) -> i32 {
    // c:3780
    ((buf.st_mode as u32 & libc::S_IFMT as u32) == libc::S_IFREG as u32) as i32 // c:3789
}

/// Port of `qualissock(UNUSED(char *name), struct stat *buf, UNUSED(off_t junk), UNUSED(char *dummy))` from Src/glob.c:3789.
/// C: `return S_ISSOCK(buf->st_mode);`
#[allow(unused_variables)]
pub fn qualissock(name: &str, buf: &libc::stat, junk: i64, dummy: &str) -> i32 {
    // c:3789
    ((buf.st_mode as u32 & libc::S_IFMT as u32) == libc::S_IFSOCK as u32) as i32
    // c:3798
}

/// Port of `qualflags(UNUSED(char *name), struct stat *buf, off_t mod, UNUSED(char *dummy))` from Src/glob.c:3798.
/// C: `return mode_to_octal(buf->st_mode) & mod;`
#[allow(unused_variables)]
/// WARNING: param names don't match C — Rust=(name, buf, dummy) vs C=(name, buf, mod, dummy)
pub fn qualflags(name: &str, buf: &libc::stat, r#mod: i64, dummy: &str) -> i32 {
    // c:3798
    (mode_to_octal(buf.st_mode as u32) as i64 & r#mod) as i32 // c:3807
}

/// Port of `qualmodeflags(UNUSED(char *name), struct stat *buf, off_t mod, UNUSED(char *dummy))` from Src/glob.c:3807.
/// C: `((v & y) == y && !(v & n))` where `y = mod & 07777`, `n = mod >> 12`.
#[allow(unused_variables)]
/// WARNING: param names don't match C — Rust=(name, buf, dummy) vs C=(name, buf, mod, dummy)
pub fn qualmodeflags(name: &str, buf: &libc::stat, r#mod: i64, dummy: &str) -> i32 {
    // c:3807
    let v = mode_to_octal(buf.st_mode as u32) as i64; // c:3818
    let y = r#mod & 0o7777;
    let n = r#mod >> 12;
    (((v & y) == y) && (v & n) == 0) as i32 // c:3818
}

/// Port of `qualiscom(UNUSED(char *name), struct stat *buf, UNUSED(off_t mod), UNUSED(char *dummy))` from Src/glob.c:3818.
/// C: `return S_ISREG(buf->st_mode) && (buf->st_mode & S_IXUGO);`
#[allow(unused_variables)]
pub fn qualiscom(name: &str, buf: &libc::stat, r#mod: i64, dummy: &str) -> i32 {
    // c:3818
    let is_reg = (buf.st_mode as u32 & libc::S_IFMT as u32) == libc::S_IFREG as u32;
    let s_ixugo: u32 = (libc::S_IXUSR | libc::S_IXGRP | libc::S_IXOTH) as u32;
    (is_reg && (buf.st_mode as u32 & s_ixugo) != 0) as i32 // c:3820
}

/// Port of `static int g_units;` from `Src/glob.c`. Time/size unit
/// selector for the qualtime / qualsize qualifier predicates. Values
/// come from the TT_* enum (TT_DAYS=0, TT_HOURS=1, TT_MINS=2,
/// TT_WEEKS=3, TT_MONTHS=4 for time; TT_BYTES=0, TT_POSIX_BLOCKS=1,
/// TT_KILOBYTES=2, etc. for size).
pub static g_units: std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0);

/// Port of `static int g_range;` from `Src/glob.c`. Comparison
/// direction for qualtime / qualsize / qualnlink: -1 = `<`, 0 = `==`,
/// +1 = `>`. Set by the glob qualifier parser.
pub static g_range: std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0);

/// Port of `static int g_amc;` from `Src/glob.c`. Which mtime to read
/// for qualtime: 0 = atime, 1 = mtime, 2 = ctime. Set by the `am`,
/// `mm`, `cm` qualifier letters.
pub static g_amc: std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0);

/// Direct port of `static int qualsize(UNUSED(char *name),
/// struct stat *buf, off_t size, UNUSED(char *dummy))` from
/// `Src/glob.c:3825-3866`. Glob-qualifier predicate: returns true
/// when `buf->st_size` (scaled by `g_units`) compares to `size`
/// via `g_range`.
///
/// **Previous fakery:** the file held a same-named helper that was
/// actually a unit-conversion *parser* `(s, units) -> Option<(i64,
/// &str)>` — wrong shape, wrong semantics, zero callers. The
/// canonical C signature is restored here; the qualifier-eval site
/// at glob.rs:3914 already inlines the equivalent (uses
/// qualifier::Size struct fields) and is the live path.
#[allow(non_snake_case)]
pub fn qualsize(_name: &str, buf: &std::fs::Metadata, size: i64, _dummy: &str) -> bool {
    use std::os::unix::fs::MetadataExt;
    use std::sync::atomic::Ordering;
    // c:3831 `zlong scaled = buf->st_size;`
    let mut scaled: i64 = buf.size() as i64;
    // c:3837-3860 — switch (g_units) ceiling-divide by the unit.
    match g_units.load(Ordering::SeqCst) {
        x if x == TT_POSIX_BLOCKS => {
            scaled = (scaled + 511) / 512; // c:3838-3841
        }
        x if x == TT_KILOBYTES => {
            scaled = (scaled + 1023) / 1024; // c:3842-3845
        }
        x if x == TT_MEGABYTES => {
            scaled = (scaled + 1_048_575) / 1_048_576; // c:3846-3849
        }
        x if x == TT_GIGABYTES => {
            scaled = (scaled + 1_073_741_823) / 1_073_741_824; // c:3851-3854
        }
        x if x == TT_TERABYTES => {
            scaled = (scaled + 1_099_511_627_775) / 1_099_511_627_776; // c:3855-3858
        }
        _ => {} // c:3860 default: bytes — no scaling.
    }
    // c:3862-3864 — `g_range < 0 ? < : g_range > 0 ? > : ==`.
    let r = g_range.load(Ordering::SeqCst);
    if r < 0 {
        scaled < size
    } else if r > 0 {
        scaled > size
    } else {
        scaled == size
    }
}

/// Direct port of `static int qualtime(UNUSED(char *name),
/// struct stat *buf, off_t days, UNUSED(char *dummy))` from
/// `Src/glob.c:3870-3901`. Glob-qualifier predicate: returns true
/// when `now - buf->{a,m,c}time` (selected by `g_amc`, scaled by
/// `g_units`) compares to `days` via `g_range`.
///
/// **Previous fakery:** same misshapen parser as the qualsize one
/// above. Restored to C signature; the qualifier-eval site at
/// glob.rs:3940 already inlines the equivalent (uses qualifier::
/// Atime struct fields with the live atime/mtime/ctime read).
#[allow(non_snake_case)]
pub fn qualtime(_name: &str, buf: &std::fs::Metadata, days: i64, _dummy: &str) -> bool {
    use std::os::unix::fs::MetadataExt;
    use std::sync::atomic::Ordering;
    // c:3876-3878 — `time(&now); diff = now - (g_amc == 0 ? st_atime
    //                  : g_amc == 1 ? st_mtime : st_ctime);`
    let now: i64 = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0);
    let amc = g_amc.load(Ordering::SeqCst);
    let stamp: i64 = match amc {
        0 => buf.atime(), // c:3877
        1 => buf.mtime(), // c:3877
        _ => buf.ctime(), // c:3878
    };
    let mut diff: i64 = now - stamp;
    // c:3880-3896 — scale by g_units.
    match g_units.load(Ordering::SeqCst) {
        x if x == TT_DAYS => diff /= 86400,    // c:3881-3883
        x if x == TT_HOURS => diff /= 3600,    // c:3884-3886
        x if x == TT_MINS => diff /= 60,       // c:3887-3889
        x if x == TT_WEEKS => diff /= 604800,  // c:3890-3892
        x if x == TT_MONTHS => diff /= 2592000, // c:3893-3895
        _ => {}                                // c:3896 default: seconds.
    }
    // c:3898-3900 — same range comparison as qualsize.
    let r = g_range.load(Ordering::SeqCst);
    if r < 0 {
        diff < days
    } else if r > 0 {
        diff > days
    } else {
        diff == days
    }
}

/// Port of `static int qualsheval(char *name, UNUSED(struct stat *buf),
/// UNUSED(off_t days), char *str)` from `Src/glob.c:3907`.
///
/// C body (c:3907-3943):
/// ```c
/// if ((prog = parse_string(str, 0))) {
///     int ef = errflag, lv = lastval;             // c:3912 save
///     unsetparam("reply");                        // c:3915
///     setsparam("REPLY", ztrdup(name));           // c:3916
///     execode(prog, 1, 0, "globqual");            // c:3919
///     ret = lastval;                              // c:3921
///     errflag = ef | (errflag & ERRFLAG_INT);     // c:3924 restore
///     lastval = lv;                               // c:3925
///     return !ret;
/// }
/// return 0;
/// ```
///
/// The `e:EXPR:` glob qualifier runs `EXPR` against each match
/// candidate with `$REPLY` pre-set to the filename. The expr is
/// evaluated IN THE CURRENT SHELL — it can read shell locals,
/// reference shell functions, set $reply etc.
///
/// The previous Rust port spawned `/bin/sh -c <expr>` via
/// `Command::new("sh")`, which:
///   1. Loses access to current zsh function/alias/local-var scope.
///   2. Runs `sh` (POSIX), not `zsh` — entire `(e:zsh-feature:)`
///      class of qualifiers silently failed.
///   3. Skipped errflag/lastval save+restore.
///
/// Fixed: route through the canonical `ShellExecutor` for in-shell
/// evaluation. Set `REPLY` via paramtab (C `setsparam`), restore
/// `errflag`/`lastval` per c:3924-3925, mask any parse-time
/// ERRFLAG_ERROR while preserving ERRFLAG_INT (user interrupt).
/// WARNING: param names don't match C — Rust=(filename, expr) vs C=(name, buf, days, str)
pub fn qualsheval(filename: &str, expr: &str) -> bool {
    // c:3907
    // c:3912 — save errflag + lastval.
    let saved_errflag = errflag.load(Ordering::Relaxed); // c:3912
    let saved_lastval = LASTVAL.load(Ordering::Relaxed); // c:3912
                                                                                 // c:3915 — `unsetparam("reply");`
    crate::ported::params::unsetparam("reply"); // c:3915
                                                // c:3916 — `setsparam("REPLY", ztrdup(name));`. Set in the
                                                // canonical paramtab so the evaluated expression sees `$REPLY`.
    crate::ported::params::setsparam("REPLY", filename); // c:3916
                                                         // c:3919 — `execode(prog, 1, 0, "globqual");`. Route through the
                                                         // executor via the exec_hooks fn-ptr installed by
                                                         // fusevm_bridge at startup. Direct ShellExecutor reach-in
                                                         // from src/ported/ is forbidden — see memory
                                                         // feedback_no_exec_script_from_ported.
    let rc = crate::ported::exec_hooks::execute_script(expr).unwrap_or(1); // c:3919
    let ret = LASTVAL.load(Ordering::Relaxed); // c:3921 ret = lastval
    let _ = rc;
    // c:3924 — `errflag = ef | (errflag & ERRFLAG_INT);`. Restore
    // pre-call errflag plus any interrupt bit set during eval.
    let post_errflag = errflag.load(Ordering::Relaxed);
    errflag.store(
        saved_errflag | (post_errflag & ERRFLAG_INT),
        Ordering::Relaxed,
    ); // c:3924
       // c:3925 — `lastval = lv;`. Restore pre-call lastval.
    LASTVAL.store(saved_lastval, Ordering::Relaxed); // c:3925
                                                                             // c:3941 — `return !ret;` — qualifier passes iff lastval is 0.
    ret == 0
}

/// Port of `qualnonemptydir(char *name, struct stat *buf, UNUSED(off_t days), UNUSED(char *str))` from Src/glob.c:3948.
/// C: opendir(name) and check if any non-`.`/`..` entries exist.
pub fn qualnonemptydir(name: &str, buf: &libc::stat, days: i64, str: &str) -> i32 {
    // c:3948
    // c:3948 — `if (!S_ISDIR(buf->st_mode)) return 0;`
    if (buf.st_mode as u32 & libc::S_IFMT as u32) != libc::S_IFDIR as u32 {
        // c:3950
        return 0;
    }
    // c:3953-3964 — opendir + readdir loop, skip "." and ".." entries.
    match fs::read_dir(name) {
        Ok(entries) => entries.filter_map(|e| e.ok()).any(|e| {
            let n = e.file_name();
            let s = n.to_string_lossy();
            s != "." && s != ".."
        }) as i32,
        Err(_) => 0,
    }
}

// =====================================================================
// Thread-local glob option snapshot — race fix.
//
// `Src/glob.c` reads `isset(NULLGLOB)` / `isset(BAREGLOBQUAL)` / etc.
// inline at each callsite during a glob. In zsh those reads hit the
// thread-local C `opts[]` array (zsh is single-threaded). In zshrs
// they hit `OPTS_LIVE` — a process-wide `RwLock<HashMap>`.
//
// Embedders that snapshot/restore options around individual glob
// invocations on multiple threads (e.g. stryke's `StrykeGlobOptsGuard`
// + `glob_par` rayon parallelism) race: thread A sets bareglobqual=1,
// calls glob; while A is mid-parse, thread B's matching guard restores
// bareglobqual=0; A's qualifier-parse step sees bareglobqual=0 and
// drops the trailing `(N)` as a literal substring, producing false
// matches.
//
// Fix: snapshot every glob-relevant option ONCE at glob() entry into
// a thread-local cache, then read all isset() inside glob from the
// snapshot. The snapshot is dropped on glob exit via an RAII guard.
// Each thread's in-flight glob() sees a coherent set of options
// regardless of concurrent setopt/unsetopt on other threads.
// =====================================================================

/// Snapshot of glob-relevant zsh options taken at glob entry. Holds
/// the live `isset(...)` value for each option that the glob engine
/// or its helpers (`parse_qualifiers`, `scanner`, `scan_pattern`,
/// `sort_matches`, `glob_emit_path`) consult.
#[derive(Debug, Clone, Copy, Default)]
pub struct GlobOptSnapshot {
    pub bareglobqual: bool,
    pub braceccl: bool,
    pub caseglob: bool,
    pub extendedglob: bool,
    pub globdots: bool,
    pub globstarshort: bool,
    pub listtypes: bool,
    pub markdirs: bool,
    pub nullglob: bool,
    pub numericglobsort: bool,
}

/// RAII guard that drops the thread-local snapshot on scope exit.
/// Constructed by `enter_glob_scope()`. Nested glob calls on the
/// same thread reuse the outer snapshot (the guard's `populated`
/// field tracks whether we installed or just observed).
pub struct GlobOptsGuard {
    populated: bool,
}

/// Sort specifier flags
// `GlobSort` / `SortOrder` / `SortSpec` deleted — C uses bit-flag
// `int tp` in `struct globsort { int tp; char *exec; }` (Src/glob.c:155):
//   tp & ~GS_DESC selects the sort key (GS_NAME/GS_DEPTH/GS_EXEC/…),
//   tp & GS_DESC reverses direction (`O` vs `o` qualifier),
//   tp << GS_SHIFT carries the follow-link variants.
// All those bits already exist as i32 constants at glob.rs:33+
// (GS_NAME / GS_DEPTH / GS_SIZE / … / GS_DESC / GS_NONE / GS__SIZE /
// …). The enum + Ascending/Descending + struct triple-wrapper was a
// Rust-only convenience with no C counterpart; callers now operate
// on the raw i32 the same way `gmatchcmp()` at glob.c:936 does.

// `TimeUnit` / `SizeUnit` / `RangeOp` enums deleted — Rust-only
// wrappers around constants/chars that exist as raw values in C:
//   `TimeUnit::Seconds` → TT_SECONDS i32 (glob.c:126 → glob.rs:99)
//   `TimeUnit::Minutes` → TT_MINS (c:123)
//   `TimeUnit::Hours`   → TT_HOURS (c:122)
//   `TimeUnit::Days`    → TT_DAYS (c:121)
//   `TimeUnit::Weeks`   → TT_WEEKS (c:124)
//   `TimeUnit::Months`  → TT_MONTHS (c:125)
//   `SizeUnit::Bytes`   → TT_BYTES (c:128)
//   `SizeUnit::PosixBlocks` → TT_POSIX_BLOCKS (c:129)
//   `SizeUnit::Kilobytes`   → TT_KILOBYTES (c:130)
//   `SizeUnit::Megabytes`   → TT_MEGABYTES (c:131)
//   `SizeUnit::Gigabytes`   → TT_GIGABYTES (c:132)
//   `SizeUnit::Terabytes`   → TT_TERABYTES (c:133)
//   `RangeOp::Less`/`Equal`/`Greater` → raw chars `<` `=` `>`
//      (zsh's qgetnum at glob.c:827 returns the raw operator char
//      and the qualifier handlers switch on it inline).

/// A glob qualifier function
// Next qualifier, must match                                              // c:139
// Alternative set of qualifiers to match                                   // c:140
// Function to call to test match                                           // c:141
#[derive(Debug, Clone)]
/// One glob qualifier — Rust-extension sum type. C uses a linked
/// list of `struct qual` (`Src/zsh.h:140-152`) with function-pointer
/// `func` per node; each variant here maps to one of C's `q*` test
/// ported (`qisreg`, `qisdir`, `qowner`, `qtime`, ...) at
/// `Src/glob.c:1080-1340`. The full `struct qual` port + per-test fn
/// dispatch lives in a later phase; this enum keeps the parsed-form
/// the per-match filter inside `scanner()` (line 500) needs.
#[allow(non_camel_case_types)]
pub enum qualifier {
    /// File type qualifiers
    IsRegular,
    IsDirectory,
    IsSymlink,
    IsSocket,
    IsFifo,
    IsBlockDev,
    IsCharDev,
    IsDevice,
    IsExecutable,

    /// Permission qualifiers
    Readable,
    Writable,
    Executable,
    WorldReadable,
    WorldWritable,
    WorldExecutable,
    GroupReadable,
    GroupWritable,
    GroupExecutable,
    Setuid,
    Setgid,
    Sticky,

    /// Ownership qualifiers
    OwnedByEuid,
    OwnedByEgid,
    OwnedByUid(u32),
    OwnedByGid(u32),

    /// Numeric qualifiers with range. `unit` is a `TT_*` i32
    /// (glob.rs:99-113 / glob.c:121-133); `op` is the raw range
    /// operator char (`<`, `=`, `>`) — mirrors C's qgetnum which
    /// returns the operator char and the handler switches inline.
    Size {
        value: u64,
        unit: i32,
        op: char,
    },
    Links {
        value: u64,
        op: char,
    },
    Atime {
        value: i64,
        unit: i32,
        op: char,
    },
    Mtime {
        value: i64,
        unit: i32,
        op: char,
    },
    Ctime {
        value: i64,
        unit: i32,
        op: char,
    },

    /// Mode specification
    Mode {
        yes: u32,
        no: u32,
    },

    /// Device number
    Device(u64),

    /// Non-empty directory
    NonEmptyDir,

    /// Shell evaluation
    Eval(String),
}

// Misnamed `gmatchcmp(&str, &str)` deleted — was a Rust-only
// locale-aware string compare claiming to be the C qsort
// comparator. The real C `gmatchcmp(Gmatch, Gmatch)` at glob.c:936
// is now ported as `gmatchcmp(&GlobMatch, &GlobMatch, &[i32], bool)`
// below. The string-compare case the old name claimed routes
// through canonical `zstrcmp` (sort.c:191).

// `GlobOptions` struct deleted — Rust-only Bag-of-options with no
// C counterpart. C reads each option directly from the global
// `opts[]` array via `isset(NULL_GLOB)` / `isset(EXTENDED_GLOB)`
// / etc. (Src/options.c). The Rust port uses the canonical
// `opt_state_get(name) -> Option<bool>`
// which reads from the same global store. Inlined at each
// callsite as `opt_state_get("name").unwrap_or(default)`.

/// Parsed glob qualifier set
#[derive(Debug, Clone, Default)]
/// Compiled qualifier list for one glob.
/// Mirrors the `struct qual *` linked list `parsepat()`
/// (Src/glob.c:791) builds — every `(qual)` after a glob pattern
/// adds to it.
#[allow(non_camel_case_types)]
pub struct qualifier_set {
    // c:138
    pub qualifiers: Vec<qualifier>,
    pub alternatives: Vec<Vec<qualifier>>,
    pub negated: bool,
    pub follow_links: bool,
    /// Packed sort-spec flags, one per `o`/`O` qualifier in the pattern.
    /// Each entry is the C `struct globsort.tp` field — `GS_NAME` /
    /// `GS_DEPTH` / `GS_EXEC` / `GS_SIZE` / `GS_ATIME` / `GS_MTIME` /
    /// `GS_CTIME` / `GS_LINKS` (or their `<< GS_SHIFT` follow-link
    /// variants), OR'd with `GS_DESC` for reverse direction.
    pub sorts: Vec<i32>, // c:155 struct globsort.tp[]
    pub first: Option<i32>,
    pub last: Option<i32>,
    pub colon_mods: Option<String>,
    pub pre_words: Vec<String>,
    pub post_words: Vec<String>,
    /// `(M)` qualifier — append `/` to directory entries in output.
    /// Direct port of zsh/Src/glob.c:1557-1561 (`case 'M'`):
    ///   `gf_markdirs = !(sense & 1)` — set when the qualifier appears
    ///   without a `^` toggle. Stored per-qualifier-set rather than per
    ///   GlobOptions so a single glob call's qualifier picks it up.
    pub mark_dirs: bool,
    /// `(T)` qualifier — append type-char (ls -F style) to every entry.
    /// Direct port of zsh/Src/glob.c:1562-1566 (`case 'T'`).
    pub list_types: bool,
    /// `(N)` qualifier — per-glob nullglob: empty result on no-match,
    /// no error. Direct port of zsh/Src/glob.c:1567-1569 (`case 'N'`):
    ///   `gf_nullglob = !(sense & 1)` — set when `(N)` appears without
    ///   the `^` toggle.
    pub nullglob: bool,
}

/// Pattern component
#[derive(Debug, Clone)]
enum PatternComponent {
    Pattern(String),
    Recursive { follow_links: bool },
}

/// Enter a glob scope: snapshot options into TLS if no outer scope
/// is active, returning a guard that clears the snapshot on Drop.
/// Re-entrant calls (nested globdata_glob via brace expansion etc.)
/// return a no-op guard that observes the existing snapshot.
pub fn enter_glob_scope() -> GlobOptsGuard {
    let already = GLOB_OPTS_TLS.with_borrow(|g| g.is_some());
    if already {
        return GlobOptsGuard { populated: false };
    }
    let snap = GlobOptSnapshot::capture();
    GLOB_OPTS_TLS.with_borrow_mut(|g| *g = Some(snap));
    GlobOptsGuard { populated: true }
}

/// Read a glob-relevant option through the TLS snapshot when one is
/// active; fall back to the live `isset()` otherwise. Use this in
/// any glob-engine helper that previously read `isset(OPT)` for one
/// of the snapshotted options.
#[inline]
pub fn glob_isset(opt: i32) -> bool {
    GLOB_OPTS_TLS.with_borrow(|g| match g {
        Some(snap) => match opt {
            x if x == BAREGLOBQUAL => snap.bareglobqual,
            x if x == BRACECCL => snap.braceccl,
            x if x == CASEGLOB => snap.caseglob,
            x if x == EXTENDEDGLOB => snap.extendedglob,
            x if x == GLOBDOTS => snap.globdots,
            x if x == GLOBSTARSHORT => snap.globstarshort,
            x if x == LISTTYPES => snap.listtypes,
            x if x == MARKDIRS => snap.markdirs,
            x if x == NULLGLOB => snap.nullglob,
            x if x == NUMERICGLOBSORT => snap.numericglobsort,
            _ => isset(opt),
        },
        None => isset(opt),
    })
}

// ===========================================================
// `impl globdata` block above kept only for the `new()`
// constructor (Default-style). All scanner / parser / qualifier
// ported below are top-level — C glob.c has them as top-level
// statics that mutate the file-static `curglobdata`. Each is
// flagged with `// RUST-ONLY` and a comment naming the closest
// C equivalent + the proper-port target (typically `scanner`
// at glob.c:500 driving `insert` at c:346).
// ===========================================================

/// Main entry point: expand a glob pattern.
///
/// Closest C equivalent: `zglob` driver at glob.c:1214 calls
/// `parsepat` (c:791) and then `scanner` (c:500). The Rust port
/// here orchestrates qualifier parsing, brace expansion (which C
/// does separately in `xpandbraces`), and the Rust scanner
/// trio (`scanner`/`scan_pattern`/`scan_recursive`).
pub fn globdata_glob(state: &mut globdata, pattern: &str) -> Vec<String> {
    // RUST-ONLY
    // Brace pre-expansion. In zsh, `xpandbraces` (zsh/Src/glob.c:2275)
    // runs during substitution before glob — patterns reaching glob()
    // are already brace-free in the production path (vm_helper handles
    // it). For direct programmatic callers of glob_with_options, run
    // the brace pass here so `GlobOptions.brace_ccl` is actually
    // consulted: with brace_ccl set, `{a-mnop}` expands to a..m,n,o,p
    // per glob.c:2424 BRACECCL block; without, only `{a,b}` lists and
    // `{1..5}`/`{a..e}` ranges expand. Recurse on each variant and
    // concatenate matches.
    let brace_ccl = glob_isset(BRACECCL);
    if hasbraces(pattern, brace_ccl) {
        let mut all = Vec::new();
        for variant in xpandbraces(pattern, brace_ccl) {
            all.extend(globdata_glob(state, &variant));
        }
        return all;
    }

    state.matches.clear();
    state.pathbuf.clear();
    state.pathpos = 0;

    // Parse qualifiers first so a bare-qualifier pattern like `dir(/)`
    // (no wildcard, just a stat-based filter) still enters the expansion
    // path. Without this, `haswilds("dir(/)")` returns false and the
    // pattern echoes back unfiltered, which defeats the whole point of
    // qualifiers.
    let (pat, quals) = parse_qualifiers(pattern);
    state.qualifiers = quals;

    // Now check wildcards on the qualifier-stripped pattern. A pure
    // literal with a qualifier (`name(.)`) still needs to enter the
    // scanner so the qualifier filter can run against the literal name.
    if !haswilds(&pat) && state.qualifiers.is_none() {
        return vec![pattern.to_string()];
    }

    // Parse the pattern into components
    if let Some(complist) = parse_pattern(&pat) {
        // Handle absolute vs relative paths
        if pat.starts_with('/') {
            state.pathbuf.push('/');
            state.pathpos = 1;
        }

        // Do the actual globbing
        scanner(state, &complist, 0);
    }

    // Sort results
    sort_matches(state);

    // Apply subscript selection
    apply_selection(state);

    // Extract filenames. Mark-dirs / list-types come from EITHER
    // the canonical global option store OR the parsed `(M)`/`(T)`
    // qualifier on this glob. Direct port of zsh/Src/glob.c:355,372
    // — output marker emission consults the per-glob `gf_markdirs`
    // / `gf_listtypes` flags which the qualifier parser at
    // glob.c:1557-1566 sets.
    let mark_dirs = glob_isset(MARKDIRS)
        || state
            .qualifiers
            .as_ref()
            .map(|q| q.mark_dirs)
            .unwrap_or(false);
    // c:1562-1566 — `gf_listtypes` is set ONLY by the `T` glob
    // qualifier (`*(T)`), NOT by the global LISTTYPES option.
    // LISTTYPES is the completion-listing option (see man zshoptions
    // "LIST_TYPES") and doesn't affect glob output. Including the
    // option here mis-decorated every executable-file glob with a
    // trailing `*` and every directory with `/` for users with the
    // default `setopt listtypes` ON.
    let list_types = state
        .qualifiers
        .as_ref()
        .map(|q| q.list_types)
        .unwrap_or(false);
    let colon_mods = state.qualifiers.as_ref().and_then(|q| q.colon_mods.clone());
    let mut results: Vec<String> = state
        .matches
        .iter()
        .map(|m| {
            let mut s = glob_emit_path(&m.path);
            if mark_dirs || list_types {
                if let Ok(meta) = fs::symlink_metadata(&m.path) {
                    let ch = file_type(meta.mode());
                    if list_types || (mark_dirs && ch == '/') {
                        s.push(ch);
                    }
                }
            }
            // Apply colon modifiers AFTER mark/list-type appendage —
            // zsh applies them last in glob.c:432 modify() per emitted
            // node, so `(M:t)` would mark THEN tail (effectively just
            // tail since the slash is gone). Faithful order.
            if let Some(ref m) = colon_mods {
                // Delegate to canonical `modify()` port in subst.rs
                // (Src/subst.c:4531). Local colon-modifier impl was
                // an invented duplicate — removed.
                s = crate::ported::subst::modify(&s, m);
            }
            s
        })
        .collect();

    // c:Src/glob.c:1872-1888 — no-match path. Return Vec::new() so
    // the caller (vm_helper.rs::expand_glob) drives the
    // NULLGLOB / NOMATCH / literal-fallback policy. Previously
    // this pushed `pattern.to_string()` on no-match, which made
    // `expand_glob` see a non-empty result and skip the NOMATCH
    // check entirely. zsh's `setopt nomatch` is on by default, so
    // `echo /never_real/*` should emit "no matches found" and
    // exit 1 — not silently print the literal. Parity bug #13
    // recurrence. Per-glob `(N)` qualifier (nullglob_per_qual)
    // and global NULLGLOB are now consulted in expand_glob too.
    let _ = state.qualifiers.as_ref().map(|q| q.nullglob);
    results
}

// `sort_matches_by_type` deleted — dead code (no callers anywhere
// in the tree). The sort path lives in `GlobMatch::compare` which
// dispatches off the canonical `GS_*` tp bits exactly like C's
// `gmatchcmp()` at glob.c:936.

/// File qualifier test functions (from glob.c qual* functions)
pub mod qualifiers {
    use std::os::unix::fs::MetadataExt;

    pub fn is_regular(path: &str) -> bool {
        std::fs::metadata(path)
            .map(|m| m.is_file())
            .unwrap_or(false)
    }

    pub fn is_directory(path: &str) -> bool {
        std::fs::metadata(path).map(|m| m.is_dir()).unwrap_or(false)
    }

    pub fn is_symlink(path: &str) -> bool {
        std::fs::symlink_metadata(path)
            .map(|m| m.file_type().is_symlink())
            .unwrap_or(false)
    }

    pub fn is_fifo(path: &str) -> bool {
        std::fs::metadata(path)
            .map(|m| (m.mode() & libc::S_IFMT as u32) == libc::S_IFIFO as u32)
            .unwrap_or(false)
    }

    pub fn is_socket(path: &str) -> bool {
        std::fs::metadata(path)
            .map(|m| (m.mode() & libc::S_IFMT as u32) == libc::S_IFSOCK as u32)
            .unwrap_or(false)
    }

    pub fn is_block_device(path: &str) -> bool {
        std::fs::metadata(path)
            .map(|m| (m.mode() & libc::S_IFMT as u32) == libc::S_IFBLK as u32)
            .unwrap_or(false)
    }

    pub fn is_char_device(path: &str) -> bool {
        std::fs::metadata(path)
            .map(|m| (m.mode() & libc::S_IFMT as u32) == libc::S_IFCHR as u32)
            .unwrap_or(false)
    }

    pub fn is_setuid(path: &str) -> bool {
        std::fs::metadata(path)
            .map(|m| (m.mode() & libc::S_ISUID as u32) != 0)
            .unwrap_or(false)
    }

    pub fn is_setgid(path: &str) -> bool {
        std::fs::metadata(path)
            .map(|m| (m.mode() & libc::S_ISGID as u32) != 0)
            .unwrap_or(false)
    }

    pub fn is_sticky(path: &str) -> bool {
        std::fs::metadata(path)
            .map(|m| (m.mode() & libc::S_ISVTX as u32) != 0)
            .unwrap_or(false)
    }

    pub fn is_readable(path: &str) -> bool {
        std::fs::metadata(path).is_ok() && std::fs::File::open(path).is_ok()
    }

    pub fn is_writable(path: &str) -> bool {
        std::fs::OpenOptions::new().write(true).open(path).is_ok()
    }

    pub fn is_executable(path: &str) -> bool {
        std::fs::metadata(path)
            .map(|m| (m.mode() & 0o111) != 0)
            .unwrap_or(false)
    }

    pub fn size_matches(path: &str, size: u64, cmp: std::cmp::Ordering) -> bool {
        std::fs::metadata(path)
            .map(|m| m.len().cmp(&size) == cmp)
            .unwrap_or(false)
    }

    pub fn mtime_matches(path: &str, secs: i64, cmp: std::cmp::Ordering) -> bool {
        std::fs::metadata(path)
            .and_then(|m| m.modified())
            .map(|t| {
                let elapsed = t.elapsed().map(|d| d.as_secs() as i64).unwrap_or(0);
                elapsed.cmp(&secs) == cmp
            })
            .unwrap_or(false)
    }

    pub fn uid_matches(path: &str, uid: u32) -> bool {
        std::fs::metadata(path)
            .map(|m| m.uid() == uid)
            .unwrap_or(false)
    }

    pub fn gid_matches(path: &str, gid: u32) -> bool {
        std::fs::metadata(path)
            .map(|m| m.gid() == gid)
            .unwrap_or(false)
    }

    pub fn nlinks_matches(path: &str, nlinks: u64, cmp: std::cmp::Ordering) -> bool {
        std::fs::metadata(path)
            .map(|m| m.nlink().cmp(&nlinks) == cmp)
            .unwrap_or(false)
    }

    /// Check if file is an executable command (from glob.c qualiscom)
    pub fn is_command(path: &str) -> bool {
        let meta = match std::fs::metadata(path) {
            Ok(m) => m,
            Err(_) => return false,
        };

        if !meta.is_file() {
            return false;
        }

        // Check if executable
        let mode = meta.mode();
        if mode & 0o111 == 0 {
            return false;
        }

        // Check if in PATH would make it a command
        // For now just check executable bit
        true
    }
}

// ============================================================================
// Pattern matching with replacement (from glob.c getmatch family)
// ============================================================================

// `MatchFlags` deleted — Rust-only bool-bag wrapper. C uses bare
// `int fl` with `SUB_*` bits from `Src/zsh.h:1981+` (mirrored at
// `zsh_h.rs:2463+`). Callers now pass an `i32` and test bits.

/// Internal match data — port of `struct imatchdata` from
/// `Src/glob.c:1751` (the local helper used by `igetmatch` and
/// friends). C fields: `imd->ustr/imd->upat/imd->mb_ind/...`. Rust
/// keeps a trimmed shape (the parts call sites actually use).
#[allow(non_camel_case_types)]
#[derive(Debug, Clone)]
pub struct imatchdata {
    pub str: String,
    pub pattern: String,
    pub match_start: usize,
    pub match_end: usize,
    pub replacement: Option<String>,
}

/// Strip a trailing `(qual)` block from a glob pattern.
/// **RUST-ONLY** — C glob.c handles qualifier parsing inline in
/// `parsepat` (c:791) as it builds the Complist. Move to that
/// shape when porting parsepat for real.
pub fn parse_qualifiers(pattern: &str) -> (String, Option<qualifier_set>) {
    // RUST-ONLY
    if !pattern.ends_with(')') {
        return (pattern.to_string(), None);
    }

    // Find matching open paren
    let bytes = pattern.as_bytes();
    let mut depth = 0;
    let mut qual_start = None;

    for i in (0..bytes.len()).rev() {
        match bytes[i] {
            b')' => depth += 1,
            b'(' => {
                depth -= 1;
                if depth == 0 {
                    qual_start = Some(i);
                    break;
                }
            }
            _ => {}
        }
    }

    let start = match qual_start {
        Some(s) => s,
        None => return (pattern.to_string(), None),
    };

    // Check for (#q...) explicit qualifier syntax
    let qual_str = &pattern[start + 1..pattern.len() - 1];
    let (is_explicit, qual_content) = if let Some(after) = qual_str.strip_prefix("#q") {
        (true, after)
    } else if glob_isset(BAREGLOBQUAL) {
        (false, qual_str)
    } else {
        return (pattern.to_string(), None);
    };

    // Don't parse as qualifiers if it contains | or ~ (alternatives/exclusions)
    if !is_explicit && (qual_content.contains('|') || qual_content.contains('~')) {
        return (pattern.to_string(), None);
    }

    // Parse the qualifiers
    let qs = parse_qualifier_string(qual_content);
    (pattern[..start].to_string(), Some(qs))
}

/// Parse the body of a `(...)` qualifier block into a qualifier_set.
/// **RUST-ONLY** — see header on `parse_qualifiers`.
fn parse_qualifier_string(s: &str) -> qualifier_set {
    // RUST-ONLY
    let mut qs = qualifier_set::default();
    let mut chars = s.chars().peekable();
    let mut negated = false;
    let mut follow = false;

    while let Some(c) = chars.next() {
        match c {
            '^' => negated = !negated,
            '-' => follow = !follow,
            ',' => {
                // Start new alternative
                if !qs.qualifiers.is_empty() {
                    qs.alternatives.push(std::mem::take(&mut qs.qualifiers));
                }
                negated = false;
                follow = false;
            }
            ':' => {
                // Colon modifiers - rest of string
                let rest: String = chars.collect();
                qs.colon_mods = Some(format!(":{}", rest));
                break;
            }
            // File type qualifiers
            '/' => qs.qualifiers.push(qualifier::IsDirectory),
            '.' => qs.qualifiers.push(qualifier::IsRegular),
            '@' => qs.qualifiers.push(qualifier::IsSymlink),
            '=' => qs.qualifiers.push(qualifier::IsSocket),
            'p' => qs.qualifiers.push(qualifier::IsFifo),
            '%' => match chars.peek() {
                Some('b') => {
                    chars.next();
                    qs.qualifiers.push(qualifier::IsBlockDev);
                }
                Some('c') => {
                    chars.next();
                    qs.qualifiers.push(qualifier::IsCharDev);
                }
                _ => qs.qualifiers.push(qualifier::IsDevice),
            },
            '*' => qs.qualifiers.push(qualifier::IsExecutable),
            // Permission qualifiers
            'r' => qs.qualifiers.push(qualifier::Readable),
            'w' => qs.qualifiers.push(qualifier::Writable),
            'x' => qs.qualifiers.push(qualifier::Executable),
            'R' => qs.qualifiers.push(qualifier::WorldReadable),
            'W' => qs.qualifiers.push(qualifier::WorldWritable),
            'X' => qs.qualifiers.push(qualifier::WorldExecutable),
            'A' => qs.qualifiers.push(qualifier::GroupReadable),
            'I' => qs.qualifiers.push(qualifier::GroupWritable),
            'E' => qs.qualifiers.push(qualifier::GroupExecutable),
            's' => qs.qualifiers.push(qualifier::Setuid),
            'S' => qs.qualifiers.push(qualifier::Setgid),
            't' => qs.qualifiers.push(qualifier::Sticky),
            // Ownership
            'U' => qs.qualifiers.push(qualifier::OwnedByEuid),
            'G' => qs.qualifiers.push(qualifier::OwnedByEgid),
            'u' => {
                let uid = parse_uid_gid(&mut chars);
                qs.qualifiers.push(qualifier::OwnedByUid(uid));
            }
            'g' => {
                let gid = parse_uid_gid(&mut chars);
                qs.qualifiers.push(qualifier::OwnedByGid(gid));
            }
            // Size
            'L' => {
                let (unit, op, val) = parse_size_spec(&mut chars);
                qs.qualifiers.push(qualifier::Size {
                    value: val,
                    unit,
                    op,
                });
            }
            // Link count
            'l' => {
                let (op, val) = parse_range_spec(&mut chars);
                qs.qualifiers.push(qualifier::Links { value: val, op });
            }
            // Times
            'a' => {
                let (unit, op, val) = schedgetfn(&mut chars);
                qs.qualifiers.push(qualifier::Atime {
                    value: val as i64,
                    unit,
                    op,
                });
            }
            'm' => {
                let (unit, op, val) = schedgetfn(&mut chars);
                qs.qualifiers.push(qualifier::Mtime {
                    value: val as i64,
                    unit,
                    op,
                });
            }
            'c' => {
                let (unit, op, val) = schedgetfn(&mut chars);
                qs.qualifiers.push(qualifier::Ctime {
                    value: val as i64,
                    unit,
                    op,
                });
            }
            // Sort qualifier — `o<key>` ascending / `O<key>`
            // descending. Mirrors the parser arm in zsh's glob.c
            // that builds `struct globsort` entries (tp = GS_* OR
            // GS_DESC, optionally shifted by GS_SHIFT for the
            // follow-links variant).
            'o' | 'O' => {
                let desc = c == 'O';
                if let Some(&sc) = chars.peek() {
                    let key: i32 = match sc {
                        'n' => {
                            chars.next();
                            GS_NAME
                        }
                        'L' => {
                            chars.next();
                            GS_SIZE
                        }
                        'l' => {
                            chars.next();
                            GS_LINKS
                        }
                        'a' => {
                            chars.next();
                            GS_ATIME
                        }
                        'm' => {
                            chars.next();
                            GS_MTIME
                        }
                        'c' => {
                            chars.next();
                            GS_CTIME
                        }
                        'd' => {
                            chars.next();
                            GS_DEPTH
                        }
                        'N' => {
                            chars.next();
                            GS_NONE
                        }
                        _ => GS_NAME,
                    };
                    let shifted = if follow && (key & GS_NORMAL) != 0 {
                        key << GS_SHIFT
                    } else {
                        key
                    };
                    let tp = shifted | (if desc { GS_DESC } else { 0 });
                    qs.sorts.push(tp);
                }
            }
            // Flags
            // c:1567-1569 — `case 'N': gf_nullglob = !(sense & 1);`.
            // Per-glob nullglob: empty result on no-match, no error.
            'N' => qs.nullglob = !negated,
            'D' => { /* dotglob handled elsewhere */ }
            'n' => { /* numsort handled elsewhere */ }
            // (M) / (T) — set per-qualifier-set flags. glob.c:1557-1566:
            //   case 'M': gf_markdirs = !(sense & 1);  break;
            //   case 'T': gf_listtypes = !(sense & 1); break;
            // `sense & 1` = the `^`-toggle bit. zshrs's parser tracks
            // `negated`; mirror by `!negated`. Read at output-emit
            // time to mark dirs / list types like coreutils ls -F.
            'M' => qs.mark_dirs = !negated,
            'T' => qs.list_types = !negated,
            'F' => qs.qualifiers.push(qualifier::NonEmptyDir),
            // Subscript
            '[' => {
                let (first, last) = parse_subscript(&mut chars);
                qs.first = first;
                qs.last = last;
            }
            _ => {}
        }
    }

    if !qs.qualifiers.is_empty() {
        qs.alternatives.push(std::mem::take(&mut qs.qualifiers));
    }

    qs.negated = negated;
    qs.follow_links = follow;
    qs
}

/// Parse a numeric uid/gid from a qualifier char stream.
/// **RUST-ONLY** — C parses these inline in parsepat.
fn parse_uid_gid(chars: &mut std::iter::Peekable<std::str::Chars>) -> u32 {
    // RUST-ONLY
    // Check for numeric or delimited string
    if chars.peek().map(|c| c.is_ascii_digit()).unwrap_or(false) {
        let mut num = String::new();
        while let Some(&c) = chars.peek() {
            if c.is_ascii_digit() {
                num.push(c);
                chars.next();
            } else {
                break;
            }
        }
        num.parse().unwrap_or(0)
    } else {
        // Delimited name - skip for now
        0
    }
}

/// Parse the unit/op/value tail of an `(L...)` size qualifier.
/// **RUST-ONLY** — C parses inline in parsepat; the size-unit
/// constants are `TT_BYTES`/`TT_KILOBYTES`/… at glob.c:128-133.
fn parse_size_spec(
    // RUST-ONLY
    chars: &mut std::iter::Peekable<std::str::Chars>,
) -> (i32, char, u64) {
    let unit: i32 = match chars.peek() {
        Some('p') | Some('P') => {
            chars.next();
            TT_POSIX_BLOCKS
        }
        Some('k') | Some('K') => {
            chars.next();
            TT_KILOBYTES
        }
        Some('m') | Some('M') => {
            chars.next();
            TT_MEGABYTES
        }
        Some('g') | Some('G') => {
            chars.next();
            TT_GIGABYTES
        }
        Some('t') | Some('T') => {
            chars.next();
            TT_TERABYTES
        }
        _ => TT_BYTES,
    };
    let (op, val) = parse_range_spec(chars);
    (unit, op, val)
}

/// Parse the unit/op/value tail of an `(a/m/c...)` time qualifier.
/// **RUST-ONLY** — C parses inline in parsepat; time-unit constants
/// are `TT_SECONDS`/`TT_MINS`/… at glob.c:121-126.
fn schedgetfn(
    // RUST-ONLY (clashes with sched.c:341 name, unrelated fn)
    chars: &mut std::iter::Peekable<std::str::Chars>,
) -> (i32, char, u64) {
    let unit: i32 = match chars.peek() {
        Some('s') => {
            chars.next();
            TT_SECONDS
        }
        Some('m') => {
            chars.next();
            TT_MINS
        }
        Some('h') => {
            chars.next();
            TT_HOURS
        }
        Some('d') => {
            chars.next();
            TT_DAYS
        }
        Some('w') => {
            chars.next();
            TT_WEEKS
        }
        Some('M') => {
            chars.next();
            TT_MONTHS
        }
        _ => TT_DAYS,
    };
    let (op, val) = parse_range_spec(chars);
    (unit, op, val)
}

/// Parse `[+-]?NUMBER` operator+value tail. Mirrors C qgetnum
/// (glob.c:827) which returns the int value; here we return the
/// operator char along with the value since callers need both.
fn parse_range_spec(chars: &mut std::iter::Peekable<std::str::Chars>) -> (char, u64) {
    // RUST-ONLY
    // C's qgetnum at glob.c:827 returns the operator char inline.
    // `+N` = greater, `-N` = less, bare digits = equal.
    let op: char = match chars.peek() {
        Some('+') => {
            chars.next();
            '>'
        }
        Some('-') => {
            chars.next();
            '<'
        }
        _ => '=',
    };
    let mut num = String::new();
    while let Some(&c) = chars.peek() {
        if c.is_ascii_digit() {
            num.push(c);
            chars.next();
        } else {
            break;
        }
    }
    let val = num.parse().unwrap_or(0);
    (op, val)
}

/// Parse `[FIRST,LAST]` subscript range. **RUST-ONLY**.
fn parse_subscript(
    // RUST-ONLY
    chars: &mut std::iter::Peekable<std::str::Chars>,
) -> (Option<i32>, Option<i32>) {
    let mut first_str = String::new();
    let mut last_str = String::new();
    let mut in_last = false;

    while let Some(&c) = chars.peek() {
        chars.next();
        if c == ']' {
            break;
        } else if c == ',' {
            in_last = true;
        } else if in_last {
            last_str.push(c);
        } else {
            first_str.push(c);
        }
    }

    let first = first_str.parse().ok();
    let last = if in_last {
        last_str.parse().ok()
    } else {
        first
    };
    (first, last)
}

/// Tokenize a glob pattern into `PatternComponent`s.
/// **RUST-ONLY** — C uses `parsecomplist` (glob.c:710) which emits
/// a `struct complist` linked list; this Rust port builds a Vec
/// of `PatternComponent` enum variants instead.
fn parse_pattern(pattern: &str) -> Option<Vec<PatternComponent>> {
    // RUST-ONLY
    let mut components = Vec::new();
    let mut current = String::new();
    let mut chars = pattern.chars().peekable();
    let mut in_bracket = false;

    // Skip leading slash for absolute paths
    if chars.peek() == Some(&'/') {
        chars.next();
    }

    while let Some(c) = chars.next() {
        match c {
            '/' if !in_bracket => {
                if !current.is_empty() {
                    components.push(PatternComponent::Pattern(current.clone()));
                    current.clear();
                }
            }
            '[' => {
                in_bracket = true;
                current.push(c);
            }
            ']' => {
                in_bracket = false;
                current.push(c);
            }
            '*' if !in_bracket && chars.peek() == Some(&'*') => {
                chars.next();
                // Check for ***
                let follow = chars.peek() == Some(&'*');
                if follow {
                    chars.next();
                }
                // Direct port of zsh/Src/glob.c:717-742 parsecomplist:
                // `**` is recursive ONLY when followed by `/` (or `***/`,
                // or when GLOBSTARSHORT is set). Without those, it should
                // collapse to a literal `*` + `*` pair (which the matcher
                // treats as a single `*` since `**` ≡ `*` for non-recursive
                // contexts in zsh). The glob_star_short option flips the
                // strict gate off so bare `**` recurses without `/`.
                let has_slash = chars.peek() == Some(&'/');
                let recursive =
                    has_slash || follow || glob_isset(GLOBSTARSHORT);
                if has_slash {
                    chars.next();
                }
                if recursive {
                    if !current.is_empty() {
                        components.push(PatternComponent::Pattern(current.clone()));
                        current.clear();
                    }
                    components.push(PatternComponent::Recursive {
                        follow_links: follow,
                    });
                    // GLOBSTARSHORT semantics — zsh/Src/glob.c:727-730
                    // `instr += ((shortglob ? 1 : 3) + follow);` leaves
                    // ONE `*` in place when entering the recursive path
                    // without a `/` separator, so `**.c` ≡ `**/*.c` and
                    // `**foo` ≡ `**/*foo`. Without this prepend, the
                    // remaining segment was parsed literally — `**.stk`
                    // became [Recursive, Pattern(".stk")], which only
                    // matched files literally named `.stk`. Gate on
                    // `!has_slash && !follow` since `**/X` and `***/X`
                    // already consumed their separator and don't need
                    // the glue star.
                    if !has_slash && !follow && chars.peek().is_some() && chars.peek() != Some(&'/')
                    {
                        current.push('*');
                    }
                } else {
                    // Strict zsh: `**foo` (no slash, no shortglob) is
                    // a literal pair of stars in the same path component.
                    // Two `*` collapse to one in zsh pattern semantics.
                    current.push('*');
                }
            }
            _ => current.push(c),
        }
    }

    if !current.is_empty() {
        components.push(PatternComponent::Pattern(current));
    }

    // Trailing `**` (or `**/`) with no following pattern — without an
    // implicit `*`, the scanner walks the tree but emits nothing, since
    // `Pattern` components are what produce match output. zshrs synthesis
    // direction (per CLAUDE.md): absorb good ideas from other shells. Both
    // zsh-strict (`**` ≡ `*` top-level) and bash-globstar (`**` ≡ `**/*`
    // recursive) are reasonable; we pick the bash-globstar interpretation
    // because `**` empty-handed should mean "everything", and `*` already
    // exists for the top-level case. A user wanting top-level only writes
    // `*`, never `**`. This makes `**(/)` ≡ "every directory recursively"
    // and `**(.)` ≡ "every file recursively" — the readings users reach
    // for first.
    if let Some(PatternComponent::Recursive { .. }) = components.last() {
        components.push(PatternComponent::Pattern("*".to_string()));
    }

    if components.is_empty() {
        None
    } else {
        Some(components)
    }
}

/// One-component scanner — match `pattern` against entries in `base`.
///
/// Body mirrors C `scanner()` glob.c:580-694 (the
/// `else { /* Do pattern matching on current path section */ }`
/// arm). Now with the chdir-based path descent + 3 `zerr("current
/// directory lost during glob")` emissions when:
///   - the accumulated path would exceed PATH_MAX and `lchdir` fails (c:539-541)
///   - the discovered match path likewise exceeds PATH_MAX and `lchdir` fails (c:608-610)
///   - `restoredir` fails at the end of the walk (c:696-697)
fn scan_pattern(
    state: &mut globdata,
    base: &str,
    pattern: &str,
    rest: &[PatternComponent],
    depth: usize,
) {
    // c:580
    let pbcwdsav = state.pathbufcwd; // c:504
    let mut ds = init_dirsav(); // c:510
    let path_max = crate::ported::zsh_system_h::PATH_MAX;

    let dir = match fs::read_dir(base) {
        Ok(d) => d,
        Err(_) => return,
    };

    for entry in dir.flatten() {
        let name = entry.file_name().to_string_lossy().to_string();

        // Skip hidden files unless pattern starts with `.`. The bash
        // alias `dotglob` resolves to `globdots` in zsh (per
        // OPT_ALIAS entry at options.c:270); we read only the canonical name.
        let no_glob_dots = !glob_isset(GLOBDOTS);
        if no_glob_dots && name.starts_with('.') && !pattern.starts_with('.') {
            continue;
        }
        let extended_glob = glob_isset(EXTENDEDGLOB);
        let case_glob = glob_isset(CASEGLOB);
        if matchpat(pattern, &name, extended_glob, case_glob) {
            let path = entry.path();

            if rest.is_empty() {
                // c:666-672 — final filename component, insert via the
                // qualifier-aware match-list push. Symlink targets get
                // their own stat for the GS_LINKED (follow-link) sort
                // variants.
                if check_qualifiers(state, &path) {
                    if let Ok(meta) = fs::symlink_metadata(&path) {
                        let name = path
                            .file_name()
                            .map(|n| n.to_string_lossy().to_string())
                            .unwrap_or_default();
                        let (tsize, tatime, tmtime, tctime, tlinks) =
                            if meta.file_type().is_symlink() {
                                if let Ok(tm) = fs::metadata(&path) {
                                    (tm.size(), tm.atime(), tm.mtime(), tm.ctime(), tm.nlink())
                                } else {
                                    (
                                        meta.size(),
                                        meta.atime(),
                                        meta.mtime(),
                                        meta.ctime(),
                                        meta.nlink(),
                                    )
                                }
                            } else {
                                (
                                    meta.size(),
                                    meta.atime(),
                                    meta.mtime(),
                                    meta.ctime(),
                                    meta.nlink(),
                                )
                            };
                        state.matches.push(gmatch {
                            name,
                            path: path.to_path_buf(),
                            size: meta.size(),
                            atime: meta.atime(),
                            mtime: meta.mtime(),
                            ctime: meta.ctime(),
                            links: meta.nlink(),
                            mode: meta.mode(),
                            uid: meta.uid(),
                            gid: meta.gid(),
                            dev: meta.dev(),
                            ino: meta.ino(),
                            target_size: tsize,
                            target_atime: tatime,
                            target_mtime: tmtime,
                            target_ctime: tctime,
                            target_links: tlinks,
                            sort_strings: Vec::new(),
                        });
                        state.matchct += 1; // c:gd_matchct++
                    }
                }
            } else {
                // c:599-613 — discovered name lengthens path; if the
                // accumulated path > PATH_MAX, descend into the cwd
                // with lchdir so further reads use shorter paths.
                if pbcwdsav == state.pathbufcwd
                    && name.len() + state.pathpos - state.pathbufcwd as usize >= path_max
                {
                    let cwd_anchor = state.pathbuf.get(state.pathbufcwd as usize..).unwrap_or("");
                    match lchdir(cwd_anchor) {
                        Ok(()) => {
                            state.pathbufcwd = state.pathpos as i32; // c:612
                        }
                        Err(_) => {
                            // c:608-610 — `zerr("current directory lost
                            // during glob"); break;` — restoredir at the
                            // end runs unconditionally so we abandon the
                            // walk cleanly.
                            zerr("current directory lost during glob");
                            break;
                        }
                    }
                }
                // c:614 — recurse into subdir.
                if path.is_dir() {
                    let old_pos = state.pathbuf.len();
                    if !state.pathbuf.is_empty() && !state.pathbuf.ends_with('/') {
                        state.pathbuf.push('/');
                    }
                    state.pathbuf.push_str(&name);
                    state.pathpos = state.pathbuf.len();
                    scanner(state, rest, depth + 1);
                    state.pathbuf.truncate(old_pos);
                    state.pathpos = old_pos;
                }
            }
        }
    }
    // c:695-702 — restore cwd if we lchdir'd partway through this walk.
    if pbcwdsav < state.pathbufcwd {
        if restoredir(&mut ds) != 0 {
            zerr("current directory lost during glob"); // c:697
        }
        state.pathbufcwd = pbcwdsav; // c:701
    }
    let _ = (depth, base); // suppress unused warnings
}

/// Recursive `**`-style descent matching `rest` from every
/// descendant directory of `base`.
/// **RUST-ONLY** — C handles recursion via the `closure` bit on
/// each `struct complist` node, not via a separate function.
fn scan_recursive(
    // RUST-ONLY
    state: &mut globdata,
    base: &str,
    rest: &[PatternComponent],
    follow_links: bool,
    depth: usize,
) {
    let dir = match fs::read_dir(base) {
        Ok(d) => d,
        Err(_) => return,
    };

    for entry in dir.flatten() {
        let name = entry.file_name().to_string_lossy().to_string();

        // Skip hidden files (bash `dotglob` aliases to zsh
        // `globdots` per OPT_ALIAS entry at options.c:270).
        if !glob_isset(GLOBDOTS) && name.starts_with('.') {
            continue;
        }

        let path = entry.path();
        let is_dir = if follow_links {
            path.is_dir()
        } else {
            entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false)
        };

        if is_dir {
            let old_pos = state.pathbuf.len();
            if !state.pathbuf.is_empty() && !state.pathbuf.ends_with('/') {
                state.pathbuf.push('/');
            }
            state.pathbuf.push_str(&name);

            // Try matching rest from this directory
            scanner(state, rest, depth + 1);

            // Continue recursing
            let next_base = state.pathbuf.clone();
            scan_recursive(state, &next_base, rest, follow_links, depth + 1);

            state.pathbuf.truncate(old_pos);
        }
    }
}

/// Drive the OR-of-AND qualifier filter against `path`. **RUST-ONLY**
/// — C glob.c does qualifier eval inline inside `insert()` (c:381+).
fn check_qualifiers(state: &globdata, path: &Path) -> bool {
    // RUST-ONLY
    let qs = match &state.qualifiers {
        Some(q) => q,
        None => return true,
    };

    if qs.alternatives.is_empty() {
        return true;
    }

    let meta = match if qs.follow_links {
        fs::metadata(path)
    } else {
        fs::symlink_metadata(path)
    } {
        Ok(m) => m,
        Err(_) => return false,
    };

    // Check each alternative (OR)
    for alt in &qs.alternatives {
        if check_qualifier_list(alt, path, &meta) {
            return !qs.negated;
        }
    }

    qs.negated
}

/// AND-chain of qualifiers — all must match. **RUST-ONLY**.
fn check_qualifier_list(quals: &[qualifier], path: &Path, meta: &Metadata) -> bool {
    // RUST-ONLY
    for q in quals {
        if !check_single_qualifier(q, path, meta) {
            return false;
        }
    }
    true
}

/// One qualifier check against (path, meta). **RUST-ONLY** — mirrors
/// the inline qualifier dispatch C does in `insert()` (glob.c:381+).
fn check_single_qualifier(qual: &qualifier, path: &Path, meta: &Metadata) -> bool {
    // RUST-ONLY
    let mode = meta.mode();
    let ft = meta.file_type();

    match qual {
        qualifier::IsRegular => ft.is_file(),
        qualifier::IsDirectory => ft.is_dir(),
        qualifier::IsSymlink => ft.is_symlink(),
        qualifier::IsSocket => mode & libc::S_IFMT as u32 == libc::S_IFSOCK as u32,
        qualifier::IsFifo => mode & libc::S_IFMT as u32 == libc::S_IFIFO as u32,
        qualifier::IsBlockDev => mode & libc::S_IFMT as u32 == libc::S_IFBLK as u32,
        qualifier::IsCharDev => mode & libc::S_IFMT as u32 == libc::S_IFCHR as u32,
        qualifier::IsDevice => {
            let fmt = mode & libc::S_IFMT as u32;
            fmt == libc::S_IFBLK as u32 || fmt == libc::S_IFCHR as u32
        }
        qualifier::IsExecutable => ft.is_file() && (mode & 0o111 != 0),
        qualifier::Readable => mode & 0o400 != 0,
        qualifier::Writable => mode & 0o200 != 0,
        qualifier::Executable => mode & 0o100 != 0,
        qualifier::WorldReadable => mode & 0o004 != 0,
        qualifier::WorldWritable => mode & 0o002 != 0,
        qualifier::WorldExecutable => mode & 0o001 != 0,
        qualifier::GroupReadable => mode & 0o040 != 0,
        qualifier::GroupWritable => mode & 0o020 != 0,
        qualifier::GroupExecutable => mode & 0o010 != 0,
        qualifier::Setuid => mode & libc::S_ISUID as u32 != 0,
        qualifier::Setgid => mode & libc::S_ISGID as u32 != 0,
        qualifier::Sticky => mode & libc::S_ISVTX as u32 != 0,
        qualifier::OwnedByEuid => meta.uid() == unsafe { libc::geteuid() },
        qualifier::OwnedByEgid => meta.gid() == unsafe { libc::getegid() },
        qualifier::OwnedByUid(uid) => meta.uid() == *uid,
        qualifier::OwnedByGid(gid) => meta.gid() == *gid,
        qualifier::Size { value, unit, op } => {
            // Inline cmp + scale — mirrors glob.c qualsize at c:1054.
            let cmp = |a: u64, b: u64| match *op {
                '<' => a < b,
                '>' => a > b,
                _ => a == b,
            };
            let size = meta.size();
            let scaled = match *unit {
                u if u == TT_BYTES => size,
                u if u == TT_POSIX_BLOCKS => size.div_ceil(512),
                u if u == TT_KILOBYTES => size.div_ceil(1024),
                u if u == TT_MEGABYTES => size.div_ceil(1048576),
                u if u == TT_GIGABYTES => size.div_ceil(1073741824),
                u if u == TT_TERABYTES => size.div_ceil(1099511627776),
                _ => size,
            };
            cmp(scaled, *value)
        }
        qualifier::Links { value, op } => {
            let cmp = |a: u64, b: u64| match *op {
                '<' => a < b,
                '>' => a > b,
                _ => a == b,
            };
            cmp(meta.nlink(), *value)
        }
        qualifier::Atime { value, unit, op } => {
            // Inline time-unit scaling — Src/glob.c:872 qualtime.
            let cmp = |a: i64, b: i64| match *op {
                '<' => a < b,
                '>' => a > b,
                _ => a == b,
            };
            let now = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs() as i64;
            let diff = now - meta.atime();
            let scaled = match *unit {
                u if u == TT_SECONDS => diff,
                u if u == TT_MINS => diff / 60,
                u if u == TT_HOURS => diff / 3600,
                u if u == TT_DAYS => diff / 86400,
                u if u == TT_WEEKS => diff / 604800,
                u if u == TT_MONTHS => diff / 2592000,
                _ => diff,
            };
            cmp(scaled, *value)
        }
        qualifier::Mtime { value, unit, op } => {
            let cmp = |a: i64, b: i64| match *op {
                '<' => a < b,
                '>' => a > b,
                _ => a == b,
            };
            let now = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs() as i64;
            let diff = now - meta.mtime();
            let scaled = match *unit {
                u if u == TT_SECONDS => diff,
                u if u == TT_MINS => diff / 60,
                u if u == TT_HOURS => diff / 3600,
                u if u == TT_DAYS => diff / 86400,
                u if u == TT_WEEKS => diff / 604800,
                u if u == TT_MONTHS => diff / 2592000,
                _ => diff,
            };
            cmp(scaled, *value)
        }
        qualifier::Ctime { value, unit, op } => {
            let cmp = |a: i64, b: i64| match *op {
                '<' => a < b,
                '>' => a > b,
                _ => a == b,
            };
            let now = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs() as i64;
            let diff = now - meta.ctime();
            let scaled = match *unit {
                u if u == TT_SECONDS => diff,
                u if u == TT_MINS => diff / 60,
                u if u == TT_HOURS => diff / 3600,
                u if u == TT_DAYS => diff / 86400,
                u if u == TT_WEEKS => diff / 604800,
                u if u == TT_MONTHS => diff / 2592000,
                _ => diff,
            };
            cmp(scaled, *value)
        }
        qualifier::Mode { yes, no } => {
            let m = mode & 0o7777;
            (m & yes) == *yes && (m & no) == 0
        }
        qualifier::Device(dev) => meta.dev() == *dev,
        qualifier::NonEmptyDir => {
            if !ft.is_dir() {
                return false;
            }
            if let Ok(mut entries) = fs::read_dir(path) {
                entries.any(|e| {
                    e.ok()
                        .map(|e| {
                            let name = e.file_name();
                            name != "." && name != ".."
                        })
                        .unwrap_or(false)
                })
            } else {
                false
            }
        }
        qualifier::Eval(_) => true, // Would need shell integration
    }
}

/// Sort the per-state matches per the qualifier `o`/`O` keys.
/// **RUST-ONLY** — C does this inline at the end of `scanner()`
/// (glob.c:1700ish, qsort with `gmatchcmp` comparator).
fn sort_matches(state: &mut globdata) {
    // RUST-ONLY
    // Default sort is GS_NAME ascending (c:204 gf_sortlist
    // initial setup). Per-qualifier `o<key>` / `O<key>` overrides.
    // c:1855-1857 — when gf_nsorts == 0 (no explicit o/O qualifier),
    // glob.c falls back to GS_NAME (or GS_NONE under shortcircuit).
    // Mirror that here so a qualifier set carrying ONLY non-sort
    // qualifiers (`Lk+0`, etc.) still sorts alphabetically.
    let specs: Vec<i32> = state
        .qualifiers
        .as_ref()
        .map(|q| {
            if q.sorts.is_empty() {
                vec![GS_NAME] // c:1856
            } else {
                q.sorts.clone()
            }
        })
        .unwrap_or_else(|| vec![GS_NAME]);

    // GS_NONE marker — caller wants no sort at all.
    if specs.iter().any(|&tp| (tp & GS_NONE) != 0) {
        return;
    }

    let numeric = glob_isset(NUMERICGLOBSORT);
    state
        .matches
        .sort_by(|a, b| gmatchcmp(a, b, &specs, numeric));
}

/// Apply `[FIRST,LAST]` qualifier subscript on the match list.
/// **RUST-ONLY** — C uses `gd_pre_first` / `gd_first` index tracking
/// during scanner emit; here we slice after the full walk.
fn apply_selection(state: &mut globdata) {
    // RUST-ONLY
    let (first, last) = match &state.qualifiers {
        Some(q) => (q.first, q.last),
        None => return,
    };

    let len = state.matches.len() as i32;
    if len == 0 {
        return;
    }

    let start = match first {
        Some(f) if f < 0 => (len + f).max(0) as usize,
        Some(f) => (f - 1).max(0) as usize,
        None => 0,
    };

    let end = match last {
        Some(l) if l < 0 => (len + l + 1).max(0) as usize,
        Some(l) => l.min(len) as usize,
        None => len as usize,
    };

    if start < end && start < state.matches.len() {
        state.matches = state.matches[start..end.min(state.matches.len())].to_vec();
    } else {
        state.matches.clear();
    }
}

// `haswilds()` is defined in `Src/pattern.c:4306`, not glob.c — the
// canonical Rust port lives at `crate::ported::pattern::haswilds`.
// This file previously carried a divergent re-implementation tracking
// bracket/escape state instead of the token-aware `zpc_disables[]` /
// SHGLOB / KSHGLOB / EXTENDEDGLOB checks the C source actually does.
// Drift deleted; glob.rs callers route through the canonical port.

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

    #[test]
    fn gs_size_offset_matches_c() {
        let _g = crate::test_util::global_state_lock();
        // c:83 — GS_SIZE = GS_SHIFT_BASE = 8.
        assert_eq!(GS_SIZE, 8);
        // c:84 — GS_ATIME = GS_SHIFT_BASE << 1 = 16.
        assert_eq!(GS_ATIME, 16);
        // c:87 — GS_LINKS = GS_SHIFT_BASE << 4 = 128.
        assert_eq!(GS_LINKS, 128);
    }

    #[test]
    fn gs_normal_covers_all_size_keys() {
        let _g = crate::test_util::global_state_lock();
        // c:99 — GS_NORMAL = SIZE | ATIME | MTIME | CTIME | LINKS.
        assert_ne!(GS_NORMAL & GS_SIZE, 0);
        assert_ne!(GS_NORMAL & GS_ATIME, 0);
        assert_ne!(GS_NORMAL & GS_MTIME, 0);
        assert_ne!(GS_NORMAL & GS_CTIME, 0);
        assert_ne!(GS_NORMAL & GS_LINKS, 0);
    }

    #[test]
    fn tt_namespaces_share_indices() {
        let _g = crate::test_util::global_state_lock();
        // c:121-126 vs c:128-133 — TT_DAYS == TT_BYTES == 0, etc.
        assert_eq!(TT_DAYS, TT_BYTES);
        assert_eq!(TT_HOURS, TT_POSIX_BLOCKS);
        assert_eq!(TT_MINS, TT_KILOBYTES);
        assert_eq!(TT_WEEKS, TT_MEGABYTES);
        assert_eq!(TT_MONTHS, TT_GIGABYTES);
        assert_eq!(TT_SECONDS, TT_TERABYTES);
    }

    #[test]
    fn max_sorts_is_12() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(MAX_SORTS, 12);
    }
}

fn expand_range(
    prefix: &str,
    content: &str,
    dotdot_pos: usize,
    suffix: &str,
) -> Option<Vec<String>> {
    // c:Src/glob.c::xpandbraces parses brace-range endpoints via
    // zstrtol, which is TOKEN-aware and treats Dash TOKEN (\u{9b})
    // as ASCII `-`. Rust's i64::parse only accepts ASCII, so
    // untokenize the content here before splitting/parsing — matches
    // C semantics without weakening the strict-TOKEN gates above.
    let owned: String;
    let content: &str = if content.chars().any(|c| {
        let cu = c as u32;
        (0x84..=0xa1).contains(&cu) && c != '\u{8f}' && c != '\u{90}' && c != '\u{9a}'
    }) {
        owned = crate::lex::untokenize(content);
        &owned
    } else {
        content
    };
    let left = &content[..dotdot_pos];
    let right_start = dotdot_pos + 2;

    // Check for second `..` for `{N..M..S}` step form. Step may be
    // signed: negative-step REVERSES the natural direction sequence
    // per zsh's brace expansion (Src/glob.c::xpandbraces recursive
    // iteration with sign tracking). Examples:
    //   {1..32..3}   →  1,4,7,…,31 (natural ascending)
    //   {1..32..-3}  → 31,28,…,1   (same set, reversed)
    //   {32..1..3}   → 32,29,…,2   (natural descending)
    //   {32..1..-3}  →  2,5,…,32   (same set, reversed)
    //
    // c:Src/glob.c:2365-2369 — `if (dotdot == 2 && *p == '.' &&`
    //                         `    p[1] == '.') {`
    //                         `    rincr = zstrtol(p+2, &p, 10);`
    //                         `    wid3 = p - dots2 - 2;`
    //                         `    if (p != str2 || !rincr)`
    //                         `        err++;`
    // The `!rincr` test (c:2368) rejects a zero step: when err > 0,
    // the C code falls past the c:2374 `if (!err)` block, so the
    // brace expansion is abandoned and the literal pattern is
    // preserved. Parity bug #15: previously the Rust port silently
    // clamped step to 1 via `.max(1)`, producing `1 2 3 4 5` for
    // `{1..5..0}` instead of zsh's literal `1..5..0`.
    let (right, incr_abs, incr_sign_negative, step_text) =
        if let Some(pos) = content[right_start..].find("..") {
            let r = &content[right_start..right_start + pos];
            let s_text = &content[right_start + pos + 2..];
            let raw: i64 = s_text.parse().unwrap_or(1);
            if raw == 0 {
                // c:2368 — `!rincr` → err++ → no expansion. Return
                // None so xpandbraces falls back to literal.
                return None;
            }
            (r, raw.unsigned_abs(), raw < 0, s_text)
        } else {
            (&content[right_start..], 1u64, false, "")
        };

    // Try numeric range
    if let (Ok(start), Ok(end)) = (left.parse::<i64>(), right.parse::<i64>()) {
        let mut results = Vec::new();

        // Iterate from `start` toward `end` with abs(step). Sign of
        // start/end relative to each other determines natural
        // direction; step is always |step|.
        let step = incr_abs.max(1) as i64;
        let mut vals: Vec<i64> = Vec::new();
        if start <= end {
            let mut v = start;
            while v <= end {
                vals.push(v);
                v += step;
            }
        } else {
            let mut v = start;
            while v >= end {
                vals.push(v);
                v -= step;
            }
        }
        if incr_sign_negative {
            vals.reverse();
        }

        // Padding: zsh pads with leading zeros when ANY of the three
        // textual fields (left endpoint, right endpoint, step) has a
        // leading zero after stripping the optional sign. Width is
        // the max textual width across left/right/step. For negative
        // values, the sign prefix counts toward width — we emit `-`
        // then zero-pad the remaining digits (`-02`, not `0-2`).
        // Direct port of Src/lex.c::dobrace_pad logic which detects
        // pad mode per the textual form of all three fields.
        let lstrip = left.trim_start_matches(['+', '-']);
        let rstrip = right.trim_start_matches(['+', '-']);
        let sstrip = step_text.trim_start_matches(['+', '-']);
        let pad = lstrip.starts_with('0')
            || rstrip.starts_with('0')
            || (!step_text.is_empty() && sstrip.starts_with('0'));
        let width = left.len().max(right.len()).max(step_text.len());

        for v in vals {
            let formatted = if pad {
                if v < 0 {
                    let abs = (-v).to_string();
                    let inner_w = width.saturating_sub(1);
                    format!("-{:0>w$}", abs, w = inner_w)
                } else {
                    format!("{:0>w$}", v, w = width)
                }
            } else {
                v.to_string()
            };
            results.push(format!("{}{}{}", prefix, formatted, suffix));
        }
        return Some(results);
    }

    // Try character range
    // c:Src/lex.c::dobrace alpha-range path — only handles bare a..z,
    // not a..z..N. zsh emits literal `{a..z..3}` because the step
    // form is numeric-only. Detect step_text presence on the char-
    // range arm and refuse to expand so the literal survives.
    if left.len() == 1 && right.len() == 1 && step_text.is_empty() {
        let start = left.chars().next()?;
        let end = right.chars().next()?;
        let (start, end, reverse) = if start <= end {
            (start, end, false)
        } else {
            (end, start, true)
        };

        let mut results = Vec::new();
        let mut chars: Vec<char> = (start..=end).collect();
        if reverse {
            chars.reverse();
        }

        for c in chars {
            results.push(format!("{}{}{}", prefix, c, suffix));
        }
        return Some(results);
    }

    None
}

fn expand_comma(
    prefix: &str,
    content: &str,
    positions: &[usize],
    suffix: &str,
) -> Option<Vec<String>> {
    // positions are CHAR indices into `content` (per the xpandbraces
    // walker above that builds them from `chars: Vec<char>`). Slice
    // by char-index, not byte-index — `&content[last..pos]` would
    // panic on multi-byte token chars like Comma TOKEN (`\u{9a}`,
    // 2 UTF-8 bytes) and Inbrace (`\u{8f}`, 2 bytes).
    let chars: Vec<char> = content.chars().collect();
    let mut results = Vec::new();
    let mut last: usize = 0;
    for &pos in positions {
        let part: String = chars[last..pos].iter().collect();
        results.push(format!("{}{}{}", prefix, part, suffix));
        last = pos + 1;
    }
    let tail: String = chars[last..].iter().collect();
    results.push(format!("{}{}{}", prefix, tail, suffix));
    Some(results)
}

fn expand_ccl(prefix: &str, content: &str, suffix: &str) -> Option<Vec<String>> {
    // c:Src/glob.c:expand_ccl — char-class range expansion for the
    // `setopt braceccl` brace shape `{m-o}` → m,n,o. Accept both
    // ASCII `-` and Dash TOKEN (\u{9b}) as the range separator —
    // the bridge passthru path delivers `{m-o}` with Dash TOKEN
    // since the lexer tokenizes `-` to Dash inside word context.
    let mut chars_set = HashSet::new();
    let chars: Vec<char> = content.chars().collect();
    let mut i = 0;

    while i < chars.len() {
        let is_range = i + 2 < chars.len() && (chars[i + 1] == '-' || chars[i + 1] == '\u{9b}');
        if is_range {
            let start = chars[i];
            let end = chars[i + 2];
            for c in start..=end {
                chars_set.insert(c);
            }
            i += 3;
        } else {
            chars_set.insert(chars[i]);
            i += 1;
        }
    }

    let mut results: Vec<String> = chars_set
        .iter()
        .map(|c| format!("{}{}{}", prefix, c, suffix))
        .collect();
    results.sort();
    Some(results)
}

// ============================================================================
// Convenience functions
// ============================================================================

/// Split a pattern at its trailing zsh-style qualifier suffix. Returns
/// `(pattern_without_qualifier, qualifier_inner)` — the inner is the bytes
/// between the matching parens, without the surrounding `()` and without
/// any leading `#q`. Returns `(pattern, None)` when there is no qualifier
/// suffix. Useful for callers that want to use the pattern half with the
/// runtime [`matchpat`] (which has no qualifier semantics) while
/// reporting or applying the qualifier separately.
/// Split a glob pattern into (path-pattern, qualifier-string).
/// Port of the qualifier-detection step in `parsepat()`
/// (Src/glob.c:791).
pub fn split_qualifier(pattern: &str) -> (&str, Option<&str>) {
    if !pattern.ends_with(')') {
        return (pattern, None);
    }
    let bytes = pattern.as_bytes();
    let mut depth = 0;
    for i in (0..bytes.len()).rev() {
        match bytes[i] {
            b')' => depth += 1,
            b'(' => {
                depth -= 1;
                if depth == 0 {
                    let inner = &pattern[i + 1..pattern.len() - 1];
                    let inner = inner.strip_prefix("#q").unwrap_or(inner);
                    return (&pattern[..i], Some(inner));
                }
            }
            _ => {}
        }
    }
    (pattern, None)
}

/// Strip redundant `.` / `CurDir` segments from relative match paths for
/// output. Rust's `read_dir(".")` yields `entry.path()` like `./foo` while
/// `read_dir("foo")` yields `foo/bar` — zsh prints the latter shape for both.
fn glob_emit_path(path: &Path) -> String {
    match path.components().next() {
        Some(Component::Prefix(_) | Component::RootDir) => path.to_string_lossy().to_string(),
        None => ".".to_string(),
        _ => {
            let mut out = PathBuf::new();
            for c in path.components() {
                match c {
                    Component::CurDir => {}
                    Component::ParentDir => out.push(".."),
                    Component::Normal(s) => out.push(s),
                    Component::Prefix(_) | Component::RootDir => {}
                }
            }
            if out.as_os_str().is_empty() {
                ".".to_string()
            } else {
                out.to_string_lossy().to_string()
            }
        }
    }
}

/// Glob with default options
// np points to a node in the list which will be expanded                  // c:1209
// into a series of nodes.                                                  // c:1210
/// Top-level glob entry point.
/// Port of `zglob(LinkList list, LinkNode np, int nountok)` from Src/glob.c:1214. Reads all option flags
/// (nullglob / extendedglob / dotglob / caseglob / globstarshort /
/// bareglobqual / braceccl / markdirs / numericglobsort / …)
/// directly from the canonical global option store via
/// `opt_state_get` — same path C uses via
/// `isset(NULL_GLOB)` etc. on the global `opts[]` array.
pub fn glob(pattern: &str) -> Vec<String> {
    // c:1214
    // Race fix: snapshot every glob-relevant option into TLS for the
    // duration of this call so concurrent setopt/unsetopt on other
    // threads can't corrupt our qualifier parse / nullglob fallback /
    // dotglob filter etc. mid-walk. See `enter_glob_scope` doc.
    let _glob_scope = enter_glob_scope();
    let mut state = globdata::new();
    globdata_glob(&mut state, pattern)
}

/// Check if path is a directory (from glob.c)
/// Check whether a glob match is a directory.
/// Port of the `S_ISDIR(stat.st_mode)` test scattered through
/// Src/glob.c.
pub fn is_directory(path: &str) -> bool {
    fs::metadata(path).map(|m| m.is_dir()).unwrap_or(false)
}

/// Check if path is a symlink
/// Check whether a glob match is a symlink.
/// Port of the `S_ISLNK(lstat.st_mode)` test in Src/glob.c.
pub fn is_symlink(path: &str) -> bool {
    fs::symlink_metadata(path)
        .map(|m| m.file_type().is_symlink())
        .unwrap_or(false)
}

/// Apply mode spec to existing mode. Port of the
/// `spec_op`/`spec_who`/`spec_perm` inline application at the end of
/// C's `qgetmodespec` (`Src/glob.c:919-922`).
pub fn apply_modespec(mode: u32, who: u32, op: char, perm: u32) -> u32 {
    match op {
        '+' => mode | perm,
        '-' => mode & !perm,
        '=' => (mode & !who) | perm,
        _ => mode,
    }
}

// ===========================================================
// Methods moved verbatim from src/ported/vm_helper because their
// C counterpart's source file maps 1:1 to this Rust module.
// Phase: glob
// ===========================================================

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

// END moved-from-exec-rs

// ===========================================================
// Methods moved verbatim from src/ported/vm_helper because their
// C counterpart's source file maps 1:1 to this Rust module.
// Phase: drift
// ===========================================================

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

// END moved-from-exec-rs

// ===========================================================
// Free ported moved verbatim from src/ported/vm_helper.
// ===========================================================
// BEGIN moved-from-exec-rs (free ported)
// !!! WARNING: RUST-ONLY HELPER — NO DIRECT C COUNTERPART !!!
// `(a|b|c)` PATH-LEVEL alternation is handled in C by patcompile()
// (Src/pattern.c:540) compiling the alternation as P_BRANCH nodes,
// then globlist() walking each branch. zshrs needs the alternation
// EXPANDED to N separate glob patterns BEFORE pattern compile so
// the fusevm bridge / vm_helper can issue N independent zglob calls.
// No single C fn does this transform — it's a Rust-only adapter that
// MUST be deleted once patcompile's P_BRANCH is fully wired and zglob
// handles alternation natively (currently a known gap).
// !!! WARNING: RUST-ONLY HELPER — NO DIRECT C COUNTERPART !!!
/// Detect a glob alternation `(a|b|c)` in `pat` and expand it to
/// the cartesian product of the alternatives substituted in place.
/// Returns `None` if the pattern has no top-level alternation.
/// "Top-level" means not inside `[...]` (character class) or
/// `(#...)` (inline flag). Only the FIRST alternation group is
/// expanded per call; the recursion in `expand_glob` handles
/// nested alternations on subsequent passes.
pub(crate) fn expand_glob_alternation(pat: &str) -> Option<Vec<String>> {
    let bytes = pat.as_bytes();
    let mut i = 0;
    let mut bracket_depth = 0;
    let mut group_start: Option<usize> = None;
    let mut group_depth = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'\\' => {
                i += 2;
                continue;
            }
            b'[' => bracket_depth += 1,
            b']' if bracket_depth > 0 => bracket_depth -= 1,
            b'(' if bracket_depth == 0 => {
                // Skip `(#...)` inline flag forms — those are
                // pattern-engine flags, not alternation groups.
                if i + 1 < bytes.len() && bytes[i + 1] == b'#' {
                    // Find matching `)` and skip past.
                    let mut d = 1;
                    let mut j = i + 1;
                    while j < bytes.len() && d > 0 {
                        j += 1;
                        if j < bytes.len() {
                            match bytes[j] {
                                b'(' => d += 1,
                                b')' => d -= 1,
                                _ => {}
                            }
                        }
                    }
                    i = j + 1;
                    continue;
                }
                if group_start.is_none() {
                    group_start = Some(i);
                }
                group_depth += 1;
            }
            b')' if bracket_depth == 0 && group_depth > 0 => {
                group_depth -= 1;
                if group_depth == 0 {
                    // Check the body for `|` — if present, it's
                    // an alternation. Otherwise plain group, leave
                    // as-is and reset the search.
                    if let Some(start) = group_start.take() {
                        let body = &pat[start + 1..i];
                        // Has top-level `|`?
                        let mut bd = 0;
                        let mut pd = 0;
                        let mut found_bar = false;
                        for c in body.bytes() {
                            match c {
                                b'[' => bd += 1,
                                b']' if bd > 0 => bd -= 1,
                                b'(' if bd == 0 => pd += 1,
                                b')' if bd == 0 && pd > 0 => pd -= 1,
                                b'|' if bd == 0 && pd == 0 => {
                                    found_bar = true;
                                    break;
                                }
                                _ => {}
                            }
                        }
                        if found_bar {
                            // Split on top-level `|`.
                            let prefix = &pat[..start];
                            let suffix = &pat[i + 1..];
                            let mut alts: Vec<String> = Vec::new();
                            let mut bd2 = 0;
                            let mut pd2 = 0;
                            let mut last = 0usize;
                            let body_bytes = body.as_bytes();
                            let mut k = 0;
                            while k < body_bytes.len() {
                                let bc = body_bytes[k];
                                match bc {
                                    b'[' => bd2 += 1,
                                    b']' if bd2 > 0 => bd2 -= 1,
                                    b'(' if bd2 == 0 => pd2 += 1,
                                    b')' if bd2 == 0 && pd2 > 0 => pd2 -= 1,
                                    b'|' if bd2 == 0 && pd2 == 0 => {
                                        alts.push(format!(
                                            "{}{}{}",
                                            prefix,
                                            &body[last..k],
                                            suffix
                                        ));
                                        last = k + 1;
                                    }
                                    _ => {}
                                }
                                k += 1;
                            }
                            alts.push(format!("{}{}{}", prefix, &body[last..], suffix));
                            return Some(alts);
                        }
                    }
                }
            }
            _ => {}
        }
        i += 1;
    }
    None
}
/// Find the byte offset of the first top-level `~` in `pat` — i.e.
/// not inside `[...]` (character class) or `(...)` (group) and not
/// at position 0 (where it would be a literal). Returns `None` if
/// no such `~` exists. Direct port of zsh's pattern.c P_EXCLUDE
/// scan: backslash-escaped `~` doesn't count, and the search
/// honors paren/bracket nesting so `[a~b]` (literal `~` in class)
/// and `(a~b)` (nested exclusion within group, handled by the
/// recursive parser in C — we treat as literal here since this
/// helper only catches the common top-level case) both pass through.
pub(crate) fn find_top_level_tilde(pat: &str) -> Option<usize> {
    let bytes = pat.as_bytes();
    let mut i = 0;
    let mut bracket_depth = 0;
    let mut paren_depth = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'\\' => {
                // Skip escaped char.
                i += 2;
                continue;
            }
            b'[' => bracket_depth += 1,
            b']' if bracket_depth > 0 => bracket_depth -= 1,
            b'(' if bracket_depth == 0 => paren_depth += 1,
            b')' if bracket_depth == 0 && paren_depth > 0 => paren_depth -= 1,
            b'~' if bracket_depth == 0 && paren_depth == 0 && i > 0 => {
                return Some(i);
            }
            _ => {}
        }
        i += 1;
    }
    None
}

/// Canonical entry point for filesystem glob expansion. Mirrors C's
/// `zglob` driver at Src/glob.c:1214 with the alternation +
/// extendedglob pre-passes inlined (zsh's `(a|b|c)` group-level
/// alternation and `pat1~pat2` exclusion).
///
/// Reads `nullglob` / `nomatch` / `extendedglob` / `dotglob` /
/// `globdots` / `caseglob` / `nocaseglob` / `globstarshort` /
/// `bareglobqual` / `braceccl` / `markdirs` / `numericglobsort` /
/// `globdots` from the canonical option store (`opt_state_get`) so
/// behavior tracks `setopt …` toggles without needing an executor.
pub fn glob_path(pattern: &str) -> Vec<String> {
    // c:1214
    // Race fix: same TLS-snapshot guard glob() uses, so glob_path
    // callers see a coherent option set for the duration of this call.
    let _glob_scope = enter_glob_scope();
    let opt = |n: &str, default: bool| opt_state_get(n).unwrap_or(default);
    // Read option state directly — matches C's per-callsite
    // `isset(NULLGLOB)` / `isset(EXTENDEDGLOB)` reads (Src/glob.c).
    let null_glob = opt("nullglob", false);
    let extended_glob = opt("extendedglob", false);
    let no_glob_dots = !(opt("dotglob", false) || opt("globdots", false));
    let case_glob = opt("caseglob", true) && !opt("nocaseglob", false);

    // c:1230 — `(a|b|c)` top-level alternation pre-pass.
    if let Some(alternatives) = expand_glob_alternation(pattern) {
        let mut out: Vec<String> = Vec::new();
        for alt in alternatives {
            let has_meta = alt.chars().any(|c| matches!(c, '*' | '?' | '[' | '('));
            if has_meta {
                out.extend(glob_path(&alt));
            } else if Path::new(&alt).exists() {
                out.push(alt);
            }
        }
        let mut seen = HashSet::new();
        out.retain(|p| seen.insert(p.clone()));
        out.sort();
        if !out.is_empty() {
            return out;
        }
        // c:1700 fall through to NOMATCH semantics below.
    }

    // c:155 (P_EXCLUDE) — extendedglob `^pat` negation + `pat1~pat2`
    // exclusion. Only applies when extendedglob option is on.
    if extended_glob {
        let last_seg_start = pattern.rfind('/').map(|i| i + 1).unwrap_or(0);
        let last_seg = &pattern[last_seg_start..];
        if last_seg.starts_with('^') && last_seg.len() > 1 {
            let prefix = &pattern[..last_seg_start];
            let neg = &last_seg[1..];
            let dir = if prefix.is_empty() {
                ".".to_string()
            } else {
                prefix.trim_end_matches('/').to_string()
            };
            let mut out = Vec::new();
            if let Ok(entries) = fs::read_dir(&dir) {
                for entry in entries.flatten() {
                    let name = entry.file_name().to_string_lossy().to_string();
                    if name.starts_with('.') && no_glob_dots {
                        continue;
                    }
                    if !matchpat(neg, &name, true, case_glob) {
                        let path = if prefix.is_empty() {
                            name
                        } else {
                            format!("{}{}", prefix, name)
                        };
                        out.push(path);
                    }
                }
            }
            out.sort();
            if !out.is_empty() {
                return out;
            }
            if null_glob {
                return Vec::new();
            }
            return vec![pattern.to_string()];
        }
        // c:155 — top-level `~` exclusion.
        let chars: Vec<char> = pattern.chars().collect();
        let mut depth_b = 0i32;
        let mut depth_p = 0i32;
        let mut split_at: Option<usize> = None;
        for (i, &c) in chars.iter().enumerate() {
            match c {
                '[' => depth_b += 1,
                ']' => depth_b -= 1,
                '(' => depth_p += 1,
                ')' => depth_p -= 1,
                '~' if depth_b == 0 && depth_p == 0 && i > 0 => {
                    split_at = Some(i);
                    break;
                }
                _ => {}
            }
        }
        if let Some(pos) = split_at {
            let lhs: String = chars[..pos].iter().collect();
            let rhs: String = chars[pos + 1..].iter().collect();
            let lhs_matches = glob_path(&lhs);
            let filtered: Vec<String> = lhs_matches
                .into_iter()
                .filter(|p| {
                    let basename = p.rsplit('/').next().unwrap_or(p);
                    !matchpat(&rhs, basename, true, case_glob)
                        && !matchpat(&rhs, p, true, case_glob)
                })
                .collect();
            if !filtered.is_empty() {
                return filtered;
            }
            if null_glob {
                return Vec::new();
            }
            return vec![pattern.to_string()];
        }
    }

    // Main walk via the canonical glob driver.
    let mut state = globdata::new();
    let matches = globdata_glob(&mut state, pattern);
    if matches.is_empty() {
        // c:Src/glob.c:1872-1888 — `Deal with failures to match`.
        // Returning empty Vec on no-match is the canonical
        // contract; the caller (vm_helper.rs::expand_glob)
        // decides NOMATCH vs nullglob vs literal-fallback. Per-
        // qualifier (N) is parsed here for the legacy callers
        // that still expect glob_path to honor it directly, but
        // even without it we return Vec::new() so the NOMATCH
        // path in expand_glob fires. Previously this returned
        // `vec![pattern.to_string()]` (the literal pattern) on
        // no-match, which made expand_glob's `if !expanded.
        // is_empty()` shortcut bypass the NOMATCH check entirely
        // — `echo /never/*` printed the literal pattern with
        // exit 0 instead of raising "no matches found". Parity
        // bug.
        let _ = parse_qualifiers(pattern); // pre-parse for side-effects
        return Vec::new();
    }
    matches
}

// `g_range` from Src/glob.c — qualifier-comparison direction
// (-1 = less than, 0 = equal, 1 = greater than).
pub static G_RANGE: std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0);

// `mode_to_octal` lives at `crate::ported::utils::mode_to_octal`
// (port of `Src/utils.c:7634` — 12 bit-by-bit POSIX permission
// mappings). Local alias kept for the call sites at c:1610/1618
// which used the masked identity before the canonical port landed.
fn mode_to_octal(mode: u32) -> u32 {
    crate::ported::utils::mode_to_octal(mode) as u32
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs::{self, File};
    use tempfile::TempDir;

    use crate::ported::options::{opt_state_set, opt_state_unset};
    use crate::ported::zsh_h::{redir, ERRFLAG_ERROR, REDIR_WRITE};

    /// Convert ASCII brace-expansion source to the lexer-tokenized
    /// form `hasbraces` / `xpandbraces` consume per c:Src/glob.c —
    /// ASCII `{` → Inbrace (\u{8f}), `}` → Outbrace (\u{90}), `,` →
    /// Comma (\u{9a}). Backslash-escaped variants (`\{`, `\}`, `\,`)
    /// emit Bnull + literal so the canonical "escape via Bnull"
    /// distinction reaches the brace walker. Used by every test in
    /// this module that wants to drive the canonical TOKEN-strict
    /// path with readable ASCII source.
    fn tok(s: &str) -> String {
        let mut out = String::with_capacity(s.len());
        let mut chars = s.chars().peekable();
        while let Some(c) = chars.next() {
            match c {
                '\\' => match chars.peek() {
                    Some('{') | Some('}') | Some(',') => {
                        out.push('\u{9f}');
                        out.push(chars.next().unwrap());
                    }
                    _ => out.push(c),
                },
                '{' => out.push('\u{8f}'),
                '}' => out.push('\u{90}'),
                ',' => out.push('\u{9a}'),
                _ => out.push(c),
            }
        }
        out
    }

    fn setup_test_dir() -> TempDir {
        let dir = TempDir::new().unwrap();
        let base = dir.path();

        // Create test files
        File::create(base.join("file1.txt")).unwrap();
        File::create(base.join("file2.txt")).unwrap();
        File::create(base.join("file3.rs")).unwrap();
        File::create(base.join(".hidden")).unwrap();

        // Create subdirectory
        fs::create_dir(base.join("subdir")).unwrap();
        File::create(base.join("subdir/nested.txt")).unwrap();

        dir
    }

    #[test]
    fn test_haswilds() {
        let _g = crate::test_util::global_state_lock();
        assert!(haswilds("*.txt"));
        assert!(haswilds("file?.txt"));
        assert!(haswilds("file[12].txt"));
        assert!(!haswilds("file.txt"));
        assert!(!haswilds("path/to/file.txt"));
    }

    #[test]
    fn test_pattern_match() {
        let _g = crate::test_util::global_state_lock();
        assert!(matchpat("*.txt", "file.txt", false, true));
        assert!(matchpat("file?.txt", "file1.txt", false, true));
        assert!(!matchpat("*.txt", "file.rs", false, true));
        assert!(matchpat("file[12].txt", "file1.txt", false, true));
        assert!(!matchpat("file[12].txt", "file3.txt", false, true));
    }

    #[test]
    fn test_brace_expansion() {
        let _g = crate::test_util::global_state_lock();
        let result = xpandbraces(&tok("{a,b,c}"), false);
        assert_eq!(result, vec!["a", "b", "c"]);

        let result = xpandbraces(&tok("file{1,2,3}.txt"), false);
        assert_eq!(result, vec!["file1.txt", "file2.txt", "file3.txt"]);

        let result = xpandbraces(&tok("{1..5}"), false);
        assert_eq!(result, vec!["1", "2", "3", "4", "5"]);

        let result = xpandbraces(&tok("{a..e}"), false);
        assert_eq!(result, vec!["a", "b", "c", "d", "e"]);
    }

    #[test]
    fn test_glob_simple() {
        let _g = crate::test_util::global_state_lock();
        let dir = setup_test_dir();
        let pattern = format!("{}/*.txt", dir.path().display());

        let mut state = globdata::new();
        let results = globdata_glob(&mut state, &pattern);

        assert_eq!(results.len(), 2);
        assert!(results.iter().any(|s| s.ends_with("file1.txt")));
        assert!(results.iter().any(|s| s.ends_with("file2.txt")));
    }

    #[test]
    fn test_glob_hidden() {
        let _g = crate::test_util::global_state_lock();
        let dir = setup_test_dir();
        let pattern = format!("{}/*", dir.path().display());

        // Default (globdots off) → hidden files skipped. `dotglob`
        // is the bash alias for zsh's canonical `globdots` option;
        // the C-faithful read goes through `isset(GLOBDOTS)` which
        // resolves the canonical name.
        opt_state_set("globdots", false);
        let mut state = globdata::new();
        let results = globdata_glob(&mut state, &pattern);
        assert!(!results.iter().any(|s| s.contains(".hidden")));

        // setopt globdots → hidden files included.
        opt_state_set("globdots", true);
        let mut state = globdata::new();
        let results = globdata_glob(&mut state, &pattern);
        assert!(results.iter().any(|s| s.contains(".hidden")));
        opt_state_set("globdots", false); // reset for other tests
    }

    #[test]
    fn test_glob_emit_path_strips_read_dir_dot_slash() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(glob_emit_path(Path::new("./sub")), "sub");
        assert_eq!(glob_emit_path(Path::new("sub/deeper")), "sub/deeper");
        assert_eq!(glob_emit_path(Path::new("././x")), "x");
        assert_eq!(glob_emit_path(Path::new("../up")), "../up");
    }

    #[test]
    fn test_file_type_char() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(file_type(libc::S_IFDIR as u32), '/');
        assert_eq!(file_type(libc::S_IFREG as u32), ' ');
        assert_eq!(file_type(libc::S_IFREG as u32 | 0o111), '*');
        assert_eq!(file_type(libc::S_IFLNK as u32), '@');
    }

    /// `Src/glob.c:2018-2036` — `file_type(mode_t filemode)` returns a
    /// single-char marker keyed off S_ISBLK/CHR/DIR/FIFO/LNK/REG/SOCK,
    /// with `S_IXUGO` (== 0o111 = S_IXUSR|S_IXGRP|S_IXOTH) distinguishing
    /// executable regular files (`*`) from non-executable (` `). The
    /// catch-all (e.g. door, port, unknown types) returns `?`.
    /// Pin every branch by position.
    #[test]
    fn file_type_every_branch_matches_c_dispatch() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(
            file_type(libc::S_IFBLK as u32),
            '#',
            "c:2020 — S_ISBLK → '#'"
        );
        assert_eq!(
            file_type(libc::S_IFCHR as u32),
            '%',
            "c:2022 — S_ISCHR → '%'"
        );
        assert_eq!(
            file_type(libc::S_IFDIR as u32),
            '/',
            "c:2024 — S_ISDIR → '/'"
        );
        assert_eq!(
            file_type(libc::S_IFIFO as u32),
            '|',
            "c:2026 — S_ISFIFO → '|'"
        );
        assert_eq!(
            file_type(libc::S_IFLNK as u32),
            '@',
            "c:2028 — S_ISLNK → '@'"
        );
        // Regular file: ' ' if not executable, '*' if executable (any bit in S_IXUGO).
        assert_eq!(
            file_type(libc::S_IFREG as u32),
            ' ',
            "c:2030 — non-executable regular file → ' '"
        );
        // Each individual exec bit triggers '*'.
        assert_eq!(
            file_type(libc::S_IFREG as u32 | 0o100),
            '*',
            "c:2030 — S_IXUSR alone is enough"
        );
        assert_eq!(
            file_type(libc::S_IFREG as u32 | 0o010),
            '*',
            "c:2030 — S_IXGRP alone is enough"
        );
        assert_eq!(
            file_type(libc::S_IFREG as u32 | 0o001),
            '*',
            "c:2030 — S_IXOTH alone is enough"
        );
        assert_eq!(
            file_type(libc::S_IFSOCK as u32),
            '=',
            "c:2033 — S_ISSOCK → '='"
        );
        // Catch-all for unknown S_IFMT — bare 0 returns '?'.
        assert_eq!(file_type(0), '?', "c:2035 — unknown st_mode → '?'");
    }

    #[test]
    fn test_zstrcmp_numeric() {
        let _g = crate::test_util::global_state_lock();
        let n = crate::zsh_h::SORTIT_NUMERICALLY as u32;
        assert_eq!(zstrcmp("file1", "file2", n), std::cmp::Ordering::Less);
        assert_eq!(zstrcmp("file10", "file2", n), std::cmp::Ordering::Greater);
        assert_eq!(zstrcmp("file10", "file10", n), std::cmp::Ordering::Equal);
    }

    /// Race-fix verification: snapshot pins bareglobqual for the
    /// duration of a glob scope even when the live store flips
    /// underneath. Mimics the stryke pattern in
    /// MenkeTechnologies/strykelang#3 — one thread is mid-glob with
    /// bareglobqual=1 snapshot when another flips it off.
    #[test]
    fn glob_opts_snapshot_isolates_concurrent_setopt() {
        let _g = crate::test_util::global_state_lock();

        // Preserve the existing live state so the test is hermetic.
        let saved = opt_state_get("bareglobqual");

        // Live store says bareglobqual=true; enter scope captures that.
        opt_state_set("bareglobqual", true);
        let _scope = enter_glob_scope();
        assert!(
            glob_isset(BAREGLOBQUAL),
            "TLS snapshot reads bareglobqual=true at scope entry"
        );

        // Simulate a concurrent thread flipping the live store.
        opt_state_set("bareglobqual", false);
        assert!(
            glob_isset(BAREGLOBQUAL),
            "TLS snapshot must still report bareglobqual=true \
             even though live store now reads false"
        );

        // Restore.
        match saved {
            Some(v) => opt_state_set("bareglobqual", v),
            None => opt_state_unset("bareglobqual"),
        }
    }

    /// After the scope guard drops, reads fall back to the live store.
    #[test]
    fn glob_opts_snapshot_clears_on_drop() {
        let _g = crate::test_util::global_state_lock();

        let saved = opt_state_get("nullglob");
        opt_state_set("nullglob", true);
        {
            let _scope = enter_glob_scope();
            assert!(glob_isset(NULLGLOB), "snapshot live=true → true inside");
        }
        // Outside scope: flip live store, read should follow live.
        opt_state_set("nullglob", false);
        assert!(
            !glob_isset(NULLGLOB),
            "post-scope: glob_isset falls back to live store"
        );

        match saved {
            Some(v) => opt_state_set("nullglob", v),
            None => opt_state_unset("nullglob"),
        }
    }

    /// Nested glob scopes share the outer snapshot — inner doesn't
    /// re-capture or clear on its own Drop.
    #[test]
    fn glob_opts_snapshot_nested_is_noop() {
        let _g = crate::test_util::global_state_lock();

        let saved = opt_state_get("extendedglob");
        opt_state_set("extendedglob", true);
        let _outer = enter_glob_scope();
        assert!(glob_isset(EXTENDEDGLOB));
        {
            let _inner = enter_glob_scope();
            // Live store flip while nested.
            opt_state_set("extendedglob", false);
            assert!(glob_isset(EXTENDEDGLOB), "inner observes outer snapshot");
        } // inner drops — outer snapshot still active.
        assert!(
            glob_isset(EXTENDEDGLOB),
            "outer snapshot survives inner drop"
        );

        match saved {
            Some(v) => opt_state_set("extendedglob", v),
            None => opt_state_unset("extendedglob"),
        }
    }

    /// c:2150 (xpandredir port) — when the redir name has no wildcard
    /// AND no `$var`/`!hist`/`{a,b}` to expand, prefork+globlist leave
    /// the name unchanged. The single-match path at c:2171 must
    /// rewrite `fn.name` to the same string and return 0 (no multi-fan).
    /// Regression that returns 1 would trigger MULTIOS dispatch on a
    /// single literal filename — wrong shell semantics.
    #[test]
    fn xpandredir_single_literal_filename_returns_zero() {
        let _g = crate::test_util::global_state_lock();
        let mut fn_ = redir {
            typ: REDIR_WRITE,
            flags: 0,
            fd1: 1,
            fd2: -1,
            name: Some("/tmp/zshrs_test_out".to_string()),
            varid: None,
            here_terminator: None,
            munged_here_terminator: None,
        };
        let mut tab: Vec<redir> = Vec::new();
        let r = xpandredir(&mut fn_, &mut tab);
        assert_eq!(r, 0, "literal filename → single match → ret=0");
        assert_eq!(
            fn_.name.as_deref(),
            Some("/tmp/zshrs_test_out"),
            "literal name must round-trip through prefork unchanged"
        );
        assert!(tab.is_empty(), "no multi-match → redirtab not appended");
    }

    /// c:2176-2177 — `>&-` (REDIR_MERGEOUT with name "-") collapses to
    /// REDIR_CLOSE per the `IS_DASH(s[0]) && !s[1]` branch. Regression
    /// where this fails leaves `>&-` as a literal merge-fd attempt,
    /// which the executor would interpret as "merge with fd -1".
    #[test]
    fn xpandredir_dash_merge_collapses_to_close() {
        let _g = crate::test_util::global_state_lock();
        let mut fn_ = redir {
            typ: REDIR_MERGEOUT,
            flags: 0,
            fd1: 1,
            fd2: -1,
            name: Some("-".to_string()),
            varid: None,
            here_terminator: None,
            munged_here_terminator: None,
        };
        let mut tab: Vec<redir> = Vec::new();
        let _ = xpandredir(&mut fn_, &mut tab);
        assert_eq!(
            fn_.typ, REDIR_CLOSE,
            "`>&-` must rewrite typ to REDIR_CLOSE"
        );
    }

    /// c:2150 — empty `fn.name` should return 0 cleanly. Catches a
    /// regression that panics on `.as_deref().unwrap()` for absent name.
    #[test]
    fn xpandredir_with_no_name_returns_zero_no_panic() {
        let _g = crate::test_util::global_state_lock();
        let mut fn_ = redir {
            typ: REDIR_WRITE,
            flags: 0,
            fd1: 1,
            fd2: -1,
            name: None,
            varid: None,
            here_terminator: None,
            munged_here_terminator: None,
        };
        let mut tab: Vec<redir> = Vec::new();
        assert_eq!(xpandredir(&mut fn_, &mut tab), 0);
    }

    /// `IN_EXPANDREDIR` static defaults to 0 — set transiently inside
    /// xpandredir per c:2165/2167. After a normal call it must restore
    /// to 0. Regression that leaks the flag would skew unrelated glob
    /// expansions outside redirections.
    #[test]
    fn in_expandredir_flag_is_zero_at_rest() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(IN_EXPANDREDIR.load(Ordering::SeqCst), 0);
    }

    /// c:4306 — `haswilds` honours backslash-escapes: `\*` is a literal
    /// star, NOT a wildcard. Regression that ignores the escape would
    /// trigger globbing on `printf '%s\n' \*`, breaking shell scripts
    /// that quote literal stars.
    #[test]
    fn haswilds_respects_backslash_escape() {
        let _g = crate::test_util::global_state_lock();
        assert!(haswilds("*.txt"), "bare * is wild");
        assert!(!haswilds(r"\*.txt"), "escaped \\* is literal — NOT wild");
        assert!(!haswilds(r"\?.txt"), "escaped \\? is literal — NOT wild");
    }

    /// c:4306 — `[` immediately enters bracket mode AND counts as a
    /// wildcard. The early return on `[` is critical — even
    /// unterminated brackets must be flagged so `cd [` doesn't try
    /// to chdir to a literal `[`.
    #[test]
    fn haswilds_open_bracket_alone_is_a_wildcard() {
        let _g = crate::test_util::global_state_lock();
        assert!(haswilds("[abc]"), "char-class is wild");
        assert!(haswilds("foo["), "even unterminated [ is wild");
    }

    /// c:4306 — wildcard chars `*` `?` inside an OPEN bracket-context
    /// are NOT additional wildcards (the bracket already is one).
    /// Regression that double-counts would make haswilds report `[*]`
    /// as wildcard-twice — cosmetic, but confuses any caller using
    /// the bool as a "should I glob?" gate that AND-tests with another
    /// flag.
    #[test]
    fn haswilds_extglob_chars_inside_bracket_dont_double_count() {
        let _g = crate::test_util::global_state_lock();
        // Once `[` is seen, function returns true immediately, so the
        // post-bracket chars don't matter. But this docs the contract.
        assert!(haswilds("[*]"));
    }

    /// c:4306 — plain text returns false. Catches a regression where
    /// any non-empty input is flagged as wild (would break `cd /tmp`
    /// by triggering glob expansion on a literal path).
    #[test]
    fn haswilds_plain_text_not_wild() {
        let _g = crate::test_util::global_state_lock();
        assert!(!haswilds("plain"));
        assert!(!haswilds(""));
        assert!(!haswilds("/usr/local/bin"));
        assert!(!haswilds("file.txt"));
    }

    /// c:4363-4371 — `#` and `^` are recognised as wildcards by
    /// `haswilds` **only when `EXTENDEDGLOB` is set**, matching the C
    /// source's `isset(EXTENDEDGLOB)` gate at pattern.c:4364/4369. `~`
    /// is **not** a filename-generation wildcard (zsh handles it as
    /// tilde expansion in a separate pipeline stage); a prior
    /// glob.rs-local `haswilds` impl returned true for `~`, which
    /// caused zglob to mis-classify tilde-prefixed args as needing
    /// filename generation. Pin the corrected behavior.
    #[test]
    fn haswilds_extended_glob_chars_recognised() {
        let _g = crate::test_util::global_state_lock();
        // EXTENDEDGLOB off → `#` and `^` are not wild.
        crate::ported::options::opt_state_set("extendedglob", false);
        assert!(!haswilds("foo#bar"), "# not wild without EXTENDEDGLOB");
        assert!(!haswilds("foo^bar"), "^ not wild without EXTENDEDGLOB");
        // EXTENDEDGLOB on → `#` and `^` are wild (c:4364, c:4369).
        crate::ported::options::opt_state_set("extendedglob", true);
        assert!(haswilds("foo#bar"), "# is extglob wild");
        assert!(haswilds("foo^bar"), "^ is extglob wild");
        crate::ported::options::opt_state_set("extendedglob", false);
        // `~` is NOT in haswilds' switch (c:4324-4373) — tilde expansion
        // is a separate pipeline stage.
        assert!(!haswilds("~/file"), "~ is NOT a filename-generation wildcard");
    }

    /// c:2514 — `matchpat` returns true for exact match. Sanity check
    /// the simplest dispatch path (the matcher recipe builds a
    /// trivial pattern, runs it).
    #[test]
    fn matchpat_exact_literal_matches() {
        let _g = crate::test_util::global_state_lock();
        assert!(matchpat("hello", "hello", false, true));
        assert!(!matchpat("hello", "world", false, true));
    }

    /// c:2514 — `matchpat` with case_sensitive=false MUST treat upper
    /// and lower as equal (`HELLO` matches `hello`). Regression keeping
    /// case-sensitive when flag is false would silently break every
    /// `[[ "$x" = (#i)foo ]]`-style match.
    #[test]
    fn matchpat_case_insensitive_when_flag_clear() {
        let _g = crate::test_util::global_state_lock();
        assert!(
            matchpat("hello", "HELLO", false, false),
            "case-insensitive match must succeed across cases"
        );
        assert!(matchpat("FoO", "foo", false, false));
    }

    /// c:2514 — case-sensitive (default) MUST reject case-different
    /// inputs. Pinning the contract.
    #[test]
    fn matchpat_case_sensitive_rejects_case_different() {
        let _g = crate::test_util::global_state_lock();
        assert!(
            !matchpat("hello", "HELLO", false, true),
            "case-sensitive default must reject HELLO != hello"
        );
    }

    /// c:2780 — `set_pat_start` returns the suffix from `offs` onward.
    /// `offs=0` → unchanged. `offs >= len` → unchanged (defensive bound).
    /// Regression that panics on out-of-range would crash the
    /// substring-globbing code.
    #[test]
    fn set_pat_start_handles_out_of_range_safely() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(set_pat_start("hello", 0), "hello");
        assert_eq!(set_pat_start("hello", 100), "hello");
        assert_eq!(set_pat_start("hello", 2), "llo");
    }

    /// c:2797 — `set_pat_end` returns the prefix up to `null_me`.
    /// Counterpart to set_pat_start. `null_me >= len` is no-op
    /// (defensive). Regression panicking on out-of-range would crash
    /// the substring-globbing code.
    #[test]
    fn set_pat_end_handles_out_of_range_safely() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(set_pat_end("hello", 100), "hello");
        assert_eq!(set_pat_end("hello", 3), "hel");
        assert_eq!(set_pat_end("hello", 0), "");
    }

    /// c:2773 — `freematchlist(None)` is a no-op (matches C's
    /// `if (repllist) freelinklist(...)`). Regression panicking on
    /// None would crash every glob-replace path with no matches.
    #[test]
    fn freematchlist_handles_none_safely() {
        let _g = crate::test_util::global_state_lock();
        freematchlist(None);
        // No assertion — survival is the test.
    }

    /// c:2773 — `freematchlist(Some(&mut Vec))` clears the list.
    /// Regression that drops a stale entry would leak match positions
    /// across calls.
    #[test]
    fn freematchlist_clears_provided_vec() {
        let _g = crate::test_util::global_state_lock();
        let mut v = vec![(0, 5), (10, 15)];
        freematchlist(Some(&mut v));
        assert!(v.is_empty(), "freematchlist must clear the input vec");
    }

    /// `Src/glob.c:2042-2142` — `hasbraces(str)` returns true when
    /// `str` contains a brace-expansion candidate. A bare lbrace/rbrace
    /// is NOT a brace expansion (it's a literal). Detection requires a
    /// matched pair containing either a comma or a dotdot range. Pin
    /// the canonical contract.
    #[test]
    fn hasbraces_matched_pair_with_comma_or_dotdot() {
        let _g = crate::test_util::global_state_lock();
        // Matched + comma → true.
        assert!(
            hasbraces(&tok("a{b,c}d"), false),
            "c:2127 — lbrace + comma + rbrace is a brace expansion"
        );
        // Matched + dotdot → true.
        assert!(
            hasbraces(&tok("file{1..3}.txt"), false),
            "c:2082 — N..M range is a brace expansion"
        );
        // Matched WITHOUT comma/dotdot → false (it's a literal).
        assert!(
            !hasbraces(&tok("{abc}"), false),
            "literal braces are NOT a brace expansion without comma or dotdot"
        );
        // Unmatched → false.
        assert!(
            !hasbraces(&tok("{abc"), false),
            "lone lbrace without matching rbrace is not brace expansion"
        );
        assert!(
            !hasbraces(&tok("abc}"), false),
            "lone rbrace is not brace expansion"
        );
        // No braces → false.
        assert!(!hasbraces(&tok("plain"), false));
        assert!(!hasbraces(&tok(""), false));
    }

    /// `Src/glob.c:2049-2063` — BRACECCL branch: when `isset(BRACECCL)`
    /// (the `brace_ccl` parameter), any non-empty matched braces
    /// become a character-class set, regardless of whether the body
    /// contains a comma. Empty pair is still not.
    #[test]
    fn hasbraces_brace_ccl_makes_any_pair_match() {
        let _g = crate::test_util::global_state_lock();
        // c:2049 — BRACECCL: non-empty pair is enough.
        assert!(
            hasbraces(&tok("{abc}"), true),
            "c:2049 — BRACECCL: non-empty pair is char-class set"
        );
        assert!(
            hasbraces(&tok("x{q}y"), true),
            "c:2049 — single-char pair counts under BRACECCL"
        );
        // Empty pair shouldn't trigger.
        assert!(
            !hasbraces(&tok("{}"), true),
            "empty pair still not a brace expansion even under BRACECCL"
        );
        // Without BRACECCL, plain literal-letter pair is NOT a brace expansion.
        assert!(
            !hasbraces(&tok("{abc}"), false),
            "c:2049 — BRACECCL off → plain literal pair stays literal"
        );
    }

    /// `Src/glob.c:2042-2142` — depth tracking: comma/dotdot count
    /// only at depth==1 in our port. So nested inner comma doesn't
    /// qualify the outer pair, but TWO independent top-level pairs
    /// (each with comma) DO trigger detection.
    #[test]
    fn hasbraces_depth_1_check_for_comma_dotdot() {
        let _g = crate::test_util::global_state_lock();
        assert!(
            hasbraces(&tok("a{1,2}b{3,4}c"), false),
            "two independent top-level pairs, first one matches at depth 1"
        );
    }

    /// Pin: `remnulargs` per `Src/glob.c:3649-3679`:
    ///   - Strings with NO inull bytes are unchanged.
    ///   - Strings with ONLY Bnullkeep: keep as-is in scan phase
    ///     (Bnullkeep is "active backslash" that hasn't triggered
    ///     copy phase yet).
    ///   - After encountering any other inull: switch to copy phase:
    ///     * Bnullkeep → '\\' (literal backslash).
    ///     * Other inulls (Snull/Dnull/Bnull/Nularg) → stripped.
    ///     * Non-inull → kept.
    ///   - Empty post-strip → replaced with single Nularg.
    #[test]
    fn remnulargs_matches_c_inull_handling() {
        let _g = crate::test_util::global_state_lock();

        // Plain ASCII unchanged (no inulls).
        let mut s = "hello".to_string();
        remnulargs(&mut s);
        assert_eq!(
            s, "hello",
            "c:3654 — no inull bytes leaves string unchanged"
        );

        // Snull-triggered copy: Snull stripped, rest kept.
        let mut s = format!("ab{}cd", Snull);
        remnulargs(&mut s);
        assert_eq!(
            s, "abcd",
            "c:3663 — Snull triggers copy; itself stripped, rest kept"
        );

        // Bnullkeep AFTER Snull trigger → '\\' (active backslash).
        let mut s = format!("ab{}c{}d", Snull, Bnullkeep);
        remnulargs(&mut s);
        assert_eq!(
            s, "abc\\d",
            "c:3666 — Bnullkeep in copy phase becomes literal '\\\\'"
        );

        // Other inulls (Bnull, Dnull) stripped in copy phase.
        let mut s = format!("a{}b{}c{}d", Snull, Bnull, Dnull);
        remnulargs(&mut s);
        assert_eq!(s, "abcd", "c:3668 — Bnull/Dnull stripped in copy phase");

        // Empty post-strip → Nularg.
        let mut s = format!("{}", Snull);
        remnulargs(&mut s);
        assert_eq!(
            s,
            format!("{}", Nularg),
            "c:3674 — empty result replaced by Nularg sentinel"
        );
    }

    /// `Src/glob.c:1085-1117` — `glob_exec_string` is a PARSER, not
    /// an executor. Extracts the qualifier inner text from `*sp`
    /// (advancing past delimiters). Previous Rust port forked
    /// `/bin/sh` to execute the cmd — that's entirely the wrong
    /// layer; execution happens at the call sites via qualsheval.
    /// Pin: plus-form extracts identifier; delimited form extracts
    /// content + advances.
    #[test]
    fn glob_exec_string_parses_qualifier_text() {
        let _g = crate::test_util::global_state_lock();
        // Plus form: identifier ends at first non-ident char.
        // C: `(+myfunc:rest)` — `s` points past `+`, plus_form=true.
        let r = glob_exec_string("myfunc rest", true);
        assert!(r.is_some(), "c:1092 — identifier parse should succeed");
        let (ident, _adv) = r.unwrap();
        assert_eq!(
            ident, "myfunc",
            "c:1092 — itype_end stops at first non-IIDENT char"
        );

        // Plus form with no identifier (immediate non-ident) — error.
        let r = glob_exec_string(" leading-space", true);
        assert!(
            r.is_none(),
            "c:1093-1096 — empty identifier emits zerr + returns None"
        );
    }

    /// `Src/glob.c:3907-3943` — `qualsheval(name, _, _, expr)` sets
    /// `$REPLY` via paramtab, evaluates `expr` IN THE CURRENT SHELL,
    /// then restores errflag+lastval. Previous Rust port spawned
    /// `/bin/sh -c expr` which:
    ///   1. Couldn't access shell locals / functions / aliases.
    ///   2. Ran `sh` (POSIX), not `zsh` — every zsh-feature qualifier
    ///      silently failed.
    ///
    /// Pin: after qualsheval, errflag is restored (mod ERRFLAG_INT),
    /// lastval is restored, and `$REPLY` is set to the filename.
    /// Easiest direct pin: errflag/lastval restore around an `expr`
    /// that mutates them.
    #[test]
    fn qualsheval_restores_errflag_and_lastval() {
        let _g = crate::test_util::global_state_lock();
        // Seed errflag and lastval with distinctive values.
        errflag.store(0, Ordering::Relaxed);
        LASTVAL.store(42, Ordering::Relaxed);
        // Even if the expr mutates these via the executor, c:3924-3925
        // restore them after.
        let _ = qualsheval("/tmp/file", ":"); // no-op expr
                                              // c:3924 — errflag restored.
        assert_eq!(
            errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR,
            0,
            "c:3924 — qualsheval must restore errflag (no ERRFLAG_ERROR leak)"
        );
        // c:3925 — lastval restored.
        assert_eq!(
            LASTVAL.load(Ordering::Relaxed),
            42,
            "c:3925 — qualsheval must restore lastval to pre-call value"
        );
        // c:3916 — $REPLY visible in paramtab.
        assert_eq!(
            crate::ported::params::getsparam("REPLY"),
            Some("/tmp/file".to_string()),
            "c:3916 — qualsheval must set $REPLY to filename"
        );
    }

    /// `Src/glob.c:2164` — `if (!errflag && isset(MULTIOS))` is the
    /// logical zero-check guarding globlist recursion. Previous Rust
    /// port used `!errflag.load(...) != 0` which is BITWISE NOT
    /// (`^-1`), evaluating to `errflag != -1` — almost-always-true.
    ///
    /// Pin: a `matchpat` smoke that DOES NOT mutate errflag, then a
    /// direct check that the fix sense is correct (errflag==0 enters
    /// the branch, errflag!=0 skips). Can't easily exercise the full
    /// xpandredir path without a redir struct + IN_EXPANDREDIR
    /// global, so this is a sense-of-the-condition pin.
    #[test]
    fn xpandredir_errflag_check_uses_logical_zero() {
        let _g = crate::test_util::global_state_lock();
        // Mirror the in-port logic with the canonical zero-check.
        let saved = errflag.load(Ordering::Relaxed);
        // c:2164 — errflag==0 path: branch should fire.
        errflag.store(0, Ordering::Relaxed);
        let zero_enters = errflag.load(Ordering::Relaxed) == 0;
        assert!(
            zero_enters,
            "c:2164 — errflag==0 enters the branch (the canonical sense)"
        );
        // c:2164 — errflag!=0 path: branch should skip.
        errflag.store(1, Ordering::Relaxed);
        let nonzero_skips = errflag.load(Ordering::Relaxed) == 0;
        assert!(
            !nonzero_skips,
            "c:2164 — errflag!=0 skips the branch (regression of bitwise-NOT bug fix)"
        );
        errflag.store(saved, Ordering::Relaxed);
    }

    // ═══════════════════════════════════════════════════════════════════
    // Additional unit coverage — pure pattern/brace/glob behaviour that
    // doesn't need a real filesystem. Uses `matchpat` for high-level
    // pattern checks (extended=false, case_sensitive=true is the most
    // common path) and `xpandbraces` for brace expansion.
    // ═══════════════════════════════════════════════════════════════════

    // ── matchpat: full-string pattern matching ───────────────────────
    #[test]
    fn matchpat_literal_no_wildcards() {
        let _g = crate::test_util::global_state_lock();
        assert!(matchpat("foo", "foo", false, true));
        assert!(!matchpat("foo", "bar", false, true));
        assert!(!matchpat("foo", "foobar", false, true));
    }

    #[test]
    fn matchpat_star_consumes_substring() {
        let _g = crate::test_util::global_state_lock();
        assert!(matchpat("a*b", "ab", false, true));
        assert!(matchpat("a*b", "ahellob", false, true));
        assert!(!matchpat("a*b", "abc", false, true));
    }

    #[test]
    fn matchpat_question_is_single_char() {
        let _g = crate::test_util::global_state_lock();
        assert!(matchpat("a?c", "abc", false, true));
        assert!(matchpat("a?c", "axc", false, true));
        assert!(!matchpat("a?c", "ac", false, true));
        assert!(!matchpat("a?c", "abbc", false, true));
    }

    #[test]
    fn matchpat_bracket_class_inline() {
        let _g = crate::test_util::global_state_lock();
        assert!(matchpat("file[abc].txt", "filea.txt", false, true));
        assert!(matchpat("file[abc].txt", "fileb.txt", false, true));
        assert!(!matchpat("file[abc].txt", "filed.txt", false, true));
    }

    #[test]
    fn matchpat_case_sensitive_strict() {
        let _g = crate::test_util::global_state_lock();
        assert!(matchpat("Foo", "Foo", false, true));
        assert!(!matchpat("Foo", "foo", false, true));
        assert!(!matchpat("Foo", "FOO", false, true));
    }

    #[test]
    fn matchpat_empty_pattern_matches_only_empty() {
        let _g = crate::test_util::global_state_lock();
        assert!(matchpat("", "", false, true));
        assert!(!matchpat("", "x", false, true));
    }

    #[test]
    fn matchpat_star_alone_matches_anything() {
        let _g = crate::test_util::global_state_lock();
        assert!(matchpat("*", "", false, true));
        assert!(matchpat("*", "a", false, true));
        assert!(matchpat("*", "abcdef", false, true));
    }

    #[test]
    fn matchpat_question_alone_one_char() {
        let _g = crate::test_util::global_state_lock();
        assert!(!matchpat("?", "", false, true));
        assert!(matchpat("?", "a", false, true));
        assert!(!matchpat("?", "ab", false, true));
    }

    // ── haswilds: meta-char detection ───────────────────────────────
    #[test]
    fn haswilds_each_glob_meta() {
        let _g = crate::test_util::global_state_lock();
        assert!(haswilds("*"));
        assert!(haswilds("?"));
        assert!(haswilds("[abc]"));
        assert!(haswilds("a*b"));
        assert!(haswilds("a?b"));
    }

    #[test]
    fn haswilds_plain_strings_have_no_wildcards() {
        let _g = crate::test_util::global_state_lock();
        assert!(!haswilds(""));
        assert!(!haswilds("plain.txt"));
        assert!(!haswilds("/abs/path/file.rs"));
        assert!(!haswilds("./rel/file"));
    }

    // ── xpandbraces: brace expansion (zsh extension, not POSIX) ─────
    #[test]
    fn xpandbraces_three_alternatives() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(xpandbraces(&tok("{a,b,c}"), false), vec!["a", "b", "c"]);
    }

    #[test]
    fn xpandbraces_with_prefix_and_suffix() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(
            xpandbraces(&tok("pre{x,y,z}post"), false),
            vec!["prexpost", "preypost", "prezpost"]
        );
    }

    #[test]
    fn xpandbraces_numeric_range_ascending() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(xpandbraces(&tok("{1..5}"), false), vec!["1", "2", "3", "4", "5"]);
    }

    #[test]
    fn xpandbraces_alpha_range_ascending() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(
            xpandbraces(&tok("{a..e}"), false),
            vec!["a", "b", "c", "d", "e"]
        );
    }

    #[test]
    fn xpandbraces_single_alternative_passes_through_literal() {
        // Real zsh 5.9 (`print -l {a}`) outputs `{a}` verbatim — no
        // expansion because there is no comma or range inside the
        // braces. xpandbraces operates on TOKEN form throughout
        // (c:Src/glob.c::xpandbraces); the eventual ASCII conversion
        // happens later in untokenize. So unit-level pass-through
        // preserves TOKEN bytes, not ASCII braces.
        let _g = crate::test_util::global_state_lock();
        let out = xpandbraces(&tok("{a}"), false);
        assert_eq!(out, vec![tok("{a}")], "zsh 5.9 returns the input verbatim (TOKEN form preserved at xpandbraces layer)");
    }

    #[test]
    fn xpandbraces_no_braces_returns_input() {
        let _g = crate::test_util::global_state_lock();
        // Pure literal has nothing to expand — should yield the input
        // as a single element (or empty for empty input).
        let out = xpandbraces(&tok("plain"), false);
        assert_eq!(out, vec!["plain"]);
    }

    // ── file_type: mode → marker char (used by `ls -F`-style output) ─
    #[test]
    fn file_type_dir_marker_is_slash() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(file_type(libc::S_IFDIR as u32), '/');
    }

    #[test]
    fn file_type_regular_plain_is_space() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(file_type(libc::S_IFREG as u32), ' ');
    }

    #[test]
    fn file_type_regular_executable_is_star() {
        let _g = crate::test_util::global_state_lock();
        // Any of the three executable bits should switch the marker.
        for x in [0o100, 0o010, 0o001] {
            assert_eq!(
                file_type(libc::S_IFREG as u32 | x),
                '*',
                "exec bit 0o{x:o} should produce '*'"
            );
        }
    }

    #[test]
    fn file_type_symlink_is_at() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(file_type(libc::S_IFLNK as u32), '@');
    }

    #[test]
    fn file_type_fifo_is_pipe() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(file_type(libc::S_IFIFO as u32), '|');
    }

    #[test]
    fn file_type_socket_is_equal() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(file_type(libc::S_IFSOCK as u32), '=');
    }

    // ═══════════════════════════════════════════════════════════════════
    // xpandbraces edge cases — anchored to `print -l <pattern>` in zsh 5.9.
    // Where zshrs diverges, the test FAILS to expose the bug.
    // ═══════════════════════════════════════════════════════════════════

    /// `{1..10..2}` → 1 3 5 7 9 (step range). zsh: 5 elements.
    #[test]
    fn xpandbraces_numeric_step_two() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(
            xpandbraces(&tok("{1..10..2}"), false),
            vec!["1", "3", "5", "7", "9"]
        );
    }

    /// `{10..1..2}` → 10 8 6 4 2 (descending step).
    #[test]
    fn xpandbraces_numeric_descending_step_two() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(
            xpandbraces(&tok("{10..1..2}"), false),
            vec!["10", "8", "6", "4", "2"]
        );
    }

    /// `{5..1}` → 5 4 3 2 1 (descending range, no step).
    #[test]
    fn xpandbraces_numeric_descending_range() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(
            xpandbraces(&tok("{5..1}"), false),
            vec!["5", "4", "3", "2", "1"]
        );
    }

    /// `{01..10}` → 01 02 03 ... 10 (zero-padded; pad preserved).
    #[test]
    fn xpandbraces_zero_padded_numeric_range() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(
            xpandbraces(&tok("{01..10}"), false),
            vec!["01", "02", "03", "04", "05", "06", "07", "08", "09", "10"]
        );
    }

    /// `{001..010}` → 001 002 ... 010 (3-digit pad preserved).
    #[test]
    fn xpandbraces_three_digit_pad_preserved() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(
            xpandbraces(&tok("{001..010}"), false),
            vec![
                "001", "002", "003", "004", "005",
                "006", "007", "008", "009", "010"
            ]
        );
    }

    /// `\{a,b,c\}` → no expansion (escaped braces aren't brace
    /// delimiters). xpandbraces returns input unchanged; the lexer
    /// upstream strips the backslashes before this layer sees them.
    /// Anchored test: zsh `print -r -- \{a,b,c\}` → `{a,b,c}` because
    /// the lexer tokenizes `\{`/`\}` to `Bnull{`/`Bnull}` before
    /// xpandbraces runs, then untokenize drops the Bnulls. At the
    /// xpandbraces-unit level (raw backslashes), the only invariant
    /// to verify is "no expansion fires" — the brace literal survives.
    #[test]
    fn xpandbraces_escaped_braces_remain_literal_anchored_to_zsh() {
        let _g = crate::test_util::global_state_lock();
        // tok() emits Bnull+ASCII `{` for `\{` and Bnull+ASCII `}` for
        // `\}`, with Comma TOKEN for the unescaped commas inside.
        // xpandbraces scans for Inbrace TOKEN only (per
        // c:Src/glob.c::xpandbraces) — finds none here, so the
        // string passes through unchanged at this layer. The Bnulls
        // are stripped later by remnulargs in prefork.
        assert_eq!(
            xpandbraces(&tok("\\{a,b,c\\}"), false),
            vec![tok("\\{a,b,c\\}")],
            "xpandbraces unit: escaped braces survive without expansion (no per-element splat)"
        );
    }

    /// `{a,b}{c,d}` → ac ad bc bd (Cartesian product).
    /// 2 * 2 = 4 elements, in row-major order.
    #[test]
    fn xpandbraces_cartesian_product_two_by_two() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(
            xpandbraces(&tok("{a,b}{c,d}"), false),
            vec!["ac", "ad", "bc", "bd"]
        );
    }

    /// `{a,{b,c}}` → a b c (nested flattened).
    #[test]
    fn xpandbraces_nested_braces_flatten() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(
            xpandbraces(&tok("{a,{b,c}}"), false),
            vec!["a", "b", "c"]
        );
    }

    /// `{}` → `{}` literal (empty brace doesn't expand). xpandbraces
    /// preserves TOKEN form at this layer (c:Src/glob.c::xpandbraces);
    /// ASCII conversion happens later in untokenize.
    #[test]
    fn xpandbraces_empty_braces_remain_literal() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(xpandbraces(&tok("{}"), false), vec![tok("{}")]);
    }

    /// `a{b,c}d{e,f}` → abde abdf acde acdf (cartesian with surrounding text).
    #[test]
    fn xpandbraces_cartesian_with_surrounding_text() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(
            xpandbraces(&tok("a{b,c}d{e,f}"), false),
            vec!["abde", "abdf", "acde", "acdf"]
        );
    }

    /// `{a..z..3}` → `{a..z..3}` literal (alpha range with step NOT expanded
    /// by zsh — surprising but verified). xpandbraces preserves TOKEN form
    /// at this layer; ASCII conversion happens later in untokenize.
    #[test]
    fn xpandbraces_alpha_step_unsupported_anchored_to_zsh() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(
            xpandbraces(&tok("{a..z..3}"), false),
            vec![tok("{a..z..3}")],
            "zsh: alpha range with step → literal (TOKEN form preserved at xpandbraces layer)"
        );
    }

    // ═══════════════════════════════════════════════════════════════════
    // zsh test-corpus pins — direct anchors to Test/D09brace.ztst.
    // Tests verify brace expansion matches zsh's documented output.
    // ═══════════════════════════════════════════════════════════════════

    /// `Test/D09brace.ztst:10-12` — basic brace expansion with
    /// nested range: `X{1,2,{3..6},7,8}Y` expands all 8 values.
    #[test]
    fn zsh_corpus_basic_brace_with_nested_range() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(
            xpandbraces(&tok("X{1,2,{3..6},7,8}Y"), false),
            vec!["X1Y", "X2Y", "X3Y", "X4Y", "X5Y", "X6Y", "X7Y", "X8Y"],
            "ztst:11 — basic brace expansion with nested range",
        );
    }

    /// `Test/D09brace.ztst:30-32` — numeric range with leading zero
    /// padding: `X{01..4}Y` → all 4 values 0-padded to 2 digits.
    #[test]
    fn zsh_corpus_numeric_range_zero_padding() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(
            xpandbraces(&tok("X{01..4}Y"), false),
            vec!["X01Y", "X02Y", "X03Y", "X04Y"],
            "ztst:32 — leading-zero padding propagates to all values",
        );
    }

    /// `Test/D09brace.ztst:34-36` — padding comes from RHS too:
    /// `X{1..04}Y` → 2-digit zero-padded.
    #[test]
    fn zsh_corpus_numeric_range_padding_from_rhs() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(
            xpandbraces(&tok("X{1..04}Y"), false),
            vec!["X01Y", "X02Y", "X03Y", "X04Y"],
            "ztst:36 — RHS padding `04` propagates",
        );
    }

    /// `Test/D09brace.ztst:38-40` — unpadded range >9: `X{7..12}Y`
    /// numbers stay unpadded.
    #[test]
    fn zsh_corpus_numeric_range_no_padding_when_unspecified() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(
            xpandbraces(&tok("X{7..12}Y"), false),
            vec!["X7Y", "X8Y", "X9Y", "X10Y", "X11Y", "X12Y"],
            "ztst:40 — no padding when neither end has leading zero",
        );
    }

    /// `Test/D09brace.ztst:42-44` — `X{07..12}Y` → 2-digit padded.
    #[test]
    fn zsh_corpus_numeric_range_lhs_padding_propagates() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(
            xpandbraces(&tok("X{07..12}Y"), false),
            vec!["X07Y", "X08Y", "X09Y", "X10Y", "X11Y", "X12Y"],
            "ztst:44 — LHS padding `07` propagates",
        );
    }

    /// `Test/D09brace.ztst:46-48` — wider RHS padding overrides:
    /// `X{7..012}Y` → 3-digit padded.
    #[test]
    fn zsh_corpus_numeric_range_max_padding_width_wins() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(
            xpandbraces(&tok("X{7..012}Y"), false),
            vec!["X007Y", "X008Y", "X009Y", "X010Y", "X011Y", "X012Y"],
            "ztst:48 — widest padding width wins",
        );
    }

    /// `Test/D09brace.ztst:50-52` — decreasing range: `X{4..1}Y` →
    /// 4,3,2,1 (reversed).
    #[test]
    fn zsh_corpus_numeric_range_decreasing() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(
            xpandbraces(&tok("X{4..1}Y"), false),
            vec!["X4Y", "X3Y", "X2Y", "X1Y"],
            "ztst:52 — decreasing range emits in reverse",
        );
    }

    /// `Test/D09brace.ztst:54-56` — combined braces: `X{1..4}{1..4}Y`
    /// → 16-element cross product.
    #[test]
    fn zsh_corpus_combined_braces_cross_product() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(
            xpandbraces(&tok("X{1..4}{1..4}Y"), false),
            vec![
                "X11Y", "X12Y", "X13Y", "X14Y",
                "X21Y", "X22Y", "X23Y", "X24Y",
                "X31Y", "X32Y", "X33Y", "X34Y",
                "X41Y", "X42Y", "X43Y", "X44Y",
            ],
            "ztst:56 — combined-brace cross product",
        );
    }

    /// `Test/D09brace.ztst:58-60` — negative numbers in range:
    /// `X{-4..4}Y` → `-4`..`4` (9 values including 0).
    #[test]
    fn zsh_corpus_negative_numbers_in_range() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(
            xpandbraces(&tok("X{-4..4}Y"), false),
            vec![
                "X-4Y", "X-3Y", "X-2Y", "X-1Y", "X0Y",
                "X1Y", "X2Y", "X3Y", "X4Y",
            ],
            "ztst:60 — negative-to-positive range",
        );
    }

    /// `Test/D09brace.ztst:62-64` — reverse-direction numeric range:
    /// `X{4..-4}Y` walks from 4 to -4 descending.
    #[test]
    fn zsh_corpus_brace_descending_range_from_positive_to_negative() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(
            xpandbraces(&tok("X{4..-4}Y"), false),
            vec![
                "X4Y", "X3Y", "X2Y", "X1Y", "X0Y",
                "X-1Y", "X-2Y", "X-3Y", "X-4Y",
            ],
            "ztst:64 — descending 4..-4 produces 9 values",
        );
    }

    /// `Test/D09brace.ztst:66-68` — stepped padded range:
    /// `X{004..-4..2}Y` = X004Y X002Y X000Y X-02Y X-04Y.
    /// Padding width 3 from LHS; step is +2 (sign of step is ignored,
    /// direction is from start to end).
    #[test]
    fn zsh_corpus_brace_stepped_padded_descending() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(
            xpandbraces(&tok("X{004..-4..2}Y"), false),
            vec!["X004Y", "X002Y", "X000Y", "X-02Y", "X-04Y"],
            "ztst:68 — stepped+padded descending",
        );
    }

    /// `Test/D09brace.ztst:74-76` — step alignment 1: `X{1..32..3}Y`
    /// = X1Y X4Y X7Y X10Y X13Y X16Y X19Y X22Y X25Y X28Y X31Y.
    /// Step 3 starting from 1, capped at 32.
    #[test]
    fn zsh_corpus_brace_step_alignment_1_to_32_step_3() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(
            xpandbraces(&tok("X{1..32..3}Y"), false),
            vec![
                "X1Y", "X4Y", "X7Y", "X10Y", "X13Y", "X16Y",
                "X19Y", "X22Y", "X25Y", "X28Y", "X31Y",
            ],
            "ztst:76 — {{1..32..3}} step alignment",
        );
    }

    /// `Test/D09brace.ztst:100-102` — `hey{a..j}there` — char range.
    #[test]
    fn zsh_corpus_brace_char_range_simple() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(
            xpandbraces(&tok("hey{a..j}there"), false),
            vec![
                "heyathere", "heybthere", "heycthere", "heydthere",
                "heyethere", "heyfthere", "heygthere", "heyhthere",
                "heyithere", "heyjthere",
            ],
            "ztst:102 — char range a..j",
        );
    }

    /// `Test/D09brace.ztst:108-110` — reverse char range:
    /// `crumbs{y..p}ooh` walks down y → p (10 values).
    #[test]
    fn zsh_corpus_brace_char_range_reverse() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(
            xpandbraces(&tok("crumbs{y..p}ooh"), false),
            vec![
                "crumbsyooh", "crumbsxooh", "crumbswooh", "crumbsvooh",
                "crumbsuooh", "crumbstooh", "crumbssooh", "crumbsrooh",
                "crumbsqooh", "crumbspooh",
            ],
            "ztst:110 — char range y..p reverse",
        );
    }

    /// `Test/D09brace.ztst:104-106` — nested brace: `gosh{1,{Z..a},2}cripes`
    /// — inner `{Z..a}` is char range Z to a in ASCII order (10 chars).
    /// Full output: gosh1cripes goshZcripes gosh[cripes gosh\cripes
    /// gosh]cripes gosh^cripes gosh_cripes gosh`cripes goshacripes
    /// gosh2cripes.
    #[test]
    fn zsh_corpus_brace_nested_with_char_range_ascii() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(
            xpandbraces(&tok("gosh{1,{Z..a},2}cripes"), false),
            vec![
                "gosh1cripes", "goshZcripes", "gosh[cripes", "gosh\\cripes",
                "gosh]cripes", "gosh^cripes", "gosh_cripes", "gosh`cripes",
                "goshacripes", "gosh2cripes",
            ],
            "ztst:106 — nested brace with ASCII char range",
        );
    }

    /// `Test/D09brace.ztst:116-118` — unmatched closing brace after
    /// matched braces stays literal: `{1..10}{..` → `1{.. 2{.. ...`.
    #[test]
    #[ignore = "ZSHRS BUG: unmatched trailing braces not preserved literally"]
    fn zsh_corpus_brace_unmatched_after_matched_left_literal() {
        let _g = crate::test_util::global_state_lock();
        assert_eq!(
            xpandbraces(&tok("{1..10}{.."), false),
            vec![
                "1{..", "2{..", "3{..", "4{..", "5{..",
                "6{..", "7{..", "8{..", "9{..", "10{..",
            ],
            "ztst:118 — unmatched trailing {{.. left literal",
        );
    }

    // ── split_qualifier: parse trailing (qual) block ─────────────────
    /// `*.txt` (no trailing parens) → (input, None).
    #[test]
    fn split_qualifier_no_parens_returns_input_and_none() {
        let _g = crate::test_util::global_state_lock();
        let (head, qual) = split_qualifier("*.txt");
        assert_eq!(head, "*.txt");
        assert_eq!(qual, None);
    }

    /// `*(N)` → ("*", Some("N")) — null-glob qualifier.
    #[test]
    fn split_qualifier_star_paren_N_extracts_null_glob_qual() {
        let _g = crate::test_util::global_state_lock();
        let (head, qual) = split_qualifier("*(N)");
        assert_eq!(head, "*");
        assert_eq!(qual, Some("N"));
    }

    /// `*(.)` → ("*", Some(".")) — regular-file qualifier.
    #[test]
    fn split_qualifier_star_paren_dot_extracts_regular_file_qual() {
        let _g = crate::test_util::global_state_lock();
        let (head, qual) = split_qualifier("*(.)");
        assert_eq!(head, "*");
        assert_eq!(qual, Some("."));
    }

    /// `*.rs(.)` → ("*.rs", Some(".")) — qualifier on glob pattern.
    #[test]
    fn split_qualifier_pattern_with_qual_extracts_correctly() {
        let _g = crate::test_util::global_state_lock();
        let (head, qual) = split_qualifier("*.rs(.)");
        assert_eq!(head, "*.rs");
        assert_eq!(qual, Some("."));
    }

    /// `*(#qN)` → ("*", Some("N")) — `#q` prefix stripped per zsh syntax.
    #[test]
    fn split_qualifier_hash_q_prefix_stripped() {
        let _g = crate::test_util::global_state_lock();
        let (head, qual) = split_qualifier("*(#qN)");
        assert_eq!(head, "*");
        assert_eq!(qual, Some("N"));
    }

    /// `*(om[1])` → ("*", Some("om[1]")) — sort-by-mtime keep first.
    #[test]
    fn split_qualifier_multichar_qual_with_brackets() {
        let _g = crate::test_util::global_state_lock();
        let (head, qual) = split_qualifier("*(om[1])");
        assert_eq!(head, "*");
        assert_eq!(qual, Some("om[1]"));
    }

    /// `(a)(b)` — multiple paren groups: split takes the OUTERMOST trailing.
    #[test]
    fn split_qualifier_multiple_groups_takes_outermost_trailing() {
        let _g = crate::test_util::global_state_lock();
        let (head, qual) = split_qualifier("(a)(b)");
        assert_eq!(head, "(a)");
        assert_eq!(qual, Some("b"));
    }

    // ═══════════════════════════════════════════════════════════════════
    // parse_qualifier_string — file-type / permission / sort qualifiers.
    // Tests call the private fn directly (same crate, same file).
    // Each qualifier letter maps to a `qualifier::*` variant per the
    // zsh glob.c arm at c:1495+. Pin the parse, not the match — the
    // match path needs a real filesystem.
    //
    // IMPORTANT: at end of parse_qualifier_string (c:3433-3435 in this
    // file), if `qualifiers` is non-empty it gets moved into
    // `alternatives[]`. So tests read the qualifier from `alternatives[0]`
    // — qualifiers itself is empty after the move.
    // ═══════════════════════════════════════════════════════════════════

    /// Helper: read the only qualifier from a single-letter parse result.
    fn first_qual(qs: &qualifier_set) -> &qualifier {
        // After the post-loop move, single-letter input lands in
        // alternatives[0][0]. Fall back to qualifiers[0] for safety in
        // case the move ever changes.
        if !qs.alternatives.is_empty() && !qs.alternatives[0].is_empty() {
            &qs.alternatives[0][0]
        } else {
            &qs.qualifiers[0]
        }
    }

    /// Empty qualifier body → no alternatives, no qualifiers.
    #[test]
    fn parse_qualifier_string_empty_returns_empty_set() {
        let _g = crate::test_util::global_state_lock();
        let qs = parse_qualifier_string("");
        assert!(qs.qualifiers.is_empty());
        assert!(qs.alternatives.is_empty());
        assert!(!qs.nullglob);
    }

    /// `/` → IsDirectory (in alternatives[0]).
    #[test]
    fn parse_qualifier_string_slash_is_directory() {
        let _g = crate::test_util::global_state_lock();
        let qs = parse_qualifier_string("/");
        assert!(matches!(first_qual(&qs), qualifier::IsDirectory));
    }

    /// `.` → IsRegular.
    #[test]
    fn parse_qualifier_string_dot_is_regular() {
        let _g = crate::test_util::global_state_lock();
        let qs = parse_qualifier_string(".");
        assert!(matches!(first_qual(&qs), qualifier::IsRegular));
    }

    /// `@` → IsSymlink.
    #[test]
    fn parse_qualifier_string_at_is_symlink() {
        let _g = crate::test_util::global_state_lock();
        let qs = parse_qualifier_string("@");
        assert!(matches!(first_qual(&qs), qualifier::IsSymlink));
    }

    /// `=` → IsSocket.
    #[test]
    fn parse_qualifier_string_equals_is_socket() {
        let _g = crate::test_util::global_state_lock();
        let qs = parse_qualifier_string("=");
        assert!(matches!(first_qual(&qs), qualifier::IsSocket));
    }

    /// `p` → IsFifo.
    #[test]
    fn parse_qualifier_string_p_is_fifo() {
        let _g = crate::test_util::global_state_lock();
        let qs = parse_qualifier_string("p");
        assert!(matches!(first_qual(&qs), qualifier::IsFifo));
    }

    /// `*` → IsExecutable.
    #[test]
    fn parse_qualifier_string_star_is_executable() {
        let _g = crate::test_util::global_state_lock();
        let qs = parse_qualifier_string("*");
        assert!(matches!(first_qual(&qs), qualifier::IsExecutable));
    }

    /// `%b` → IsBlockDev.
    #[test]
    fn parse_qualifier_string_pct_b_is_block_device() {
        let _g = crate::test_util::global_state_lock();
        let qs = parse_qualifier_string("%b");
        assert!(matches!(first_qual(&qs), qualifier::IsBlockDev));
    }

    /// `%c` → IsCharDev.
    #[test]
    fn parse_qualifier_string_pct_c_is_char_device() {
        let _g = crate::test_util::global_state_lock();
        let qs = parse_qualifier_string("%c");
        assert!(matches!(first_qual(&qs), qualifier::IsCharDev));
    }

    /// `r` / `w` / `x` → Readable / Writable / Executable.
    #[test]
    fn parse_qualifier_string_perm_letters_map_to_perm_qualifiers() {
        let _g = crate::test_util::global_state_lock();
        for (letter, expected) in [
            ("r", qualifier::Readable),
            ("w", qualifier::Writable),
            ("x", qualifier::Executable),
        ] {
            let qs = parse_qualifier_string(letter);
            assert_eq!(
                std::mem::discriminant(first_qual(&qs)),
                std::mem::discriminant(&expected),
                "letter {letter:?} should map to {expected:?}"
            );
        }
    }

    /// `U` → OwnedByEuid (process EUID).
    #[test]
    fn parse_qualifier_string_capital_U_is_owned_by_euid() {
        let _g = crate::test_util::global_state_lock();
        let qs = parse_qualifier_string("U");
        assert!(matches!(first_qual(&qs), qualifier::OwnedByEuid));
    }

    /// `G` → OwnedByEgid.
    #[test]
    fn parse_qualifier_string_capital_G_is_owned_by_egid() {
        let _g = crate::test_util::global_state_lock();
        let qs = parse_qualifier_string("G");
        assert!(matches!(first_qual(&qs), qualifier::OwnedByEgid));
    }

    /// Multiple file-type qualifiers stack — `./` → IsRegular then IsDirectory
    /// both end up in alternatives[0].
    #[test]
    fn parse_qualifier_string_multiple_letters_stack_in_one_alternative() {
        let _g = crate::test_util::global_state_lock();
        let qs = parse_qualifier_string("./");
        assert_eq!(qs.alternatives.len(), 1);
        assert_eq!(qs.alternatives[0].len(), 2);
        assert!(matches!(qs.alternatives[0][0], qualifier::IsRegular));
        assert!(matches!(qs.alternatives[0][1], qualifier::IsDirectory));
    }

    /// `,` separates alternatives — `/,.` → two alternatives, each with one
    /// qualifier (IsDirectory and IsRegular respectively).
    #[test]
    fn parse_qualifier_string_comma_creates_two_alternatives() {
        let _g = crate::test_util::global_state_lock();
        let qs = parse_qualifier_string("/,.");
        assert_eq!(qs.alternatives.len(), 2, "two alternatives expected");
        assert!(matches!(qs.alternatives[0][0], qualifier::IsDirectory));
        assert!(matches!(qs.alternatives[1][0], qualifier::IsRegular));
    }

    /// `:` introduces colon-modifiers; rest captured into colon_mods.
    #[test]
    fn parse_qualifier_string_colon_captures_modifiers_in_field() {
        let _g = crate::test_util::global_state_lock();
        let qs = parse_qualifier_string(":h");
        assert_eq!(qs.colon_mods.as_deref(), Some(":h"));
    }

    /// `:` after a qualifier captures BOTH.
    #[test]
    fn parse_qualifier_string_qualifier_then_colon_mod() {
        let _g = crate::test_util::global_state_lock();
        let qs = parse_qualifier_string("/:h");
        assert!(matches!(first_qual(&qs), qualifier::IsDirectory));
        assert_eq!(qs.colon_mods.as_deref(), Some(":h"));
    }

    /// `N` flag → nullglob set, no qualifier pushed.
    #[test]
    fn parse_qualifier_string_capital_N_sets_nullglob_flag() {
        let _g = crate::test_util::global_state_lock();
        let qs = parse_qualifier_string("N");
        assert!(qs.nullglob, "(N) must set nullglob");
        assert!(qs.alternatives.is_empty(), "N doesn't push to qualifiers");
    }

    /// `M` flag → mark_dirs.
    #[test]
    fn parse_qualifier_string_capital_M_sets_mark_dirs_flag() {
        let _g = crate::test_util::global_state_lock();
        let qs = parse_qualifier_string("M");
        assert!(qs.mark_dirs, "(M) must set mark_dirs");
    }

    /// `T` flag → list_types.
    #[test]
    fn parse_qualifier_string_capital_T_sets_list_types_flag() {
        let _g = crate::test_util::global_state_lock();
        let qs = parse_qualifier_string("T");
        assert!(qs.list_types, "(T) must set list_types");
    }

    // ── split_qualifier integration with parse_qualifier_string ──────
    /// `*(.)` — split yields ("*", Some(".")); parse yields IsRegular.
    #[test]
    fn split_then_parse_dot_qualifier_yields_is_regular() {
        let _g = crate::test_util::global_state_lock();
        let (head, qual) = split_qualifier("*(.)");
        assert_eq!(head, "*");
        let qs = parse_qualifier_string(qual.unwrap());
        assert!(matches!(first_qual(&qs), qualifier::IsRegular));
    }

    /// `*(/)` — directory-only glob.
    #[test]
    fn split_then_parse_slash_qualifier_yields_is_directory() {
        let _g = crate::test_util::global_state_lock();
        let (_, qual) = split_qualifier("*(/)");
        let qs = parse_qualifier_string(qual.unwrap());
        assert!(matches!(first_qual(&qs), qualifier::IsDirectory));
    }

    // ═══════════════════════════════════════════════════════════════════
    // Sort qualifiers — `o<key>` ascending, `O<key>` descending.
    // ═══════════════════════════════════════════════════════════════════

    /// `oN` — sort by NONE (no sorting key requested).
    #[test]
    fn parse_qualifier_string_oN_pushes_gs_none() {
        let _g = crate::test_util::global_state_lock();
        let qs = parse_qualifier_string("oN");
        assert_eq!(qs.sorts.len(), 1);
        assert_ne!(qs.sorts[0] & GS_NONE, 0, "oN must set GS_NONE bit");
    }

    /// `on` — sort by name ascending.
    #[test]
    fn parse_qualifier_string_on_pushes_gs_name_ascending() {
        let _g = crate::test_util::global_state_lock();
        let qs = parse_qualifier_string("on");
        assert_eq!(qs.sorts.len(), 1);
        assert_eq!(qs.sorts[0] & GS_NAME, GS_NAME);
        assert_eq!(qs.sorts[0] & GS_DESC, 0);
    }

    /// `On` — sort by name descending.
    #[test]
    fn parse_qualifier_string_On_pushes_gs_name_descending() {
        let _g = crate::test_util::global_state_lock();
        let qs = parse_qualifier_string("On");
        assert_eq!(qs.sorts.len(), 1);
        assert_eq!(qs.sorts[0] & GS_NAME, GS_NAME);
        assert_eq!(qs.sorts[0] & GS_DESC, GS_DESC);
    }

    /// Multiple sort keys stack.
    #[test]
    fn parse_qualifier_string_chained_sort_keys_stack() {
        let _g = crate::test_util::global_state_lock();
        let qs = parse_qualifier_string("onOL");
        assert_eq!(qs.sorts.len(), 2);
    }

    // ── Size qualifier — `L<unit><op><value>` ───────────────────────
    // NOTE: zshrs's parse_range_spec normalises `+` (greater) → '>' and
    // `-` (less) → '<' for the internal op char, matching C's qgetnum
    // convention (Src/glob.c c:1620-ish).

    /// `Lk+1` — size > 1 kilobyte. zsh syntax: `L<unit><op><value>`
    /// (unit char BEFORE op).
    #[test]
    fn parse_qualifier_string_Lk_plus_one_size_kilobyte() {
        let _g = crate::test_util::global_state_lock();
        let qs = parse_qualifier_string("Lk+1");
        match first_qual(&qs) {
            qualifier::Size { value, unit, op } => {
                assert_eq!(*value, 1);
                assert_eq!(*unit, TT_KILOBYTES);
                assert_eq!(*op, '>', "+ is stored as '>' (greater than)");
            }
            other => panic!("expected Size, got {other:?}"),
        }
    }

    /// `L-100` — size < 100 (default unit bytes). Stored op is '<'.
    #[test]
    fn parse_qualifier_string_L_minus_100_size_bytes() {
        let _g = crate::test_util::global_state_lock();
        let qs = parse_qualifier_string("L-100");
        match first_qual(&qs) {
            qualifier::Size { value, unit, op } => {
                assert_eq!(*value, 100);
                assert_eq!(*unit, TT_BYTES);
                assert_eq!(*op, '<', "- is stored as '<' (less than)");
            }
            other => panic!("expected Size, got {other:?}"),
        }
    }

    /// `Lm+1` — size > 1 megabyte; unit recognised.
    #[test]
    fn parse_qualifier_string_Lm_megabyte_unit() {
        let _g = crate::test_util::global_state_lock();
        let qs = parse_qualifier_string("Lm+1");
        match first_qual(&qs) {
            qualifier::Size { unit, .. } => assert_eq!(*unit, TT_MEGABYTES),
            other => panic!("expected Size, got {other:?}"),
        }
    }

    // ── Time qualifier — same op normalisation ───────────────────────
    /// `m-1` — modified less than 1 day ago. Stored op '<'.
    #[test]
    fn parse_qualifier_string_m_minus_1_day_default_unit() {
        let _g = crate::test_util::global_state_lock();
        let qs = parse_qualifier_string("m-1");
        match first_qual(&qs) {
            qualifier::Mtime { value, unit, op } => {
                assert_eq!(*value, 1);
                assert_eq!(*unit, TT_DAYS);
                assert_eq!(*op, '<');
            }
            other => panic!("expected Mtime, got {other:?}"),
        }
    }

    /// `mh+24` — modified more than 24 hours ago. Stored op '>'.
    #[test]
    fn parse_qualifier_string_mh_plus_24_hours() {
        let _g = crate::test_util::global_state_lock();
        let qs = parse_qualifier_string("mh+24");
        match first_qual(&qs) {
            qualifier::Mtime { value, unit, op } => {
                assert_eq!(*value, 24);
                assert_eq!(*unit, TT_HOURS);
                assert_eq!(*op, '>');
            }
            other => panic!("expected Mtime, got {other:?}"),
        }
    }

    /// `a-7` — accessed less than 7 days ago. Stored op '<'.
    #[test]
    fn parse_qualifier_string_a_minus_7_days() {
        let _g = crate::test_util::global_state_lock();
        let qs = parse_qualifier_string("a-7");
        match first_qual(&qs) {
            qualifier::Atime { value, unit, op } => {
                assert_eq!(*value, 7);
                assert_eq!(*unit, TT_DAYS);
                assert_eq!(*op, '<');
            }
            other => panic!("expected Atime, got {other:?}"),
        }
    }

    // ── Subscript qualifier — `[N]` keep first ───────────────────────
    /// `[1]` — first entry only.
    #[test]
    fn parse_qualifier_string_bracket_one_sets_first_to_one() {
        let _g = crate::test_util::global_state_lock();
        let qs = parse_qualifier_string("[1]");
        assert_eq!(qs.first, Some(1));
    }

    /// `om[1]` — sort by mtime, keep first.
    #[test]
    fn parse_qualifier_string_om_bracket_one_sort_and_subscript() {
        let _g = crate::test_util::global_state_lock();
        let qs = parse_qualifier_string("om[1]");
        assert_eq!(qs.sorts.len(), 1);
        assert_eq!(qs.sorts[0] & GS_MTIME, GS_MTIME);
        assert_eq!(qs.first, Some(1));
    }
}