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
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
18787
18788
18789
18790
18791
18792
18793
18794
18795
18796
18797
18798
18799
18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818
18819
18820
18821
18822
18823
18824
18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871
18872
18873
18874
18875
18876
18877
18878
18879
18880
18881
18882
18883
18884
18885
18886
18887
18888
18889
18890
18891
18892
18893
18894
18895
18896
18897
18898
18899
18900
18901
18902
18903
18904
18905
18906
18907
18908
18909
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079
19080
19081
19082
19083
19084
19085
19086
19087
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145
19146
19147
19148
19149
19150
19151
19152
19153
19154
19155
19156
19157
19158
19159
19160
19161
19162
19163
19164
19165
19166
19167
19168
19169
19170
19171
19172
19173
19174
19175
19176
19177
19178
19179
19180
19181
19182
19183
19184
19185
19186
19187
19188
19189
19190
19191
19192
19193
19194
19195
19196
19197
19198
19199
19200
19201
19202
19203
19204
19205
19206
19207
19208
19209
19210
19211
19212
19213
19214
19215
19216
19217
19218
19219
19220
19221
19222
19223
19224
19225
19226
19227
19228
19229
19230
19231
19232
19233
19234
19235
19236
19237
19238
19239
19240
19241
19242
19243
19244
19245
19246
19247
19248
19249
19250
19251
19252
19253
19254
19255
19256
19257
19258
19259
19260
19261
19262
19263
19264
19265
19266
19267
19268
19269
19270
19271
19272
19273
19274
19275
19276
19277
19278
19279
19280
19281
19282
19283
19284
19285
19286
19287
19288
19289
19290
19291
19292
19293
19294
19295
19296
19297
19298
19299
19300
19301
19302
19303
19304
19305
19306
19307
19308
19309
19310
19311
19312
19313
19314
19315
19316
19317
19318
19319
19320
19321
19322
19323
19324
19325
19326
19327
19328
19329
19330
19331
19332
19333
19334
19335
19336
19337
19338
19339
19340
19341
19342
19343
19344
19345
19346
19347
19348
19349
19350
19351
19352
19353
19354
19355
19356
19357
19358
19359
19360
19361
19362
19363
19364
19365
19366
19367
19368
19369
19370
19371
19372
19373
19374
19375
19376
19377
19378
19379
19380
19381
19382
19383
19384
19385
19386
19387
19388
19389
19390
19391
19392
19393
19394
19395
19396
19397
19398
19399
19400
19401
19402
19403
19404
19405
19406
19407
19408
19409
19410
19411
19412
19413
19414
19415
19416
19417
19418
19419
19420
19421
19422
19423
19424
19425
19426
19427
19428
19429
19430
19431
19432
19433
19434
19435
19436
19437
19438
19439
19440
19441
19442
19443
19444
19445
19446
19447
19448
19449
19450
19451
19452
19453
19454
19455
19456
19457
19458
19459
19460
19461
19462
19463
19464
19465
19466
19467
19468
19469
19470
19471
19472
19473
19474
19475
19476
19477
19478
19479
19480
19481
19482
19483
19484
19485
19486
19487
19488
19489
19490
19491
19492
19493
19494
19495
19496
19497
19498
19499
19500
19501
19502
19503
19504
19505
19506
19507
19508
19509
19510
19511
19512
19513
19514
19515
19516
19517
19518
19519
19520
19521
19522
19523
19524
19525
19526
19527
19528
19529
19530
19531
19532
19533
19534
19535
19536
19537
19538
19539
19540
19541
19542
19543
19544
19545
19546
19547
19548
19549
19550
19551
19552
19553
19554
19555
19556
19557
19558
19559
19560
19561
19562
19563
19564
19565
19566
19567
19568
19569
19570
19571
19572
19573
19574
19575
19576
19577
19578
19579
19580
19581
19582
19583
19584
19585
19586
19587
19588
19589
19590
19591
19592
19593
19594
19595
19596
19597
19598
19599
19600
19601
19602
19603
19604
19605
19606
19607
19608
19609
19610
19611
19612
19613
19614
19615
19616
19617
19618
19619
19620
19621
19622
19623
19624
19625
19626
19627
19628
19629
19630
19631
19632
19633
19634
19635
19636
19637
19638
19639
19640
19641
19642
19643
19644
19645
19646
19647
19648
19649
19650
19651
19652
19653
19654
19655
19656
19657
19658
19659
19660
19661
19662
19663
19664
19665
19666
19667
19668
19669
19670
19671
19672
19673
19674
19675
19676
19677
19678
19679
19680
19681
19682
19683
19684
19685
19686
19687
19688
19689
19690
19691
19692
19693
19694
19695
19696
19697
19698
19699
19700
19701
19702
19703
19704
19705
19706
19707
19708
19709
19710
19711
19712
19713
19714
19715
19716
19717
19718
19719
19720
19721
19722
19723
19724
19725
19726
19727
19728
19729
19730
19731
19732
19733
19734
19735
19736
19737
19738
19739
19740
19741
19742
19743
19744
19745
19746
19747
19748
19749
19750
19751
19752
19753
19754
19755
19756
19757
19758
19759
19760
19761
19762
19763
19764
19765
19766
19767
19768
19769
19770
19771
19772
19773
19774
19775
19776
19777
19778
19779
19780
19781
19782
19783
19784
19785
19786
19787
19788
19789
19790
19791
19792
19793
19794
19795
19796
19797
19798
19799
19800
19801
19802
19803
19804
19805
19806
19807
19808
19809
19810
19811
19812
19813
19814
19815
19816
19817
19818
19819
19820
19821
19822
19823
19824
19825
19826
19827
19828
19829
19830
19831
19832
19833
19834
19835
19836
19837
19838
19839
19840
19841
19842
19843
19844
19845
19846
19847
19848
19849
19850
19851
19852
19853
19854
19855
19856
19857
19858
19859
19860
19861
19862
19863
19864
19865
19866
19867
19868
19869
19870
19871
19872
19873
19874
19875
19876
19877
19878
19879
19880
19881
19882
19883
19884
19885
19886
19887
19888
19889
19890
19891
19892
19893
19894
19895
19896
19897
19898
19899
19900
19901
19902
19903
19904
19905
19906
19907
19908
19909
19910
19911
19912
19913
19914
19915
19916
19917
19918
19919
19920
19921
19922
19923
19924
19925
19926
19927
19928
19929
19930
19931
19932
19933
19934
19935
19936
19937
19938
19939
19940
19941
19942
19943
19944
19945
19946
19947
19948
19949
19950
19951
19952
19953
19954
19955
19956
19957
19958
19959
19960
19961
19962
19963
19964
19965
19966
19967
19968
19969
19970
19971
19972
19973
19974
19975
19976
19977
19978
19979
19980
19981
19982
19983
19984
19985
19986
19987
19988
19989
19990
19991
19992
19993
19994
19995
19996
19997
19998
19999
20000
20001
20002
20003
20004
20005
20006
20007
20008
20009
20010
20011
20012
20013
20014
20015
20016
20017
20018
20019
20020
20021
20022
20023
20024
20025
20026
20027
20028
20029
20030
20031
20032
20033
20034
20035
20036
20037
20038
20039
20040
20041
20042
20043
20044
20045
20046
20047
20048
20049
20050
20051
20052
20053
20054
20055
20056
20057
20058
20059
20060
20061
20062
20063
20064
20065
20066
20067
20068
20069
20070
20071
20072
20073
20074
20075
20076
20077
20078
20079
20080
20081
20082
20083
20084
20085
20086
20087
20088
20089
20090
20091
20092
20093
20094
20095
20096
20097
20098
20099
20100
20101
20102
20103
20104
20105
20106
20107
20108
20109
20110
20111
20112
20113
20114
20115
20116
20117
20118
20119
20120
20121
20122
20123
20124
20125
20126
20127
20128
20129
20130
20131
20132
20133
20134
20135
20136
20137
20138
20139
20140
20141
20142
20143
20144
20145
20146
20147
20148
20149
20150
20151
20152
20153
20154
20155
20156
20157
20158
20159
20160
20161
20162
20163
20164
20165
20166
20167
20168
20169
20170
20171
20172
20173
20174
20175
20176
20177
20178
20179
20180
20181
20182
20183
20184
20185
20186
20187
20188
20189
20190
20191
20192
20193
20194
20195
20196
20197
20198
20199
20200
20201
20202
20203
20204
20205
20206
20207
20208
20209
20210
20211
20212
20213
20214
20215
20216
20217
20218
20219
20220
20221
20222
20223
20224
20225
20226
20227
20228
20229
20230
20231
20232
20233
20234
20235
20236
20237
20238
20239
20240
20241
20242
20243
20244
20245
20246
20247
20248
20249
20250
20251
20252
20253
20254
20255
20256
20257
20258
20259
20260
20261
20262
20263
20264
20265
20266
20267
20268
20269
20270
20271
20272
20273
20274
20275
20276
20277
20278
20279
20280
20281
20282
20283
20284
20285
20286
20287
20288
20289
20290
20291
20292
20293
20294
20295
20296
20297
20298
20299
20300
20301
20302
20303
20304
20305
20306
20307
20308
20309
20310
20311
20312
20313
20314
20315
20316
20317
20318
20319
20320
20321
20322
20323
20324
20325
20326
20327
20328
20329
20330
20331
20332
20333
20334
20335
20336
20337
20338
20339
20340
20341
20342
20343
20344
20345
20346
20347
20348
20349
20350
20351
20352
20353
20354
20355
20356
20357
20358
20359
20360
20361
20362
20363
20364
20365
20366
20367
20368
20369
20370
20371
20372
20373
20374
20375
20376
20377
20378
20379
20380
20381
20382
20383
20384
20385
20386
20387
20388
20389
20390
20391
20392
20393
20394
20395
20396
20397
20398
20399
20400
20401
20402
20403
20404
20405
20406
20407
20408
20409
20410
20411
20412
20413
20414
20415
20416
20417
20418
20419
20420
20421
20422
20423
20424
20425
20426
20427
20428
20429
20430
20431
20432
20433
20434
20435
20436
20437
20438
20439
20440
20441
20442
20443
20444
20445
20446
20447
20448
20449
20450
20451
20452
20453
20454
20455
20456
20457
20458
20459
20460
20461
20462
20463
20464
20465
20466
20467
20468
20469
20470
20471
20472
20473
20474
20475
20476
20477
20478
20479
20480
20481
20482
20483
20484
20485
20486
20487
20488
20489
20490
20491
20492
20493
20494
20495
20496
20497
20498
20499
20500
20501
20502
20503
20504
20505
20506
20507
20508
20509
20510
20511
20512
20513
20514
20515
20516
20517
20518
20519
20520
20521
20522
20523
20524
20525
20526
20527
20528
20529
20530
20531
20532
20533
20534
20535
20536
20537
20538
20539
20540
20541
20542
20543
20544
20545
20546
20547
20548
20549
20550
20551
20552
20553
20554
20555
20556
20557
20558
20559
20560
20561
20562
20563
20564
20565
20566
20567
20568
20569
20570
20571
20572
20573
20574
20575
20576
20577
20578
20579
20580
20581
20582
20583
20584
20585
20586
20587
20588
20589
20590
20591
20592
20593
20594
20595
20596
20597
20598
20599
20600
20601
20602
20603
20604
20605
20606
20607
20608
20609
20610
20611
20612
20613
20614
20615
20616
20617
20618
20619
20620
20621
20622
20623
20624
20625
20626
20627
20628
20629
20630
20631
20632
20633
20634
20635
20636
20637
20638
20639
20640
20641
20642
20643
20644
20645
20646
20647
20648
20649
20650
20651
20652
20653
20654
20655
20656
20657
20658
20659
20660
20661
20662
20663
20664
20665
20666
20667
20668
20669
20670
20671
20672
20673
20674
20675
20676
20677
20678
20679
20680
20681
20682
20683
20684
20685
20686
20687
20688
20689
20690
20691
20692
20693
20694
20695
20696
20697
20698
20699
20700
20701
20702
20703
20704
20705
20706
20707
20708
20709
20710
20711
20712
20713
20714
20715
20716
20717
20718
20719
20720
20721
20722
20723
20724
20725
20726
20727
20728
20729
20730
20731
20732
20733
20734
20735
20736
20737
20738
20739
20740
20741
20742
20743
20744
20745
20746
20747
20748
20749
20750
20751
20752
20753
20754
20755
20756
20757
20758
20759
20760
20761
20762
20763
20764
20765
20766
20767
20768
20769
20770
20771
20772
20773
20774
20775
20776
20777
20778
20779
20780
20781
20782
20783
20784
20785
20786
20787
20788
20789
20790
20791
20792
20793
20794
20795
20796
20797
20798
20799
20800
20801
20802
20803
20804
20805
20806
20807
20808
20809
20810
20811
20812
20813
20814
20815
20816
20817
20818
20819
20820
20821
20822
20823
20824
20825
20826
20827
20828
20829
20830
20831
20832
20833
20834
20835
20836
20837
20838
20839
20840
20841
20842
20843
20844
20845
20846
20847
20848
20849
20850
20851
20852
20853
20854
20855
20856
20857
20858
20859
20860
20861
20862
20863
20864
20865
20866
20867
20868
20869
20870
20871
20872
20873
20874
20875
20876
20877
20878
20879
20880
20881
20882
20883
20884
20885
20886
20887
20888
20889
20890
20891
20892
20893
20894
20895
20896
20897
20898
20899
20900
20901
20902
20903
20904
20905
20906
20907
20908
20909
20910
20911
20912
20913
20914
20915
20916
20917
20918
20919
20920
20921
20922
20923
20924
20925
20926
20927
20928
20929
20930
20931
20932
20933
20934
20935
20936
20937
20938
20939
20940
20941
20942
20943
20944
20945
20946
20947
20948
20949
20950
20951
20952
20953
20954
20955
20956
20957
20958
20959
20960
20961
20962
20963
20964
20965
20966
20967
20968
20969
20970
20971
20972
20973
20974
20975
20976
20977
20978
20979
20980
20981
20982
20983
20984
20985
20986
20987
20988
20989
20990
20991
20992
20993
20994
20995
20996
20997
20998
20999
21000
21001
21002
21003
21004
21005
21006
21007
21008
21009
21010
21011
21012
21013
21014
21015
21016
21017
21018
21019
21020
21021
21022
21023
21024
21025
21026
21027
21028
21029
21030
21031
21032
21033
21034
21035
21036
21037
21038
21039
21040
21041
21042
21043
21044
21045
21046
21047
21048
21049
21050
21051
21052
21053
21054
21055
21056
21057
21058
21059
21060
21061
21062
21063
21064
21065
21066
21067
21068
21069
21070
21071
21072
21073
21074
21075
21076
21077
21078
21079
21080
21081
21082
21083
21084
21085
21086
21087
21088
21089
21090
21091
21092
21093
21094
21095
21096
21097
21098
21099
21100
21101
21102
21103
21104
21105
21106
21107
21108
21109
21110
21111
21112
21113
21114
21115
21116
21117
21118
21119
21120
21121
21122
21123
21124
21125
21126
21127
21128
21129
21130
21131
21132
21133
21134
21135
21136
21137
21138
21139
21140
21141
21142
21143
21144
21145
21146
21147
21148
21149
21150
21151
21152
21153
21154
21155
21156
21157
21158
21159
21160
21161
21162
21163
21164
21165
21166
21167
21168
21169
21170
21171
21172
21173
21174
21175
21176
21177
21178
21179
21180
21181
21182
21183
21184
21185
21186
21187
21188
21189
21190
21191
21192
21193
21194
21195
21196
21197
21198
21199
21200
21201
21202
21203
21204
21205
21206
21207
21208
21209
21210
21211
21212
21213
21214
21215
21216
21217
21218
21219
21220
21221
21222
21223
21224
21225
21226
21227
21228
21229
21230
21231
21232
21233
21234
21235
21236
21237
21238
21239
21240
21241
21242
21243
21244
21245
21246
21247
21248
21249
21250
21251
21252
21253
21254
21255
21256
21257
21258
21259
21260
21261
21262
21263
21264
21265
21266
21267
21268
21269
21270
21271
21272
21273
21274
21275
21276
21277
21278
21279
21280
21281
21282
21283
21284
21285
21286
21287
21288
21289
21290
21291
21292
21293
21294
21295
21296
21297
21298
21299
21300
21301
21302
21303
21304
21305
21306
21307
21308
21309
21310
21311
21312
21313
21314
21315
21316
21317
21318
21319
21320
21321
21322
21323
21324
21325
21326
21327
21328
21329
21330
21331
21332
21333
21334
21335
21336
21337
21338
21339
21340
21341
21342
21343
21344
21345
21346
21347
21348
21349
21350
21351
21352
21353
21354
21355
21356
21357
21358
21359
21360
21361
21362
21363
21364
21365
21366
21367
21368
21369
21370
21371
21372
21373
21374
21375
21376
21377
21378
21379
21380
21381
21382
21383
21384
21385
21386
21387
21388
21389
21390
21391
21392
21393
21394
21395
21396
21397
21398
21399
21400
21401
21402
21403
21404
21405
21406
21407
21408
21409
21410
21411
21412
21413
21414
21415
21416
21417
21418
21419
21420
21421
21422
21423
21424
21425
21426
21427
21428
21429
21430
21431
21432
21433
21434
21435
21436
21437
21438
21439
21440
21441
21442
21443
21444
21445
21446
21447
21448
21449
21450
21451
21452
21453
21454
21455
21456
21457
21458
21459
21460
21461
21462
21463
21464
21465
21466
21467
21468
21469
21470
21471
21472
21473
21474
21475
21476
21477
21478
21479
21480
21481
21482
21483
21484
21485
21486
21487
21488
21489
21490
21491
21492
21493
21494
21495
21496
21497
21498
21499
21500
21501
21502
21503
21504
21505
21506
21507
21508
21509
21510
21511
21512
21513
21514
21515
21516
21517
21518
21519
21520
21521
21522
21523
21524
21525
21526
21527
21528
21529
21530
21531
21532
21533
21534
21535
21536
21537
21538
21539
21540
21541
21542
21543
21544
21545
21546
21547
21548
21549
21550
21551
21552
21553
21554
21555
21556
21557
21558
21559
21560
21561
21562
21563
21564
21565
21566
21567
21568
21569
21570
21571
21572
21573
21574
21575
21576
21577
21578
21579
21580
21581
21582
21583
21584
21585
21586
21587
21588
21589
21590
21591
21592
21593
21594
21595
21596
21597
21598
21599
21600
21601
21602
21603
21604
21605
21606
21607
21608
21609
21610
21611
21612
21613
21614
21615
21616
21617
21618
21619
21620
21621
21622
21623
21624
21625
21626
21627
21628
21629
21630
21631
21632
21633
21634
21635
21636
21637
21638
21639
21640
21641
21642
21643
21644
21645
21646
21647
21648
21649
21650
21651
21652
21653
21654
21655
21656
21657
21658
21659
21660
21661
21662
21663
21664
21665
21666
21667
21668
21669
21670
21671
21672
21673
21674
21675
21676
21677
21678
21679
21680
21681
21682
21683
21684
21685
21686
21687
21688
21689
21690
21691
21692
21693
21694
21695
21696
21697
21698
21699
21700
21701
21702
21703
21704
21705
21706
21707
21708
21709
21710
21711
21712
21713
21714
21715
21716
21717
21718
21719
21720
21721
21722
21723
21724
21725
21726
21727
21728
21729
21730
21731
21732
21733
21734
21735
21736
21737
21738
21739
21740
21741
21742
21743
21744
21745
21746
21747
21748
21749
21750
21751
21752
21753
21754
21755
21756
21757
21758
21759
21760
21761
21762
21763
21764
21765
21766
21767
21768
21769
21770
21771
21772
21773
21774
21775
21776
21777
21778
21779
21780
21781
21782
21783
21784
21785
21786
21787
21788
21789
21790
21791
21792
21793
21794
21795
21796
21797
21798
21799
21800
21801
21802
21803
21804
21805
21806
21807
21808
21809
21810
21811
21812
21813
21814
21815
21816
21817
21818
21819
21820
21821
21822
21823
21824
21825
21826
21827
21828
21829
21830
21831
21832
21833
21834
21835
21836
21837
21838
21839
21840
21841
21842
21843
21844
21845
21846
21847
21848
21849
21850
21851
21852
21853
21854
21855
21856
21857
21858
21859
21860
21861
21862
21863
21864
21865
21866
21867
21868
21869
21870
21871
21872
21873
21874
21875
21876
21877
21878
21879
21880
21881
21882
21883
21884
21885
21886
21887
21888
21889
21890
21891
21892
21893
21894
21895
21896
21897
21898
21899
21900
21901
21902
21903
21904
21905
21906
21907
21908
21909
21910
21911
21912
21913
21914
21915
21916
21917
21918
21919
21920
21921
21922
21923
21924
21925
21926
21927
21928
21929
21930
21931
21932
21933
21934
21935
21936
21937
21938
21939
21940
21941
21942
21943
21944
21945
21946
21947
21948
21949
21950
21951
21952
21953
21954
21955
21956
21957
21958
21959
21960
21961
21962
21963
21964
21965
21966
21967
21968
21969
21970
21971
21972
21973
21974
21975
21976
21977
21978
21979
21980
21981
21982
21983
21984
21985
21986
21987
21988
21989
21990
21991
21992
21993
21994
21995
21996
21997
21998
21999
22000
22001
22002
22003
22004
22005
22006
22007
22008
22009
22010
22011
22012
22013
22014
22015
22016
22017
22018
22019
22020
22021
22022
22023
22024
22025
22026
22027
22028
22029
22030
22031
22032
22033
22034
22035
22036
22037
22038
22039
22040
22041
22042
22043
22044
22045
22046
22047
22048
22049
22050
22051
22052
22053
22054
22055
22056
22057
22058
22059
22060
22061
22062
22063
22064
22065
22066
22067
22068
22069
22070
22071
22072
22073
22074
22075
22076
22077
22078
22079
22080
22081
22082
22083
22084
22085
22086
22087
22088
22089
22090
22091
22092
22093
22094
22095
22096
22097
22098
22099
22100
22101
22102
22103
22104
22105
22106
22107
22108
22109
22110
22111
22112
22113
22114
22115
22116
22117
22118
22119
22120
22121
22122
22123
22124
22125
22126
22127
22128
22129
22130
22131
22132
22133
22134
22135
22136
22137
22138
22139
22140
22141
22142
22143
22144
22145
22146
22147
22148
22149
22150
22151
22152
22153
22154
22155
22156
22157
22158
22159
22160
22161
22162
22163
22164
22165
22166
22167
22168
22169
22170
22171
22172
22173
22174
22175
22176
22177
22178
22179
22180
22181
22182
22183
22184
22185
22186
22187
22188
22189
22190
22191
22192
22193
22194
22195
22196
22197
22198
22199
22200
22201
22202
22203
22204
22205
22206
22207
22208
22209
22210
22211
22212
22213
22214
22215
22216
22217
22218
22219
22220
22221
22222
22223
22224
22225
22226
22227
22228
22229
22230
22231
22232
22233
22234
22235
22236
22237
22238
22239
22240
22241
22242
22243
22244
22245
22246
22247
22248
22249
22250
22251
22252
22253
22254
22255
22256
22257
22258
22259
22260
22261
22262
22263
22264
22265
22266
22267
22268
22269
22270
22271
22272
22273
22274
22275
22276
22277
22278
22279
22280
22281
22282
22283
22284
22285
22286
22287
22288
22289
22290
22291
22292
22293
22294
22295
22296
22297
22298
22299
22300
22301
22302
22303
22304
22305
22306
22307
22308
22309
22310
22311
22312
22313
22314
22315
22316
22317
22318
22319
22320
22321
22322
22323
22324
22325
22326
22327
22328
22329
22330
22331
22332
22333
22334
22335
22336
22337
22338
22339
22340
22341
22342
22343
22344
22345
22346
22347
22348
22349
22350
22351
22352
22353
22354
22355
22356
22357
22358
22359
22360
22361
22362
22363
22364
22365
22366
22367
22368
22369
22370
22371
22372
22373
22374
22375
22376
22377
22378
22379
22380
22381
22382
22383
22384
22385
22386
22387
22388
22389
22390
22391
22392
22393
22394
22395
22396
22397
22398
22399
22400
22401
22402
22403
22404
22405
22406
22407
22408
22409
22410
22411
22412
22413
22414
22415
22416
22417
22418
22419
22420
22421
22422
22423
22424
22425
22426
22427
22428
22429
22430
22431
22432
22433
22434
22435
22436
22437
22438
22439
22440
22441
22442
22443
22444
22445
22446
22447
22448
22449
22450
22451
22452
22453
22454
22455
22456
22457
22458
22459
22460
22461
22462
22463
22464
22465
22466
22467
22468
22469
22470
22471
22472
22473
22474
22475
22476
22477
22478
22479
22480
22481
22482
22483
22484
22485
22486
22487
22488
22489
22490
22491
22492
22493
22494
22495
22496
22497
22498
22499
22500
22501
22502
22503
22504
22505
22506
22507
22508
22509
22510
22511
22512
22513
22514
22515
22516
22517
22518
22519
22520
22521
22522
22523
22524
22525
22526
22527
22528
22529
22530
22531
22532
22533
22534
22535
22536
22537
22538
22539
22540
22541
22542
22543
22544
22545
22546
22547
22548
22549
22550
22551
22552
22553
22554
22555
22556
22557
22558
22559
22560
22561
22562
22563
22564
22565
22566
22567
22568
22569
22570
22571
22572
22573
22574
22575
22576
22577
22578
22579
22580
22581
22582
22583
22584
22585
22586
22587
22588
22589
22590
22591
22592
22593
22594
22595
22596
22597
22598
22599
22600
22601
22602
22603
22604
22605
22606
22607
22608
22609
22610
22611
22612
22613
22614
22615
22616
22617
22618
22619
22620
22621
22622
22623
22624
22625
22626
22627
22628
22629
22630
22631
22632
22633
22634
22635
22636
22637
22638
22639
22640
22641
22642
22643
22644
22645
22646
22647
22648
22649
22650
22651
22652
22653
22654
22655
22656
22657
22658
22659
22660
22661
22662
22663
22664
22665
22666
22667
22668
22669
22670
22671
22672
22673
22674
22675
22676
22677
22678
22679
22680
22681
22682
22683
22684
22685
22686
22687
22688
22689
22690
22691
22692
22693
22694
22695
22696
22697
22698
22699
22700
22701
22702
22703
22704
22705
22706
22707
22708
22709
22710
22711
22712
22713
22714
22715
22716
22717
22718
22719
22720
22721
22722
22723
22724
22725
22726
22727
22728
22729
22730
22731
22732
22733
22734
22735
22736
22737
22738
22739
22740
22741
22742
22743
22744
22745
22746
22747
22748
22749
22750
22751
22752
22753
22754
22755
22756
22757
22758
22759
22760
22761
22762
22763
22764
22765
22766
22767
22768
22769
22770
22771
22772
22773
22774
22775
22776
22777
22778
22779
22780
22781
22782
22783
22784
22785
22786
22787
22788
22789
22790
22791
22792
22793
22794
22795
22796
22797
22798
22799
22800
22801
22802
22803
22804
22805
22806
22807
22808
22809
22810
22811
22812
22813
22814
22815
22816
22817
22818
22819
22820
22821
22822
22823
22824
22825
22826
22827
22828
22829
22830
22831
22832
22833
22834
22835
22836
22837
22838
22839
22840
22841
22842
22843
22844
22845
22846
22847
22848
22849
22850
22851
22852
22853
22854
22855
22856
22857
22858
22859
22860
22861
22862
22863
22864
22865
22866
22867
22868
22869
22870
22871
22872
22873
22874
22875
22876
22877
22878
22879
22880
22881
22882
22883
22884
22885
22886
22887
22888
22889
22890
22891
22892
22893
22894
22895
22896
22897
22898
22899
22900
22901
22902
22903
22904
22905
22906
22907
22908
22909
22910
22911
22912
22913
22914
22915
22916
22917
22918
22919
22920
22921
22922
22923
22924
22925
22926
22927
22928
22929
22930
22931
22932
22933
22934
22935
22936
22937
22938
22939
22940
22941
22942
22943
22944
22945
22946
22947
22948
22949
22950
22951
22952
22953
22954
22955
22956
22957
22958
22959
22960
22961
22962
22963
22964
22965
22966
22967
22968
22969
22970
22971
22972
22973
22974
22975
22976
22977
22978
22979
22980
22981
22982
22983
22984
22985
22986
22987
22988
22989
22990
22991
22992
22993
22994
22995
22996
22997
22998
22999
23000
23001
23002
23003
23004
23005
23006
23007
23008
23009
23010
23011
23012
23013
23014
23015
23016
23017
23018
23019
23020
23021
23022
23023
23024
23025
23026
23027
23028
23029
23030
23031
23032
23033
23034
23035
23036
23037
23038
23039
23040
23041
23042
23043
23044
23045
23046
23047
23048
23049
23050
23051
23052
23053
23054
23055
23056
23057
23058
23059
23060
23061
23062
23063
23064
23065
23066
23067
23068
23069
23070
23071
23072
23073
23074
23075
23076
23077
23078
23079
23080
23081
23082
23083
23084
23085
23086
23087
23088
23089
23090
23091
23092
23093
23094
23095
23096
23097
23098
23099
23100
23101
23102
23103
23104
23105
23106
23107
23108
23109
23110
23111
23112
23113
23114
23115
23116
23117
23118
23119
23120
23121
23122
23123
23124
23125
23126
23127
23128
23129
23130
23131
23132
23133
23134
23135
23136
23137
23138
23139
23140
23141
23142
23143
23144
23145
23146
23147
23148
23149
23150
23151
23152
23153
23154
23155
23156
23157
23158
23159
23160
23161
23162
23163
23164
23165
23166
23167
23168
23169
23170
23171
23172
23173
23174
23175
23176
23177
23178
23179
23180
23181
23182
23183
23184
23185
23186
23187
23188
23189
23190
23191
23192
23193
23194
23195
23196
23197
23198
23199
23200
23201
23202
23203
23204
23205
23206
23207
23208
23209
23210
23211
23212
23213
23214
23215
23216
23217
23218
23219
23220
23221
23222
23223
23224
23225
23226
23227
23228
23229
23230
23231
23232
23233
23234
23235
23236
23237
23238
23239
23240
23241
23242
23243
23244
23245
23246
23247
23248
23249
23250
23251
23252
23253
23254
23255
23256
23257
23258
23259
23260
23261
23262
23263
23264
23265
23266
23267
23268
23269
23270
23271
23272
23273
23274
23275
23276
23277
23278
23279
23280
23281
23282
23283
23284
23285
23286
23287
23288
23289
23290
23291
23292
23293
23294
23295
23296
23297
23298
23299
23300
23301
23302
23303
23304
23305
23306
23307
23308
23309
23310
23311
23312
23313
23314
23315
23316
23317
23318
23319
23320
23321
23322
23323
23324
23325
23326
23327
23328
23329
23330
23331
23332
23333
23334
23335
23336
23337
23338
23339
23340
23341
23342
23343
23344
23345
23346
23347
23348
23349
23350
23351
23352
23353
23354
23355
23356
23357
23358
23359
23360
23361
23362
23363
23364
23365
23366
23367
23368
23369
23370
23371
23372
23373
23374
23375
23376
23377
23378
23379
23380
23381
23382
23383
23384
23385
23386
23387
23388
23389
23390
23391
23392
23393
23394
23395
23396
23397
23398
23399
23400
23401
23402
23403
23404
23405
23406
23407
23408
23409
23410
23411
23412
23413
23414
23415
23416
23417
23418
23419
23420
23421
23422
23423
23424
23425
23426
23427
23428
23429
23430
23431
23432
23433
23434
23435
23436
23437
23438
23439
23440
23441
23442
23443
23444
23445
23446
23447
23448
23449
23450
23451
23452
23453
23454
23455
23456
23457
23458
23459
23460
23461
23462
23463
23464
23465
23466
23467
23468
23469
23470
23471
23472
23473
23474
23475
23476
23477
23478
23479
23480
23481
23482
23483
23484
23485
23486
23487
23488
23489
23490
23491
23492
23493
23494
23495
23496
23497
23498
23499
23500
23501
23502
23503
23504
23505
23506
23507
23508
23509
23510
23511
23512
23513
23514
23515
23516
23517
23518
23519
23520
23521
23522
23523
23524
23525
23526
23527
23528
23529
23530
23531
23532
23533
23534
23535
23536
23537
23538
23539
23540
23541
23542
23543
23544
23545
23546
23547
23548
23549
23550
23551
23552
23553
23554
23555
23556
23557
23558
23559
23560
23561
23562
23563
23564
23565
23566
23567
23568
23569
23570
23571
23572
23573
23574
23575
23576
23577
23578
23579
23580
23581
23582
23583
23584
23585
23586
23587
23588
23589
23590
23591
23592
23593
23594
23595
23596
23597
23598
23599
23600
23601
23602
23603
23604
23605
23606
23607
23608
23609
23610
23611
23612
23613
23614
23615
23616
23617
23618
23619
23620
23621
23622
23623
23624
23625
23626
23627
23628
23629
23630
23631
23632
23633
23634
23635
23636
23637
23638
23639
23640
23641
23642
23643
23644
23645
23646
23647
23648
23649
23650
23651
23652
23653
23654
23655
23656
23657
23658
23659
23660
23661
23662
23663
23664
23665
23666
23667
23668
23669
23670
23671
23672
23673
23674
23675
23676
23677
23678
23679
23680
23681
23682
23683
23684
23685
23686
23687
23688
23689
23690
23691
23692
23693
23694
23695
23696
23697
23698
23699
23700
23701
23702
23703
23704
23705
23706
23707
23708
23709
23710
23711
23712
23713
23714
23715
23716
23717
23718
23719
23720
23721
23722
23723
23724
23725
23726
23727
23728
23729
23730
23731
23732
23733
23734
23735
23736
23737
23738
23739
23740
23741
23742
23743
23744
23745
23746
23747
23748
23749
23750
23751
23752
23753
23754
23755
23756
23757
23758
23759
23760
23761
23762
23763
23764
23765
23766
23767
23768
23769
23770
23771
23772
23773
23774
23775
23776
23777
23778
23779
23780
23781
23782
23783
23784
23785
23786
23787
23788
23789
23790
23791
23792
23793
23794
23795
23796
23797
23798
23799
23800
23801
23802
23803
23804
23805
23806
23807
23808
23809
23810
23811
23812
23813
23814
23815
23816
23817
23818
23819
23820
23821
23822
23823
23824
23825
23826
23827
23828
23829
23830
23831
23832
23833
23834
23835
23836
23837
23838
23839
23840
23841
23842
23843
23844
23845
23846
23847
23848
23849
23850
23851
23852
23853
23854
23855
23856
23857
23858
23859
23860
23861
23862
23863
23864
23865
23866
23867
23868
23869
23870
23871
23872
23873
23874
23875
23876
23877
23878
23879
23880
23881
23882
23883
23884
23885
23886
23887
23888
23889
23890
23891
23892
23893
23894
23895
23896
23897
23898
23899
23900
23901
23902
23903
23904
23905
23906
23907
23908
23909
23910
23911
23912
23913
23914
23915
23916
23917
23918
23919
23920
23921
23922
23923
23924
23925
23926
23927
23928
23929
23930
23931
23932
23933
23934
23935
23936
23937
23938
23939
23940
23941
23942
23943
23944
23945
23946
23947
23948
23949
23950
23951
23952
23953
23954
23955
23956
23957
23958
23959
23960
23961
23962
23963
23964
23965
23966
23967
23968
23969
23970
23971
23972
23973
23974
23975
23976
23977
23978
23979
23980
23981
23982
23983
23984
23985
23986
23987
23988
23989
23990
23991
23992
23993
23994
23995
23996
//! fusevm bytecode-VM bridge for ShellExecutor.
//!
//! ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
//! !!! LAST-RESORT FILE — NOT FOR NEW LOGIC !!!
//!
//! This file is a **bridge**, not a port. It exists ONLY because zshrs uses
//! a fusevm bytecode VM where C zsh uses its own wordcode walker (Src/exec.c
//! `execlist`). Every line here is plumbing that hooks fusevm opcodes onto
//! the canonical ports in `src/ported/`.
//!
//! **Before adding code to this file, STOP and ask:**
//!
//! 1. Is this logic that already lives in `src/ported/`?
//! → Call the canonical fn. Don't reinline.
//!
//! 2. Is this logic that SHOULD live in `src/ported/` but isn't ported yet?
//! → Port it. Add it to `src/ported/<file>.rs` with a `c:` citation.
//! Then call the canonical fn from here.
//!
//! 3. Is this purely fusevm/bytecode plumbing (Op decode, Value conversion,
//! VM-stack manipulation, thread-local executor pointer, etc.)?
//! → OK to put it here. Cite the closest C analog in the comment.
//!
//! **NEVER:** reinvent paramsubst/expansion/glob/typeset/redirect logic here.
//! Those have canonical ports in `src/ported/subst.rs`, `src/ported/glob.rs`,
//! `src/ported/builtin.rs`, etc. The bridge should be SHRINKING over time,
//! not growing.
//!
//! See also: memory `feedback_no_shortcuts_in_porting` (port C bodies
//! faithfully, no structural shells), `feedback_no_exec_script_from_ported`
//! (the inverse direction — src/ported must not call back into the bridge).
//! ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
//!
//! **Extension** — has no Src/exec.c counterpart. C zsh's `Src/exec.c::execlist`
//! (and related routines) implement the native **wordcode VM** that executes
//! compiler output from `parse.c`. zshrs compiles the parsed AST to fusevm
//! bytecode and runs it on a stack VM; this
//! file holds the bridge between fusevm's `ShellHost` trait and our
//! `ShellExecutor` state, the thread-local executor pointer, all
//! `BUILTIN_*` opcode constants, and the giant `register_builtins`
//! handler table that wires zsh builtins onto fusevm CallBuiltin
//! opcodes.
#![allow(unused_imports)]
use indexmap::IndexMap;
use std::collections::{HashMap, HashSet};
use std::env;
use std::path::PathBuf;
use crate::exec_jobs::JobState;
use crate::intercepts::Intercept;
use crate::ported::vm_helper::*;
use std::io::Write;
// ═══════════════════════════════════════════════════════════════════════════
// Thread-local executor context for VM builtin dispatch
// ═══════════════════════════════════════════════════════════════════════════
use crate::ported::options::opt_state_get;
use crate::ported::zsh_h::{isset, options, ERREXIT, MAX_OPS};
use fusevm::op::redirect_op as r;
use fusevm::shell_builtins::*;
use fusevm::Value;
use std::cell::{Cell, RefCell};
use std::cmp::Ordering;
use std::ffi::CString;
use std::fs;
use std::io::BufRead;
use std::io::Read;
use std::io::Write as _;
use std::os::unix::fs::FileTypeExt;
use std::os::unix::fs::MetadataExt;
use std::os::unix::fs::PermissionsExt;
use std::os::unix::io::AsRawFd;
use std::os::unix::io::IntoRawFd;
use std::time::Instant;
use std::time::{SystemTime, UNIX_EPOCH};
thread_local! {
/// Mirror of C zsh's `doneps4` local in execcmd_exec
/// (Src/exec.c:2517+). Tracks whether PS4 has been emitted
/// for the current xtrace line so a coalesced sequence of
/// XTRACE_ASSIGN + XTRACE_ARGS produces ONE line:
/// `<PS4>a=1 b=2 echo 1 2\n`
/// instead of three. Reset to false by XTRACE_ARGS /
/// XTRACE_NEWLINE after emitting the trailing `\n`.
static XTRACE_DONE_PS4: Cell<bool> = const { Cell::new(false) };
/// A NOMATCH raised by a typeset-family command's words BEFORE its first
/// postassign, set aside by BUILTIN_TYPESET_POSTASSIGNS_BEGIN and put
/// back by BUILTIN_TYPESET_POSTASSIGNS_END.
static TYPESET_WORD_GLOB_FAILED: Cell<bool> = const { Cell::new(false) };
/// Number of postassign words of the typeset-family command about to
/// dispatch, set by BUILTIN_TYPESET_POSTASSIGNS_BEGIN. C keeps those in
/// the command's `assigns` list, not `args` (c:Src/parse.c:2003-2008),
/// so they never become `$_` (c:Src/exec.c:3546).
static TYPESET_POSTASSIGN_COUNT: Cell<Option<usize>> = const { Cell::new(None) };
/// Set by BUILTIN_TYPESET_POSTASSIGNS_END when a NOMATCH fired in one of
/// the postassigns. Consumed by `dispatch_builtin`.
static TYPESET_POSTASSIGN_GLOB_FAILED: Cell<bool> = const { Cell::new(false) };
/// Port of C's `FILE *xtrerr` xtrace stream (Src/exec.c:81). C builds
/// each trace line in this stdio buffer — `printprompt4` does
/// `fprintf(xtrerr, …)`, then args via `fputs`/`fputc` — and
/// `fflush(xtrerr)` writes the WHOLE line to stderr in one syscall
/// (makecline c:2122-2123, addvars c:2588, condition c:1372). That
/// single flush is exactly why a forked pipeline stage's trace line
/// reaches the shared stderr fd atomically and never interleaves with
/// a concurrent stage. zshrs previously emitted PS4 and the command
/// text as separate `eprint!` writes, which raced under load. Model
/// the FILE buffer as this thread-local String (a forked child owns
/// its own copy); `xtrerr_fputs` appends, `xtrerr_flush` does the
/// single write.
static XTRERR: RefCell<String> = const { RefCell::new(String::new()) };
/// !!! WARNING: RUST-ONLY HELPER !!! `(scope depth, newxtrerr fd)` for
/// each simple command whose redirect scope took a copy of stderr for
/// xtrace (c:Src/exec.c:3766-3772). C holds newxtrerr in an
/// `execcmd_exec` local and closes it on the way out (c:4445-4452);
/// zshrs closes it when that redirect scope ends.
static XTRERR_COPIES: RefCell<Vec<(usize, i32)>> = const { RefCell::new(Vec::new()) };
/// Stack of (RETFLAG, BREAKS, CONTFLAG, EXIT_PENDING) tuples saved
/// at try-block exit so the always-arm body can run cleanly even
/// when the try-block fired `return` / `break` / `continue` /
/// `exit`. Restored right before the post-always re-jump so the
/// escape resumes propagation past the construct.
/// c:Src/exec.c WC_TRYBLOCK — zsh's wordcode walker handles this
/// inline; the zshrs port lifts it into a paired SET / RESTORE
/// pair around the always-arm.
/// Tuple: `(retflag, breaks, contflag, exit_pending, try_errflag,
/// try_interrupt)`. The last two are c:Src/loop.c:762-763's
/// `save_try_errflag` / `save_try_interrupt` — the ENCLOSING try
/// block's values, restored at c:778-779 so nested
/// `{…} always {…}` constructs don't leak `$TRY_BLOCK_ERROR`
/// outward.
static TRY_ESCAPE_SAVE: RefCell<Vec<(i32, i32, i32, i32, i64, i64)>> =
const { RefCell::new(Vec::new()) };
/// Re-entry guard for BUILTIN_DEBUG_TRAP. While the DEBUG trap
/// body is running, the per-statement DEBUG_TRAP dispatch in the
/// trap body must NOT re-fire (otherwise infinite recursion +
/// stack overflow). zsh's in_trap counter at Src/signals.c
/// serves the same purpose.
static DEBUG_TRAP_REENTRY: Cell<bool> = const { Cell::new(false) };
/// Stack of (saved_stdout, saved_stderr) tuples pushed by
/// `cmd_subst` around its nested-VM run. RUST-ONLY: zsh forks
/// each cmdsub so trap output during the cmdsub naturally
/// lands on the PARENT's stdout. zshrs's in-process cmdsub
/// dups fd 1 → pipe, so a trap firing during cmdsub would
/// emit into the captured value. Traps consult this stack
/// to route their body output to the topmost saved_stdout
/// instead of the cmdsub's fd 1. Bug #56 in docs/BUGS.md.
pub static CMDSUBST_OUTER_FDS: RefCell<Vec<(i32, i32)>> =
const { RefCell::new(Vec::new()) };
/// c:Src/exec.c:5025 getproc (PATH_DEV_FD branch) — the parent
/// keeps the `>(cmd)` pipe WRITE end open under `/dev/fd/N`,
/// parks it in the job's filelist (`fdtable[fd] =
/// FDT_PROC_SUBST; addfilelist(NULL, fd)`), and deletefilelist
/// closes it when the consuming job finishes — that close is
/// what lets the `>(cmd)` child's reader see EOF. zshrs runs
/// commands in-process, so the equivalent is: record
/// `(scope_depth, fd)` here and drain after the consuming
/// command (external exec or builtin dispatch) completes.
static PSUB_PENDING_FDS: RefCell<Vec<(usize, i32)>> = const { RefCell::new(Vec::new()) };
/// `(scope_depth, path)` for `=(cmd)` temp files, unlinked at the same
/// job-end boundary as the pending fds (c:Src/jobs.c deletefilelist).
static PSUB_PENDING_FILES: RefCell<Vec<(usize, String)>> = const { RefCell::new(Vec::new()) };
/// Scope depth for PSUB_PENDING_FDS tagging. Incremented around
/// nested execution contexts (cmd-subst bodies, shell-function
/// bodies) so a command running INSIDE the nested context only
/// drains its own `>(cmd)` fds, never the enclosing command's
/// (e.g. `tee >(wc) $(print x)` — print must not close tee's
/// fd). Mirrors C's per-job filelist ownership.
static PSUB_SCOPE_DEPTH: Cell<usize> = const { Cell::new(0) };
/// Forked `<(cmd)`/`>(cmd)` child pids awaiting reap. Drained
/// non-blockingly (WNOHANG) by note_psub_child so proc-sub children
/// don't accumulate as zombies across a shell session.
static PSUB_CHILDREN: RefCell<Vec<i32>> = const { RefCell::new(Vec::new()) };
}
/// Record a proc-sub child pid and best-effort reap any already-exited
/// proc-sub children (WNOHANG). Non-blocking: still-running children
/// stay parked and get reaped on a later call.
pub(crate) fn note_psub_child(pid: i32) {
if pid <= 0 {
return;
}
PSUB_CHILDREN.with(|v| {
let mut v = v.borrow_mut();
v.push(pid);
v.retain(|&p| {
let mut status = 0;
// WNOHANG: reap if exited, else keep parked.
let r = unsafe { libc::waitpid(p, &mut status, libc::WNOHANG) };
// r == p → reaped; r == 0 → still running (keep); r < 0 →
// already gone/not ours (drop).
r == 0
});
});
}
/// Port of `fputs(s, xtrerr)` / `fprintf(xtrerr, "%s", s)` (Src/exec.c):
/// append `s` to the buffered xtrace line. Nothing reaches stderr until
/// [`xtrerr_flush`] (the port of `fflush(xtrerr)`) writes the line whole.
pub(crate) fn xtrerr_fputs(s: &str) {
XTRERR.with(|b| b.borrow_mut().push_str(s));
}
/// Port of `fflush(xtrerr)` (Src/exec.c:1373/2123/2596): write the
/// buffered xtrace line to stderr in ONE `write` and clear the buffer, so
/// the line lands on the shared fd atomically (no interleaving across
/// concurrent pipeline stages).
pub(crate) fn xtrerr_flush() {
XTRERR.with(|b| {
let mut buf = b.borrow_mut();
if !buf.is_empty() {
// c:Src/utils.c:1714 — the line goes to `xtrerr`, which is
// stderr unless a simple command's redirect scope holds a copy
// of the pre-redirection stderr (c:Src/exec.c:3766-3772).
let fd = crate::ported::utils::xtrerr.load(std::sync::atomic::Ordering::Relaxed);
// c:Src/exec.c:2061 — the pieces were written with `quotedzputs(s, xtrerr)`,
// which emits METAFIED text un-metafied (a lone high byte from
// `mb_niceformat` under a single-byte locale is one byte on the wire).
let bytes = crate::ported::utils::unmetafy_str(&buf);
if fd == libc::STDERR_FILENO {
use std::io::Write;
let _ = std::io::stderr().write_all(&bytes);
} else {
let _ = crate::ported::utils::write_loop(fd, &bytes);
}
buf.clear();
}
});
}
/// RAII guard bumping the psub scope depth — see PSUB_SCOPE_DEPTH.
pub(crate) struct PsubScope;
impl PsubScope {
pub(crate) fn enter() -> Self {
PSUB_SCOPE_DEPTH.with(|d| d.set(d.get() + 1));
PsubScope
}
}
impl Drop for PsubScope {
fn drop(&mut self) {
PSUB_SCOPE_DEPTH.with(|d| d.set(d.get().saturating_sub(1)));
}
}
/// RAII guard bumping `$ZSH_SUBSHELL` for the duration of an
/// in-process command substitution.
///
/// c:Src/exec.c:1161 — entersubsh() does `zsh_subshell++;` and zsh's
/// cmdsub FORKS, so the increment dies with the child and the parent's
/// value is untouched. zshrs runs cmdsubs in-process on a nested VM,
/// so the visible param must be bumped on entry and restored on exit.
/// Writes paramtab u_val directly because ZSH_SUBSHELL is PM_READONLY
/// (same bypass pattern as the subshell-builtin bump below); also
/// mirrors into ported::exec::zsh_subshell so exec.c:4376-style
/// `forked | zsh_subshell` reads agree.
pub(crate) struct CmdSubstSubshellBump {
saved_val: i64,
saved_str: Option<String>,
}
impl CmdSubstSubshellBump {
pub(crate) fn enter() -> Self {
let mut saved_val = 0i64;
let mut saved_str = None;
if let Ok(mut tab) = crate::ported::params::paramtab().write() {
if let Some(pm) = tab.get_mut("ZSH_SUBSHELL") {
saved_val = pm.u_val;
saved_str = pm.u_str.clone();
pm.u_val = saved_val + 1;
pm.u_str = Some((saved_val + 1).to_string());
pm.node.flags &= !(crate::ported::zsh_h::PM_UNSET as i32);
}
}
crate::ported::exec::zsh_subshell.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
CmdSubstSubshellBump {
saved_val,
saved_str,
}
}
}
impl Drop for CmdSubstSubshellBump {
fn drop(&mut self) {
if let Ok(mut tab) = crate::ported::params::paramtab().write() {
if let Some(pm) = tab.get_mut("ZSH_SUBSHELL") {
pm.u_val = self.saved_val;
pm.u_str = self.saved_str.take();
}
}
crate::ported::exec::zsh_subshell.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
}
}
/// `addfilelist(nam, 0)` (c:Src/exec.c:4960) for an `=(cmd)` temp file:
/// park it for the job-end unlink in `close_pending_psub_fds`, tagged with
/// the current scope depth.
pub(crate) fn psub_pending_file_add(nam: &str) {
let depth = PSUB_SCOPE_DEPTH.with(|d| d.get());
PSUB_PENDING_FILES.with(|v| v.borrow_mut().push((depth, nam.to_string())));
}
/// Port of deletefilelist() from Src/jobs.c (the `>(cmd)` fd arm):
/// closes every pending proc-subst write end created at or inside
/// the current scope depth, exactly when C deletes the consuming
/// job's filelist (getproc parks the fd there via
/// `addfilelist(NULL, fd)`, Src/exec.c:5025+).
fn close_pending_psub_fds() {
close_pending_psub_from(PSUB_SCOPE_DEPTH.with(|d| d.get()));
}
/// c:Src/jobs.c:1452-1460 cleanfilelists — at shell exit EVERY job's
/// filelist is deleted, whichever scope parked it, so the pending `>(cmd)`
/// fds and `=(cmd)` temp files of all depths go. Called from
/// `jobs::cleanfilelists`: these lists stand in for the jobtab filelists
/// (see PSUB_PENDING_FDS).
pub(crate) fn cleanfilelists_pending() {
close_pending_psub_from(0);
}
/// The drain behind both: everything parked at scope `depth` or deeper.
fn close_pending_psub_from(depth: usize) {
PSUB_PENDING_FDS.with(|v| {
v.borrow_mut().retain(|&(d, fd)| {
if d >= depth {
unsafe { libc::close(fd) };
false
} else {
true
}
});
});
// c:Src/jobs.c deletefilelist — `=(cmd)` temp files are unlinked at the
// same job-end boundary. `f==(print x); [[ -f $f ]]` is false after the
// command line ends.
PSUB_PENDING_FILES.with(|v| {
v.borrow_mut().retain(|(d, path)| {
if *d >= depth {
let _ = fs::remove_file(path);
false
} else {
true
}
});
});
}
/// RAII drain guard — instantiated at the top of the consuming-
/// command paths (dispatch_builtin, ZshrsHost::exec) so the pending
/// `>(cmd)` write ends close on every exit path once the command
/// finished, exactly when C's job filelist would be deleted.
struct PsubFdGuard;
impl Drop for PsubFdGuard {
fn drop(&mut self) {
close_pending_psub_fds();
}
}
/// Peek the outermost cmdsub-saved (stdout, stderr) fds, if any.
/// Returns None when no cmdsub is currently capturing. Used by the
/// trap dispatcher in `src/ported/signals.rs::dotrap` to route trap
/// body output to the parent's real stdout (matching zsh's forked
/// cmdsub behaviour) instead of the cmdsub's pipe-bound fd 1.
/// Bug #56 in docs/BUGS.md.
/// !!! WARNING: RUST-ONLY HELPER — NO C COUNTERPART !!!
///
/// C keeps a shell function in exactly ONE place — the `Shfunc` node in
/// `shfunctab` — so `dosavetrap` copies a `TRAP<SIG>` function by
/// duplicating that node (`Src/signals.c:638-656`) and `endtrapscope`
/// puts it back with a single `shfunctab->addnode` (c:929-931).
///
/// zshrs splits one function across FIVE stores: the `shfunc` node in
/// `shfunctab` (metadata + body text) plus the executor's
/// `functions_compiled` (the fusevm `Chunk` that actually runs),
/// `function_source`, `function_line_base` and `function_def_file`.
/// Snapshotting only the hashtable node therefore restores the outer
/// function's *metadata* while the inner function's *bytecode* keeps
/// running. `FuncSnapshot` captures all five so the C-level "copy the
/// node" / "add the node back" steps are faithful in behaviour.
#[derive(Default)]
pub struct FuncSnapshot {
pub shf: Option<crate::ported::zsh_h::shfunc>,
pub chunk: Option<fusevm::Chunk>,
pub source: Option<String>,
pub line_base: Option<i64>,
pub def_file: Option<Option<String>>,
}
impl FuncSnapshot {
/// True when `name` had no definition at snapshot time — restoring
/// such a snapshot deletes the function everywhere.
pub fn is_empty(&self) -> bool {
self.shf.is_none() && self.chunk.is_none() && self.source.is_none()
}
}
/// !!! WARNING: RUST-ONLY HELPER — NO C COUNTERPART !!!
/// Capture every store that holds `name`'s definition. See
/// [`FuncSnapshot`].
pub fn snapshot_function(name: &str) -> FuncSnapshot {
let shf = crate::ported::hashtable::shfunctab_lock()
.read()
.ok()
.and_then(|t| t.get(name).cloned());
let (chunk, source, line_base, def_file) = try_with_executor(|exec| {
(
exec.functions_compiled.get(name).cloned(),
exec.function_source.get(name).cloned(),
exec.function_line_base.get(name).copied(),
exec.function_def_file.get(name).cloned(),
)
})
.unwrap_or((None, None, None, None));
FuncSnapshot {
shf,
chunk,
source,
line_base,
def_file,
}
}
/// !!! WARNING: RUST-ONLY HELPER — NO C COUNTERPART !!!
/// Put a [`FuncSnapshot`] back under `name`. An empty snapshot (the
/// function did not exist when it was taken) removes it from every
/// store, mirroring C's `removehashnode(shfunctab, …)`.
pub fn restore_function(name: &str, snap: FuncSnapshot) {
if let Ok(mut t) = crate::ported::hashtable::shfunctab_lock().write() {
match snap.shf {
Some(shf) => {
t.add(shf);
}
None => {
t.remove(name);
}
}
}
let _ = try_with_executor(|exec| {
match snap.chunk {
Some(c) => {
exec.functions_compiled.insert(name.to_string(), c);
}
None => {
exec.functions_compiled.remove(name);
}
}
match snap.source {
Some(s) => {
exec.function_source.insert(name.to_string(), s);
}
None => {
exec.function_source.remove(name);
}
}
match snap.line_base {
Some(n) => {
exec.function_line_base.insert(name.to_string(), n);
}
None => {
exec.function_line_base.remove(name);
}
}
match snap.def_file {
Some(f) => {
exec.function_def_file.insert(name.to_string(), f);
}
None => {
exec.function_def_file.remove(name);
}
}
});
}
pub fn cmdsubst_outer_stdout() -> Option<i32> {
CMDSUBST_OUTER_FDS.with(|s| s.borrow().last().map(|(o, _)| *o))
}
thread_local! {
/// The pipeline fds a stage still has to install onto 0/1, as
/// `(input, output)` with -1 meaning "leave this fd alone".
///
/// c:Src/exec.c:3720-3724 — the pipe's read/write ends are the
/// FIRST entries of the command's multio table:
/// /* Add pipeline input/output to mnodes */
/// if (input) addfd(forked, save, mfds, 0, input, 0, NULL);
/// if (output) addfd(forked, save, mfds, 1, output, 1, NULL);
/// and that runs AFTER prefork (c:3304) + globlist (c:3702) have
/// expanded the command's argument words. So a `$(...)` inside a
/// stage's ARGS reads the shell's original fd 0, not the pipe:
/// `print -rl -- c a b | print -r -- "[$(cat)]"` prints `[]`.
/// (The stage's own fork at c:3000 happens before the expansion,
/// which is why `${x::=v}` in a non-last stage doesn't survive —
/// but the fds are still installed after it.)
///
/// zshrs's [`BUILTIN_RUN_PIPELINE`] forks per stage, so it parks
/// the stage's fds here instead of dup2'ing them itself, and the
/// compiled stage chunk installs them via
/// [`BUILTIN_PIPE_FDS_INSTALL`] at the C-faithful point: after the
/// arg-word ops, before the redirect scope
/// (compile_zsh.rs::emit_stage_fds_install). A compound stage
/// (`{ … }`, `( … )`, a function) installs at chunk entry — its
/// body legitimately reads the pipe.
static PENDING_STAGE_FDS: std::cell::Cell<(i32, i32)> = const { std::cell::Cell::new((-1, -1)) };
}
/// Park the current stage's `(input, output)` pipe fds for the stage
/// chunk's `BUILTIN_PIPE_FDS_INSTALL` to pick up. Returns the previous
/// value so a nested pipeline (`print -- "$(a | b)" | c`) can restore
/// the outer stage's still-uninstalled fds when it finishes.
fn stage_fds_park(input: i32, output: i32) -> (i32, i32) {
PENDING_STAGE_FDS.with(|c| c.replace((input, output)))
}
/// Take (and clear) the parked stage fds.
fn stage_fds_take() -> (i32, i32) {
PENDING_STAGE_FDS.with(|c| c.replace((-1, -1)))
}
// Thread-local pointer to the current ShellExecutor.
// Set before VM execution, cleared after. Used by builtin handlers.
thread_local! {
static CURRENT_EXECUTOR: RefCell<Option<*mut ShellExecutor>> = const { RefCell::new(None) };
/// The installed session executor, registered by
/// `exec::install_session_executor`. Lets [`with_session_context`]
/// establish a VM execution context for STARTUP work that runs
/// before the loop's first `execode` enters one (rc-file sourcing in
/// `run_init_scripts`, c:1914). Mirrors exec.rs's own
/// `SESSION_EXECUTOR`; kept here so the context helper lives next to
/// `ExecutorContext`/`CURRENT_EXECUTOR`.
static SESSION_EXECUTOR_PTR: std::cell::Cell<Option<*mut ShellExecutor>> = const { std::cell::Cell::new(None) };
/// GLOB_ASSIGN eligibility carrier. Set true by BUILTIN_MARK_GLOB_ELIGIBLE
/// (emitted by the compiler ONLY when a scalar-assignment RHS carries an
/// UNQUOTED glob token — Star/Quest/Inbrack), read+cleared by the next
/// BUILTIN_SET_VAR. Matches C zsh's `GLOB_ASSIGN` (Src/exec.c:2554): only
/// a literal unquoted glob pattern in the wordcode is globbed; values from
/// `$param` / `$(cmd)` / quoted strings are NOT (verified against zsh).
/// The runtime SET_VAR value arrives untokenized (the compiler DQ-wraps to
/// suppress compile-time globbing), so quoting can no longer be recovered
/// from the value bytes — this flag carries the compile-time decision.
static SET_VAR_GLOB_ELIGIBLE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// c:Src/exec.c:3088-3096 — the next builtin dispatch comes from a
/// WC_TYPESET command, which looks the builtin up with `getnode2`
/// (DISABLED ignored). Set by BUILTIN_TYPESET_RESWD, consumed by
/// dispatch_builtin.
///
/// !!! WARNING: RUST-ONLY CARRIER !!! C knows `type == WC_TYPESET` in the
/// same function that looks the builtin up; here the compile-time fact has
/// to cross from the marker op to the dispatch op.
static TYPESET_RESWD_DISPATCH: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// c:Src/exec.c:4147-4154 — `addvars(state, varspc, flags); if (errflag)
/// { …; lastval = 1; fixfds(save); goto done; }`: an expansion error in
/// the prefix assignments of `X=… cmd` skips `cmd`. Set by
/// BUILTIN_SEAL_INLINE_ENV (the point right after those assignments),
/// consumed by the dispatch that would run the command, and cleared by
/// BUILTIN_END_INLINE_ENV so it never outlives the command.
///
/// !!! WARNING: RUST-ONLY CARRIER !!! C tests errflag inline between
/// addvars and the dispatch in one function; here those are separate
/// VM ops, and errflag alone cannot tell this skip from an error raised
/// by the command words, which C handles at c:3760 instead.
static PREFIX_ASSIGN_FAILED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// The command word of the `X=… cmd` whose prefix assignments are
/// expanding right now: Some between BUILTIN_PREFIX_ASSIGNS_START and
/// BUILTIN_SEAL_INLINE_ENV, "" when the word is an expansion that only
/// BUILTIN_EXEC_DYNAMIC resolves.
///
/// !!! WARNING: RUST-ONLY CARRIER !!! C decides whether to fork
/// (c:Src/exec.c:3719-3730) before addvars runs, so a `${name?msg}` in
/// the assignments already knows which process it is in
/// (c:Src/subst.c:3371 `mypid == getpid()`). zshrs expands them in the
/// shell before the dispatch op resolves the command.
static PREFIX_ASSIGN_CMD: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
/// A `${name?msg}` in those assignments owes c:Src/subst.c:3375's
/// `zexit(1)` unless the command turns out to be forked; see
/// `prefix_assign_defer_exit`.
static PREFIX_ASSIGN_EXIT_PENDING: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// Set by BUILTIN_EXEC_DYNAMIC_REDIRS, taken by the next
/// BUILTIN_EXEC_DYNAMIC: that command had redirections.
static EXEC_DYNAMIC_REDIRS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// Facts about the next command that only its EXTERNAL spawn acts on; an
/// external spawn consumes them, any other command clears them.
/// EXEC_CARRIER_DASH — c:Src/exec.c:772-776, the `-` precommand
/// (BINF_DASH), set by BUILTIN_EXEC_DASH: argv[0] is prefixed with `-`.
/// EXEC_CARRIER_FORKED — c:Src/exec.c:3063/4369, set by
/// BUILTIN_EXEC_FORKED_SIMPLE: the child forked for this command execs it.
///
/// !!! WARNING: RUST-ONLY CARRIER !!! C accumulates BINF_DASH into
/// `cflags` in the same function that calls `execute()`; here the
/// compile-time fact crosses from the marker op to the spawn.
static EXEC_DASH: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
/// c:Src/exec.c:3536-3538 — the job text of the simple command about to
/// dispatch (BUILTIN_JOB_TEXT). The foreground external wait takes it;
/// a builtin or function dispatch drops it.
///
/// !!! WARNING: RUST-ONLY CARRIER !!! C computes `text` in execcmd_exec,
/// the function that also forks and waits.
static JOB_TEXT: std::cell::RefCell<Option<fusevm::Value>> = const { std::cell::RefCell::new(None) };
/// zshrs-only: the alias the command about to dispatch was written as, with
/// the number of words in its body (BUILTIN_ALIAS_ORIGIN). `call_function`
/// takes it, so an `intercept` on the alias name can fire.
///
/// !!! WARNING: RUST-ONLY CARRIER !!! No C counterpart.
static ALIAS_ORIGIN: std::cell::RefCell<Option<(String, usize, String)>> = const { std::cell::RefCell::new(None) };
/// Counts sublists (bumped by BUILTIN_STMT_PROLOGUE_FAST). Together with
/// REDIR_SCOPE_OPENED it tells a builtin whether the redirect scope on
/// top of the stack belongs to its own command.
///
/// !!! WARNING: RUST-ONLY CARRIER !!! C's `execcmd_exec` holds the
/// command's `save[]` array locally and tests `save[1] == -2`
/// (c:Src/exec.c:4300); zshrs keeps one shared scope stack for simple
/// and compound commands alike.
static SUBLIST_SERIAL: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
/// `(SUBLIST_SERIAL, stack depth)` recorded when the newest redirect
/// scope opened. A simple command opens its scope right before its own
/// dispatch, inside its sublist; a compound command's body starts a new
/// sublist first.
static REDIR_SCOPE_OPENED: std::cell::Cell<(u64, usize)> = const { std::cell::Cell::new((0, 0)) };
/// Per open redirect scope (index = depth - 1): whether ERRFLAG_ERROR
/// was clear when the scope opened. c:Src/exec.c:3637-3643 aborts on an
/// argument-expansion errflag BEFORE the redirect loop, so an errflag
/// first seen while a redirection is applied came from that
/// redirection's own target (xpandredir). See redir_target_expansion_failed.
static REDIR_SCOPE_ERRFLAG_CLEAN: std::cell::RefCell<Vec<bool>> =
const { std::cell::RefCell::new(Vec::new()) };
/// c:Src/exec.c:3775-3777 — `if (input) addfd(forked, save, mfds, 0,
/// input, 0, NULL);` seeds `mfds[0]` with the pipeline input BEFORE the
/// stage command's redirect list is walked, so an input redirection
/// joins the pipe as a second multio member (`cat o1 | cat <o2` reads
/// both). BUILTIN_PIPE_FDS_INSTALL records the sublist serial it
/// installed the pipe in; the redirect scope that opens in the same
/// sublist (the stage command's own) turns it into PIPE_INPUT_SCOPE.
///
/// !!! WARNING: RUST-ONLY CARRIER !!! C does both steps inside one
/// execcmd_exec call; zshrs splits them across two VM ops.
static PIPE_INPUT_INSTALLED: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
/// Redirect-stack depth of the scope whose fd-0 redirection must keep
/// the pipeline input as its first multio member; consumed by the first
/// such redirection.
static PIPE_INPUT_SCOPE: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
}
/// Register the session executor pointer (called from
/// `install_session_executor`). See [`with_session_context`].
pub fn register_session_executor(exec: &mut ShellExecutor) {
SESSION_EXECUTOR_PTR.with(|c| c.set(Some(exec as *mut ShellExecutor)));
}
/// Run `f` with the registered session executor established as
/// `CURRENT_EXECUTOR`, so code reaching the live executor via
/// `try_with_executor` works even when no per-command `execode` context
/// is active yet.
///
/// Sole caller: `zsh_main`'s `run_init_scripts()` (c:1914), which
/// sources `.zshenv`/`.zshrc`/`.zlogin` via `source()` BEFORE the loop's
/// first `execode`. Without an active context those sourced bodies
/// `try_with_executor` → `None` → no-op, so the shell silently ignored
/// the user's dotfiles. The scope is entered once around the startup
/// sourcing window and dropped before the loop begins — deliberately NOT
/// Run `f` with the registered session executor established as
/// `CURRENT_EXECUTOR`, so code reaching the live executor via
/// `try_with_executor` works even when no per-command `execode` context
/// is active yet.
///
/// Sole caller: `zsh_main`'s `run_init_scripts()` (c:1914), which
/// sources `.zshenv`/`.zshrc`/`.zlogin` via `source()` BEFORE the loop's
/// first `execode`. Without an active context those sourced bodies
/// `try_with_executor` → `None` → no-op, so the shell silently ignored
/// the user's dotfiles. The scope is entered once around the startup
/// sourcing window and dropped before the loop begins.
///
/// `execute_script_zsh_pipeline` now carries the same session-executor
/// rung of its own (exec.rs), since `execstring` callers that fire
/// BETWEEN commands — `checksched`, `dotrap` — have no active context
/// either and were silently dropping their command. That rung is reached
/// only when `CURRENT_EXECUTOR` is unset, so a nested command
/// substitution (which always runs inside a chunk, and therefore inside
/// an `ExecutorContext`) takes the active-executor path as before and
/// never re-enters the session executor.
pub fn with_session_context<R>(f: impl FnOnce() -> R) -> R {
let ptr = SESSION_EXECUTOR_PTR.with(|c| c.get());
match ptr {
// SAFETY: set by install_session_executor to an executor that
// outlives the single-threaded interactive session.
Some(ptr) => {
let _ctx = ExecutorContext::enter(unsafe { &mut *ptr });
f()
}
None => f(),
}
}
/// Merge finished background-compinit results into shell state, callable
/// from any site (active VM context first, session executor otherwise —
/// the ZLE completion path runs OUTSIDE a VM frame, where
/// `try_with_executor` alone is None and $_comps stayed empty forever).
pub fn drain_compinit_bg_hook() {
if try_with_executor(|exec| exec.drain_compinit_bg()).is_some() {
return;
}
let ptr = SESSION_EXECUTOR_PTR.with(|c| c.get());
if let Some(ptr) = ptr {
// SAFETY: per with_session_context.
let _ctx = ExecutorContext::enter(unsafe { &mut *ptr });
unsafe { (*ptr).drain_compinit_bg() }
}
}
/// Run the body of a PLAIN sourced file through the per-command loop —
/// `ShellExecutor::execute_script_per_command`, the port of the
/// `switch (loop(0, 0))` arm of C's `source()` (c:Src/init.c:1625-1641).
///
/// `bin_dot` (`src/ported/builtin.rs`, C's `Src/builtin.c:6118`
/// `ret = source(enam = buf);`) is the only caller. It lives HERE rather
/// than beside the other executor accessors in `src/ported/exec.rs`
/// because everything under `src/ported/` is a line-by-line port and
/// `build.rs` rejects a `fn` there with no C counterpart — this bridge
/// shim has none, since C's `source()` reaches its interpreter through
/// plain globals where Rust needs an explicit executor handle.
///
/// Executor ladder, in the order the sibling wrappers in `exec.rs` use:
/// the innermost ACTIVE executor when one is in scope — inside
/// `$(source f)` that is the sub-VM that owns the capture, which is why
/// the substitution still collects the file's output — and the installed
/// session executor otherwise, for a `source` that runs before the main
/// loop's first `execode` has entered a context. `Ok(0)` with neither,
/// matching `exec::execute_script`'s no-executor return.
pub fn source_file_per_command(src: &str) -> Result<i32, String> {
if let Some(r) = try_with_executor(|exec| exec.execute_script_per_command(src)) {
return r;
}
let ptr = SESSION_EXECUTOR_PTR.with(|c| c.get());
match ptr {
// SAFETY: per with_session_context.
Some(ptr) => {
let _ctx = ExecutorContext::enter(unsafe { &mut *ptr });
unsafe { (*ptr).execute_script_per_command(src) }
}
None => Ok(0),
}
}
/// Run the deparsed text of an ALREADY-COMPILED `.zwc` program on the live
/// executor — the compiled arm of `source()`, `execode(prog, 1, 0,
/// "filecode")` (c:Src/init.c:1621).
///
/// Same executor resolution as [`source_file_per_command`]: the live
/// executor when one is in scope, the installed session executor otherwise,
/// `Ok(0)` with neither. See
/// [`crate::vm_helper::ShellExecutor::execute_zwc_program`] for why the plain
/// script entry point is wrong here.
pub fn execute_zwc_program(src: &str) -> Result<i32, String> {
if let Some(r) = try_with_executor(|exec| exec.execute_zwc_program(src)) {
return r;
}
let ptr = SESSION_EXECUTOR_PTR.with(|c| c.get());
match ptr {
// SAFETY: per with_session_context.
Some(ptr) => {
let _ctx = ExecutorContext::enter(unsafe { &mut *ptr });
unsafe { (*ptr).execute_zwc_program(src) }
}
None => Ok(0),
}
}
/// RAII guard that sets/clears the thread-local executor pointer.
///
/// Idempotent: calling `enter` when a context is already active is a no-op
/// for the entry side, and the guard's drop only clears the thread-local if
/// *this* call was the one that set it. Nested `execute_command` invocations
/// (e.g. from inside a builtin handler) reuse the outer pointer instead of
/// stomping it.
pub(crate) struct ExecutorContext {
we_set_it: bool,
}
impl ExecutorContext {
pub(crate) fn enter(executor: &mut ShellExecutor) -> Self {
let we_set_it = CURRENT_EXECUTOR.with(|cell| {
let mut slot = cell.borrow_mut();
if slot.is_some() {
false
} else {
*slot = Some(executor as *mut ShellExecutor);
true
}
});
ExecutorContext { we_set_it }
}
}
impl Drop for ExecutorContext {
fn drop(&mut self) {
if self.we_set_it {
CURRENT_EXECUTOR.with(|cell| {
*cell.borrow_mut() = None;
});
}
}
}
/// Access the current executor from a builtin handler.
/// # Safety
/// Only call this from within a VM execution context (after ExecutorContext::enter).
#[inline]
pub(crate) fn with_executor<F, R>(f: F) -> R
where
F: FnOnce(&mut ShellExecutor) -> R,
{
CURRENT_EXECUTOR.with(|cell| {
let ptr = cell
.borrow()
.expect("with_executor called outside VM context");
// SAFETY: The pointer is valid for the duration of VM execution,
// and we're single-threaded within the executor.
let executor = unsafe { &mut *ptr };
f(executor)
})
}
/// Non-panicking variant of [`with_executor`]: runs `f` against the
/// current executor and returns `Some(result)`, or `None` when no
/// executor is in scope (`CURRENT_EXECUTOR` unset — e.g. unit tests /
/// compsys contexts with no fusevm bridge running).
///
/// This is the primitive the `crate::ported::exec` accessor wrappers
/// (array/assoc/dispatch_function_call/execute_script/...) use to
/// reach the live executor while preserving the exact "no executor →
/// fall back to the direct param table / default value" semantics that
/// the deleted `exec_hooks` OnceLock layer encoded via its
/// "is-the-hook-installed?" check. `CURRENT_EXECUTOR` being set is the
/// faithful equivalent of "the bridge installed the hooks".
#[inline]
pub(crate) fn try_with_executor<F, R>(f: F) -> Option<R>
where
F: FnOnce(&mut ShellExecutor) -> R,
{
CURRENT_EXECUTOR.with(|cell| {
let ptr = (*cell.borrow())?;
// SAFETY: same contract as with_executor — the pointer is valid
// for the duration of VM execution and access is single-threaded.
let executor = unsafe { &mut *ptr };
Some(f(executor))
})
}
/// Look up a canonical builtin by name in `BUILTINS` and dispatch
/// via `execbuiltin` (Src/builtin.c:250). NO shadow check — calls the
/// builtin even if a user function with the same name exists. Used by
/// the `builtin foo` prefix opcode (which explicitly bypasses function
/// lookup per zsh semantics) and by internal call sites where shadowing
/// is unwanted. For zsh's normal name-resolution order (function shadows
/// builtin), use `dispatch_builtin` instead.
/// Shell-identifier prefix for diagnostic lines. Reads the canonical
/// scriptname (`zsh` in `--zsh` parity mode, `zshrs` otherwise) so a
/// single helper replaces hardcoded `"zshrs:"` literals across the
/// file's eprintln paths.
fn shname() -> String {
crate::ported::utils::scriptname_get().unwrap_or_else(|| "zshrs".to_string())
}
/// c:Src/subst.c:505-507 + Src/exec.c:3378-3380 — per-command
/// CSH_NULL_GLOB outcome check. During this command's word expansion
/// `expand_glob` accumulated `badcshglob |= 1` per failed glob and
/// `|= 2` per successful one (Src/glob.c:1871-1875). Exactly 1 —
/// failures and no successes — is the csh-style error: `no match`,
/// command skipped, status 1. Any other value (0 = no globs, 2/3 =
/// at least one matched) is silent. Always resets the counter for
/// the next command (C resets at prefork entry, subst.rs:1307).
/// Returns true when the error fired; callers mirror their
/// glob_failed handling (builtins leave ERRFLAG_ERROR set so the
/// script aborts, externals clear it so the next sublist runs —
/// verified against zsh 5.9.1).
/// Restore the user's GLOB_SUBST after a `${~spec}` carrier flip
/// (see subst::TILDE_GLOBSUBST_CARRIER). Runs at the same
/// command-dispatch boundaries that consume glob_failed /
/// badcshglob — by then every glob op of the current word pipeline
/// has read the carrier.
pub(crate) fn consume_tilde_globsubst_carrier() {
// The default-word report belongs to the word pipeline just finished too.
crate::ported::subst::DEFAULT_WORD_GLOBSUBST_OFF.with(|c| c.set(false));
crate::ported::subst::TILDE_GLOBSUBST_CARRIER.with(|c| {
if let Some(saved) = c.take() {
crate::ported::options::opt_state_set("globsubst", saved);
}
});
}
/// Pop `argc` stack slots for a whole-array assignment: the LAST popped
/// (deepest pushed) is the param name, the rest are the values in stack
/// order, with any `Value::Array` flattened to its elements. Mirrors the
/// Flatten an array-assignment RHS value into scalar strings, descending
/// through nested `Value::Array`s. zsh arrays are always flat, so recursion
/// only collapses the wrapper layers the compiler introduces — in particular
/// the single `Value::Array` built by `Op::MakeArray` for `arr=(...)` literals
/// (used to dodge `CallBuiltin`'s u8 argc cap), whose own elements may
/// themselves be arrays from an unquoted `$other_array` expansion. A
/// one-level flatten would stringify those inner arrays into a single element.
fn flatten_array_value(v: Value, out: &mut Vec<String>) {
match v {
Value::Array(items) => {
for it in items.iter() {
flatten_array_value(it.clone(), out);
}
}
other => out.push(other.to_str()),
}
}
/// c:Src/exec.c:2595-2598, 2605-2608, 2620-2623 (addvars) — `if (errflag)
/// { state->pc = opc; return; }` after ecgetlist, prefork and globlist. An
/// array assignment whose element expansion failed (`x=( *(zz) )`, a NOMATCH)
/// never reaches assignaparam, so the parameter keeps its old type and value.
/// Shared gate of BUILTIN_SET_ARRAY / BUILTIN_APPEND_ARRAY.
fn array_assignment_expansion_failed() -> bool {
(crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed)
& crate::ported::zsh_h::ERRFLAG_ERROR)
!= 0
|| with_executor(|exec| exec.current_command_glob_failed.get())
}
/// pop/flatten prologue of BUILTIN_SET_ARRAY / BUILTIN_APPEND_ARRAY.
fn pop_array_args_with_name(vm: &mut fusevm::VM, argc: u8) -> (String, Vec<String>) {
let n = argc as usize;
let mut popped: Vec<Value> = Vec::with_capacity(n);
for _ in 0..n {
popped.push(vm.pop());
}
popped.reverse();
let name = popped.pop().map(|v| v.to_str()).unwrap_or_default();
let mut values: Vec<String> = Vec::new();
for v in popped {
flatten_array_value(v, &mut values);
}
(name, values)
}
/// c:Src/exec.c:3785-3796 — the redirect loop runs `xpandredir(fn, redir)`
/// on each target and then `if (errflag) { closemnodes(mfds); fixfds(save);
/// execerr(); }`: an expansion error in a target (`> $((1/0))`,
/// `> ${u?msg}`, a NULL_GLOB `> nx(N)`) is a failed redirection. zshrs
/// expands the target before the redirect op runs, so the op sees the
/// errflag: when it was clear as this command's redirect scope opened, mark
/// the redirection failed and skip it. The redirect_failed gates then treat
/// it like any other failure — for an external command, which C forks before
/// this loop (c:3719), only the child dies (call_function).
/// !!! RUST-ONLY HELPER: C tests errflag inline in the redirect loop.
fn redir_target_expansion_failed(exec: &mut ShellExecutor) -> bool {
if (crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed)
& crate::ported::zsh_h::ERRFLAG_ERROR)
== 0
{
return false;
}
let depth = exec.redirect_scope_stack.len();
let clean_at_open = depth > 0
&& REDIR_SCOPE_ERRFLAG_CLEAN.with(|v| v.borrow().get(depth - 1).copied().unwrap_or(false));
if clean_at_open {
exec.redirect_failed = true;
}
clean_at_open
}
/// Asked by paramsubst's `${name?msg}` arms before they take
/// c:Src/subst.c:3375's `zexit(1)`: true when the expansion belongs to the
/// prefix assignments of `X=… cmd`, whose process is not known yet. The exit
/// is then owed (PREFIX_ASSIGN_EXIT_PENDING) and `settle_prefix_assign_exit`
/// pays it once the command word resolves.
pub(crate) fn prefix_assign_defer_exit() -> bool {
let assigning = PREFIX_ASSIGN_CMD.with(|c| c.borrow().is_some());
if assigning {
PREFIX_ASSIGN_EXIT_PENDING.with(|c| c.set(true));
}
assigning
}
/// Pays a deferred `${name?msg}` exit once `name` (the expanded command word,
/// "" for none) is known. c:Src/exec.c:3719-3730 forks an external command
/// before c:4358 runs its prefix assignments, so the error ends only that
/// child (c:3377 `_exit(1)`, c:4359 `if (errflag) _exit(1)`): the shell sees
/// status 1, which the dispatch's PREFIX_ASSIGN_FAILED arm reports. A shell
/// function, a builtin or no command at all runs the assignments in the
/// shell (c:4157), which exits there (c:3375).
fn settle_prefix_assign_exit(name: &str) {
if !PREFIX_ASSIGN_EXIT_PENDING.with(|c| c.replace(false)) {
return;
}
let forked = !name.is_empty()
&& !with_executor(|exec| exec.function_exists(name))
&& !crate::ported::builtin::createbuiltintable().contains_key(name);
if !forked {
crate::ported::builtin::STOPMSG.store(1, std::sync::atomic::Ordering::Relaxed); // c:3374
// !!! DASH-FAMILY GATE (dash_mode::fatal_error_status): same as the
// paramsubst arms. !!!
crate::ported::builtin::zexit(
crate::extensions::dash_mode::fatal_error_status().unwrap_or(1),
crate::ported::zsh_h::ZEXIT_NORMAL,
); // c:3375
}
}
thread_local! {
/// Set by BUILTIN_CMD_NAME_GLOB_MARK: the command-name word failed to glob.
static CMD_NAME_GLOB_FAILED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// Consume the command-name-glob-failed mark.
fn take_cmd_name_glob_failed() -> bool {
CMD_NAME_GLOB_FAILED.with(|c| c.replace(false))
}
/// c:Src/exec.c:3719 + 3755-3763 — an external command is forked
/// (execcmd_fork) BEFORE `globlist(args, 0)`, so a NOMATCH (or the
/// CSH_NULL_GLOB `no match`, c:Src/subst.c:505-507) raised while globbing
/// its arguments ends the CHILD with status 1; the shell's errflag stays
/// clean and the next command runs (`rm *nomatch; print after` prints the
/// error, then `after`). zshrs globs in the shell, so every path that runs
/// a name zsh would fork for calls this first: `Some(1)` means skip the
/// command, with this command's ERRFLAG_ERROR taken back out.
fn external_glob_failure_status() -> Option<i32> {
consume_tilde_globsubst_carrier();
let failed = with_executor(|exec| exec.current_command_glob_failed.replace(false))
|| consume_badcshglob();
if !failed {
return None;
}
if take_cmd_name_glob_failed() {
// c:Src/exec.c:3350-3354 + 3757-3760 — the name was globbed in the
// shell, so errflag stays set and the list ends.
with_executor(|exec| exec.set_last_status(1));
return Some(1);
}
crate::ported::utils::errflag.fetch_and(
!crate::ported::zsh_h::ERRFLAG_ERROR,
std::sync::atomic::Ordering::Relaxed,
);
with_executor(|exec| exec.set_last_status(1));
Some(1)
}
fn consume_badcshglob() -> bool {
let v = crate::ported::glob::BADCSHGLOB.swap(0, std::sync::atomic::Ordering::Relaxed);
if v == 1 {
crate::ported::utils::zerr("no match"); // c:Src/subst.c:507
true
} else {
false
}
}
/// Map a builtin name to the zsh module that owns it, IFF zsh does
/// not auto-load that builtin on first use. Used by
/// `dispatch_builtin_raw` to gate `--zsh` mode dispatch behind
/// `zmodload`, mirroring `zsh -fc <name>` returning 127 for these
/// names without an explicit module load.
///
/// Returns `Some(module_name)` if `name` belongs to a non-auto-load
/// module per the per-module `Src/Modules/<x>.c` `bintab[]` plus
/// the auto-load flag set at module-build time. `None` for core
/// builtins and for auto-loaded module builtins (sched, log, echotc,
/// echoti, zformat, zparseopts, zregexparse, zstyle, strftime,
/// private, vared, zle, bindkey, comp*) which work without zmodload.
fn module_bound_builtin_module(name: &str) -> Option<&'static str> {
match name {
"zftp" => Some("zsh/zftp"),
"zsocket" => Some("zsh/net/socket"),
"ztcp" => Some("zsh/net/tcp"),
"zstat" => Some("zsh/stat"),
"zselect" => Some("zsh/zselect"),
"zpty" => Some("zsh/zpty"),
"zprof" => Some("zsh/zprof"),
"zsystem" | "syserror" => Some("zsh/system"),
"clone" => Some("zsh/clone"),
"zcurses" => Some("zsh/curses"),
"ztie" | "zuntie" | "zgdbmpath" => Some("zsh/db/gdbm"),
"pcre_compile" | "pcre_match" | "pcre_study" => Some("zsh/pcre"),
"example" => Some("zsh/example"),
"cap" | "getcap" | "setcap" => Some("zsh/cap"),
"zgetattr" | "zsetattr" | "zdelattr" | "zlistattr" => Some("zsh/attr"),
// c:Src/Modules/datetime.c — `strftime` is registered via
// partab[] when zsh/datetime loads. Verified by
// `zsh -fc 'strftime -s s %Y 0'` → 127 "command not found".
"strftime" => Some("zsh/datetime"),
_ => None,
}
}
/// Lookup half of [`try_run_registered_builtin`]: the handler for a
/// zshrs-original opcode builtin NAME, or `None`. Split from the run half so
/// the `builtin` precommand walk can ask whether the name exists before the
/// redirections open (c:Src/exec.c:3489 `builtintab->getnode`) without
/// running the command.
///
/// !!! Keep in sync with the matching `vm.register_builtin(...)` closures in
/// `register_builtins`: both must route a name to the same executor method.
fn registered_builtin(name: &str) -> Option<fn(&[String]) -> i32> {
let f: fn(&[String]) -> i32 = match name {
"ai" => |argv| with_executor(|e| e.builtin_ai(argv)),
"async" => |argv| with_executor(|e| e.builtin_async(argv)),
"await" => |argv| with_executor(|e| e.builtin_await(argv)),
"barrier" => |argv| with_executor(|e| e.builtin_barrier(argv)),
"peach" => |argv| with_executor(|e| e.builtin_peach(argv)),
"pmap" => |argv| with_executor(|e| e.builtin_pmap(argv)),
"pgrep" => |argv| with_executor(|e| e.builtin_pgrep(argv)),
"intercept" => |argv| with_executor(|e| e.builtin_intercept(argv)),
"intercept_proceed" => |argv| with_executor(|e| e.builtin_intercept_proceed(argv)),
"doctor" => |argv| with_executor(|e| e.builtin_doctor(argv)),
"dbview" => |argv| with_executor(|e| e.builtin_dbview(argv)),
"profile" => |argv| with_executor(|e| e.builtin_profile(argv)),
"provenance" => |argv| with_executor(|e| e.builtin_provenance(argv)),
"zbanner" => |argv| with_executor(|e| e.builtin_zbanner(argv)),
"caller" => |argv| with_executor(|e| e.builtin_caller(argv)),
"help" => |argv| with_executor(|e| e.builtin_help(argv)),
"cdreplay" => |argv| with_executor(|e| e.builtin_cdreplay(argv)),
"zsleep" => |argv| crate::extensions::ext_builtins::zsleep(argv),
_ => return None,
};
Some(f)
}
/// Whether NAME is a zshrs-original opcode builtin or an enabled
/// host-registered native command: the names [`try_run_registered_builtin`]
/// would run.
pub(crate) fn is_registered_builtin(name: &str) -> bool {
registered_builtin(name).is_some() || crate::native_cmds::is_enabled(name)
}
/// Whether NAME is an autoload stub that has not been loaded yet: an enabled
/// shfunctab entry with PM_UNDEFINED set (c:Src/zsh.h:1895). Loading clears
/// the flag (c:Src/exec.c:5790, c:5815); a function defined in the shell
/// never carries it. Gates the native zmv/zcp/zln/zcalc ports, which stand
/// in for the fpath load of the stock autoload functions only.
fn autoload_stub_pending(name: &str) -> bool {
crate::ported::hashtable::shfunctab_lock()
.read()
.ok()
.and_then(|t| t.get(name).map(|f| (f.node.flags as u32 & crate::ported::zsh_h::PM_UNDEFINED as u32) != 0))
.unwrap_or(false)
}
/// Whether a shell function named NAME shadows a builtin of that name at
/// command dispatch (c:Src/exec.c:3485-3489: `shfunctab->getnode` before
/// `builtintab->getnode`). `getnode` skips DISABLED nodes (c:Src/hashtable.c:239), so a function
/// switched off with `disable -f NAME` does not shadow (Bug #221 in
/// docs/BUGS.md). `functions_compiled` keeps the body regardless of the
/// DISABLED flag, hence the shfunctab probe first.
fn user_fn_shadows_builtin(name: &str) -> bool {
let disabled = crate::ported::hashtable::shfunctab_lock()
.read()
.ok()
.and_then(|t| {
let entry = t.get_including_disabled(name)?;
Some((entry.node.flags as u32 & crate::ported::zsh_h::DISABLED as u32) != 0)
})
.unwrap_or(false);
!disabled && with_executor(|exec| exec.functions_compiled.contains_key(name))
}
/// The builtin table as the `builtin` precommand modifier consults it
/// (c:Src/exec.c:3489 `builtintab->getnode(builtintab, cmdarg)`): the ported
/// table minus DISABLED nodes (`getnode` skips them, so `disable typeset;
/// builtin typeset` is "no such builtin"), plus the zshrs builtins that live
/// outside it: the daemon `z*` family and the opcode builtins above.
pub(crate) fn builtin_prefix_finds(name: &str) -> bool {
if crate::daemon::builtins::is_zshrs_builtin(name) {
return true;
}
let disabled = crate::ported::builtin::BUILTINS_DISABLED
.lock()
.map(|s| s.contains(name))
.unwrap_or(false);
(crate::ported::builtin::createbuiltintable().contains_key(name) && !disabled)
|| is_registered_builtin(name)
}
/// Run a daemon `z*` builtin (zcache, zd, zjob, …) by name. They are
/// dispatched by name instead of living in builtintab, so each resolver that
/// can land on a builtin name — literal head, `$var` head, `builtin NAME` —
/// routes them through here. `None` when `name` is not one of them.
fn run_daemon_builtin(name: &str, rest: &[String]) -> Option<i32> {
if !crate::daemon::builtins::is_zshrs_builtin(name) {
return None;
}
// Streaming builtins (`zlog tail -f`) poll this between waits so Ctrl-C
// ends them; the daemon crate cannot see the shell's `errflag`.
let _ = crate::daemon::builtins::INTERRUPT_CHECK.set(|| {
crate::ported::utils::errflag.shell_load(std::sync::atomic::Ordering::Relaxed)
& crate::ported::zsh_h::ERRFLAG_INT
!= 0
});
let argv: Vec<String> = std::iter::once(name.to_string())
.chain(rest.iter().cloned())
.collect();
// c:Src/exec.c:4231 `dont_queue_signals()` — a builtin runs with signals
// delivered, not queued, so Ctrl-C reaches a streaming builtin while it
// runs. Some resolvers reach here without `dispatch_builtin`'s bracket.
let q = crate::ported::signals_h::queue_signal_level();
crate::ported::signals_h::dont_queue_signals();
let status = crate::daemon::builtins::try_dispatch(name, &argv).unwrap_or(1);
crate::ported::signals_h::restore_queue_signals(q);
Some(status)
}
/// Dispatch a zshrs-ORIGINAL builtin by NAME, argv-style. These are
/// registered as fusevm opcodes in [`register_builtins`] (async, doctor,
/// peach, …), so a *literal* name compiles to `CallBuiltin` and runs. But
/// they are absent from the static `BUILTINS` port table and the merged
/// `builtintab`, so when the command name is resolved only at run time —
/// `$var` indirection, `builtin NAME` — the ported command-resolution path
/// never finds them and reports "command not found" / "no such builtin",
/// even though `whence` (correctly) calls them builtins. The
/// `register_builtins` closures use the VM only to pop args and then call an
/// executor method, so the identical dispatch works here from any parent-side
/// resolver that has an executor — no VM re-entry (which would alias the
/// running `&mut VM`). Returns `None` for a name that is not one of them, so
/// the caller falls through to external lookup.
///
/// !!! Keep in sync with the matching `vm.register_builtin(...)` closures in
/// `register_builtins`: both must route a name to the same executor method.
pub(crate) fn try_run_registered_builtin(name: &str, argv: &[String]) -> Option<i32> {
if let Some(run) = registered_builtin(name) {
return Some(run(argv));
}
// Host-registered native commands (`extensions/native_cmds.rs`): the
// fat binary's sibling runtimes — `git` (zvcs), `arb` (arblang),
// `stryke` (strykelang) in the zshrs-native build. Unknown here in the
// thin shell, where the table is empty and this falls through to
// `None` exactly as before.
//
// Reached from the two places that ask "is this a builtin?": the
// pre-PATH arm of the ZshrsHost dispatch (after functions and after
// builtintab, so a user `git()` still shadows it) and the forced
// `builtin NAME` precommand. `command git` consults neither, so the
// escape hatch to the `git` on PATH is untouched.
//
// The registry's contract is full argv — argv[0] is the command name
// as invoked, which zvcs needs for its `git-<verb>` dashed form and
// for its `zvcs: <command>: <reason>` diagnostics — while every arm
// above takes the operands alone, so the name is spliced back on here.
if !crate::native_cmds::is_enabled(name) {
return None;
}
let full: Vec<String> = std::iter::once(name.to_string())
.chain(argv.iter().cloned())
.collect();
crate::native_cmds::dispatch(name, &full)
}
/// `command -v` / `command -V`: c:Src/exec.c:3149-3157 — `pushnode(preargs,
/// "command"); hn = &commandbn.node; is_builtin = 1;`, i.e. bin_whence with
/// the BIN_COMMAND funcid. `post` is the flag words then the names; `dash_p`
/// says a `-p` was among the flags.
fn command_whence(post: &[String], dash_p: bool) -> i32 {
let mut ops = options {
ind: [0u8; MAX_OPS],
args: Vec::new(),
argscount: 0,
argsalloc: 0,
};
let mut name_pos = 0usize;
let mut flag_byte = b'v';
for (i, a) in post.iter().enumerate() {
if a.starts_with('-') && a.len() >= 2 {
let body = &a.as_bytes()[1..];
if body.contains(&b'V') {
flag_byte = b'V';
}
name_pos = i + 1;
} else {
name_pos = i;
break;
}
}
ops.ind[flag_byte as usize] = 1;
// c:Src/builtin.c:4157 + c:4165-4167 — bin_whence reads `-p` off
// `ops` twice: to prefer a builtin over an external for
// `command -p[vV]`, and as `findcmd`'s `default_path` argument.
if dash_p {
ops.ind[b'p' as usize] = 1;
}
let whence_args: Vec<String> = post[name_pos..].to_vec();
crate::ported::builtin::bin_whence(
"command",
&whence_args,
&ops,
crate::ported::hashtable_h::BIN_COMMAND,
)
}
/// Whether the redirect scope on top of the stack was opened by the
/// command now dispatching — its OWN redirections — rather than by an
/// enclosing compound command. C asks the same of the command's local
/// `redir` list / `save[]` array (c:Src/exec.c:3651, c:4300).
/// !!! RUST-ONLY — no C counterpart.
pub(crate) fn own_redirect_scope(exec: &ShellExecutor) -> bool {
let depth = exec.redirect_scope_stack.len();
depth > 0 && REDIR_SCOPE_OPENED.with(|c| c.get()) == (SUBLIST_SERIAL.with(|c| c.get()), depth)
}
pub(crate) fn dispatch_builtin_raw(name: &str, args: Vec<String>) -> i32 {
// !!! WARNING: RUST-ONLY — NO C COUNTERPART !!!
// Native p10k engine intercept (src/extensions/p10k): sourcing
// powerlevel10k.zsh-theme activates the Rust segment engine
// instead of executing the ~13k-line zsh theme. The user's
// `.p10k.zsh` CONFIG is NOT intercepted — it sources normally so
// its POWERLEVEL9K_* typesets land in the paramtab, which the
// engine reads live at every render. Placed here (the chokepoint
// every builtin route funnels through) so `source`, `.`, and
// `builtin source` all hit it.
if matches!(name, "source" | ".") {
if let Some(status) = crate::p10k::maybe_intercept_theme_source(&args) {
// Register a `p10k` stub function so `${+functions[p10k]}`
// guards in .zshrc templates stay truthy. The body forwards
// to the bridge-intercepted `zshrs-p10k-api` name so
// `p10k segment` (custom-segment protocol) and the other
// API subcommands reach the native engine (p10k_api).
try_with_executor(|exec| {
let _ = exec.execute_script("function p10k() { zshrs-p10k-api \"$@\" }");
});
return status;
}
}
// Native p10k API dispatch — the `p10k` stub function forwards
// here (see the theme intercept above). Must run before the
// generic builtintab lookup: the name is not a real builtin.
if let Some(status) = crate::p10k::maybe_intercept_command(name, &args) {
return status;
}
// c:Src/exec.c:3674-3682 — a builtin runs in the current shell.
crate::exec_jobs::mark_thisjob_cursh(true);
// c:Src/exec.c:2700-2717 — `private` is an autoloaded builtin in
// zsh (autofeature b:private of zsh/param/private): first use
// runs ensurefeature → require_module → load_module → boot_,
// marking the module MOD_INIT_B (what `zmodload -e` reads) and
// installing the wrap_private FuncWrap (param_private.c:712).
// doshfunc gates the wrapper dispatch on that load state, so
// this require_module is what activates private scoping. The
// raw dispatcher is the chokepoint every builtin route funnels
// through; require_module is idempotent after the first call
// (needs_load checks MOD_INIT_B).
if name == "private" {
if let Ok(mut tab) = crate::ported::module::MODULESTAB.lock() {
let _ = crate::ported::module::require_module(
&mut tab,
"zsh/param/private",
None,
0,
false,
);
// c:2710 ensurefeature
}
}
// c:Src/Modules/param_private.c:682-685 setup_ — loading
// zsh/param/private REPLACES the `local` builtintab node's
// handlerfunc + optstr with bin_private's ("Even more horrible
// hack"), so once the module is loaded `local` IS bin_private: it
// accepts the -P/-Pa private-scope flags, and without -P delegates
// to bin_typeset, which already treats `local` and `private`
// identically (is_locallike, builtin.rs:3666). Replicate the swap by
// routing `local` through the `private` node only after the module
// is loaded — before then, `local -P` still errors "bad option: -P"
// exactly like stock zsh. The `private` node carries the augmented
// optstr (with P) that the `local` node lacks.
if name == "local"
&& crate::ported::module::MODULESTAB
.lock()
.map(|t| t.is_bound("zsh/param/private"))
.unwrap_or(false)
{
// c:Src/Modules/param_private.c:683-685 — the swap copies EXACTLY
// two fields:
// ((Builtin)hn)->handlerfunc = bintab[0].handlerfunc;
// ((Builtin)hn)->optstr = bintab[0].optstr;
// `defopts` is NOT copied, so the `local` node keeps its own
// (NULL) defaults while `private`'s node keeps `"P"`. That is
// what makes `local x` delegate straight to bin_typeset
// (c:225-229 `if (!OPT_ISSET(ops, 'P'))`) while `private x`
// opens a private scope. Dispatching `local` through the
// `private` NODE inherited defopts="P", so every `local NAME`
// ran the private-promotion path: `() { local h=scalar;
// private -A h }` reported "can't change type of private param"
// where zsh reports "can't change scope of existing param"
// (V10private.ztst:13), and `local` silently made privates.
// zshrs's builtintab maps to `&'static builtin` rows in an
// immutable static, so mirror C's field swap on a private
// static copy of the `local` node instead of mutating the table.
static LOCAL_AS_PRIVATE: std::sync::LazyLock<crate::ported::zsh_h::builtin> =
std::sync::LazyLock::new(|| crate::ported::zsh_h::builtin {
// c:683 `save_local = *(Builtin)hn;` — start from the
// real `local` row so name/flags/minargs/maxargs/funcid/
// defopts all stay `local`'s.
node: crate::ported::zsh_h::hashnode {
next: None,
nam: "local".to_string(),
flags: (crate::ported::zsh_h::BINF_PLUSOPTS
| crate::ported::zsh_h::BINF_MAGICEQUALS
| crate::ported::zsh_h::BINF_PSPECIAL
| crate::ported::zsh_h::BINF_ASSIGN) as i32,
},
// c:684 — handlerfunc from bintab[0] (bin_private).
handlerfunc: Some(
crate::ported::modules::param_private::bin_private
as crate::ported::zsh_h::HandlerFunc,
),
minargs: 0,
maxargs: -1,
funcid: 0,
// c:685 — optstr from bintab[0] (private's, which adds `P`).
// Same string as the `private` row in builtin.rs (5.9.2's `p`).
optstr: Some("AE:%F:%HL:%PR:%TUZ:%ahi:%lmnprtux".to_string()),
// c:683-685 — NOT copied: `local` keeps its own defaults.
defopts: None,
});
let bn_ptr = &*LOCAL_AS_PRIVATE as *const _ as *mut _;
return crate::ported::builtin::execbuiltin(args, Vec::new(), bn_ptr);
}
// c:Bugs #475/#504/#555 — bash-only builtins (`mapfile`,
// `readarray`, `compopt`) should emit "command not found" in
// `--zsh` mode matching zsh's external-command-lookup miss.
// The per-opcode closures for caller/help/complete/compgen
// already gate via IS_ZSH_MODE at their registration sites;
// names without dedicated opcodes (compopt/mapfile/readarray)
// route through this generic builtintab lookup and need the
// gate here.
if crate::IS_ZSH_MODE.load(std::sync::atomic::Ordering::Relaxed)
&& matches!(name, "compopt" | "mapfile" | "readarray")
{
eprintln!("zsh:1: command not found: {}", name);
let _ = args;
return 127;
}
// c:Src/exec.c:2700-2724 resolvebuiltin — autoloaded-builtin stub
// (registered by `zmodload -ab MOD NAME`, Src/module.c:426
// add_autobin) fires on first use: ensurefeature loads the owning
// module, then dispatch proceeds against the real builtin. Must
// run BEFORE the module-bound 127 gate below — `zmodload -ab
// zsh/zselect zselect; zselect` previously died there with
// `command not found` because the gate only checked is_loaded,
// never the autoload ledger.
if let Some(rc) = crate::ported::exec::resolvebuiltin(name) {
if rc != 0 {
// Load failed or feature undefined — diagnostics already
// printed (load_module zwarn / resolvebuiltin zerr).
// C's execbuiltin head returns 1 (Src/builtin.c:264-267).
return 1;
}
// Module loaded — fall through; the is_loaded gates below now
// pass and the normal dispatch chain runs the real builtin.
}
// c:Src/Modules/<mod>.c boot_/setup_ chain — module-bound builtins
// (zftp, zsocket, ztcp, zstat, etc.) are only registered into
// `builtintab` when their module is loaded via `zmodload`. In
// zsh `-fc` (the parity test harness's invocation), the modules
// are NOT pre-loaded, so each name reports "command not found"
// with exit 127. zshrs intentionally pre-loads all module bintabs
// in `createbuiltintable` (builtin.rs:131-152) for the default
// mode so users can call these without `zmodload`; that auto-load
// diverges from zsh's gate behavior. Match zsh's stance only when
// the user explicitly asked for parity via `--zsh`.
//
// The list is the union of builtins from modules that zsh does
// NOT auto-load (verified via `zsh -fc <name>` returning 127):
// zsh/zftp → zftp
// zsh/net/socket → zsocket
// zsh/net/tcp → ztcp
// zsh/stat → zstat (NOT `stat`; that name resolves to
// /bin/stat on PATH per zsh's setup)
// zsh/zselect → zselect
// zsh/zpty → zpty
// zsh/zprof → zprof
// zsh/system → zsystem, syserror
// zsh/clone → clone
// zsh/curses → zcurses
// zsh/db/gdbm → ztie, zuntie, zgdbmpath
// zsh/pcre → pcre_compile, pcre_match, pcre_study
// zsh/example → example
// zsh/cap → cap, getcap, setcap
// zsh/attr → zgetattr, zsetattr, zdelattr, zlistattr
if crate::IS_ZSH_MODE.load(std::sync::atomic::Ordering::Relaxed)
&& module_bound_builtin_module(name)
.map(|m| {
!crate::ported::module::MODULESTAB
.lock()
.map(|t| t.is_loaded(m))
.unwrap_or(false)
})
.unwrap_or(false)
{
eprintln!("zsh:1: command not found: {}", name);
let _ = args;
return 127;
}
// c:Src/Modules/files.c:806-824 — zsh/files registers `chmod`,
// `chown`, `chgrp`, `ln`, `mkdir`, `mv`, `rm`, `rmdir`, `sync`
// (plus their `zf_*` aliases) into builtintab on module load.
// Without an explicit `zmodload zsh/files`, zsh resolves the
// names through PATH lookup — `zsh -fc 'chmod +x f'` runs
// `/bin/chmod`, whose argv-parser accepts symbolic modes like
// `+x` that bin_chmod's octal-only parser rejects with
// "invalid mode `+x'". The shadow-aware wrapper at
// `dispatch_builtin` (line 438) already has this gate, but the
// direct `dispatch_builtin_raw` path used by fusevm's
// CallBuiltin opcode bypasses it. Mirror the gate here so the
// low-level dispatch matches C's PATH-fall-through behavior.
// The gate is NOT emulation-mode dependent. C has no `zsh/files`
// builtins in `builtintab` until the module is loaded, in ANY mode, so a
// bare `rm`/`mv`/`chmod` falls through to PATH — `chmod +x FILE` runs
// /bin/chmod and succeeds. Conditioning this on `IS_ZSH_MODE` meant the
// native binary answered `chmod +x` from `bin_chmod`'s octal-only parser
// ("invalid mode `+x'"), and `rm -s` / `mv -s` from the module's argument
// parser instead of the system tool's. `dispatch_builtin` at :1087 already
// gates unconditionally; this low-level `CallBuiltin` path did not.
if files_builtin_runs_from_path(name) {
// PATH lookup uses the LITERAL name: bare `mkdir` finds
// /bin/mkdir; a `zf_*` alias finds nothing and exits 127 —
// matching zsh -fc `zf_mkdir d` → "command not found:
// zf_mkdir" (the aliases exist ONLY in the loaded module's
// builtintab, Src/Modules/files.c:816-824; PATH has no
// /bin/zf_rm). The previous zf_-strip silently ran the
// system binary instead.
if let Some(status) = external_glob_failure_status() {
return status;
}
let status = with_executor(|exec| exec.execute_external(name, &args, &[])).unwrap_or(127);
return status;
}
// c:Src/Modules/stat.c:637-638 — zsh/stat registers BOTH `stat`
// and `zstat`. `zstat` is in the module_bound 127-gate above (no
// /usr/bin/zstat exists), but the bare `stat` name must FALL
// THROUGH to PATH when zsh/stat isn't loaded — zsh -fc
// 'stat -f %Lp f' runs /usr/bin/stat, while bin_stat's parser
// rejects stat(1) flags ("bad option: -c"). Same fall-through
// shape as the zsh/files gate above.
if crate::IS_ZSH_MODE.load(std::sync::atomic::Ordering::Relaxed)
&& name == "stat"
&& !crate::ported::module::MODULESTAB
.lock()
.map(|t| t.is_loaded("zsh/stat"))
.unwrap_or(false)
{
let status = with_executor(|exec| exec.execute_external(name, &args, &[])).unwrap_or(127);
return status;
}
// c:Src/exec.c:3050-3068 — builtin lookup hits `builtintab` (the
// merged table containing module-provided builtins). The previous
// port walked only the core `BUILTINS` slice, so per-module
// entries like `log` (Src/Modules/watch.c:693 `BUILTIN("log", …,
// bin_log, …)`) were registered into builtintab via
// createbuiltintable but never reached at dispatch — `log` fell
// through to PATH and ran `/usr/bin/log`. Bug #72 in docs/BUGS.md.
let tab = crate::ported::builtin::createbuiltintable();
if let Some(bn_static) = tab.get(name) {
let bn_ptr = *bn_static as *const _ as *mut _;
return crate::ported::builtin::execbuiltin(args, Vec::new(), bn_ptr);
}
1
}
/// Shadow-aware dispatch matching zsh's name-resolution order:
/// alias → reserved word → **function (shadows builtin)** → builtin →
/// external. All `BUILTIN_X` opcode handlers route through here so a
/// user-defined `cd () { … }` (or `r`, `fc`, `which`, … anything in
/// fusevm's name→opcode map) takes precedence over the C builtin —
/// matching `Src/exec.c:execcmd_exec`'s dispatch at c:3050-3068.
/// Without this, compile-time builtin resolution silently ignored
/// user wrappers (e.g. ZPWR's `cd () { builtin cd "$@"; … }`).
/// True for builtins that are bound by zsh/files's boot_/setup_
/// chain (Src/Modules/files.c:806-824). These are the bare-name
/// `mkdir`/`rm`/`mv`/`ln`/`chmod`/`chown`/`chgrp`/`sync`/`rmdir`
/// AND their `zf_*` aliases at c:816-824. Without explicit
/// `zmodload zsh/files`, the names fall through to PATH lookup
/// (zsh's `type rm` reports `/bin/rm`). Bug #28.
fn module_gated_files_builtin(name: &str) -> bool {
matches!(
name,
"mkdir"
| "rmdir"
| "rm"
| "mv"
| "ln"
| "chmod"
| "chown"
| "chgrp"
| "sync"
| "zf_mkdir"
| "zf_rmdir"
| "zf_rm"
| "zf_mv"
| "zf_ln"
| "zf_chmod"
| "zf_chown"
| "zf_chgrp"
| "zf_sync"
)
}
/// A zsh/files name while the module is not loaded: C has no such entry in
/// `builtintab` then, so the name runs from PATH like any external.
fn files_builtin_runs_from_path(name: &str) -> bool {
module_gated_files_builtin(name)
&& !crate::ported::module::MODULESTAB
.lock()
.map(|t| t.is_loaded("zsh/files"))
.unwrap_or(false)
}
thread_local! {
/// Set when a command-word glob (BUILTIN_GLOB_EXPAND / BUILTIN_GLOBLIST)
/// is what raised errflag, so the abort takes C's globlist status
/// (c:Src/exec.c:3760 `lastval = 1`) rather than the prefork one
/// (c:3523 `if (!lastval) lastval = 1`).
///
/// !!! WARNING: RUST-ONLY CARRIER !!! C knows which of the two checks
/// it is at; zshrs expands and globs each word in one pass and reaches
/// a single gate at dispatch.
static GLOB_WORD_ERRFLAG: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// Run a command-word glob and note whether it raised errflag.
fn glob_word_noting_errflag(raw: Value, skip_glob: bool) -> Value {
use std::sync::atomic::Ordering;
let before = crate::ported::utils::errflag.load(Ordering::Relaxed) & crate::ported::zsh_h::ERRFLAG_ERROR;
let out = glob_expand_word_value(raw, skip_glob);
if before == 0
&& crate::ported::utils::errflag.load(Ordering::Relaxed) & crate::ported::zsh_h::ERRFLAG_ERROR != 0
{
GLOB_WORD_ERRFLAG.with(|c| c.set(true));
}
out
}
/// Glob one BUILTIN_EXPAND_TEXT mode-10 result inside BUILTIN_GLOBLIST.
/// EXPAND_TEXT left the glob-eligible words tokenized (their `haswilds`
/// test, c:Src/glob.c:1230, ran on the tokenized word) and every other word
/// untokenized, so the token test picks the same words out again; noglob was
/// already applied there. The glob call and the empty-result shapes are the
/// ones mode 0 uses.
fn glob_tokenized_word(raw: Value, noglob: bool) -> Value {
use std::sync::atomic::Ordering;
let words: Vec<String> = match &raw {
Value::Array(items) => items.iter().map(|v| v.to_str()).collect(),
other => vec![other.to_str()],
};
let mut parts: Vec<String> = Vec::with_capacity(words.len());
for w in words {
// c:Src/glob.c:1872 — NO_GLOB leaves the word literal; a word that came
// back tokenized only for its deferred filesub reaches here too.
// c:Src/glob.c:1230 — `unset(EXECOPT)` is part of the same early return.
if noglob
|| !crate::ported::zsh_h::isset(crate::ported::zsh_h::EXECOPT)
|| !crate::ported::pattern::haswilds(&w)
{
// c:Src/glob.c:1232 — zglob untokenizes a word it does not glob; a
// deferred `=cmd` / `~user` that filesub left alone (NOMATCH off)
// still carries its token.
parts.push(crate::ported::lex::untokenize(&w).to_string());
continue;
}
let ef = || crate::ported::utils::errflag.load(Ordering::Relaxed) & crate::ported::zsh_h::ERRFLAG_ERROR;
let before = ef();
let globbed = with_executor(|exec| exec.expand_glob(&w));
if before == 0 && ef() != 0 {
GLOB_WORD_ERRFLAG.with(|c| c.set(true)); // c:Src/exec.c:3760-3761
}
parts.extend(globbed);
}
if parts.len() == 1 {
Value::str(parts.into_iter().next().unwrap_or_default())
} else {
Value::array(parts.into_iter().map(Value::str).collect())
}
}
/// The value of a word whose prefork an `(e)` NULL stopped
/// (c:Src/subst.c:142-147): each node left in the list, rendered with its quote
/// tokens (c:Src/exec.c:2134 untokenize), one word per node.
fn stopped_nodes_value(nodes: Vec<String>) -> Value {
let mut words: Vec<Value> = nodes
.iter()
.map(|n| Value::str(crate::ported::lex::untokenize_ztokens(n)))
.collect();
match words.len() {
0 => Value::str(String::new()),
1 => words.remove(0),
_ => Value::array(words),
}
}
/// Run the filesub BUILTIN_EXPAND_TEXT mode 10 deferred on one word's
/// elements (c:Src/subst.c:178-182, `flags` 0 for a command argument).
fn filesub_deferred_word(raw: Value) -> Value {
let expand = |s: String| -> String {
if s.starts_with(crate::ported::zsh_h::Tilde) || s.starts_with(crate::ported::zsh_h::Equals) {
crate::ported::subst::filesub(&s, 0)
} else {
s
}
};
match raw {
Value::Array(items) => {
Value::array(items.iter().map(|v| Value::str(expand(v.to_str()))).collect())
}
other => Value::str(expand(other.to_str())),
}
}
/// Status for a command whose words raised errflag, stored into LASTVAL:
/// c:Src/exec.c:3760-3761 `lastval = 1` after a globlist error, else
/// c:3523-3524 `if (!lastval) lastval = 1` after a prefork error.
fn words_errflag_status() -> i32 {
use std::sync::atomic::Ordering;
let status = if GLOB_WORD_ERRFLAG.with(|c| c.replace(false)) {
1 // c:3761
} else {
match crate::ported::builtin::LASTVAL.load(Ordering::Relaxed) {
0 => 1, // c:3524
lastval => lastval,
}
};
crate::ported::builtin::LASTVAL.store(status, Ordering::Relaxed);
status
}
thread_local! {
/// c:Src/subst.c:142-147 / c:326-327 — paramsubst returned NULL (a failed
/// `(e)` re-lex), so prefork stops: the current word ends at the `$`
/// (c:1878) and the later words of the same list stay unexpanded. Read,
/// never cleared, by BUILTIN_PREFORK_CUT_CHECK; cleared at the sublist
/// prologue and when the command dispatches.
///
/// !!! WARNING: RUST-ONLY CARRIER !!! C's NULL return unwinds prefork's
/// loop in one step; zshrs expands a command's words across many VM ops.
static PREFORK_CUT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// Take `subst::PARAMSUBST_NULL` right after a direct paramsubst call and
/// turn it into the PREFORK_CUT carrier.
fn take_paramsubst_null() -> bool {
let null_return = crate::ported::subst::PARAMSUBST_NULL.with(|c| c.replace(false));
if null_return {
PREFORK_CUT.with(|c| c.set(true));
}
null_return
}
/// Consume the `-` precommand carrier (see BUILTIN_EXEC_DASH).
pub(crate) fn take_exec_dash() -> bool {
take_exec_carrier() & EXEC_CARRIER_DASH != 0
}
/// `EXEC_DASH` bit: the `-` precommand (c:Src/exec.c:772-776).
pub(crate) const EXEC_CARRIER_DASH: u8 = 1;
/// `EXEC_DASH` bit: exec in the already-forked child (c:Src/exec.c:4369).
pub(crate) const EXEC_CARRIER_FORKED: u8 = 2;
/// `EXEC_DASH` bit: the exec replaces the shell itself, so SHLVL drops first
/// (exec_shlvl_decrement).
pub(crate) const EXEC_CARRIER_SHLVL: u8 = 4;
/// c:Src/exec.c:3717 — `nsigtrapped || havefiles() || fdtable_flocks`: what
/// stops an exiting list's last command from exec'ing in place. nsigtrapped
/// counts real traps only (c:Src/signals.c:725 — an ignored signal is not
/// counted); zshrs keeps string traps in traps_table as well as sigtrapped.
fn fake_exec_blocked() -> bool {
use crate::ported::zsh_h::{ZSIG_FUNC, ZSIG_TRAPPED};
let trapped = crate::ported::signals::sigtrapped
.lock()
.map(|t| t.iter().any(|&st| st & (ZSIG_TRAPPED | ZSIG_FUNC) != 0))
.unwrap_or(true)
|| crate::ported::builtin::traps_table()
.lock()
.map(|t| t.values().any(|body| !body.is_empty()))
.unwrap_or(true);
let files = crate::ported::jobs::JOBTAB
.get()
.and_then(|tab| tab.lock().ok().map(|jt| crate::ported::jobs::havefiles(&jt)))
.unwrap_or(false);
trapped
|| files
|| crate::ported::utils::FDTABLE_FLOCKS.load(std::sync::atomic::Ordering::Relaxed) != 0
}
/// c:Src/exec.c:4332-4336 —
/// ```c
/// if (!subsh) {
/// /* for either implicit or explicit "exec", decrease $SHLVL
/// * as we're now done as a shell */
/// if (!forked)
/// setiparam("SHLVL", --shlvl);
/// ```
/// For an exec that replaces the shell itself (explicit `exec`, or the fake
/// exec of the `-c` string's last command): the command inherits one level
/// LESS than the shell counted for itself — it is taking the shell's place,
/// not nesting inside it.
///
/// C gets the environment update for free: SHLVL is PM_EXPORTED (from
/// `addenv` in createparamtable, c:Src/params.c:951), and `setiparam` on an
/// exported parameter runs setnumvalue → setstrvalue(NULL) → export_param →
/// addenv (c:2872, c:2841, c:2672). zshrs's `setnumvalue`
/// (src/ported/params.rs:5588-5595) has no `setstrvalue(v, NULL)` tail, so
/// the paramtab write alone would leave the environment holding the
/// pre-decrement number and the exec'd command would read one too high.
/// Publish it explicitly.
pub(crate) fn exec_shlvl_decrement() {
let cur = crate::ported::params::getsparam("SHLVL")
.and_then(|s| s.parse::<i64>().ok())
.unwrap_or(1);
crate::ported::params::setiparam("SHLVL", cur - 1); // c:4336
crate::ported::params::addenv("SHLVL", &(cur - 1).to_string()); // c:2672
}
/// Take the job text of the command being dispatched (see JOB_TEXT).
pub(crate) fn take_job_text() -> Option<String> {
JOB_TEXT.with(|t| t.borrow_mut().take()).map(|v| v.to_str())
}
/// Consume every external-spawn carrier bit (see EXEC_DASH).
pub(crate) fn take_exec_carrier() -> u8 {
EXEC_DASH.with(|c| c.replace(0))
}
pub(crate) fn dispatch_builtin(name: &str, args: Vec<String>) -> i32 {
// c:Src/exec.c:772-776 — BINF_DASH only changes an external's argv[0].
take_exec_dash();
take_job_text();
PREFORK_CUT.with(|c| c.set(false)); // the words are complete
// c:Src/exec.c getproc + Src/jobs.c deletefilelist — close any
// `>(cmd)` write ends owned by this command once it finishes
// (drops on every return path below).
let _psub_fds = PsubFdGuard;
// c:Src/exec.c — when any redirect in the current scope failed
// (e.g. noclobber blocked a `>` overwrite), zsh refuses to
// execute the command and exits with status 1. The Rust port
// still applied the command (writing to the /dev/null sink
// installed by host_apply_redirect's noclobber arm) so the
// success status overwrote the intended 1. Short-circuit here
// for builtins (the external-exec equivalent lives in
// ZshrsHost::exec).
let redir_failed = with_executor(|exec| {
let f = exec.redirect_failed;
exec.redirect_failed = false;
f
});
if redir_failed {
// c:Src/exec.c:4367-4386 — POSIX special-builtin escalation:
// a failed redirect on a PSPECIAL builtin (set, readonly,
// typeset, ...) under POSIX_BUILTINS is FATAL in a
// non-interactive shell (`exit(1)` at c:4383). The `command`
// prefix resets this (BINF_COMMAND, c:4369) — that path
// dispatches through bin_command, not here.
if crate::ported::zsh_h::isset(crate::ported::zsh_h::POSIXBUILTINS)
&& !crate::ported::zsh_h::isset(crate::ported::zsh_h::INTERACTIVE)
&& builtin_is_pspecial(name)
{
use std::sync::atomic::Ordering;
crate::ported::builtin::EXIT_VAL.store(1, Ordering::Relaxed);
crate::ported::builtin::EXIT_PENDING.store(1, Ordering::Relaxed);
}
// c:Src/exec.c:252-256 execerr — `redir_err = lastval = 1;`. The
// redirect arm already stored it, but the statement prologue between
// the Redirect op and this call (BUILTIN_XTRACE_ARGS) copies the VM's
// stale status back over LASTVAL, and the errflag abort that follows
// exits with LASTVAL: `print hi <&""` exited 0 where zsh exits 1.
// !!! DASH-FAMILY GATE !!! dash reports a redirection failure as 2.
let st = crate::extensions::dash_mode::fatal_error_status().unwrap_or(1);
crate::ported::builtin::LASTVAL.store(st, std::sync::atomic::Ordering::Relaxed);
return st;
}
// c:Src/glob.c:1876-1880 NOMATCH path — when expand_glob() failed
// on a no-match glob, zsh aborts the simple command after zerr()
// printed "no matches found". In C, this works because zerr()
// sets ERRFLAG_ERROR (Src/utils.c) and execcmd_exec()
// (Src/exec.c:3050+) checks errflag before invoking the builtin
// table. Rust's builtin dispatch doesn't sit on the same errflag
// gate, so we explicitly consume the per-command glob-fail cell
// and short-circuit with status 1. Mirrors the external-path
// guard at host_exec_external (line 5167). Without this:
// `echo /never/*` would print empty (silently rolled back to ""
// by the empty glob expansion). Parity bug #13.
//
// A zsh/files name that runs from PATH (the arm below) is an external:
// its glob failure ends the forked child, not the shell.
if files_builtin_runs_from_path(name) {
if let Some(status) = external_glob_failure_status() {
return status;
}
}
consume_tilde_globsubst_carrier();
let glob_failed = with_executor(|exec| {
let f = exec.current_command_glob_failed.get();
exec.current_command_glob_failed.set(false); // c:1879 cleanup
f
});
let postassign_glob_failed = TYPESET_POSTASSIGN_GLOB_FAILED.with(|c| c.replace(false));
if postassign_glob_failed && !glob_failed {
// c:Src/exec.c:4167-4285 — a typeset-family command's postassigns
// (every word from its first `NAME=…` on, c:Src/parse.c:1986-1989 and
// c:2008-2050) are globbed inside the builtin branch, after the
// command words: `globlist(…); if (errflag) { …; break; }`. Then
// c:4287 `if (!errflag) { … lastval = ret; }` skips the builtin
// WITHOUT storing a status, so `lastval` keeps the previous command's
// value (`print hi; local -a a=(zzq*)` exits 0, after `false` 1)
// while ERRFLAG_ERROR still ends the script. A command word globbed
// before them fails at c:3755-3763 instead, with `lastval = 1`.
return crate::ported::builtin::LASTVAL.load(std::sync::atomic::Ordering::Relaxed);
}
if glob_failed {
// c:Src/glob.c:1876-1880 + Src/exec.c — NOMATCH zerr sets
// ERRFLAG_ERROR (via utils.c:184). For a BUILTIN command the
// expansion runs IN the shell process, so errflag stays set
// and the rest of the input aborts (zsh -fc 'echo /nope_*;
// echo after' prints nothing after the error — verified
// against zsh 5.9). The continue-after-nomatch behaviour
// belongs ONLY to externals: C forks BEFORE expansion there,
// so the child's zerr can't touch the parent's errflag (zsh
// -fc 'ls /nope_*; echo after' prints `after`) — that path's
// clear lives in fn exec / execute_external. Leave
// ERRFLAG_ERROR set here; BUILTIN_ERREXIT_CHECK trigger 4
// aborts the remaining script at the next command boundary.
return 1; // c:1880 — command aborted, status 1
}
// c:Src/subst.c:505-507 — CSH_NULL_GLOB sibling of the NOMATCH
// gate above: all of this command's globs failed silently (words
// dropped, badcshglob accumulated 1s and no 2s) → `no match`,
// skip the builtin, status 1. Like the NOMATCH path, ERRFLAG
// from zerr stays set for builtins so the rest of the script
// aborts (zsh -fc 'setopt cshnullglob; print *nope* x; print
// after' prints only the error — verified zsh 5.9.1).
if consume_badcshglob() {
// c:Src/exec.c:3380 — `lastval = 1;` so the shell's final
// exit status reflects the aborted command.
with_executor(|exec| exec.set_last_status(1));
return 1;
}
// c:Src/exec.c:4162-4295 — assignment-builtin (BINF_ASSIGN family:
// typeset / declare / local / export / readonly / integer / float /
// private) whose `name=value` postassign arg raised errflag while
// its RHS was preforked (PREFORK_ASSIGN, c:4239-4245) — the classic
// case is a math error in `typeset -F fv=$((1/0))`. The postassign
// loop `break`s on errflag (c:4243) and then `if (!errflag)
// execbuiltin(...)` (c:4287) SKIPS the builtin entirely, so `lastval`
// is left UNCHANGED from before the command (0 fresh, 1 after
// `false`). This differs from a PLAIN assignment `x=$((1/0))`, which
// goes through execsimple c:1375 `lv = errflag ? errflag : cmdoutval`
// → 1, and from a NON-assign builtin `print $((1/0))`, whose main
// args-prefork errflag lands on c:3760 `lastval = 1`. Only the
// assignment-BUILTIN postassign path preserves the prior status.
// Mirror it here: the fusevm reg_passthru dispatch still calls us
// with errflag set (unlike C's pre-invoke gate), so consume that
// state and return the prior LASTVAL instead of running the builtin.
{
use std::sync::atomic::Ordering;
let live = crate::ported::utils::errflag.load(Ordering::Relaxed);
let ef = live & crate::ported::zsh_h::ERRFLAG_ERROR;
let hard = live & crate::ported::zsh_h::ERRFLAG_HARD;
// Only the SOFT recoverable error (math failure like `$((1/0))`,
// ERRFLAG_ERROR without ERRFLAG_HARD) preserves the prior status
// per c:4287. A HARD error (`${var?msg}`, which c:Src/subst.c
// OR's ERRFLAG_HARD onto errflag) is a script-abort that yields
// status 1 regardless of the prior status — leave that to the
// normal dispatch/abort path below (which returns 1 and keeps
// ERRFLAG_HARD set for the downstream errexit gate).
if ef != 0 && hard == 0 && builtin_is_assign_family(name) {
// c:4287 — execbuiltin skipped; lastval unchanged.
return crate::ported::builtin::LASTVAL.load(Ordering::Relaxed);
}
// c:Src/exec.c:3523-3525 — an expansion error in the command words
// (prefork, c:3357-3359) ends the command before anything runs:
// if (errflag) { if (!lastval) lastval = 1; … return; }
// so the previous command's non-zero status survives
// (`nosuchcmd; print ${.bad}` exits 127). A glob failure took the
// c:3760 `lastval = 1` return above; a HARD error keeps status 1.
if ef != 0 && hard == 0 {
return words_errflag_status();
}
}
if let Some(status) = user_fn_override_unadvised(name, &args) {
// c:Src/jobs.c:1748 waitonejob — canonical single-command
// pipestats update via the no-procs else-branch.
crate::ported::builtin::LASTVAL.store(status, std::sync::atomic::Ordering::Relaxed);
crate::ported::jobs::waitonejob(-1);
return status;
}
// c:Src/builtin.c:587 + Src/exec.c:3056 — a builtin disabled via
// `disable <name>` has its `DISABLED` flag set in `builtintab`;
// `builtintab->getnode` (the DISABLED-filtering accessor) returns
// NULL for it at lookup time, so execcmd_exec falls through to
// PATH lookup and runs the external. The Rust port stores the
// disabled set in `BUILTINS_DISABLED`; the previous dispatcher
// only checked the immutable `createbuiltintable` HashMap which
// never reflects disablement — so `disable echo; echo hi` kept
// running the bin_echo builtin. Bug #106 in docs/BUGS.md.
//
// dispatch_builtin (the high-level wrapper used by the BUILTIN_*
// opcode handlers and reg_passthru! callsites) is the correct
// gate: `dispatch_builtin_raw` is the low-level entry point
// used by `bin_builtin` itself which MUST bypass the disabled
// set (man zshbuiltins: `builtin name` runs the builtin
// regardless of disable state). Place the check here so the
// bypass path stays clean.
// c:Src/exec.c:3088-3096 — a WC_TYPESET command finds the builtin with
// `getnode2`, which ignores DISABLED: `disable typeset` leaves the
// reserved-word form running the builtin.
let typeset_reswd = TYPESET_RESWD_DISPATCH.with(|c| c.replace(false));
let disabled = !typeset_reswd
&& crate::ported::builtin::BUILTINS_DISABLED
.lock()
.map(|s| s.contains(name))
.unwrap_or(false);
if disabled {
let status = with_executor(|exec| exec.execute_external(name, &args, &[])).unwrap_or(127);
crate::ported::builtin::LASTVAL.store(status, std::sync::atomic::Ordering::Relaxed);
crate::ported::jobs::waitonejob(-1);
return status;
}
// c:Src/Modules/files.c:806-814 — `mkdir`, `rm`, `mv`, `ln`, `chmod`,
// `chown`, `chgrp`, `sync`, `rmdir` are bound by the `zsh/files`
// module's boot_/setup_ chain. Without explicit `zmodload zsh/files`,
// these bare names fall through to PATH (`/bin/rm`, `/usr/bin/chmod`,
// etc.) in zsh; `type rm` reports `rm is /bin/rm`. The `zf_*`
// aliases (`zf_rm`, `zf_chmod`, …) are bound by the same module
// and gated the same way. Bug #28 in docs/BUGS.md.
if files_builtin_runs_from_path(name) {
// PATH lookup uses the literal name. In --zsh parity mode
// `zf_rm` must 127 like zsh -fc (no /bin/zf_rm); default
// zshrs mode keeps the convenience zf_-strip so the alias
// still reaches the system binary.
let path_name = if crate::IS_ZSH_MODE.load(std::sync::atomic::Ordering::Relaxed) {
name
} else {
name.strip_prefix("zf_").unwrap_or(name)
};
let status =
with_executor(|exec| exec.execute_external(path_name, &args, &[])).unwrap_or(127);
crate::ported::builtin::LASTVAL.store(status, std::sync::atomic::Ordering::Relaxed);
crate::ported::jobs::waitonejob(-1);
return status;
}
// c:Src/exec.c:3997 `int q = queue_signal_level();`
// c:Src/exec.c:4231 `dont_queue_signals();`
// c:Src/exec.c:4243 `restore_queue_signals(q);`
//
// C runs EVERY builtin with signal queueing switched OFF. Two
// consequences the zshrs port was missing:
//
// 1. `dont_queue_signals()` DRAINS the pending queue (it calls
// run_queued_signals()), so a signal that arrived while an
// enclosing scope held queue_signals() — doshfunc holds one
// for the whole call, c:Src/exec.c:5835 — fires its trap at
// the NEXT command boundary rather than at function exit.
// 2. While the builtin runs, queueing stays off, so a signal the
// builtin sends to itself (`kill -USR1 $$`) dispatches the
// trap synchronously inside the builtin — which is why zsh
// prints pre/trap/post for
// `f() { print pre; kill -USR1 $$; print post }`.
//
// Without this bracket every trap raised inside a function was
// deferred to the enclosing unqueue_signals() (i.e. script end).
// c:Src/exec.c:3546 — `setunderscore((args && nonempty(args)) ?
// ((char *) getdata(lastnode(args))) : "");`. execcmd_exec sets `$_`
// to the last word of the command it is ABOUT to run — after the
// words were expanded, before the builtin/external executes — so a
// builtin that READS `_` at run time (`typeset -p _`, `${(P)…}`,
// `$parameters[_]`) sees its own last argument, not the previous
// command's. zshrs only did this for a handful of builtins (echo,
// print, true, false, `:`) and for the external/function paths;
// every reg_passthru! builtin was left reading the stale value.
// C's `args` list carries argv[0], so a bare `cat` sets `_=cat` —
// hence the fallback to `name` when there are no arguments.
// c:Src/parse.c:2003-2008 — under the TYPESET reserved word the words
// from the first `NAME=…` on are postassigns, not args: `local b c=2`
// sets `_=b`, `typeset -g a=1` sets `_=-g`.
let n_post = TYPESET_POSTASSIGN_COUNT.with(|c| c.take()).filter(|_| typeset_reswd).unwrap_or(0);
let n_args = args.len().saturating_sub(n_post);
let underscore = args[..n_args].last().cloned().unwrap_or_else(|| name.to_string()); // c:3546
crate::ported::params::set_zunderscore(std::slice::from_ref(&underscore)); // c:3546
let q = crate::ported::signals_h::queue_signal_level(); // c:3997
crate::ported::signals_h::dont_queue_signals(); // c:4231
// c:Src/exec.c:4300 `save[1] == -2` — this command's own redirections
// did not touch fd 1.
let stdout_unredirected = with_executor(|exec| {
!(own_redirect_scope(exec)
&& exec
.redirect_scope_stack
.last()
.is_some_and(|top| top.iter().any(|&(fd, _)| fd == 1)))
});
let ret = dispatch_builtin_raw(name, args);
// c:Src/exec.c:4298-4305
// fflush(stdout);
// if (save[1] == -2) {
// if (ferror(stdout)) {
// zwarn("write error: %e", errno);
// clearerr(stdout);
// }
// } else
// clearerr(stdout);
let ferror = crate::stdout_ferror::take_stdout_ferror();
if ferror != 0 && stdout_unredirected {
crate::ported::utils::zwarn(&format!(
"write error: {}",
crate::ported::utils::zsh_errno_msg(ferror)
));
}
// c:Src/exec.c:4289-4293 — "In case of interruption assume builtin
// status is less useful than what interrupt set":
// if (!(errflag & ERRFLAG_INT)) lastval = ret;
// The SIGINT handler wrote `lastval = 128 + SIGINT` (c:Src/signals.c:463)
// and a forced INT-trap return wrote its own value (c:Src/signals.c:1202),
// both into LASTVAL. Hand that back, so the VM's trailing SetStatus
// publishes it instead of the interrupted builtin's 0:
// zsh -f -i -c 'kill -INT $$' → exit 130 (zshrs exited 0)
let status = if (crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed)
& crate::ported::zsh_h::ERRFLAG_INT)
!= 0
{
crate::ported::builtin::LASTVAL.load(std::sync::atomic::Ordering::Relaxed)
} else {
ret
};
crate::ported::signals_h::restore_queue_signals(q); // c:4243
// c:Src/jobs.c:1748 waitonejob — canonical single-command pipestats update.
crate::ported::builtin::LASTVAL.store(status, std::sync::atomic::Ordering::Relaxed);
crate::ported::jobs::waitonejob(-1);
// c:Src/exec.c:4367-4386 — done: tail. A PSPECIAL builtin that
// raised errflag under POSIX_BUILTINS exits the non-interactive
// shell with status 1 ("hard error in POSIX" — e.g. bin_dot's
// zerrnam at Src/builtin.c:6133). Arm the deferred-exit pair so
// the next ERREXIT_CHECK unwinds; EXIT_VAL=1 matches C's
// hardcoded exit(1), NOT the builtin's own status (dot returns
// 127 but POSIX exits 1).
if crate::ported::zsh_h::isset(crate::ported::zsh_h::POSIXBUILTINS)
&& !crate::ported::zsh_h::isset(crate::ported::zsh_h::INTERACTIVE)
&& builtin_is_pspecial(name)
&& (crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed)
& crate::ported::zsh_h::ERRFLAG_ERROR)
!= 0
{
use std::sync::atomic::Ordering;
crate::ported::builtin::EXIT_VAL.store(1, Ordering::Relaxed);
crate::ported::builtin::EXIT_PENDING.store(1, Ordering::Relaxed);
}
status
}
/// c:Src/zsh.h:1467 BINF_PSPECIAL — true when `name` is a POSIX
/// special builtin per the canonical builtin table flags
/// (Src/builtin.c:48-129: `.`, `:`, break, continue, declare, eval,
/// exit, export, float, integer, local, readonly, return, set,
/// shift, source, times, trap, typeset, unset).
fn builtin_is_pspecial(name: &str) -> bool {
crate::ported::builtin::createbuiltintable()
.get(name)
.map(|b| (b.node.flags as u32 & crate::ported::zsh_h::BINF_PSPECIAL) != 0)
.unwrap_or(false)
}
/// c:Src/zsh.h:1486 BINF_ASSIGN — the assignment-builtin family
/// (typeset / declare / local / export / readonly / integer / float /
/// private). Their `name=value` args are handled as postassigns
/// (c:Src/exec.c:4162-4295), whose errflag-abort skips execbuiltin and
/// preserves the prior `lastval`. Read the flag straight from the
/// builtin table (same pattern as `builtin_is_pspecial`).
fn builtin_is_assign_family(name: &str) -> bool {
crate::ported::builtin::createbuiltintable()
.get(name)
.map(|b| (b.node.flags as u32 & crate::ported::zsh_h::BINF_ASSIGN) != 0)
.unwrap_or(false)
}
// The former `install_exec_hooks()` fn-pointer registry is gone. Code
// under `src/ported/` now reaches `ShellExecutor` operations
// (array/assoc storage, script eval, function dispatch, command
// substitution) through the `crate::ported::exec::*` accessor wrappers,
// which resolve the live executor via `try_with_executor`
// (`CURRENT_EXECUTOR`). The bridge lives in exec.rs — the sanctioned
// fusevm-access exception — per `feedback_no_exec_script_from_ported` /
// `feedback_no_shellexecutor_in_ported`.
/// The outcome of c:`Src/subst.c:3914-3927`, the JOIN half of the
/// join-then-split block: either the vector was collapsed onto a scalar
/// (`isarr = 0`) or it survived as an array (`isarr` still non-zero).
enum JoinC3914 {
/// c:3917 / c:3925 — `val = sepjoin(aval, …, 1); isarr = 0;`
Joined(String),
/// Neither arm fired; `aval` reaches c:3931 with `isarr` non-zero, and
/// that gate (`force_split && !isarr`) then keeps the split off too.
Elements(Vec<String>),
}
/// Port of the JOIN half of c:`Src/subst.c:3914-3927`, for an ARRAY-shaped
/// UNQUOTED expansion whose `spbreak` is non-zero — i.e. c:3912's gate is open
/// and c:3913's `force_split` is 1 (the `ssub` callers join at c:4226 instead
/// and never reach here).
///
/// ```c
/// if (isarr || quoted_array_with_offset) {
/// if (nojoin == 0 || sep) {
/// val = sepjoin(aval, sep, 1);
/// isarr = 0;
/// } else if (force_split &&
/// (spsep || nojoin == 2 || (!ifs && isarr < 0))) {
/// val = sepjoin(aval, (nojoin == 1 ? NULL : spsep), 1);
/// isarr = 0;
/// }
/// }
/// ```
///
/// `sep`/`spsep` are the `(j:…:)` / `(s:…:)` separators, which never reach the
/// compiler fast paths (a flagged expansion goes to `paramsubst`), so the two
/// live discriminators are `nojoin` and whether IFS is UNSET or merely EMPTY:
///
/// * c:1819 / c:2569 — `nojoin = !(ifs && *ifs)`, i.e. 1 when IFS is unset OR
/// set to the empty string, 0 for any non-empty IFS.
/// * c:3030-3032 — `if (isarr) { if (nojoin) isarr = -1; }`. This is why a
/// `[*]` splice and a `[@]` splice behave IDENTICALLY here: whenever `nojoin`
/// is set they are BOTH `isarr < 0`, and when it is clear c:3916 joins them
/// both. The `[@]`-vs-`[*]` distinction only survives into the QUOTED arm at
/// c:3033, which this block is never reached with.
///
/// So: a non-empty IFS joins on `IFS[0]`; an UNSET IFS joins on `sepjoin`'s
/// default `" "` (c:`Src/utils.c:3936-3945`); an EMPTY IFS joins on nothing at
/// all and the element vector survives.
fn join_c3914(elems: Vec<String>, ifs: Option<&str>) -> JoinC3914 {
// c:1819 — `!(ifs && *ifs)`.
let nojoin = !matches!(ifs, Some(s) if !s.is_empty());
// c:Src/utils.c:3936-3945 `sepjoin(s, NULL, heap)` — the separator is the
// first metachar of `ifs`, except that a NULL `ifs` (unset) or one whose
// first byte is already a space takes the literal `" "` fast path.
let sep = match ifs {
Some(s) if !s.starts_with(' ') => s.chars().next().map(String::from).unwrap_or_default(),
_ => " ".to_string(),
};
// c:3916 `nojoin == 0`, then c:3919-3925's `(!ifs && isarr < 0)`.
if !nojoin || ifs.is_none() {
JoinC3914::Joined(elems.join(&sep))
} else {
JoinC3914::Elements(elems)
}
}
/// Port of c:`Src/subst.c:3932` `aval = sepsplit(val, spsep, 0, 1)` with
/// `spsep == NULL` (so c:`Src/utils.c:3971-3972` falls through to
/// `spacesplit(s, allownull=0, …)`), followed by c:`Src/subst.c:184-187`'s
/// empty-word removal.
///
/// `spacesplit` distinguishes the two kinds of empty field, and that is the
/// whole reason this cannot be a plain `split().filter(non-empty)`:
///
/// * An empty field delimited by IFS-NON-whitespace comes back as `nulstring`
/// (c:`Src/subst.c:36` `char nulstring[] = {Nularg, '\0'};`, emitted at
/// c:`Src/utils.c:3732` and c:3752). That word is one byte long, so prefork's
/// `uremnode` at c:186 keeps it and `remnulargs` at c:169 turns it into `""`.
/// `IFS=:; a=(x '' y)` therefore splits `x::y` back to THREE words.
/// * A field left by a skipped run of IFS-WHITESPACE is a real `""`
/// (c:`Src/utils.c:3734` / c:3757) and c:186 DOES delete it — unless the
/// caller is attaching it to neighbouring text, which is what `keep_empties`
/// (the `BUILTIN_FORCE_SPLIT` argc contract) says.
/// c:Src/glob.c:3663 `remnulargs` for a finished word: remove the c:36
/// `nulstring` markers a deferring word kept through its segments (see
/// BUILTIN_FORCE_SPLIT and `paramsubst_to_value_pf`), once the end-of-word drop
/// has decided which empty nodes survive. A marker-free value is returned as is.
/// argc bits the compiler adds to the segment path's end-of-word drop
/// (BUILTIN_ARRAY_DROP_EMPTY / BUILTIN_WORD_ELIDE_EMPTY) when the word's first
/// or last segment is a quoted empty literal (`""`, `''`). c:Src/subst.c:36 —
/// the lexer leaves its Dnull/Snull in the word, so the node that literal is
/// glued to is non-empty at c:183 and survives: the first node for a leading
/// literal, the last for a trailing one (c:4366-4437).
pub const WORD_DROP_KEEPS_FIRST: u8 = 4;
/// See [`WORD_DROP_KEEPS_FIRST`].
pub const WORD_DROP_KEEPS_LAST: u8 = 8;
/// Whether node `i` (of `0..=last`) is anchored by a quoted empty literal.
fn word_drop_keeps(argc: u8, i: usize, last: usize) -> bool {
(i == 0 && argc & WORD_DROP_KEEPS_FIRST != 0) || (i == last && argc & WORD_DROP_KEEPS_LAST != 0)
}
fn strip_nulstring_markers(v: Value) -> Value {
let nul = crate::ported::zsh_h::Nularg;
match v {
Value::Array(items) if items.iter().any(|x| x.as_str_cow().contains(nul)) => Value::array(
items
.iter()
.map(|x| Value::str(x.as_str_cow().replace(nul, "")))
.collect(),
),
Value::Str(s) if s.contains(nul) => Value::str(s.replace(nul, "")),
other => other,
}
}
fn sepsplit_c3932(s: &str, keep_empties: bool) -> Vec<String> {
let raw = crate::ported::utils::sepsplit(s, None, false);
let nulstring = crate::ported::zsh_h::Nularg.to_string();
let mut out: Vec<String> = Vec::with_capacity(raw.len());
for w in raw {
if w == nulstring {
out.push(String::new());
} else if w.is_empty() {
if keep_empties {
out.push(String::new());
}
} else {
out.push(w);
}
}
out
}
/// c:`Src/subst.c:3932-3938` for a bare read: `sepsplit` plus the 0/1/N shape.
/// Inside a word that opened with `BUILTIN_WORD_DEFER_EMPTIES`, c:184-187 runs on
/// the FINISHED node (after c:4366-4437 glue the affixes on), so the truly empty
/// edge fields go out raw for the end-of-word drop to judge:
/// `setopt shwordsplit; a=(a b ''); print -l x${a}y` is `xa` `b` `y`.
fn split_words_c3932(val: &str) -> Value {
if crate::ported::subst::PARAMSUBST_AFFIXES_DEFERRED.with(|c| c.get()) > 0 {
return splice_words_value(crate::ported::utils::sepsplit(val, None, false));
}
splice_words_value(sepsplit_c3932(val, false))
}
/// c:`Src/subst.c:3933-3938` — how a split (or untouched) word vector reaches
/// the caller: nothing at all, a SCALAR for a single field, an array otherwise.
///
/// ```c
/// if (!aval || !aval[0]) val = dupstring("");
/// else if (!aval[1]) val = aval[0];
/// else isarr = nojoin ? 1 : 2;
/// ```
fn splice_words_value(words: Vec<String>) -> Value {
match words.len() {
0 => Value::array(Vec::new()),
1 => Value::str(words.into_iter().next().unwrap()),
_ => Value::array(words.into_iter().map(Value::str).collect()),
}
}
/// c:`Src/subst.c:184-187` — prefork's `uremnode` deletes an UNQUOTED word that
/// came out empty. Applied to an element vector that c:3912's gate left alone.
fn prefork_c184_drop_empty(elems: Vec<String>) -> Vec<String> {
elems.into_iter().filter(|e| !e.is_empty()).collect()
}
/// Read a parameter as `paramsubst` does at c:`Src/subst.c:2916-2917`, which is
/// where both halves of the value come from:
///
/// ```c
/// if ((isarr = (v->scanflags & SCANPM_ISVAR_AT) ? -1
/// : v->scanflags ? 1 : 0)) {
/// … aval = getarrvalue(v);
/// } else {
/// … val = getstrvalue(v);
/// ```
///
/// The `bool` is that `isarr != 0` test — whether `fetchvalue` handed back an
/// ARRAY (or a hash, whose values `getarrvalue` enumerates) rather than a
/// scalar. Every caller needs it, because c:3914's join arm and c:3931's split
/// arm are mutually exclusive on exactly that bit.
///
/// A scalar comes back as a one-element vector so the two shapes share a type;
/// the `bool` is what tells them apart (a genuine one-element ARRAY is not the
/// same thing, though c:3899-3906 goes on to treat it as a scalar for the
/// join/split block — that rule belongs to the caller, not here).
fn param_value_elems_c2916(exec: &mut ShellExecutor, name: &str) -> (Vec<String>, bool) {
if let Some(v) = crate::dash_mode::bash_special_array(name) {
// bash `"${PIPESTATUS[*]}"` / `"${FUNCNAME[*]}"` join.
return (v, true);
}
if name == "@" || name == "*" || name == "argv" {
// c:Src/params.c:392,393,430 — the three IPDEF9 rows over `pparams`.
return (exec.pparams(), true);
}
if let Some(assoc_map) = exec.assoc(name) {
// c:Src/params.c — assoc-splat values for `"${h[@]}"` / `"${h[*]}"`.
// Bug #109 in docs/BUGS.md.
return (assoc_map.values().cloned().collect::<Vec<_>>(), true);
}
if let Some(arr) = exec.array(name) {
// bash sparse arrays: `"${a[*]}"` joins only LIVE elements, dropping
// hole slots. No-op in --zsh (no holes tracked).
return (crate::bash_arrays::compact(name, arr), true);
}
if let Some(arr) = crate::ported::subst::arrays_get(name) {
// c:Src/Modules/parameter.c:2239-2291 partab[] — the PM_ARRAY magic
// specials (reswords/patchars/dis_*/…) are getfn-backed, so
// `getaparam`'s `pm->u.arr` read (behind `exec.array`) comes back NULL
// and the join fell through to the scalar fallback, which is empty.
// Same omission the `[@]` splat had.
return (arr, true);
}
if let Some(map) = crate::ported::subst::assoc_get(name) {
// c:Src/Modules/parameter.c:2235-2298 partab[] — the PM_HASHED magic
// assocs (aliases/functions/options/…) live behind a scanfn+getfn pair,
// not in the executor's assoc storage, so `exec.assoc` above misses
// them and `${aliases[*]}` joined an empty scalar where zsh joins the
// alias VALUES.
return (map.values().cloned().collect::<Vec<_>>(), true);
}
(vec![exec.get_variable(name)], false) // c:2927 getstrvalue
}
/// Register all zsh builtins with the VM.
/// c:Src/exec.c:4473-4509 (`save_params`) — the per-name body of the loop,
/// run for a prefix assignment while its inline-env frame is still recording.
/// Shared by the scalar (BUILTIN_SET_VAR) and array (BUILTIN_SET_ARRAY)
/// assignment builtins: C walks every WC_ASSIGN in the chain regardless of
/// its type (c:4510-4511 advances over WC_ASSIGN_SCALAR and array words alike).
fn save_inline_prefix_param(exec: &mut ShellExecutor, name: &str) {
// c:Src/exec.c:4475-4478 (54941) — `ss = itype_end(s, INAMESPC, 0);
// slen = *ss == '[' || *ss == Inbrack ? ss - s : strlen(s);`: a
// subscripted assignment (`H[2,4]=oo f`) saves its base parameter.
let name = match name.find('[') {
Some(i) => name[..i].to_string(),
None => name.to_string(),
};
let prev_env = env::var(&name).ok();
// c:Src/exec.c:4476 — `pm = paramtab->getnode(paramtab, s)`.
// c:4491-4493 — an existing name is SNAPSHOTTED, not removed:
// `tpm = zshcalloc(...); tpm->node.nam = ztrdup(pm->node.nam);
// copyparam(tpm, pm, 0);` — the WHOLE Param, type flags and
// value union together. Saving only `getsparam(name)` (a
// scalar string) is what destroyed every non-scalar: an array
// came back as the IFS-joined string retyped to PM_SCALAR, and
// an association came back as None — the scalar getter has
// nothing to read for a PM_HASHED param — so the restore took
// the "did not exist" arm and unset it outright.
let pm_snapshot: Option<crate::ported::zsh_h::param> = {
let live = crate::ported::params::paramtab()
.read()
.ok()
.and_then(|t| t.get(&name).map(|p| (**p).clone()));
// c:4480 / c:4494 — three arms, and the third saves
// nothing: a PM_SPECIAL that is also PM_READONLY leaves
// `tpm` NULL and only joins the remove list (c:4504).
let fakecopy = live.as_ref().map(|p| {
(p.node.flags & crate::ported::zsh_h::PM_SPECIAL as i32) != 0
});
let live = match (live, fakecopy) {
(Some(p), Some(true))
if (p.node.flags & crate::ported::zsh_h::PM_READONLY as i32) != 0 =>
{
None
}
(other, _) => other,
};
live.map(|mut tpm| {
// c:Src/params.c:1273-1291 — copyparam reads the value
// back through the type's GSU getfn rather than trusting
// the union slot it already holds, because a special's or
// a tied scalar's value does not live there.
match crate::ported::zsh_h::PM_TYPE(tpm.node.flags as u32) {
crate::ported::zsh_h::PM_INTEGER => {
// c:1279 — `tpm->u.val = pm->gsu.i->getfn(pm);`
// A special's getfn (`uidgetfn`, `gidgetfn`, …) does not
// read `u.val`, which `getiparam` returns for any
// PM_INTEGER node: `UID=$UID cmd` saved 0 and the restore
// ran `setuid(0)`. zshrs reaches those getfns by name.
tpm.u_val = crate::ported::params::lookup_special_var(&name)
.and_then(|v| v.parse::<i64>().ok())
.unwrap_or_else(|| crate::ported::params::getiparam(&name));
}
crate::ported::zsh_h::PM_EFLOAT
| crate::ported::zsh_h::PM_FFLOAT => {
// c:1283 — `tpm->u.dval = pm->gsu.f->getfn(pm);`
tpm.u_dval = crate::ported::params::getnparam(&name).1;
}
crate::ported::zsh_h::PM_ARRAY => {
// c:1286 — `tpm->u.arr = zarrdup(pm->gsu.a->getfn(pm));`
tpm.u_arr = crate::ported::params::getaparam(&name);
}
crate::ported::zsh_h::PM_HASHED => {
// c:1289 — `tpm->u.hash = copyparamtable(...)`.
// See `hashed_snapshot` below for where the pairs go.
}
_ => {
// c:1276 — `tpm->u.str = ztrdup(pm->gsu.s->getfn(pm));`
tpm.u_str = crate::ported::params::getsparam(&name);
}
}
// c:1269-1272 / c:1301-1302 — the `!fakecopy` postlude:
// the copy is going back into the parameter table as a
// REAL parameter, so it stops being special and gets the
// standard get/set vtable for its type. That is what
// makes a user's `typeset -T PAIR pair` scalar come back
// as a plain scalar holding the joined string instead of
// re-reading the partner array the prefix assignment
// just overwrote.
if fakecopy == Some(false) {
tpm.node.flags &= !(crate::ported::zsh_h::PM_SPECIAL as i32); // c:1271
crate::ported::params::assigngetset(&mut tpm); // c:1302
}
tpm
})
};
// !!! RUST-ONLY FIELD — THE SECOND HALF OF c:1289 !!!
// C keeps an association's pairs in `pm->u.hash`, so
// `copyparam`'s `copyparamtable` copy travels inside the Param
// above and `restore_params`' `tpm->gsu.h->setfn(tpm, pm->u.hash)`
// (c:4561) puts them back. zshrs keeps them in the name-keyed
// `paramtab_hashed_storage` instead, OUTSIDE the Param —
// `arrhashsetfn`, the only writer of whole associations, never
// populates `u_hash` at all (the same structural mismatch
// `stdunsetfn` documents at params.rs:11044). So the pairs have
// to be carried alongside the node and put back alongside it.
let hashed_snapshot = if pm_snapshot.as_ref().is_some_and(|p| {
crate::ported::zsh_h::PM_TYPE(p.node.flags as u32)
== crate::ported::zsh_h::PM_HASHED
}) {
crate::ported::params::paramtab_hashed_storage()
.lock()
.ok()
.and_then(|m| m.get(&name).cloned())
} else {
None
};
exec.inline_env_stack
.last_mut()
.unwrap()
.saved
.push(crate::vm_helper::SavedInlineParam {
name: name.clone(),
pm: pm_snapshot,
hashed: hashed_snapshot,
prev_env,
});
}
pub(crate) fn register_builtins(vm: &mut fusevm::VM) {
// src/ported/ reaches the live executor (param store, function
// dispatch, nested script/cmdsubst exec) through the
// `crate::ported::exec::*` accessor wrappers, which read
// `CURRENT_EXECUTOR` via `try_with_executor`. No install step is
// needed: the executor is in scope for the duration of any VM run
// (set by `ExecutorContext::enter`), so the wrappers resolve it
// directly. (Replaces the former `exec_hooks` OnceLock fn-ptr
// registry, now deleted.)
// Engage fusevm's tiered JIT (block + tracing) so hot, fully-eligible
// numeric chunks run in native code and — with the `jit-disk-cache`
// feature (on by default) — persist that native code to
// `~/.cache/fusevm-jit`, letting repeated zsh invocations skip Cranelift
// codegen. fusevm gates the JIT on per-chunk eligibility and warms up by
// an invocation threshold, falling back to the interpreter for any chunk
// it cannot compile (e.g. host-builtin/`Extended` command dispatch), so
// enabling it here never changes observable behaviour — it only caches
// the numeric hot path. Idempotent: re-enabling on each VM is a no-op.
vm.enable_tracing_jit();
// Macro for builtins that user functions are allowed to shadow.
// zsh dispatch order is alias → function → builtin; without the
// try_user_fn_override probe a `cat() { ... }; cat` would silently
// run the C builtin and ignore the user function.
macro_rules! reg_overridable {
($vm:expr, $id:expr, $name:literal, $method:ident) => {
$vm.register_builtin($id, |vm, argc| {
let args = pop_args(vm, argc);
// c:Src/exec.c getproc + Src/jobs.c deletefilelist —
// close `>(cmd)` write ends owned by this command
// once it finishes (shadows bypass dispatch_builtin
// and ZshrsHost::exec, so they need their own guard:
// `tee >(wc -c) </dev/null` left wc blocked).
let _psub_fds = PsubFdGuard;
if let Some(s) = try_user_fn_override($name, &args) {
return Value::Status(s);
}
// c:Src/exec.c — redirect failure in the current
// scope means the command must NOT run. coreutils
// shadows (cat / head / tail / etc.) take a separate
// dispatch path from dispatch_builtin, so they need
// their own gate. Without this `cat <&3` after a
// closed-fd diagnostic still ran the shadow and
// overwrote $? from the forced 1.
let redir_failed = with_executor(|exec| {
let f = exec.redirect_failed;
exec.redirect_failed = false;
f
});
// c:Src/exec.c:4343-4350 — the prefix assignments of an
// external run in the forked child (`addvars(…); if
// (errflag) _exit(1);`): `UID=0 date` is skipped with
// status 1 and the shell's errflag stays clean.
let prefix_failed = PREFIX_ASSIGN_FAILED.with(|c| c.replace(false));
if redir_failed || prefix_failed {
// c:Src/exec.c:3719 forks the external command these
// shadows stand in for BEFORE the redirection loop at
// c:3785, so a redirection `zerr` (`cat <&""` → "file
// number expected") lands in the child: the shell only
// sees status 1 (c:252-256 execerr in the child) and runs
// the next command. Same rule as call_function's arm.
let bits = if prefix_failed {
crate::ported::zsh_h::ERRFLAG_ERROR | crate::ported::zsh_h::ERRFLAG_HARD
} else {
crate::ported::zsh_h::ERRFLAG_ERROR
};
crate::ported::utils::errflag.fetch_and(
!bits,
std::sync::atomic::Ordering::Relaxed,
);
// A NOMATCH / NULL_GLOB failure in the redirect target's
// filename generation belongs to the same child.
let _ = external_glob_failure_status();
// dash: a failed redirection is status 2 (dash_mode::fatal_error_status).
let st = if prefix_failed {
1
} else {
crate::extensions::dash_mode::fatal_error_status().unwrap_or(1)
};
crate::ported::builtin::LASTVAL.store(st, std::sync::atomic::Ordering::Relaxed);
return Value::Status(st);
}
// A failed argument glob fails in that forked child too.
if let Some(status) = external_glob_failure_status() {
return Value::Status(status);
}
// `[builtins].coreutils_shadows = off` in
// ~/.zshrs/zshrs.toml (or `ZSHRS_NO_COREUTILS_SHADOWS=1`
// env override) bypasses the in-process shadow and
// fork-execs the real /bin/X. Safety valve for any
// script that hits an edge-case divergence between
// the zshrs shadow and system coreutils. Cached
// after first call, so the hot path is one atomic
// load per shadowed-builtin invocation.
// c:Src/exec.c:3545-3547 — these shadows stand in for
// EXTERNAL commands (`cat`, `head`, …), which in zsh reach
// execcmd_exec and set `$_` to the command's last word
// before running. The in-process shadow below bypasses
// dispatch_builtin AND execute_external_bg, so without this
// `cat f; print $_` reported the PREVIOUS command's last
// argument.
{
let last = args.last().cloned().unwrap_or_else(|| $name.to_string());
crate::ported::params::set_zunderscore(std::slice::from_ref(&last));
// c:3546
}
// With the shadow off (always under `--zsh`) the name is the
// external command it stands in for, so it takes the external
// path: c:Src/exec.c:4369 `execute()` replaces a child already
// forked for it (`sleep 5 &`, a pipeline stage) instead of
// forking again, and a signal sent to the job reaches the
// command itself (`kill -HUP %1` is `hangup`, not `exit 1`).
if !crate::daemon_presence::coreutils_shadows_enabled() {
return Value::Status(with_executor(|exec| {
exec.execute_external($name, &args, &[]).unwrap_or(127)
}));
}
let status = with_executor(|exec| exec.$method(&args));
Value::Status(status)
});
};
}
// Pure-passthru builtin: pops args, routes to canonical
// `dispatch_builtin(name, args)` (which goes via execbuiltin →
// BUILTINS[name] → bin_X). No pre/post bridge work. Used by
// ~25 handlers that were 4-line copy-paste boilerplate.
macro_rules! reg_passthru {
($vm:expr, $id:expr, $name:literal) => {
$vm.register_builtin($id, |vm, argc| {
let args = pop_args(vm, argc);
// function > builtin: a same-named user function wins over
// the builtin on the normal (CallBuiltin) invocation path.
// The compiler's `user_function_shadow` already routes the
// same-compile-unit case through CallFunction; this probe
// extends that to the cross-unit / interactive case (define
// `zstyle() { … }` on one line, call it on the next). The
// forced `builtin NAME` / `command NAME` paths dispatch
// through their own handlers, not this one, so they still
// reach the builtin as required.
if let Some(s) = try_user_fn_override($name, &args) {
return Value::Status(s);
}
Value::Status(dispatch_builtin($name, args))
});
};
}
// zshrs-original extension builtins (async / peach / doctor / …) that
// route to an ExecutorContext method. Like `reg_overridable!`, they
// probe `try_user_fn_override` FIRST so a user function of the same
// name wins — zsh's alias → function → builtin dispatch order. Without
// the probe, `doctor() { … }; doctor` silently ran the builtin and
// ignored the function (function > builtin violated for these).
macro_rules! reg_ext_overridable {
($vm:expr, $id:expr, $name:literal, $method:ident) => {
$vm.register_builtin($id, |vm, argc| {
let args = pop_args(vm, argc);
if let Some(s) = try_user_fn_override($name, &args) {
return Value::Status(s);
}
Value::Status(with_executor(|exec| exec.$method(&args)))
});
};
}
// Core builtins
vm.register_builtin(BUILTIN_CD, |vm, argc| {
let args = pop_args(vm, argc);
if let Some(s) = try_user_fn_override("cd", &args) {
return Value::Status(s);
}
// c:Src/builtin.c:1258 — the chpwd hook runs inside cd_new_pwd.
Value::Status(dispatch_builtin("cd", args))
});
vm.register_builtin(BUILTIN_PWD, |vm, argc| {
let args = pop_args(vm, argc);
if let Some(s) = try_user_fn_override("pwd", &args) {
return Value::Status(s);
}
// Route through the canonical execbuiltin path so the `rLP`
// optstr at BUILTINS["pwd"] is parsed into `ops`.
let status = dispatch_builtin("pwd", args);
Value::Status(status)
});
vm.register_builtin(BUILTIN_ECHO, |vm, argc| {
let args = pop_args(vm, argc);
if let Some(s) = try_user_fn_override("echo", &args) {
return Value::Status(s);
}
// Update `$_` to the last arg before running. C zsh sets
// zunderscore in execcmd_exec for every simple command,
// including builtins.
crate::ported::params::set_zunderscore(&args);
let status = dispatch_builtin("echo", args);
Value::Status(status)
});
vm.register_builtin(BUILTIN_PRINT, |vm, argc| {
let args = pop_args(vm, argc);
if let Some(s) = try_user_fn_override("print", &args) {
return Value::Status(s);
}
crate::ported::params::set_zunderscore(&args);
let status = dispatch_builtin("print", args);
Value::Status(status)
});
reg_passthru!(vm, BUILTIN_PRINTF, "printf");
reg_passthru!(vm, BUILTIN_EXPORT, "export");
reg_passthru!(vm, BUILTIN_UNSET, "unset");
// `source` (Src/builtin.c c:116) wired to bin_dot via BUILTINS.
reg_passthru!(vm, BUILTIN_SOURCE, "source");
reg_passthru!(vm, BUILTIN_DOT, ".");
reg_passthru!(vm, BUILTIN_LOGOUT, "logout");
vm.register_builtin(BUILTIN_EXIT, |vm, argc| {
let args = pop_args(vm, argc);
// AOP intercepts (zshrs extension). A bare `exit` reads the status of
// the previous command, which the advice must not disturb.
if let Some(done) = advise_keeping_status(vm, "exit", &args) {
return done;
}
let status = dispatch_builtin("exit", args);
Value::Status(status)
});
vm.register_builtin(BUILTIN_RETURN, |vm, argc| {
let args = pop_args(vm, argc);
// AOP intercepts (zshrs extension). A bare `return` reads the status of
// the previous command, which the advice must not disturb.
if let Some(done) = advise_keeping_status(vm, "return", &args) {
return done;
}
// zsh: bare `return` (no arg) returns with the status of
// the most recently executed command — `false; return`
// returns 1, not 0. Direct port of zsh's bin_break/RETURN.
// The executor's `last_status` is stale here (synced at
// statement boundaries, not after each VM op), so read
// the live `vm.last_status` instead.
let live_status = vm.last_status;
let status = {
// Sync canonical LASTVAL to the VM's view BEFORE
// bin_break("return") reads it for the no-arg fallback.
with_executor(|exec| exec.set_last_status(live_status));
dispatch_builtin("return", args)
};
Value::Status(status)
});
vm.register_builtin(BUILTIN_TRUE, |vm, argc| {
let args = pop_args(vm, argc);
if let Some(s) = try_user_fn_override("true", &args) {
return Value::Status(s);
}
// c:Src/exec.c:1257 — zsh sets `zunderscore` AT THE END of
// each command (the `if (!noerrs)` block runs `zsfree(prev_argv0); …;
// zunderscore = …`). For no-arg `true`, $_ becomes the
// command name itself. Set DIRECTLY (not via pending_underscore)
// so the NEXT command's argv-expansion of `$_` reads "true",
// not the stale prior value — pending_underscore is consumed
// by pop_args which runs AFTER argv expansion, too late.
// c:Src/exec.c:1257 — `zunderscore = …` at end-of-command.
// With args, $_ = args.last(). Without args, $_ = command name.
// Write DIRECTLY to the canonical zunderscore static (the
// underscoregetfn at params.rs:7003 reads from there); the
// paramtab "_" slot is shadowed by lookup_special_var so
// set_scalar on it has no effect on `$_` reads.
if args.is_empty() {
crate::ported::params::set_zunderscore(&["true".to_string()]);
} else {
crate::ported::params::set_zunderscore(&args);
}
// Route through canonical execbuiltin so PS4 xtrace fires
// via the c:442 printprompt4 path.
Value::Status(dispatch_builtin("true", args))
});
vm.register_builtin(BUILTIN_FALSE, |vm, argc| {
let args = pop_args(vm, argc);
if let Some(s) = try_user_fn_override("false", &args) {
return Value::Status(s);
}
// Direct set; see BUILTIN_TRUE above for rationale.
if args.is_empty() {
crate::ported::params::set_zunderscore(&["false".to_string()]);
} else {
crate::ported::params::set_zunderscore(&args);
}
// Route through canonical execbuiltin — see BUILTIN_TRUE
// above for the same rationale (xtrace + fast-path removal).
let status = dispatch_builtin("false", args);
Value::Status(status)
});
vm.register_builtin(BUILTIN_COLON, |vm, argc| {
let args = pop_args(vm, argc);
// AOP intercepts (zshrs extension): this opcode builtin has no
// user-function probe, so its advice runs here.
if let Some(status) = run_command_intercepts(":", &args) {
return Value::Status(status);
}
// Direct set; see BUILTIN_TRUE above for rationale.
if args.is_empty() {
crate::ported::params::set_zunderscore(&[":".to_string()]);
} else {
crate::ported::params::set_zunderscore(&args);
}
let status = dispatch_builtin(":", args);
Value::Status(status)
});
// `[ … ]` — c:Src/builtin.c:7231 `bin_test` with BIN_BRACKET. See
// BUILTIN_TEST_BRACKET.
vm.register_builtin(BUILTIN_TEST_BRACKET, |vm, argc| {
let args = pop_args(vm, argc);
// AOP intercepts (zshrs extension): this opcode builtin has no
// user-function probe, so its advice runs here.
if let Some(status) = run_command_intercepts("[", &args) {
return Value::Status(status);
}
Value::Status(dispatch_builtin("[", args))
});
vm.register_builtin(BUILTIN_TEST, |vm, argc| {
let args = pop_args(vm, argc);
// AOP intercepts (zshrs extension): this opcode builtin has no
// user-function probe, so its advice runs here.
if let Some(status) = run_command_intercepts("test", &args) {
return Value::Status(status);
}
// c:Src/builtin.c:7231 `bin_test` with funcid BIN_TEST. The `[`
// spelling compiles to BUILTIN_TEST_BRACKET, so this slot is only ever
// `test`. It used to guess the spelling from a trailing `]`, which ran
// `test a ]` as `[ a ]` (status 0) where zsh reports "condition
// expected: a" (status 2), and ran `[ a` as `test a`.
Value::Status(dispatch_builtin("test", args))
});
// Variable declaration. `local` (Src/builtin.c bin_local) handles
// the scope chain (`pm->old = oldpm` at Src/params.c:1137 inside
// createparam, `pm->level = locallevel` at Src/builtin.c:2576).
// `typeset` / `declare` are aliases — fusevm maps both to
// BUILTIN_TYPESET; compile_zsh special-cases `declare` to keep
// the `declare:` error prefix.
reg_passthru!(vm, BUILTIN_LOCAL, "local");
reg_passthru!(vm, BUILTIN_TYPESET, "typeset");
reg_passthru!(vm, BUILTIN_DECLARE, "declare");
reg_passthru!(vm, BUILTIN_READONLY, "readonly");
reg_passthru!(vm, BUILTIN_INTEGER, "integer");
reg_passthru!(vm, BUILTIN_FLOAT, "float");
reg_passthru!(vm, BUILTIN_READ, "read");
// c:Bug #504 — fusevm reserves BUILTIN_MAPFILE for the bash
// mapfile/readarray builtins. Neither exists in zsh; in --zsh
// parity mode the dispatch must emit "command not found" + rc=127
// matching zsh's external-command-lookup miss. The previous wiring
// left BUILTIN_MAPFILE unregistered, so fusevm's VM treated the op
// as a no-op rc=0 — `mapfile` (and `readarray`) silently succeeded
// in --zsh mode. The host gate in `dispatch_builtin_raw` never
// fired because the compile path emitted `Op::CallBuiltin(31, ..)`
// directly. Register the slot so the gate runs (or a future
// non-zsh mode can wire in a real impl).
vm.register_builtin(fusevm::shell_builtins::BUILTIN_MAPFILE, |vm, argc| {
let args = pop_args(vm, argc);
// AOP intercepts (zshrs extension): this opcode builtin has no
// user-function probe, so its advice runs here.
if let Some(status) = run_command_intercepts("mapfile", &args) {
return Value::Status(status);
}
// The fusevm name→id map collapses both `mapfile` and
// `readarray` to the same opcode; pick the right diagnostic
// by sniffing the user's actual invocation. The xtrace ARGS
// push earlier records the cmd-prefix as the bottom of the
// popped argv, but `args` here excludes the prefix — so we
// can't recover the user-typed name from the stack. Default
// to `mapfile` (the more-common spelling); both produce
// identical diagnostics in any case.
if crate::IS_ZSH_MODE.load(std::sync::atomic::Ordering::Relaxed) {
eprintln!("zsh:1: command not found: mapfile");
let _ = args;
return Value::Status(127);
}
// Non-zsh modes (bash drop-in): mapfile / readarray reads lines
// from stdin (or `-u fd`) into an array. Handled by the ported
// bash builtin in ext_builtins.
Value::Status(crate::extensions::ext_builtins::readarray(&args))
});
reg_passthru!(vm, BUILTIN_BREAK, "break");
reg_passthru!(vm, BUILTIN_CONTINUE, "continue");
reg_passthru!(vm, BUILTIN_SHIFT, "shift");
vm.register_builtin(BUILTIN_EVAL, |vm, argc| {
// Direct port of `bin_eval(UNUSED(char *nam), char **argv, UNUSED(Options ops), UNUSED(int func))` body from Src/builtin.c:6151:
// `if (!*argv) return 0;`
// `prog = parse_string(zjoin(argv, ' ', 1), 1);`
// `execode(prog, 1, 0, "eval");`
// The execode invocation lives here (not in the canonical
// free-fn) because it must run through the bytecode VM's
// current executor — the same VM that's mid-dispatch.
let mut args = pop_args(vm, argc);
// AOP intercepts (zshrs extension): this opcode builtin has no
// user-function probe, so its advice runs here.
if let Some(status) = run_command_intercepts("eval", &args) {
return Value::Status(status);
}
// c:Src/builtin.c:407-411 — generic `--` end-of-options
// strip applied by `execbuiltin` for builtins that have
// NULL optstr AND no BINF_HANDLES_OPTS. `eval` qualifies
// (Src/builtin.c:65 `BUILTIN("eval", BINF_PSPECIAL, ...,
// NULL, NULL)`). The BUILTIN_EVAL fast-path bypasses
// execbuiltin, so we mirror the strip inline. Bug #319.
if args.first().is_some_and(|s| s == "--") {
args.remove(0);
}
if args.is_empty() {
return Value::Status(0); // c:6160
}
let src = args.join(" "); // c:6166
// c:Src/builtin.c:6164-6165 — `if (!ineval) scriptname =
// "(eval)";`. Diagnostics emitted while the eval body runs
// (command-not-found, parse errors, etc.) use scriptname as
// the source-context prefix. Without setting it here the
// BUILTIN_EVAL fast-path leaked the outer "zsh" prefix
// through, breaking the `(eval):N:` convention zsh uses
// for in-eval errors. Bug #420.
// c:Src/builtin.c:6209 — `execode(prog, 1, 0, "eval");`. execode
// (c:Src/exec.c:1245-1266) APPENDS its context argument to
// `zsh_eval_context` for the duration of the body, so code inside
// `eval` sees `cmdarg:eval` (and `cmdarg:shfunc:eval` when the eval is
// in a function). zshrs pushed "shfunc" and, since #1065, "cmdsubst",
// but never "eval". Popped on every return path by the guard, matching
// execode's stack discipline. Bug #1065 (eval leg).
let _eval_ctx_guard = crate::ported::exec::EvalContextFrame::push("eval");
// c:Src/builtin.c:6163-6178 — `eval` pushes a funcstack frame named
// "(eval)" (tp = FS_EVAL), gated on `ineval = !isset(EVALLINENO)` /
// `if (!ineval)` — i.e. pushed when EVAL_LINENO is SET, which is the
// zsh default. zshrs already set `scriptname = "(eval)"` (below) but
// never pushed the frame, so `eval '…${#funcstack}'` reported 0 where
// zsh reports 1, and inside a function `${(j:,:)funcstack}` was `f`
// rather than `(eval),f`. Both shells already agreed under
// `unsetopt evallineno` (no frame), so the option gate is load-bearing
// and is mirrored here. Popped on every return path by the guard.
// Bug #1066.
// The push itself is the canonical port (`EvalFuncstackFrame::push`,
// exec.rs, c:6155-6193) — shared with `eval_string`, which the
// compsys `_dispatch` port uses for its `eval "$comp"` sites so both
// eval entry points produce a byte-identical `(eval)` frame. It was
// inline here and set `lineno`/`flineno` to 0 with no `filename`,
// which C computes at c:6161 / c:6174-6188 — so `$functrace` read
// `<caller>:0` and `$funcfiletrace` lost the defining file.
let _eval_fs_guard = crate::ported::exec::EvalFuncstackFrame::push();
let oscriptname = crate::ported::utils::scriptname_get();
crate::ported::utils::set_scriptname(Some("(eval)".to_string()));
// Recursion backstop — c:Src/jobs.c:1878-1884. zsh caps eval recursion
// via its job table (every eval'd pipeline grabs a job slot; the table
// caps at MAX_MAXJOBS → "job table full or recursion limit exceeded").
// The fusevm runtime allocates no job per pipeline, and nested evals
// push no funcstack frame (INEVAL suppression, c:6164), so eval nesting
// is invisible to both the job table AND FUNCNEST/FUNCSTACK — runaway
// `eval`-string recursion overflowed the 256 MB main-thread stack →
// uncatchable SIGBUS. Track eval re-entry depth (the Rust proxy for
// held job slots) and refuse at the same MAX_MAXJOBS ceiling.
let eval_depth = crate::vm_helper::EVAL_RECURSION_DEPTH.with(|d| {
let v = d.get() + 1;
d.set(v);
v
});
let mut status = if eval_depth >= crate::ported::jobs::MAX_MAXJOBS {
crate::ported::utils::zerr("job table full or recursion limit exceeded");
1
} else {
with_executor(|exec| {
// c:6175 execode — no end-of-script hooks (c:Src/builtin.c:6213)
exec.execute_string_without_exit_hooks(&src).unwrap_or(1)
})
};
crate::vm_helper::EVAL_RECURSION_DEPTH.with(|d| d.set(d.get().saturating_sub(1)));
// c:Src/builtin.c:6211-6212 — `if (errflag && !lastval)
// lastval = errflag;`
// c:Src/builtin.c:6221 — `errflag &= ~ERRFLAG_ERROR;`
// eval is a CONTAINMENT boundary: an error inside the eval
// body (readonly reassign, bad assoc set, ${unset?msg}, …)
// breaks the eval body's lists via errflag, then eval clears
// the flag and returns lastval, and the CALLER's next list
// runs. zsh 5.9: `eval 'assoc=(odd)'; echo "after $?"`
// prints `after 1` in -c, script, and stdin contexts.
{
use std::sync::atomic::Ordering;
let ef = crate::ported::utils::errflag.load(Ordering::Relaxed)
& crate::ported::zsh_h::ERRFLAG_ERROR;
if ef != 0 && status == 0 {
status = ef; // c:6212 lastval = errflag
}
crate::ported::utils::errflag
.fetch_and(!crate::ported::zsh_h::ERRFLAG_ERROR, Ordering::Relaxed);
// The NOMATCH cell is the Rust half of that error state (set
// beside `zerr` for c:Src/glob.c:1877). The builtin dispatcher
// reads it BEFORE the next command runs, so one left over from
// `eval 'x=( *nomatch )'` skipped the caller's next command.
with_executor(|exec| exec.current_command_glob_failed.set(false));
}
crate::ported::utils::set_scriptname(oscriptname);
Value::Status(status)
});
// `builtin foo args…`: precmd-modifier that forces builtin dispatch,
// bypassing alias AND function lookup. Without this, `builtin cd /`
// inside a user `cd () { … }` wrapper recurses (real-world ZPWR pattern).
// Handler pops argc args from the stack, treats args[0] as the builtin
// name, and dispatches the rest via `dispatch_builtin` → `execbuiltin`
// → `bin_*` directly. No function/alias lookup happens.
vm.register_builtin(BUILTIN_BUILTIN, |vm, argc| {
let args = pop_args(vm, argc);
// c:Src/exec.c:3483-3487 — the precommand-modifier walk checks
// `shfunctab` for the command word BEFORE `builtintab`, and only
// skips that check once a prefix has already been consumed
// (`cflags & (BINF_BUILTIN|BINF_COMMAND)`). So on the FIRST word a
// shell function literally named `builtin` shadows the builtin —
// `builtin() { ... }; builtin whence -va x` runs the function.
// zshrs resolves `builtin` at bytecode-compile time (no function
// table yet), so the shadow test has to happen here, at dispatch.
if let Some(status) = try_user_fn_override("builtin", &args) {
return Value::Status(status);
}
// c:Src/exec.c:3760-3763 — `if (errflag) { lastval = 1; goto err; }`
// after argument expansion: a bad glob qualifier or pattern in the
// words (`builtin print x(a)` "number expected") skips the builtin
// with status 1 and leaves errflag set, so the script ends. This
// handler is reached without dispatch_builtin's gates, and ran the
// builtin, which reported 0.
if (crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed)
& crate::ported::zsh_h::ERRFLAG_ERROR)
!= 0
{
// c:3523-3525 / c:3760-3762 — see words_errflag_status.
return Value::Status(words_errflag_status());
}
// c:Src/exec.c:3104-3146 — the precommand walk strips a `-` word after
// `builtin` too (it is itself a BINF_PREFIX node, c:Src/builtin.c:42);
// when nothing is left, c:3380-3406 is the empty-command return and
// `builtin -` succeeds without running anything.
let mut full = Vec::with_capacity(args.len() + 1);
full.push("builtin".to_string());
full.extend(args.iter().cloned());
if crate::ported::exec::execcmd_compile_head(&full, crate::ported::zsh_h::WC_SIMPLE)
.is_empty_command
{
return Value::Status(0);
}
let Some((name, rest)) = args.split_first() else {
// `builtin` with no args → list builtins (zsh emits nothing,
// exit 0). Match that behavior; the BIN_BUILTIN bin_* in C
// does the same default-list-nothing.
return Value::Status(0);
};
// zshrs extension builtins (daemon z* family: zd, zcache, zjob,
// …) are dispatched by name via try_dispatch instead of living
// in builtintab — but they ARE builtins, so the `builtin`
// precommand must reach them (`builtin zd ping` errored
// "no such builtin: zd" while bare `zd ping` worked).
if let Some(status) = run_daemon_builtin(name, rest) {
return Value::Status(status);
}
// c:Src/exec.c:3435-3436 — `builtin NAME` with NAME not in
// builtintab emits `zwarn("no such builtin: %s", cmdarg)`
// and returns 1. zshrs's dispatch_builtin_raw bare-returned 1
// silently. Probe the table here so the diagnostic fires
// before dispatch.
let tab = crate::ported::builtin::createbuiltintable();
// c:Src/exec.c:3489-3499 — `builtintab->getnode` skips DISABLED
// entries, so `disable typeset; builtin typeset x=1` is "no such
// builtin: typeset" with status 1, like a name that was never a builtin.
let disabled = crate::ported::builtin::BUILTINS_DISABLED
.lock()
.map(|s| s.contains(name.as_str()))
.unwrap_or(false);
if !tab.contains_key(name.as_str()) || disabled {
// zshrs-original opcode builtins (async, doctor, peach, …) aren't
// in builtintab; `builtin NAME` must still reach them.
if let Some(status) = try_run_registered_builtin(name, rest) {
return Value::Status(status);
}
// c:Src/exec.c:3436 — `zwarn("no such builtin: %s", cmdarg);`.
// Route through the ported `zwarn` rather than formatting the
// prefix by hand: zwarn emits zsh's `zsh:LINE:` prefix, and the
// hand-rolled `eprintln!` here printed `zshrs:1:` instead. Of the
// twelve error shapes probed this was the ONLY one carrying the
// wrong prefix — the ported twin at exec.rs:9878 already used
// zwarn correctly, so this was a reimplementation shadowing a
// faithful port (same shape as #1027 / #1031 / #1044 / #1050).
// Bug #1063.
crate::ported::utils::zwarn(&format!("no such builtin: {}", name));
return Value::Status(1);
}
// `builtin foo` MUST bypass function shadow — that's the whole
// point of the prefix. Use the _raw helper, not the shadow-aware
// one. Without this, `cd () { builtin cd "$@"; }` recurses.
// c:Src/exec.c:3484 — BINF_BUILTIN suppresses the shfunctab probe.
// `bin_compadd` runs that probe itself, so publish the modifier across
// the call (see `ForcedBuiltinGuard`).
let _forced = crate::ported::zle::complete::ForcedBuiltinGuard::enter();
Value::Status(dispatch_builtin_raw(name, rest.to_vec()))
});
// `command foo args…` — BINF_COMMAND prefix (Src/builtin.c:44). Zsh
// semantic: bypass alias+function lookup, search builtin then $PATH.
// Without this, `cd () { command cd "$@" }` would re-invoke the user
// wrapper (same root cause as the `builtin` bug). Flags `-p`/`-v`/`-V`
// route to bin_whence with BIN_COMMAND funcid; bare `command foo`
// dispatches builtin if present, else external (no fork — direct
// spawn via execute_external since zshrs is non-forking).
// BUILTIN_COMMAND — `command [-p] [-v|-V] cmd args…` BIN_PREFIX
// (Src/builtin.c:45). PURE PASSTHRU: prepend "command" and hand
// to `exec::execcmd_compile_head` (the fusevm-bytecode-time head
// resolver mirroring `Src/exec.c::execcmd_exec` precommand-modifier
// walk at c:3104-3187). That helper already does the -p / -v / -V
// option parsing, surfaces `has_command_vv` for the whence
// redirect, and reports the dispatch shape (is_builtin vs external).
vm.register_builtin(BUILTIN_COMMAND, |vm, argc| {
let args = pop_args(vm, argc);
// c:Src/exec.c:3483-3487 — same shfunctab-before-builtintab rule
// as BUILTIN_BUILTIN above: a shell function named `command`
// shadows the `command` precommand modifier on the first word.
if let Some(status) = try_user_fn_override("command", &args) {
return Value::Status(status);
}
let mut full = Vec::with_capacity(args.len() + 1);
full.push("command".to_string());
full.extend(args.clone());
let dispatch =
crate::ported::exec::execcmd_compile_head(&full, crate::ported::zsh_h::WC_SIMPLE);
let post = &full[dispatch.precmd_skip..];
// c:Src/exec.c:3212-3214 — `} else if (has_p) { /* Use default path */
// use_defpath = 1; … }`. `-p` is a flag carried down to the exec
// (c:4369 `execute(args, cflags, use_defpath)`) and to whence
// (c:Src/builtin.c:4165-4167 `findcmd(*argv, 1, func == BIN_COMMAND &&
// OPT_ISSET(ops,'p'))`), where the compiled-in DEFAULT_PATH
// (configure.ac:1954, `getconf _CS_PATH` at build time) is searched
// directly. C never assigns to `$path` for this.
//
// command's OWN options end at the first non-flag arg —
// everything after the command name belongs to IT. The
// previous `.any()` scan over ALL args stole `-p` from
// `command mkdir -p DIR` (zconvey.plugin.zsh:44), stripping
// the flag before /bin/mkdir ran → "File exists" errors on
// every re-source.
let mut lead = 0usize;
let mut dash_p = false;
let mut kept_flags: Vec<String> = Vec::new();
for a in post.iter() {
let s = a.as_str();
if s == "--" {
lead += 1;
break;
}
if s.starts_with('-')
&& s.len() >= 2
&& s[1..].chars().all(|c| c == 'p' || c == 'v' || c == 'V')
{
if s.contains('p') {
dash_p = true;
}
// -v / -V drive the whence-style lookup downstream —
// keep them in post (only the PATH-reset `p` is
// consumed here).
let rest: String = s[1..].chars().filter(|c| *c != 'p').collect();
if !rest.is_empty() {
kept_flags.push(format!("-{}", rest));
}
lead += 1;
continue;
}
break;
}
// !!! DASH-FAITHFUL GATE (no C counterpart) !!! dash's `command` knows only
// -p -v -V; any other `-x` word is "Illegal option" (status 2), not a
// command name.
if crate::dash_mode::dash_faithful() {
if let Some(bad) = post[lead..]
.first()
.filter(|s| s.len() >= 2 && s.starts_with('-') && *s != "--")
.and_then(|s| s[1..].chars().find(|c| !matches!(c, 'p' | 'v' | 'V')))
{
crate::ported::utils::zwarnnam("command", &format!("Illegal option -{bad}"));
return Value::Status(2);
}
}
let mut post: Vec<String> = {
let mut v = kept_flags;
v.extend(post[lead..].iter().cloned());
v
};
// c:Src/exec.c:3176-3177 — `BINF_COMMAND` arm strips a single
// leading `--` end-of-options marker.
// `execcmd_compile_head` (src/ported/exec.rs:1042) performs
// this removal on its LOCAL `preargs` Vec but doesn't surface
// the modified args; the caller still sees `--` in `full` and
// tried to dispatch it as the command name. Bug #251. Mirror
// the C strip here so `command -- echo hi` and
// `command -p -- echo hi` route correctly.
if let Some(first) = post.first() {
if first == "--" {
post.remove(0);
}
}
let post = post.as_slice();
// The previous implementation spelled `-p` as a temporary `$PATH`
// reassignment around the call, seeded by forking `getconf PATH`.
// Three things were wrong with that and all three are gone now:
// every `$PATH` write empties `cmdnamtab` (c:Src/params.c pathsetfn),
// so the entry `execcmd_exec` had just made for the command was wiped
// on restore and `hash` came back empty where the oracle lists the
// command; the child process inherited the DEFAULT_PATH in its
// environment instead of the caller's `$PATH`; and a shell whose point
// is not forking paid a fork per `command -p` for a value the C build
// bakes in at configure time.
// c:Src/exec.c:3760-3763 — `if (errflag) { lastval = 1; goto err; }`
// after argument expansion. The in-shell forms (`command -v`, and a
// builtin under POSIX_BUILTINS) keep errflag, so the script ends; the
// external form clears it below, as its forked child would.
let expansion_error = (crate::ported::utils::errflag
.load(std::sync::atomic::Ordering::Relaxed)
& crate::ported::zsh_h::ERRFLAG_ERROR)
!= 0;
if expansion_error && (dispatch.has_command_vv || dispatch.is_builtin) {
// c:3523-3525 / c:3760-3762 — see words_errflag_status.
return Value::Status(words_errflag_status());
}
if dispatch.has_command_vv {
return Value::Status(command_whence(post, dash_p));
}
if dispatch.is_empty_command {
return Value::Status(0);
}
let Some((name, rest)) = post.split_first() else {
return Value::Status(0);
};
// c:Src/exec.c:3275-3278 — `execcmd_compile_head` cleared
// hn for the BINF_COMMAND + !POSIXBUILTINS case, surfacing
// is_builtin=false. Run as external. Under POSIXBUILTINS
// dispatch.is_builtin would be true; honour it.
let n = name.clone();
let r = rest.to_vec();
if dispatch.is_builtin
&& crate::ported::builtin::BUILTINS
.iter()
.any(|b| b.node.nam == n.as_str())
{
// c:Src/exec.c:3484 — BINF_COMMAND suppresses it too.
let _forced = crate::ported::zle::complete::ForcedBuiltinGuard::enter();
return Value::Status(dispatch_builtin_raw(&n, r));
}
// c:Src/exec.c:3755-3763 — `globlist(args, 0); if (errflag) { lastval
// = 1; goto err; }`. Without POSIX_BUILTINS `command NAME` is always
// an external, and C forks before that globlist, so a NOMATCH error
// skips the command in the child while the parent's errflag stays
// clean: `command ls zzq*; print $?` prints the error, then 1. Here
// the words were expanded in the shell, so drop the failed command
// and its ERRFLAG_ERROR the way the external dispatcher does. Any
// other expansion error (`command print x(a)` "number expected")
// takes the same path.
let glob_failed = with_executor(|exec| {
let f = exec.current_command_glob_failed.get();
exec.current_command_glob_failed.set(false);
f
});
// A prefork error (c:3357-3359, a bad `${…}` or math) happens BEFORE
// that fork, in the shell: c:3523-3525 keeps a non-zero lastval and
// errflag ends the list (`command print ${.bad}` after `(exit 5)`
// exits 5). Only a globlist error belongs to the forked child.
if expansion_error && !glob_failed && !GLOB_WORD_ERRFLAG.with(|c| c.get()) {
return Value::Status(words_errflag_status());
}
GLOB_WORD_ERRFLAG.with(|c| c.set(false));
if (glob_failed || expansion_error) && take_cmd_name_glob_failed() {
with_executor(|exec| exec.set_last_status(1));
return Value::Status(1);
}
if glob_failed || expansion_error {
crate::ported::utils::errflag.fetch_and(
!crate::ported::zsh_h::ERRFLAG_ERROR,
std::sync::atomic::Ordering::Relaxed,
);
with_executor(|exec| exec.set_last_status(1));
return Value::Status(1);
}
// c:Src/exec.c:3719 forks the external command before the redirection
// loop at c:3785, so a redirection that failed (`command cat <&""` →
// "file number expected") fails in the child: the command never runs
// and the shell continues with status 1. The redirect arm only
// records the failure; without consuming it here `command cat` ran
// the real cat on the untouched stdin and blocked.
let redir_failed = with_executor(|exec| {
let f = exec.redirect_failed;
exec.redirect_failed = false;
f
});
if redir_failed {
crate::ported::utils::errflag.fetch_and(
!crate::ported::zsh_h::ERRFLAG_ERROR,
std::sync::atomic::Ordering::Relaxed,
);
crate::ported::builtin::LASTVAL.store(1, std::sync::atomic::Ordering::Relaxed);
return Value::Status(1);
}
// c:Src/exec.c:3275-3278 — `command NAME` asks for the thing on
// `PATH`, not the in-process one. The host-registered native commands
// (`extensions/native_cmds.rs`) are caught inside `execute_external`,
// which is this very call, so they are marked as explicitly forced
// past for its duration — matching what `command cat` already does to
// the coreutils shadow.
let _forced = crate::native_cmds::force_external();
// c:Src/exec.c:4369 — `execute(args, cflags, use_defpath)`. The `-p`
// flag is the third argument, not a mutation of the environment.
Value::Status(
with_executor(|exec| {
if dash_p {
exec.execute_external_defpath(&n, &r, &[])
} else {
exec.execute_external(&n, &r, &[])
}
})
.unwrap_or(127),
)
});
// `exec cmd args…` — BINF_EXEC prefix (Src/builtin.c:45). Zsh
// semantic: replace the current shell process with `cmd`. On Unix
// this is `execvp(2)`; the call only returns on error. zshrs is
// non-forking, so the shell process IS the calling process —
// execvp here directly replaces it. Options `-a name` (override
// argv[0]), `-c` (clean env), `-l` (login shell — prepend `-`)
// ported minimally; advanced redirect-only `exec >file` is handled
// upstream by compile_zsh and never reaches this handler.
vm.register_builtin(BUILTIN_EXEC, |vm, argc| {
let args = pop_args(vm, argc);
// AOP intercepts (zshrs extension). A bare `exec` reads the status of
// the previous command, which the advice must not disturb.
if let Some(done) = advise_keeping_status(vm, "exec", &args) {
return done;
}
// c:Src/exec.c:3029-3278 — the precommand walk, `exec` included:
// its options (c:3178-3274, `-a`/`-c`/`-l` and the "exec requires
// a command to execute" / "unknown exec flag" errors), then any
// further BINF_PREFIX word (`command`, `builtin`, `exec`, `-`) whose
// flags join cflags with BINF_EXEC still set (c:3116-3118). So
// `exec command X` runs the external X in the shell's place and
// `exec builtin X` the builtin. Under POSIX_BUILTINS the walk stops
// after `exec`'s options (c:3098-3103): the name is a command.
let mut full = Vec::with_capacity(args.len() + 1);
full.push("exec".to_string());
full.extend(args);
let walk = crate::ported::exec::execcmd_compile_head(&full, crate::ported::zsh_h::WC_SIMPLE);
if (crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed)
& crate::ported::zsh_h::ERRFLAG_ERROR)
!= 0
{
vm.last_status = 1; // c:3205 `lastval = 1;`
crate::ported::builtin::LASTVAL.store(1, std::sync::atomic::Ordering::Relaxed);
return Value::Status(1); // c:3203-3207 / c:3230-3234 / c:3249-3256 `goto done`
}
if walk.has_command_vv {
// c:3149-3157 — whence, then the exec'd shell is gone.
let post = &walk.preargs[walk.precmd_skip..];
let dash_p = post.iter().take_while(|a| a.starts_with('-')).any(|a| a.contains('p'));
let status = command_whence(post, dash_p);
let _ = std::io::stdout().flush();
std::process::exit(status);
}
if walk.is_empty_command {
// `exec` with no command + no redirects = no-op success
// (c:3365-3406; the redirect-only form never reaches here).
return Value::Status(0);
}
let args: Vec<String> = walk.preargs[walk.precmd_skip..].to_vec();
let cmd = args[0].clone();
// c:Src/exec.c:3373-3379 — `else if (isset(RESTRICTED) && (cflags &
// BINF_EXEC) && do_exec) { zerrnam("exec", "%s: restricted", ...);
// lastval = 1; return; }`
if crate::ported::zsh_h::isset(crate::ported::zsh_h::RESTRICTED) {
crate::ported::utils::zerrnam("exec", &format!("{}: restricted", cmd));
vm.last_status = 1;
crate::ported::builtin::LASTVAL.store(1, std::sync::atomic::Ordering::Relaxed);
return Value::Status(1);
}
if (walk.cflags & crate::ported::zsh_h::BINF_BUILTIN) != 0 && !walk.is_builtin {
// c:3490-3492 — `zwarn("no such builtin: %s", cmdarg); lastval = 1;`
crate::ported::utils::zwarn(&format!("no such builtin: {}", cmd));
return Value::Status(1);
}
let login = (walk.cflags & crate::ported::zsh_h::BINF_DASH) != 0; // c:3246
let clean_env = (walk.cflags & crate::ported::zsh_h::BINF_CLEARENV) != 0; // c:3243
let argv0_override = walk.exec_argv0.clone(); // c:3263-3274
// c:4369 — `execute(args, cflags, use_defpath)`: `exec command -p X`.
let use_defpath = walk.use_defpath;
let prog = if use_defpath && !cmd.contains('/') {
crate::ported::exec::search_defpath(&cmd, libc::PATH_MAX as usize).unwrap_or_else(|| cmd.clone())
} else {
cmd.clone()
};
let rest: Vec<String> = args[1..].to_vec();
let display_argv0 = match argv0_override {
Some(a) => a,
None => {
if login {
format!("-{}", cmd)
} else {
cmd.clone()
}
}
};
// c:Src/exec.c:3468/3582 — execcmd bails out before running anything
// once a redirection has failed: the failure calls zerr, which sets
// errflag, and both bail-outs test it. `exec` is not exempt, so
// exec ls 3>&98; print after
// in zsh reports the bad fd, does NOT run ls, and the SHELL SURVIVES
// to run `print after`. zshrs consumed the flag in
// BUILTIN_EXEC_PERM_REDIRS (returning status 1) but then dispatched
// the command regardless — replacing the shell with it, so anything
// after the exec never ran, and `exec 99>&98` reported a spurious
// `command not found: 99` for the leftover fd word.
if with_executor(|exec| {
let f = exec.redirect_failed;
exec.redirect_failed = false;
f
}) {
vm.last_status = 1;
return Value::Status(1);
}
// c:Src/exec.c::execcmd — `exec funcname` runs the function
// in-process as the shell's last act, then exits with the
// function's status. zsh's dispatcher falls through from the
// BINF_EXEC prefix into the normal Builtin/External/Function
// resolution and only execvp's if the target ISN'T a
// function. Bug #101 in docs/BUGS.md: zshrs's exec went
// straight to execvp and errored `not found` for shell
// functions.
//
// For both subshell and top-level contexts: dispatch through
// the function/builtin lookup first; only fall through to
// execvp/spawn if the name isn't shell-resolvable.
// c:Src/exec.c:3098-3103 — `else if (isset(POSIXBUILTINS) &&
// (cflags & BINF_EXEC)) break;` "POSIX doesn't allow "exec" to
// operate on builtins or shell functions": the walk stops before
// the shfunctab and builtintab lookups, so the name is searched
// as an external command. A walked chain has already resolved the
// head (c:3104-3108 skips functions after `builtin` / `command`).
let has_user_fn = walk.is_shfunc; // c:3104-3108
if has_user_fn {
let status =
with_executor(|exec| exec.dispatch_function_call(&cmd, &rest).unwrap_or(127));
// Top-level `exec funcname` — exit the shell with the
// function's status (mirrors C's "exec replaces shell as
// last act"). Subshell `(exec funcname)` — return through
// the EXIT_PENDING path so the subshell body aborts and
// the parent resumes via subshell_end.
let in_subshell_now = exec_in_process_subshell();
if in_subshell_now {
crate::ported::builtin::EXIT_VAL
.store(status, std::sync::atomic::Ordering::Relaxed);
crate::ported::builtin::EXIT_PENDING.store(1, std::sync::atomic::Ordering::Relaxed);
return Value::Status(status);
}
std::process::exit(status);
}
// c:Src/exec.c — builtin path: `exec builtin` runs the
// builtin in-process and exits.
let bn_in_tab = walk.is_builtin; // c:3120-3129
if bn_in_tab {
let status = dispatch_builtin_raw(&cmd, rest.clone());
let in_subshell_now = exec_in_process_subshell();
if in_subshell_now {
crate::ported::builtin::EXIT_VAL
.store(status, std::sync::atomic::Ordering::Relaxed);
crate::ported::builtin::EXIT_PENDING.store(1, std::sync::atomic::Ordering::Relaxed);
return Value::Status(status);
}
std::process::exit(status);
}
// c:Src/exec.c — `exec` inside a subshell (`(exec cmd)`)
// replaces ONLY the subshell child process; the parent shell
// continues. C zsh always forks for `(...)`, so the actual
// execvp lands in the forked child. zshrs runs subshells via
// a snapshot/restore pattern in the SAME process — calling
// execvp here would replace the parent too. Bug #94 in
// docs/BUGS.md.
//
// Detect subshell context via the non-empty
// `subshell_snapshots` stack. When in a subshell: spawn the
// command as a child, wait for it, then signal the subshell
// body to abort (return Status(N) and the caller's
// subshell_end will pop the snapshot and resume the parent).
let in_subshell = exec_in_process_subshell();
if in_subshell && !clean_env {
let status = exec_execute(&args, walk.exec_argv0.clone(), login, use_defpath, false);
crate::ported::builtin::EXIT_VAL.store(status, std::sync::atomic::Ordering::Relaxed);
crate::ported::builtin::EXIT_PENDING.store(1, std::sync::atomic::Ordering::Relaxed);
return Value::Status(status);
}
if in_subshell {
// c:Src/exec.c:4352 `closem(FDT_INTERNAL, 0)` before execve.
crate::lowfd::cloexec_internal_fds();
let mut command = std::process::Command::new(&prog);
command.arg0(&display_argv0);
command.args(&rest);
if clean_env {
command.env_clear();
}
// Queue signals across spawn+wait so the SIGCHLD reaper
// can't reap this child before child.wait() does — see
// ForegroundWaitGuard.
let _wait_guard = ForegroundWaitGuard::enter();
let status = match command.spawn() {
Ok(mut child) => match child.wait() {
Ok(s) => crate::exec_jobs::wait_status_val(s),
Err(_) => 127,
},
Err(e) => {
// c:Src/exec.c:797 — `zerr("%e: %s", lerrno, arg0)`
// when arg0 contains `/`.
// c:872-876 — when arg0 has no `/` (PATH search
// path), C tracks the "good" errno
// via `isgooderr`; if all PATH entries
// were ENOENT-not-good, eno stays 0
// and C emits `command not found: %s`
// instead of strerror.
// %e expands to strerror(errno) with the first
// letter lowercased (unless errno == EIO; see
// Src/utils.c:362-368). `zerr` prepends the
// scriptname:lineno: prefix — matching zsh's
// canonical `zsh:N: <errmsg>: <cmd>` pattern.
// Previously emitted `zshrs: exec: {}: not found`
// (wrong prefix, hardcoded message, missing
// lineno). Bug #140 in docs/BUGS.md.
let errno = e.raw_os_error().unwrap_or(libc::ENOENT);
let has_slash = cmd.contains('/');
if !has_slash && errno == libc::ENOENT {
// c:876 — PATH search exhausted with no good
// errno → `command not found: arg0`.
crate::ported::utils::zerr(&format!("command not found: {}", crate::ported::utils::nicedupstring(&cmd)));
} else {
let mut errmsg = crate::ported::compat::strerror(errno);
if errno != libc::EIO {
if let Some(c) = errmsg.chars().next() {
errmsg = format!(
"{}{}",
c.to_ascii_lowercase(),
&errmsg[c.len_utf8()..]
);
}
}
crate::ported::utils::zerr(&format!("{}: {}", errmsg, cmd));
}
// c:881 — `_exit((eno == EACCES || eno == ENOEXEC) ? 126 : 127);`
if errno == libc::EACCES || errno == libc::ENOEXEC {
126
} else {
127
}
}
};
// Mark the subshell as exec-replaced so subsequent body
// commands skip — mirrors the post-execvp "child process
// is gone" reality in C. EXIT_PENDING + EXIT_VAL drive
// the next ERREXIT_CHECK to unwind to the subshell-end
// patch.
crate::ported::builtin::EXIT_VAL.store(status, std::sync::atomic::Ordering::Relaxed);
crate::ported::builtin::EXIT_PENDING.store(1, std::sync::atomic::Ordering::Relaxed);
return Value::Status(status);
}
// Both guards of exec_shlvl_decrement hold here: the in-subshell
// form returned at the branch above (so `subsh` is false), and this
// call replaces THIS process rather than a child (so `forked` is
// false).
exec_shlvl_decrement();
// c:Src/exec.c:4369 — `execute(args, cflags, use_defpath)` in this
// very process, exec'ing in place (see exec_execute). `exec -c`
// keeps the Command route below: C hands it `blank_env` (c:778-779),
// which carries no `_` either.
if !clean_env {
std::process::exit(exec_execute(&args, walk.exec_argv0.clone(), login, use_defpath, true));
}
let mut command = std::process::Command::new(&prog);
command.arg0(&display_argv0);
command.args(&rest);
if clean_env {
command.env_clear();
}
use std::os::unix::process::CommandExt;
// `exec` returns the OS error iff exec(2) failed; on success
// it never returns. Match zsh: print the error to stderr with
// the `exec` prefix and exit 127 (cmd not found) or 126 (not
// executable).
// c:Src/exec.c:4352 `closem(FDT_INTERNAL, 0)` before execve.
crate::lowfd::cloexec_internal_fds();
let err = command.exec();
// c:Src/exec.c:797 / c:872-876 — same format as in-subshell
// branch. arg0-has-/ → `<strerror>: <cmd>`; arg0-no-/ +
// ENOENT → `command not found: <cmd>`. Lowercase strerror
// first letter unless EIO. Bug #140 in docs/BUGS.md.
let errno = err.raw_os_error().unwrap_or(libc::ENOENT);
let has_slash = cmd.contains('/');
if !has_slash && errno == libc::ENOENT {
crate::ported::utils::zerr(&format!("command not found: {}", crate::ported::utils::nicedupstring(&cmd)));
} else {
let mut errmsg = crate::ported::compat::strerror(errno);
if errno != libc::EIO {
if let Some(c) = errmsg.chars().next() {
errmsg = format!("{}{}", c.to_ascii_lowercase(), &errmsg[c.len_utf8()..]);
}
}
crate::ported::utils::zerr(&format!("{}: {}", errmsg, cmd));
}
// c:881 — `_exit((eno == EACCES || eno == ENOEXEC) ? 126 : 127);`
let code = if errno == libc::EACCES || errno == libc::ENOEXEC {
126
} else {
127
};
std::process::exit(code);
});
reg_passthru!(vm, BUILTIN_LET, "let");
// Job control
reg_passthru!(vm, BUILTIN_JOBS, "jobs");
reg_passthru!(vm, BUILTIN_FG, "fg");
reg_passthru!(vm, BUILTIN_BG, "bg");
reg_passthru!(vm, BUILTIN_KILL, "kill");
reg_passthru!(vm, BUILTIN_DISOWN, "disown");
reg_passthru!(vm, BUILTIN_WAIT, "wait");
reg_passthru!(vm, BUILTIN_SUSPEND, "suspend");
// History — `fc` / `history` / `r` all route to `bin_fc` (zsh
// registers them as aliases of the same builtin per Src/builtin.c).
reg_passthru!(vm, BUILTIN_FC, "fc");
reg_passthru!(vm, BUILTIN_HISTORY, "history");
reg_passthru!(vm, BUILTIN_R, "r");
// Aliases — alias is `BINF_MAGICEQUALS` per Src/builtin.c:50.
// c:Src/exec.c:3298-3304 — when a builtin has BINF_MAGICEQUALS,
// execcmd_exec sets esprefork = PREFORK_TYPESET and calls
// `prefork(args, esprefork, NULL)` on the argv. prefork (subst.c:
// 100) drives `filesub` on each word (c:133), which (c:677-686)
// looks for the assignment Equals and runs `filesubstr` on the
// VALUE side. That's how `alias bad===` triggers equalsubstr's
// "= not found" via the inner Equals after the first `=`.
//
// The fusevm dispatch path doesn't go through execcmd_exec, so
// BUILTIN_ALIAS previously passed args straight to bin_alias with
// no expansion — `alias x=~/foo` stored literal `~/foo` (no tilde
// expand), `alias bad===` stored a broken entry without firing
// the "= not found" diagnostic. The prefork(PREFORK_TYPESET) runs
// per arg word via BUILTIN_MAGIC_EQUALS_PREFORK ops that
// compile_simple emits BEFORE the redirect scope opens (matching
// c:3304 prefork-before-addfd order), so the dispatch here is a
// plain passthrough — re-running prefork would double-fire the
// "= not found" diagnostic.
reg_passthru!(vm, BUILTIN_ALIAS, "alias");
// c:Src/exec.c:3298-3304 — per-word magic-equals prefork; see the
// const doc at BUILTIN_MAGIC_EQUALS_PREFORK. prefork's filesub
// trigger (subst.c:678 `strchr(*namptr+1, Equals)`) looks for the
// EQUALS TOKEN, not literal `=`. The fusevm path delivers args
// already-untokenized, so re-tokenize each element via
// `shtokenize` (the same call C's lexer makes implicitly when
// assembling the word) so prefork sees Equals tokens at `=`
// boundaries and Tilde tokens at `~` starts. After prefork
// expands, untokenize for storage.
vm.register_builtin(BUILTIN_MAGIC_EQUALS_PREFORK, |vm, _argc| {
let raw = vm.pop();
let inputs: Vec<String> = match raw {
Value::Array(items) => items.iter().map(|v| v.to_str()).collect(),
other => vec![other.to_str()],
};
let mut as_linklist: crate::ported::linklist::LinkList<String> = Default::default();
for s in &inputs {
let mut tokd = s.clone();
crate::ported::glob::shtokenize(&mut tokd);
as_linklist.push_back(tokd);
}
let mut rf = 0i32;
crate::ported::subst::prefork(
&mut as_linklist,
crate::ported::zsh_h::PREFORK_TYPESET,
&mut rf,
);
let mut expanded: Vec<String> = Vec::with_capacity(inputs.len());
while let Some(s) = as_linklist.pop_front() {
expanded.push(crate::ported::lex::untokenize(&s).to_string());
}
if expanded.len() == 1 {
Value::str(expanded.into_iter().next().unwrap())
} else {
Value::array(expanded.into_iter().map(Value::str).collect())
}
});
// Options. `setopt` (BIN_SETOPT=0) / `unsetopt` (BIN_UNSETOPT=1)
// share bin_setopt (options.c:580) — funcid bit discriminates
// the polarity via BUILTINS table entries.
reg_passthru!(vm, BUILTIN_SET, "set");
reg_passthru!(vm, BUILTIN_SETOPT, "setopt");
reg_passthru!(vm, BUILTIN_UNSETOPT, "unsetopt");
vm.register_builtin(BUILTIN_SHOPT, |vm, argc| {
let args = pop_args(vm, argc);
// AOP intercepts (zshrs extension): this opcode builtin has no
// user-function probe, so its advice runs here.
if let Some(status) = run_command_intercepts("shopt", &args) {
return Value::Status(status);
}
// `shopt` is a BASH builtin; no shell in the zsh family has it
// (c:Src/builtin.c:40-137 `builtins[]` has no `shopt` row), so
// outside bash drop-in mode the name must resolve through PATH
// like any other unknown command — `zsh -fc shopt` →
// `zsh:1: command not found: shopt`, rc 127.
//
// compile_zsh:3109 already forces `builtin_id = None` for the
// literal name so the compile-time `CallBuiltin` fast path is
// skipped, but that guard alone stopped working: the emitted
// `Op::CallFunction` reaches fusevm's run-time
// `VM::run_builtin_by_name` (fusevm-0.23.0/src/vm.rs:3348 →
// :979) once the host's `call_function` answers None, and THAT
// resolves the name straight back to this registered handler.
// mapfile / readarray / compopt survive only because their
// opcodes gate on the mode inside the handler; do the same
// here. Mirrors the BUILTIN_COMPGEN / BUILTIN_COMPLETE gates
// below, including their user-function precedence: a shell
// function named `shopt` (bashcompinit-style shims define one)
// still wins over the fall-through.
if !crate::extensions::dash_mode::bash_mode() {
if crate::ported::utils::getshfunc("shopt").is_some() {
let status = with_executor(|exec| exec.dispatch_function_call("shopt", &args))
.unwrap_or(127);
return Value::Status(status);
}
// PATH lookup with the literal name, so the diagnostic and
// the status are the shell's own external-miss ones
// (`zsh:1:` under --zsh, `zshrs:1:` natively) rather than a
// second hand-rolled spelling of them.
let status =
with_executor(|exec| exec.execute_external("shopt", &args, &[])).unwrap_or(127);
return Value::Status(status);
}
let status = crate::extensions::ext_builtins::shopt(&args);
Value::Status(status)
});
reg_passthru!(vm, BUILTIN_EMULATE, "emulate");
reg_passthru!(vm, BUILTIN_GETOPTS, "getopts");
reg_passthru!(vm, BUILTIN_AUTOLOAD, "autoload");
reg_passthru!(vm, BUILTIN_FUNCTIONS, "functions");
reg_passthru!(vm, BUILTIN_TRAP, "trap");
reg_passthru!(vm, BUILTIN_DIRS, "dirs");
// pushd / popd dispatch through canonical bin_cd via execbuiltin
// — the BUILTINS table at src/ported/builtin.rs:9298 wires
// `pushd` to bin_cd with funcid=BIN_PUSHD, and `popd` similarly
// with BIN_POPD. Without these reg_passthru lines the fusevm
// BUILTIN_PUSHD/POPD opcodes had no handler installed, so the
// emitted CallBuiltin(110, …) silently returned a no-op and the
// dirstack/$dirstack/pwd all stayed unchanged.
reg_passthru!(vm, BUILTIN_PUSHD, "pushd");
reg_passthru!(vm, BUILTIN_POPD, "popd");
// type / whence / where / which all route through `bin_whence`
// (canonical port at `src/ported/builtin.rs:3734` of
// `Src/builtin.c:3975`). Each gets its own opcode so funcid +
// defopts come from the BUILTINS table entry — execbuiltin
// applies them correctly via the module-level dispatch_builtin.
reg_passthru!(vm, BUILTIN_WHENCE, "whence");
reg_passthru!(vm, BUILTIN_TYPE, "type");
reg_passthru!(vm, BUILTIN_WHICH, "which");
reg_passthru!(vm, BUILTIN_WHERE, "where");
reg_passthru!(vm, BUILTIN_HASH, "hash");
reg_passthru!(vm, BUILTIN_REHASH, "rehash");
// `unhash`/`unalias`/`unfunction` share `bin_unhash` (Src/builtin.c
// c:4350) but each carries its own funcid (BIN_UNHASH /
// BIN_UNALIAS / BIN_UNFUNCTION) in the BUILTINS table.
reg_passthru!(vm, BUILTIN_UNHASH, "unhash");
vm.register_builtin(BUILTIN_UNALIAS, |vm, argc| {
let args = pop_args(vm, argc);
// AOP intercepts (zshrs extension): this opcode builtin has no
// user-function probe, so its advice runs here.
if let Some(status) = run_command_intercepts("unalias", &args) {
return Value::Status(status);
}
Value::Status(dispatch_builtin("unalias", args))
});
vm.register_builtin(BUILTIN_UNFUNCTION, |vm, argc| {
let args = pop_args(vm, argc);
Value::Status(dispatch_builtin("unfunction", args))
});
// Completion
vm.register_builtin(BUILTIN_COMPGEN, |vm, argc| {
let args = pop_args(vm, argc);
// c:Bug #475/#555 — `compgen` is a bash-only builtin. In
// `--zsh` mode emit "command not found" matching zsh's
// external-command lookup miss — UNLESS a user FUNCTION of
// that name exists: zsh has no such builtin, so bashcompinit's
// `compgen() {...}` definition wins the dispatch there. The
// unconditional 127 shadowed it and broke every
// bashcompinit-style completion file (zsh-more-completions
// _msync/_gocomplete/_qshell/_cw), spraying "command not
// found: complete" at every deferred compinit load.
// c:Src/exec.c:3105-3110 — a shell FUNCTION is consulted before the
// builtin table, UNCONDITIONALLY. This check used to sit INSIDE the
// `IS_ZSH_MODE` arm below, so in NATIVE mode zshrs's own extension
// builtin ran and a user function of the same name was ignored.
//
// Live cost: `bashcompinit` defines shell functions named `complete`
// and `compgen`, so in native mode `complete -F _fn cmd` silently
// registered NOTHING and returned 0:
// zsh -f _comps[zzbashc]=[_bash_complete -F _zzfn]
// zshrs -f _comps[zzbashc]=[] <- BUG
// zshrs --zsh -f _comps[zzbashc]=[_bash_complete -F _zzfn]
// That breaks every bashcompinit-bridged completer on the host.
//
// `try_user_fn_override` is the shape the correct registrations
// already use — `zsleep` (below) and `compdef` — which is why
// `compdef` alone always worked.
if let Some(status) = try_user_fn_override("compgen", &args) {
return Value::Status(status);
}
if crate::IS_ZSH_MODE.load(std::sync::atomic::Ordering::Relaxed) {
// No user function, and `compgen` is a bash-only builtin, so in a
// zsh-emulation shell it genuinely does not exist.
eprintln!("zsh:1: command not found: compgen");
let _ = args;
return Value::Status(127);
}
let status = with_executor(|exec| exec.builtin_compgen(&args));
Value::Status(status)
});
vm.register_builtin(BUILTIN_COMPLETE, |vm, argc| {
let args = pop_args(vm, argc);
// c:Bug #475 — `complete` is a bash-only builtin. Same gate +
// user-function precedence as BUILTIN_COMPGEN above.
// Same unconditional function-before-builtin rule as BUILTIN_COMPGEN
// above (c:Src/exec.c:3105-3110); this check was inside the mode gate
// too, so `bashcompinit`'s `complete` function lost to the extension
// builtin in native mode.
if let Some(status) = try_user_fn_override("complete", &args) {
return Value::Status(status);
}
if crate::IS_ZSH_MODE.load(std::sync::atomic::Ordering::Relaxed) {
eprintln!("zsh:1: command not found: complete");
let _ = args;
return Value::Status(127);
}
let status = with_executor(|exec| exec.builtin_complete(&args));
Value::Status(status)
});
reg_passthru!(vm, BUILTIN_COMPADD, "compadd");
reg_passthru!(vm, BUILTIN_COMPSET, "compset");
// See the const's doc comment for the contract. Stack (bottom→top):
// base, e1, …, eN — argc = N + 1.
// See the consts' doc comments.
vm.register_builtin(BUILTIN_TYPESET_POSTASSIGNS_BEGIN, |vm, argc| {
let n_post = (argc == 1).then(|| vm.pop().to_int().max(0) as usize);
TYPESET_POSTASSIGN_COUNT.with(|c| c.set(n_post));
let word_failed = with_executor(|exec| exec.current_command_glob_failed.replace(false));
TYPESET_WORD_GLOB_FAILED.with(|c| c.set(word_failed));
Value::Int(0)
});
// See BUILTIN_TYPESET_RESWD.
vm.register_builtin(BUILTIN_TYPESET_RESWD, |_vm, _argc| {
TYPESET_RESWD_DISPATCH.with(|c| c.set(true));
Value::Int(0)
});
// See BUILTIN_EXEC_DASH.
vm.register_builtin(BUILTIN_EXEC_DASH, |_vm, _argc| {
EXEC_DASH.with(|c| c.set(c.get() | EXEC_CARRIER_DASH));
Value::Int(0)
});
// See BUILTIN_EXECPLINE_CHILD_BLOCK / _UNBLOCK.
// The depth argument is absent from chunks compiled before the job frame
// was added (the autoload cache); those keep the signal half only.
vm.register_builtin(BUILTIN_EXECPLINE_CHILD_BLOCK, |vm, argc| {
crate::ported::signals_h::child_block(); // c:Src/exec.c:1748
// argc 2: the pipeline is a lone current-shell compound command.
let cursh = argc == 2 && vm.pop().to_int() != 0;
if argc >= 1 {
let depth = vm.pop().to_int() as u32;
let frame = vm as *const fusevm::VM as usize;
crate::exec_jobs::execpline_slot_open(frame, depth); // c:Src/exec.c:1656-1666
if cursh {
crate::exec_jobs::mark_thisjob_cursh(false); // c:Src/exec.c:3674-3680
}
}
Value::Int(0)
});
vm.register_builtin(BUILTIN_EXECPLINE_CHILD_UNBLOCK, |vm, argc| {
if argc == 1 {
let depth = vm.pop().to_int() as u32;
let frame = vm as *const fusevm::VM as usize;
crate::exec_jobs::execpline_slot_close(frame, depth); // c:Src/jobs.c:1754, exec.c:1981
}
crate::ported::signals_h::child_unblock(); // c:Src/exec.c:2017
Value::Int(0)
});
// See BUILTIN_ALIAS_ORIGIN.
vm.register_builtin(BUILTIN_ALIAS_ORIGIN, |vm, _argc| {
let command = vm.pop().to_str();
let body_words = vm.pop().to_int().max(0) as usize;
let alias = vm.pop().to_str();
ALIAS_ORIGIN.with(|a| *a.borrow_mut() = Some((alias, body_words, command)));
Value::Int(0)
});
// See BUILTIN_JOB_TEXT.
vm.register_builtin(BUILTIN_JOB_TEXT, |vm, _argc| {
let text = vm.pop();
JOB_TEXT.with(|t| *t.borrow_mut() = Some(text));
Value::Int(0)
});
// See BUILTIN_EXEC_FORKED_SIMPLE.
vm.register_builtin(BUILTIN_EXEC_FORKED_SIMPLE, |vm, argc| {
let mode = if argc >= 1 { vm.pop().to_int() } else { 0 };
let exiting_tail = mode != 0;
let this_vm = vm as *const fusevm::VM as usize;
if mode == 2 {
// The `-c` string's last command (compile_zsh exiting_tail_mode
// 2): the shell exits after it, so it is exec'd in place under
// the same conditions, and not being forked it takes SHLVL down
// (c:Src/exec.c:4334-4336).
if !fake_exec_blocked() {
EXEC_DASH.with(|c| c.set(c.get() | EXEC_CARRIER_FORKED | EXEC_CARRIER_SHLVL));
}
return Value::Int(0);
}
if exiting_tail {
// c:Src/exec.c:3715-3718 — the fake exec of an exiting list's
// last command needs `last1 == 1` (the compiler's mark, in a
// child that was forked) and no traps, no files for the job to
// clean up and no flock()s to keep: `nsigtrapped || havefiles()
// || fdtable_flocks` otherwise forks as usual.
if FORKED_SIMPLE_VM.with(|f| f.get()) != this_vm || fake_exec_blocked() {
return Value::Int(0);
}
}
if FORKED_SIMPLE_VM.with(|f| f.replace(0)) == this_vm {
EXEC_DASH.with(|c| c.set(c.get() | EXEC_CARRIER_FORKED));
}
Value::Int(0)
});
// See BUILTIN_PREFORK_CUT_CHECK.
vm.register_builtin(BUILTIN_PREFORK_CUT_CHECK, |_vm, _argc| {
// c:Src/subst.c:118-121 — prefork's word loop also returns once
// errflag is set, before expanding the next word.
let errflag_set = crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed)
& crate::ported::zsh_h::ERRFLAG_ERROR
!= 0;
Value::Bool(PREFORK_CUT.with(|c| c.get()) || errflag_set)
});
// See BUILTIN_GLOBLIST. c:Src/subst.c:488-498 globlist:
// badcshglob = 0;
// for (node = firstnode(list); !errflag && node; node = next)
// { next = nextnode(node); zglob(list, node, nocheck); }
// `badcshglob` stays with the per-word glob path (glob_expand_word_value
// feeds consume_badcshglob), so only the loop shape changes here.
vm.register_builtin(BUILTIN_GLOBLIST, |vm, argc| {
let text_mask = vm.pop().to_int() as u64;
let mask = vm.pop().to_int() as u64;
let n = (argc as usize).saturating_sub(2);
let mut words: Vec<Value> = (0..n).map(|_| vm.pop()).collect();
words.reverse();
let noglob =
opt_state_get("noglob").unwrap_or(false) || !opt_state_get("glob").unwrap_or(true);
let errflag_set = || {
(crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed)
& crate::ported::zsh_h::ERRFLAG_ERROR)
!= 0
};
// c:Src/subst.c:165-191 — prefork's second pass: filesub on each word
// in order, returning at the first error, before globlist ever runs.
// Only EXPAND_TEXT mode-10 words deferred theirs (see that arm).
for (i, word) in words.iter_mut().enumerate() {
if errflag_set() {
break; // c:187-190
}
// c:178 — `if (unset(SHFILEEXPANSION))`: under SH_FILE_EXPANSION
// the file expansion already ran in the first pass (c:122-138),
// BEFORE substitution, so a `~` that arrived through a GLOB_SUBST
// expansion stays literal (`emulate sh; v='~/x'; print $v`).
if i < 64
&& text_mask & (1u64 << i) != 0
&& !crate::ported::zsh_h::isset(crate::ported::zsh_h::SHFILEEXPANSION)
{
*word = filesub_deferred_word(std::mem::replace(word, Value::Int(0)));
}
}
let mut out: Vec<Value> = Vec::with_capacity(n);
for (i, word) in words.into_iter().enumerate() {
let stopped = errflag_set(); // c:494 `!errflag`
let bit = if i < 64 { 1u64 << i } else { 0 };
if stopped || (mask | text_mask) & bit == 0 {
out.push(word);
} else if text_mask & bit != 0 {
out.push(glob_tokenized_word(word, noglob)); // c:495 zglob
} else {
out.push(glob_word_noting_errflag(word, noglob)); // c:495 zglob
}
}
for v in out {
vm.push(v);
}
Value::Int(0)
});
vm.register_builtin(BUILTIN_TYPESET_POSTASSIGNS_END, |_vm, _argc| {
let word_failed = TYPESET_WORD_GLOB_FAILED.with(|c| c.replace(false));
let postassign_failed =
with_executor(|exec| exec.current_command_glob_failed.replace(word_failed));
TYPESET_POSTASSIGN_GLOB_FAILED.with(|c| c.set(postassign_failed));
Value::Int(0)
});
vm.register_builtin(BUILTIN_TYPESET_PAREN_PACK, |vm, argc| {
let mut vals: Vec<Value> = Vec::with_capacity(argc as usize);
for _ in 0..argc {
vals.push(vm.pop());
}
vals.reverse();
let mut it = vals.into_iter();
let mut out = it.next().map(|v| v.to_str()).unwrap_or_default();
for v in it {
match v {
// Array → splice items as separate elements (splat);
// empty array contributes nothing (empty elision).
Value::Array(items) => {
for item in items.iter() {
out.push('\u{1f}');
out.push_str(&item.to_str());
}
}
other => {
out.push('\u{1f}');
out.push_str(&other.to_str());
}
}
}
Value::str(out)
});
vm.register_builtin(BUILTIN_TYPESET_PAREN_CLOSE, |vm, _argc| {
let base = vm.pop().to_str();
Value::str(format!("{}\u{1f})", base))
});
vm.register_builtin(BUILTIN_COMPDEF, |vm, argc| {
let args = pop_args(vm, argc);
// AOP intercepts (zshrs extension): this opcode builtin has no
// user-function probe, so its advice runs here.
if let Some(status) = run_command_intercepts("compdef", &args) {
return Value::Status(status);
}
// ACTUALLY A ZSH FUNCTION: compdef is defined by `compinit`, it is
// never a builtin. Without the completion system set up it is
// command-not-found (127) in every mode — `zsh -f; compdef` prints
// "command not found: compdef". A user/compsys `compdef` FUNCTION
// (autoload compinit → compinit defines compdef) wins and runs the
// fast native impl; otherwise it's command-not-found. Previously the
// extension builtin ran in native mode (bare `compdef` → "I need
// arguments"), diverging from zsh.
// compinit installs a `compdef` function stub (see
// NATIVE_COMPDEF_MARKER) purely so `${+functions[compdef]}` is
// true; route that exact body to the fast native impl instead of
// dispatching the stub. A genuine user/compsys compdef function
// (any other body) still wins via try_user_fn_override below.
let is_native_stub = crate::ported::hashtable::shfunctab_lock()
.read()
.ok()
.and_then(|t| t.get("compdef").and_then(|shf| shf.body.clone()))
.map(|b| b.trim() == crate::extensions::ext_builtins::NATIVE_COMPDEF_MARKER)
.unwrap_or(false);
if is_native_stub {
return Value::Status(with_executor(|exec| exec.builtin_compdef(&args)));
}
if let Some(s) = try_user_fn_override("compdef", &args) {
return Value::Status(s);
}
if with_executor(|exec| exec.function_exists("compdef")) {
return Value::Status(with_executor(|exec| exec.builtin_compdef(&args)));
}
eprintln!("zsh:1: command not found: compdef");
Value::Status(127)
});
vm.register_builtin(BUILTIN_COMPINIT, |vm, argc| {
let args = pop_args(vm, argc);
// AOP intercepts (zshrs extension): this opcode builtin has no
// user-function probe, so its advice runs here.
if let Some(status) = run_command_intercepts("compinit", &args) {
return Value::Status(status);
}
// ACTUALLY A ZSH FUNCTION: compinit is a contrib FUNCTION (autoloaded
// from $fpath), never a builtin. Without `autoload -Uz compinit` it is
// command-not-found
// (127) in every mode — `zsh -f; compinit` prints
// "command not found: compinit". zshrs previously ran its builtin
// unconditionally, so bare `compinit` succeeded. Gate on a compinit
// function entry existing (which `autoload -Uz compinit` creates);
// once the user has autoloaded/defined it, run zshrs's implementation.
if !with_executor(|exec| exec.function_exists("compinit")) {
eprintln!("zsh:1: command not found: compinit");
let _ = args;
return Value::Status(127);
}
Value::Status(with_executor(|exec| exec.builtin_compinit(&args)))
});
reg_ext_overridable!(vm, BUILTIN_CDREPLAY, "cdreplay", builtin_cdreplay);
// Zsh-specific
reg_passthru!(vm, BUILTIN_ZSTYLE, "zstyle");
reg_passthru!(vm, BUILTIN_ZMODLOAD, "zmodload");
reg_passthru!(vm, BUILTIN_BINDKEY, "bindkey");
reg_passthru!(vm, BUILTIN_ZLE, "zle");
reg_passthru!(vm, BUILTIN_VARED, "vared");
reg_passthru!(vm, BUILTIN_ZCOMPILE, "zcompile");
reg_passthru!(vm, BUILTIN_ZFORMAT, "zformat");
reg_passthru!(vm, BUILTIN_ZPARSEOPTS, "zparseopts");
reg_passthru!(vm, BUILTIN_ZREGEXPARSE, "zregexparse");
// Resource limits
reg_passthru!(vm, BUILTIN_ULIMIT, "ulimit");
reg_passthru!(vm, BUILTIN_LIMIT, "limit");
reg_passthru!(vm, BUILTIN_UNLIMIT, "unlimit");
reg_passthru!(vm, BUILTIN_UMASK, "umask");
// Misc
reg_passthru!(vm, BUILTIN_TIMES, "times");
vm.register_builtin(BUILTIN_CALLER, |vm, argc| {
let args = pop_args(vm, argc);
// AOP intercepts (zshrs extension): this opcode builtin has no
// user-function probe, so its advice runs here.
if let Some(status) = run_command_intercepts("caller", &args) {
return Value::Status(status);
}
// c:Bug #475 — `caller` is a bash-only builtin. In `--zsh`
// mode emit the canonical "command not found" diagnostic
// and rc=127 matching zsh's external-command-lookup miss.
if crate::IS_ZSH_MODE.load(std::sync::atomic::Ordering::Relaxed) {
eprintln!("zsh:1: command not found: caller");
let _ = args;
return Value::Status(127);
}
Value::Status(with_executor(|exec| exec.builtin_caller(&args)))
});
vm.register_builtin(BUILTIN_HELP, |vm, argc| {
let args = pop_args(vm, argc);
// c:Bug #475 — `help` is a bash-only builtin. Same gate as
// BUILTIN_CALLER above.
if crate::IS_ZSH_MODE.load(std::sync::atomic::Ordering::Relaxed) {
eprintln!("zsh:1: command not found: help");
let _ = args;
return Value::Status(127);
}
Value::Status(with_executor(|exec| exec.builtin_help(&args)))
});
reg_passthru!(vm, BUILTIN_ENABLE, "enable");
reg_passthru!(vm, BUILTIN_DISABLE, "disable");
reg_passthru!(vm, BUILTIN_TTYCTL, "ttyctl");
reg_passthru!(vm, BUILTIN_SYNC, "sync");
reg_passthru!(vm, BUILTIN_MKDIR, "mkdir");
reg_passthru!(vm, BUILTIN_STRFTIME, "strftime");
vm.register_builtin(BUILTIN_ZSLEEP, |vm, argc| {
let args = pop_args(vm, argc);
// function > builtin: a user `zsleep() { … }` wins.
if let Some(s) = try_user_fn_override("zsleep", &args) {
return Value::Status(s);
}
Value::Status(crate::extensions::ext_builtins::zsleep(&args))
});
reg_passthru!(vm, BUILTIN_ZSYSTEM, "zsystem");
// PCRE
reg_passthru!(vm, BUILTIN_PCRE_COMPILE, "pcre_compile");
reg_passthru!(vm, BUILTIN_PCRE_MATCH, "pcre_match");
reg_passthru!(vm, BUILTIN_PCRE_STUDY, "pcre_study");
// Database (GDBM)
reg_passthru!(vm, BUILTIN_ZTIE, "ztie");
reg_passthru!(vm, BUILTIN_ZUNTIE, "zuntie");
reg_passthru!(vm, BUILTIN_ZGDBMPATH, "zgdbmpath");
// Prompt
//
// ACTUALLY ZSH FUNCTIONS: `promptinit` is Functions/Prompts/promptinit,
// and `prompt` is a function that file defines — neither is a builtin,
// but fusevm's name table hands both an opcode. Resolve them the way
// execcmd does a name that is not in builtintab (c:Src/exec.c:3484-3488
// shfunctab probe, else the command search): run the shell function,
// or fall to the external lookup and its "command not found".
//
// A native stand-in used to answer both names: a hard-coded theme list
// (one of them, `minimal`, not shipped by 5.9) in place of promptinit's
// `$^fpath/prompt_*_setup(N)` scan, so a user's own themes were never
// listed, and a `prompt` that shadowed the real function even after
// promptinit had defined it — `prompt -l` printed one theme per line,
// `prompt -h THEME` never showed the theme's help, and `prompt adam1`
// assigned a canned PS1 without running prompt_adam1_setup.
vm.register_builtin(BUILTIN_PROMPTINIT, |vm, argc| {
let args = pop_args(vm, argc);
if let Some(s) = try_user_fn_override("promptinit", &args) {
return Value::Status(s);
}
let argv: Vec<String> = std::iter::once("promptinit".to_string()).chain(args).collect();
Value::Status(with_executor(|exec| exec.host_exec_external(&argv)))
});
vm.register_builtin(BUILTIN_PROMPT, |vm, argc| {
let args = pop_args(vm, argc);
if let Some(s) = try_user_fn_override("prompt", &args) {
return Value::Status(s);
}
let argv: Vec<String> = std::iter::once("prompt".to_string()).chain(args).collect();
Value::Status(with_executor(|exec| exec.host_exec_external(&argv)))
});
// Async / Parallel (zshrs extensions) — all overridable by a
// same-named user function (function > builtin).
reg_ext_overridable!(vm, BUILTIN_ASYNC, "async", builtin_async);
reg_ext_overridable!(vm, BUILTIN_AWAIT, "await", builtin_await);
reg_ext_overridable!(vm, BUILTIN_PMAP, "pmap", builtin_pmap);
reg_ext_overridable!(vm, BUILTIN_PGREP, "pgrep", builtin_pgrep);
reg_ext_overridable!(vm, BUILTIN_PEACH, "peach", builtin_peach);
reg_ext_overridable!(vm, BUILTIN_BARRIER, "barrier", builtin_barrier);
// `ai` — zshrs-original LLM builtin (`src/extensions/ai.rs`).
// fusevm's name registry maps `"ai"` to `BUILTIN_AI` (264), so the
// compiler emits `CallBuiltin(BUILTIN_AI)` for a literal `ai`. The VM
// silently skips an unregistered id: without this line `ai` is a no-op.
reg_ext_overridable!(vm, BUILTIN_AI, "ai", builtin_ai);
// Intercept (AOP)
reg_ext_overridable!(vm, BUILTIN_INTERCEPT, "intercept", builtin_intercept);
reg_ext_overridable!(
vm,
BUILTIN_INTERCEPT_PROCEED,
"intercept_proceed",
builtin_intercept_proceed
);
// Debug / Profile
reg_ext_overridable!(vm, BUILTIN_DOCTOR, "doctor", builtin_doctor);
reg_ext_overridable!(vm, BUILTIN_DBVIEW, "dbview", builtin_dbview);
reg_ext_overridable!(vm, BUILTIN_PROFILE, "profile", builtin_profile);
reg_ext_overridable!(vm, BUILTIN_PROVENANCE, "provenance", builtin_provenance);
reg_passthru!(vm, BUILTIN_ZPROF, "zprof");
// ═══════════════════════════════════════════════════════════════════════
// Coreutils builtins (anti-fork, gated by !posix_mode)
//
// All of these are routinely wrapped by user functions in real
// dotfiles (zpwr, oh-my-zsh, etc.) — `cat() { ... }`, `ls() { ... }`,
// `find() { ... }`. Each handler MUST consult try_user_fn_override
// first (via reg_overridable!) so the user definition wins, matching
// zsh's alias → function → builtin dispatch order.
// ═══════════════════════════════════════════════════════════════════════
reg_overridable!(vm, BUILTIN_CAT, "cat", builtin_cat);
reg_overridable!(vm, BUILTIN_HEAD, "head", builtin_head);
reg_overridable!(vm, BUILTIN_TAIL, "tail", builtin_tail);
reg_overridable!(vm, BUILTIN_WC, "wc", builtin_wc);
reg_overridable!(vm, BUILTIN_BASENAME, "basename", builtin_basename);
reg_overridable!(vm, BUILTIN_DIRNAME, "dirname", builtin_dirname);
reg_overridable!(vm, BUILTIN_TOUCH, "touch", builtin_touch);
reg_overridable!(vm, BUILTIN_REALPATH, "realpath", builtin_realpath);
reg_overridable!(vm, BUILTIN_SORT, "sort", builtin_sort);
reg_overridable!(vm, BUILTIN_FIND, "find", builtin_find);
reg_overridable!(vm, BUILTIN_UNIQ, "uniq", builtin_uniq);
reg_overridable!(vm, BUILTIN_CUT, "cut", builtin_cut);
reg_overridable!(vm, BUILTIN_TR, "tr", builtin_tr);
reg_overridable!(vm, BUILTIN_SEQ, "seq", builtin_seq);
reg_overridable!(vm, BUILTIN_REV, "rev", builtin_rev);
reg_overridable!(vm, BUILTIN_TEE, "tee", builtin_tee);
reg_overridable!(vm, BUILTIN_SLEEP, "sleep", builtin_sleep);
reg_overridable!(vm, BUILTIN_WHOAMI, "whoami", builtin_whoami);
reg_overridable!(vm, BUILTIN_ID, "id", builtin_id);
reg_overridable!(vm, BUILTIN_HOSTNAME, "hostname", builtin_hostname);
reg_overridable!(vm, BUILTIN_UNAME, "uname", builtin_uname);
reg_overridable!(vm, BUILTIN_DATE, "date", builtin_date);
reg_overridable!(vm, BUILTIN_MKTEMP, "mktemp", builtin_mktemp);
// `cp` — zshrs extension (NOT in upstream zsh; upstream's
// zsh/files module ships `ln`/`mv`/`rm`/`chmod`/`chown` but no
// `cp`). In-process implementation in
// `ext_builtins::cp_impl` — recursive copy with -r/-R, -f, -i,
// -n, -p (chown + utimensat), -v. ID 263 is the first slot
// past fusevm's built-in range (260-262) and before BUILTIN_MAX
// (280).
/// `BUILTIN_CP` constant.
pub const BUILTIN_CP: u16 = 263;
reg_overridable!(vm, BUILTIN_CP, "cp", builtin_cp);
// Pipeline execution — bytecode-native fork-per-stage. Pops N sub-chunk
// indices, forks N children with stdin/stdout wired through N-1 pipes,
// each child runs its stage's compiled bytecode and exits. Parent waits
// and returns the last stage's status.
//
// Caveats: post-fork in a multi-threaded program, only async-signal-safe
// ops are POSIX-safe. We violate this (running the bytecode VM after fork
// touches mutexes like REGEX_CACHE). In practice, most pipeline stages
// don't touch shared mutex state — externals fork/exec away, builtins do
// pure I/O. Risks are bounded; if a stage does touch a held mutex, the
// child deadlocks.
vm.register_builtin(BUILTIN_RUN_PIPELINE, |vm, argc| {
let n = argc as usize;
if n == 0 {
return Value::Status(0);
}
// c:Src/exec.c — every pipeline stage forks from the current
// shell state, so each stage observes the pre-pipeline $? until
// it runs its own command. Stage sub-VMs start fresh with
// last_status=0, so seed them with the parent's lastval; without
// this `false; echo $? | cat` prints 0 instead of zsh's 1.
let parent_status = vm.last_status;
// Pop N sub-chunk indices (LIFO → reverse to stage order)
let mut indices: Vec<u16> = Vec::with_capacity(n);
for _ in 0..n {
indices.push(vm.pop().to_int() as u16);
}
indices.reverse();
// Clone each stage's sub-chunk
let stages: Vec<fusevm::Chunk> = indices
.iter()
.filter_map(|&i| vm.chunk.sub_chunks.get(i as usize).cloned())
.collect();
if stages.len() != n {
return Value::Status(1);
}
// Single stage — no pipe, just run inline
if n == 1 {
let stage = stages.into_iter().next().unwrap();
crate::fusevm_disasm::maybe_print_stdout("pipeline:single", &stage);
let mut stage_vm = fusevm::VM::new(stage);
stage_vm.last_status = parent_status;
register_builtins(&mut stage_vm);
let _ = stage_vm.run();
return Value::Status(stage_vm.last_status);
}
// A `time`d pipeline: record each forked stage for dumptime (see
// TimedPipeline). Taken, so a pipeline nested in a stage runs untimed.
let mut timed = TIMED_PIPELINE
.with(|t| t.borrow_mut().take())
.filter(|t| t.texts.len() == n);
let mut child_started: Vec<std::time::Instant> = Vec::with_capacity(n - 1);
// c:Src/exec.c:1748 — `child_block();` before any stage is forked,
// held through the in-shell last stage and the stage waits below,
// released at c:2017. See ChildBlockSpan.
#[cfg(unix)]
let _child_block = ChildBlockSpan::enter();
// Build N-1 pipes
let mut pipes: Vec<(i32, i32)> = Vec::with_capacity(n - 1);
for _ in 0..n - 1 {
let mut fds = [0i32; 2];
if unsafe { libc::pipe(fds.as_mut_ptr()) } < 0 {
// Cleanup any pipes we already created
for (r, w) in &pipes {
unsafe {
libc::close(*r);
libc::close(*w);
}
}
return Value::Status(1);
}
pipes.push((fds[0], fds[1]));
}
// zsh runs the LAST stage of a pipeline in the CURRENT shell
// (not a forked child) so a trailing `read x` keeps its
// assignment in the parent. Other shells (bash) fork every
// stage. Honor zsh by leaving stage N-1 inline. Forks the
// first N-1 stages with fork(); runs the last in this process
// with stdin dup2'd to the last pipe's read end and stdout
// restored after.
let last_idx = n - 1;
let stages_vec: Vec<fusevm::Chunk> = stages.into_iter().collect();
let mut child_pids: Vec<libc::pid_t> = Vec::with_capacity(n - 1);
for (i, chunk) in stages_vec.iter().take(last_idx).enumerate() {
match unsafe { libc::fork() } {
-1 => {
// fork failed — kill any children we already started
for pid in &child_pids {
unsafe { libc::kill(*pid, libc::SIGTERM) };
}
for (r, w) in &pipes {
unsafe {
libc::close(*r);
libc::close(*w);
}
}
return Value::Status(1);
}
0 => {
forked_child_subsh_levels(); // c:Src/exec.c:1221
EXECCMD_FORKED.with(|f| f.set(true)); // c:Src/exec.c:3063 `last1 = forked = 1`
// Reset SIGPIPE to default so a broken-pipe write
// kills the child cleanly instead of triggering a
// Rust println! panic. The parent shell ignores
// SIGPIPE so it can handle EPIPE itself, but child
// pipeline stages should die quietly when their
// downstream stage closes early (e.g. `seq | head -3`).
unsafe {
libc::signal(libc::SIGPIPE, libc::SIG_DFL);
}
// c:Src/exec.c — pipeline children are forked
// subshells; their EXIT trap context is reset so
// the parent's `trap '...' EXIT` doesn't fire when
// the child exits. Mirror by dropping EXIT from
// the inherited traps_table inside the child.
// c:Src/exec.c:2917-2918 — a forked PIPELINE stage enters
// the subshell with ESUB_KEEPTRAP:
// if ((type != WC_SUBSH) && !(how & Z_ASYNC))
// flags |= ESUB_KEEPTRAP;
// so entersubsh's c:1127 reset loop is SKIPPED and the
// stage keeps the parent's traps. Only the EXIT trap goes,
// so the parent's `trap '…' EXIT` does not fire when the
// stage exits. Applying the full reset here instead was
// wrong: it wiped the inherited-SIGQUIT record and the
// parent's other trap flags inside every pipeline stage.
//
// Drop it from BOTH stores, since a body-less entry lives
// only in sigtrapped and the `trap` listing now reads it
// (c:Src/builtin.c:7358-7361); clearing just the body left
// `trap | grep -c EXIT` reporting the stale flag.
if let Ok(mut tt) = crate::ported::builtin::traps_table().lock() {
tt.remove("EXIT");
}
if let Ok(mut st) = crate::ported::signals::sigtrapped.lock() {
if let Some(slot) = st.get_mut(crate::ported::signals_h::SIGEXIT as usize) {
*slot = 0;
}
}
// c:Src/exec.c:2862 → 1219 — pipeline children run
// entersubsh with ESUB_PGRP, which clears the job
// table (clearjobtab, Src/jobs.c:1780). Without
// this, `sleep 5 & jobs -p | wc -l` reports 1 in
// the forked stage where zsh reports 0. The fork
// already copy-isolates the statics, so mutating
// them here can't leak to the parent.
with_executor(|exec| {
let monitor =
crate::ported::zsh_h::isset(crate::ported::zsh_h::MONITOR) as i32;
crate::ported::jobs::clearjobtab(&mut exec.jobs, monitor);
});
// c:Src/exec.c:1153-1154 — the same entersubsh call sets
// `subsh = 1` in the forked stage. PRINT_EXIT_VALUE reads
// it (c:4309 `&& !subsh`), which is why zsh prints nothing
// for the failing stage of `false | true`.
crate::ported::exec::subsh.store(1, std::sync::atomic::Ordering::Relaxed);
*crate::ported::jobs::THISJOB
.get_or_init(|| std::sync::Mutex::new(-1))
.lock()
.unwrap() = -1;
// c:Src/exec.c:3720-3724 — the stage's own fds go
// onto 0/1 only AFTER its argument words have been
// expanded (prefork c:3304 / globlist c:3702), so
// park them and let the stage chunk's
// BUILTIN_PIPE_FDS_INSTALL do the dup2 at the
// C-faithful point. `print -rl -- c a b |
// print -r -- "[$(cat)]" | cat` therefore prints
// `[]` — the middle stage's `$(cat)` reads the
// shell's stdin, not the pipe.
let in_fd = if i > 0 { pipes[i - 1].0 } else { -1 };
let out_fd = pipes[i].1;
// (Pipe-output MULTIOS marking — c:Src/exec.c:3724 —
// is emitted INTO the stage chunk by compile_pipe
// via BUILTIN_PIPE_OUTPUT_MARK, gated on the stage's
// top-level command actually carrying redirects, so
// a nested `{ echo a > f; } | cat` body redirect
// does not wrongly join the pipe.)
// Close every pipe fd this stage doesn't need. The
// two it does keep are closed by the install op
// right after their dup2.
for (r, w) in &pipes {
unsafe {
if *r != in_fd && *r != out_fd {
libc::close(*r);
}
if *w != in_fd && *w != out_fd {
libc::close(*w);
}
}
}
stage_fds_park(in_fd, out_fd);
// Run this stage's bytecode on a fresh VM
crate::fusevm_disasm::maybe_print_stdout(
&format!("pipeline:child:stage:{i}"),
chunk,
);
let mut stage_vm = fusevm::VM::new(chunk.clone());
stage_vm.last_status = parent_status;
register_builtins(&mut stage_vm);
let _ = stage_vm.run();
// Flush any buffered output before exiting
let _ = std::io::stdout().flush();
let _ = std::io::stderr().flush();
std::process::exit(stage_vm.last_status);
}
pid => {
child_pids.push(pid);
child_started.push(std::time::Instant::now()); // c:Src/jobs.c:1480 bgtime
}
}
}
// Parent runs the LAST stage inline. Save stdin, park the last
// pipe's read end for the chunk's BUILTIN_PIPE_FDS_INSTALL
// (c:Src/exec.c:3722 `addfd(..., 0, input, 0, NULL)` — after
// the stage's args are expanded, so `… | print -r -- "[$(cat)]"`
// has its `$(cat)` read the shell's stdin, not the pipe), run
// the chunk, restore stdin. Close every other pipe fd so the
// producer side gets EOF when the last upstream stage exits.
// Shell-internal save — keep it out of the script's fd range (movefd,
// c:Src/exec.c:2425).
let saved_stdin = unsafe { libc::fcntl(libc::STDIN_FILENO, libc::F_DUPFD_CLOEXEC, 10) };
let last_in_fd = if last_idx > 0 {
pipes[last_idx - 1].0
} else {
-1
};
// Close all pipe fds in the parent except the one the last
// stage still has to install. (Children already have their own
// copies; the install op closes the read end after its dup2.)
for (r, w) in &pipes {
unsafe {
if *r != last_in_fd {
libc::close(*r);
}
libc::close(*w);
}
}
let outer_stage_fds = stage_fds_park(last_in_fd, -1);
// Run the last stage's bytecode on a sub-VM with the host wired up.
// By default (zsh semantics) the sub-VM runs IN THIS PROCESS so the
// last stage's reads/assignments update the parent's state directly
// (`echo x | read v` sets $v; `cmd | mapfile arr` sets arr).
//
// !!! BASH-MODE GATE !!! bash forks EVERY pipeline stage (unless
// `shopt -s lastpipe`), so the last stage runs in a SUBSHELL and its
// variable/array assignments do NOT persist — `echo x | read v; echo
// $v` prints an empty line, `cmd | mapfile arr` leaves arr unset.
// Fork the last stage under `--bash` to match. The parent's existing
// `stage_fds_take()` below closes its `last_in_fd` copy; the forked
// child inherits the parked pipe fd and installs it onto stdin, and
// the writer stages (already forked) supply its input.
//
// c:Src/exec.c:3042-3043 — zsh itself forks the last stage of a
// multi-stage pipeline under sh emulation:
// if ((how & Z_ASYNC) || output ||
// (last1 == 2 && input && EMULATION(EMULATE_SH))) {
// ... execcmd_fork(...)
// so `emulate sh -c 'echo x | read v; echo $v'` prints an empty
// line. ksh emulation keeps the in-shell last stage.
let mut last_proc: Option<crate::ported::zsh_h::process> = None;
// The pdksh line (mksh / pdksh) forks the last stage too: `mksh -c 'echo x |
// read v; echo $v'` prints an empty line. ksh93 keeps it in the shell.
// `shopt -s lastpipe` keeps bash's last stage in the current shell too.
let last_stage_status = if (crate::dash_mode::bash_mode()
&& crate::dash_mode::bash_shopt_get("lastpipe") != Some(true))
|| crate::dash_mode::pdksh_family()
|| (crate::ported::zsh_h::EMULATION(crate::ported::zsh_h::EMULATE_SH)
&& !crate::dash_mode::bash_mode())
{
let last_chunk = stages_vec.into_iter().last().unwrap();
crate::fusevm_disasm::maybe_print_stdout("pipeline:last", &last_chunk);
match unsafe { libc::fork() } {
-1 => 1,
0 => {
forked_child_subsh_levels(); // c:Src/exec.c:1221
EXECCMD_FORKED.with(|f| f.set(true)); // c:Src/exec.c:3063 `last1 = forked = 1`
// Subshell child: run the last stage, then _exit with its
// status. Reset SIGPIPE + drop the EXIT trap like the
// other pipeline children above.
unsafe { libc::signal(libc::SIGPIPE, libc::SIG_DFL) };
if let Ok(mut t) = crate::ported::builtin::traps_table().lock() {
t.remove("EXIT");
}
let mut stage_vm = fusevm::VM::new(last_chunk);
stage_vm.last_status = parent_status;
register_builtins(&mut stage_vm);
stage_vm.set_shell_host(Box::new(ZshrsHost));
let _ = stage_vm.run();
let st = stage_vm.last_status;
let _ = std::io::stdout().flush();
let _ = std::io::stderr().flush();
unsafe { libc::_exit(st) };
}
pid => {
let started = std::time::Instant::now();
// Same EINTR retry as the stage reap loop below.
let waited = wait4_eintr(pid);
// c:Src/exec.c:3042-3043 — this last stage forked, so it
// is a process of a timed job whatever its command is.
if let (Some(t), Some((status, ru))) = (timed.as_ref(), waited.as_ref()) {
last_proc = Some(timed_proc(pid, &t.texts[n - 1], *status, ru, started));
}
match waited.map(|(status, _)| status) {
Some(status) if libc::WIFEXITED(status) => libc::WEXITSTATUS(status),
Some(status) if libc::WIFSIGNALED(status) => 128 + libc::WTERMSIG(status),
Some(_) => 1,
None => 0,
}
}
}
} else {
let last_chunk = stages_vec.into_iter().last().unwrap();
crate::fusevm_disasm::maybe_print_stdout("pipeline:last", &last_chunk);
// A timed pipeline's in-shell last stage is a process of the job
// only when it forks (TimedPipeline::last_forks); its times are
// those of the externals it waits for (FG_CHILD_TIMES). Not a
// RUSAGE_CHILDREN delta: the reaper on another thread can collect
// a forked stage inside this window and its usage would land here.
let last_timed = timed.as_ref().filter(|t| t.last_forks).map(|_| {
FG_CHILD_TIMES.with(|c| c.set(Some((0, 0))));
std::time::Instant::now()
});
let mut stage_vm = fusevm::VM::new(last_chunk);
stage_vm.last_status = parent_status;
register_builtins(&mut stage_vm);
stage_vm.set_shell_host(Box::new(ZshrsHost));
// The externals this stage waits for are not the job's process
// group leader (the first stage is), so they skip update_job's
// foreground tail; see exec_jobs::foreground_job_signalled.
crate::exec_jobs::NOT_JOB_LEADER.with(|d| d.set(d.get() + 1));
let _ = stage_vm.run();
crate::exec_jobs::NOT_JOB_LEADER.with(|d| d.set(d.get() - 1));
let _ = std::io::stdout().flush();
let _ = std::io::stderr().flush();
if let (Some(t), Some(started)) = (timed.as_ref(), last_timed) {
let (utime, stime) = FG_CHILD_TIMES.with(|c| c.take()).unwrap_or((0, 0));
let mut ru: libc::rusage = unsafe { std::mem::zeroed() };
ru.ru_utime = usec_timeval(utime);
ru.ru_stime = usec_timeval(stime);
let status = (stage_vm.last_status & 0xff) << 8; // W_EXITCODE
last_proc = Some(timed_proc(0, &t.texts[n - 1], status, &ru, started));
}
stage_vm.last_status
};
// Reclaim the read end if the stage chunk never reached its
// install op (an expansion error aborted it, or the stage was
// a shape that dispatches without one), then restore the outer
// stage's still-pending fds for a nested pipeline.
let (leftover_in, _) = stage_fds_take();
if leftover_in >= 0 {
unsafe { libc::close(leftover_in) };
}
stage_fds_park(outer_stage_fds.0, outer_stage_fds.1);
// Restore stdin
if saved_stdin >= 0 {
unsafe {
libc::dup2(saved_stdin, libc::STDIN_FILENO);
libc::close(saved_stdin);
}
}
// Wait for all forked stages, capture per-stage statuses for PIPESTATUS.
let mut pipestatus: Vec<i32> = Vec::with_capacity(n);
for (i, pid) in child_pids.into_iter().enumerate() {
// EINTR retry: the SIGCHLD handler interrupts this wait and
// leaves `status` untouched, which used to read back as a
// clean exit 0 for every forked stage. See waitpid_eintr.
let waited = match timed.as_mut() {
Some(t) => wait4_eintr(pid).map(|(status, ru)| {
let started = child_started.get(i).copied().unwrap_or_else(std::time::Instant::now);
t.procs.push(timed_proc(pid, &t.texts[i], status, &ru, started));
status
}),
None => waitpid_eintr(pid),
};
if i == 0 {
// c:Src/jobs.c:497-498 — `if (pn->pid == jn->gleader) status =
// pn->status;`: the first stage leads the job's process group,
// and its status is the one update_job's foreground tail reads.
if let Some(status) = waited {
crate::exec_jobs::foreground_job_signalled(status);
}
}
let s = match waited {
Some(status) if libc::WIFEXITED(status) => libc::WEXITSTATUS(status),
Some(status) if libc::WIFSIGNALED(status) => 128 + libc::WTERMSIG(status),
Some(_) => 1,
// Unreapable (ECHILD — the handler got there first).
// Nothing better to report than success; the stage's
// real status is gone.
None => 0,
};
pipestatus.push(s);
}
// Append the in-parent last-stage status so `pipestatus` ends
// with N entries (one per stage).
pipestatus.push(last_stage_status);
if let Some(mut t) = timed {
t.procs.extend(last_proc);
TIMED_PIPELINE.with(|slot| *slot.borrow_mut() = Some(t));
}
// Pipeline exit status: by default, the LAST stage's status.
// With `setopt pipefail` (or `set -o pipefail`), use the
// first non-zero stage status (so failures earlier in the
// pipeline propagate even if the last stage succeeded).
let pipefail_on = with_executor(|exec| opt_state_get("pipefail").unwrap_or(false));
let last_status = if pipefail_on {
pipestatus
.iter()
.copied()
.rfind(|&s| s != 0)
.or_else(|| pipestatus.last().copied())
.unwrap_or(0)
} else {
*pipestatus.last().unwrap_or(&0)
};
// c:Src/params.c:265,438 — only `pipestatus` (lowercase) is the
// zsh special parameter; bash's `PIPESTATUS` doesn't exist in
// zsh's special-params table. Prior port also populated
// `PIPESTATUS` "for portability" — but that's a real divergence
// from zsh: a script doing `[[ -z $PIPESTATUS ]]` to detect
// zsh-vs-bash would mis-classify. Bug #64 in docs/BUGS.md.
// c:Src/jobs.c:438-441 (storepipestats) — the per-stage statuses go
// into the C globals `pipestats[]` / `numpipestats` whatever the
// emulation. Under sh/ksh `pipestatus` is not a special parameter
// (no PM_SPECIAL, so the paramtab mirror below is skipped), but the
// globals still carry the pipeline — `--mksh`'s `$PIPESTATUS` and
// doshfunc's funcsave snapshot (c:Src/exec.c:5864) read them.
{
use crate::ported::jobs::{NUMPIPESTATS, PIPESTATS};
use std::sync::Mutex;
let count = pipestatus.len().min(crate::ported::zsh_h::MAX_PIPESTATS);
let p = PIPESTATS.get_or_init(|| Mutex::new([0; crate::ported::zsh_h::MAX_PIPESTATS]));
if let Ok(mut pguard) = p.lock() {
pguard[..count].copy_from_slice(&pipestatus[..count]); // c:438 memcpy
}
let n = NUMPIPESTATS.get_or_init(|| Mutex::new(0));
if let Ok(mut nguard) = n.lock() {
*nguard = count; // c:441
}
}
with_executor(|exec| {
// c:Src/jobs.c:83 `int pipestats[MAX_PIPESTATS]` — the values
// live in that C GLOBAL, reached through `pipestatus`'s GSU
// (c:Src/params.c pipestatgetfn). A `typeset -h +g pipestatus`
// local shadow carries no PM_SPECIAL and no GSU, so the C
// writer cannot reach it; skip the paramtab mirror likewise or
// the shadow loses its PM_UNSET (B02typeset.ztst:37,38).
let shadowed = crate::ported::params::paramtab()
.read()
.ok()
.and_then(|t| {
t.get("pipestatus")
.map(|pm| (pm.node.flags & crate::ported::zsh_h::PM_SPECIAL as i32) == 0)
})
.unwrap_or(false);
if !shadowed {
let strs: Vec<String> = pipestatus.iter().map(|s| s.to_string()).collect();
exec.set_array("pipestatus".to_string(), strs);
}
});
Value::Status(last_status)
});
// Array→String join. Pops one value; if it's an Array (e.g. from Op::Glob),
// joins string-coerced elements with a single space. Pass-through for
// non-arrays so the op is safe to chain after any String-or-Array producer.
// Scalar coercion of an assembled word: pop a Value; if it's an
// Array (produced by a splice segment like `"$@"` / `"${arr[@]}"`),
// IFS[0]-join it to a single scalar; a scalar passes through. This
// is the assignment-context coercion C zsh applies in multsub when
// the expansion is the RHS of a SCALAR assignment (Src/subst.c
// c:3032 sepjoin under ssub) — `v="$@"` joins the positionals with
// ${IFS[1]} rather than leaving an array whose splat would lose all
// but the first element. Joins via sepjoin so a custom / empty IFS
// is honored (not a hardcoded space).
vm.register_builtin(BUILTIN_ARRAY_JOIN, |vm, _argc| {
let val = vm.pop();
match val {
Value::Array(items) => {
let strs: Vec<String> = items.iter().map(|v| v.to_str()).collect();
Value::str(crate::ported::utils::sepjoin(&strs, None))
}
other => other,
}
});
// `cmd &` background execution. Compile_list emits this for any item
// followed by ListOp::Amp: the job text + the cmd's sub-chunk index are
// pushed, then this builtin pops both, looks up the chunk, forks. The
// child detaches via setsid (so SIGINT to the foreground job doesn't kill
// it), runs the bytecode on a fresh VM with builtins re-registered, exits
// with the last status. The parent registers the job in the canonical
// JOBTAB (c:Src/exec.c::execpline Z_ASYNC arm) and returns Status(0).
vm.register_builtin(BUILTIN_RUN_BG, |vm, _argc| {
// `&|` / `&!` set disown → the job is dropped from the table (no
// `[N] pid` announcement, no `[N] done`), matching C exec.c:1752-1758.
let disown = vm.pop().to_int() != 0;
// Stage count. 1 for anything but a multi-stage pipeline; the compiler
// pushes one (text, sub_chunk_index) pair per stage ahead of it.
let nstages = vm.pop().to_int().max(1) as usize;
let mut stages: Vec<(usize, String)> = Vec::with_capacity(nstages);
for _ in 0..nstages {
let idx = vm.pop().to_int() as usize;
let text = vm.pop().to_str();
stages.push((idx, text));
}
stages.reverse(); // popped last-stage-first
let chunks: Vec<fusevm::Chunk> = match stages
.iter()
.map(|(i, _)| vm.chunk.sub_chunks.get(*i).cloned())
.collect::<Option<Vec<_>>>()
{
Some(c) => c,
None => return Value::Status(1),
};
// c:Src/exec.c:1748 — `child_block();`, released by the async arm's
// `child_unblock();` (c:1815) once the job is registered. A child
// that exits at once must not be reaped before `addproc` knows its
// pid. See ChildBlockSpan.
#[cfg(unix)]
let _child_block = ChildBlockSpan::enter();
if nstages > 1 {
// c:Src/exec.c:1795 — the Z_ASYNC arm runs execpline2 in THIS
// shell, so every stage is forked here and becomes its own proc
// entry on the one job. Build the N-1 pipes, fork N children, and
// addproc each; nothing in the parent waits.
let mut pipes: Vec<(i32, i32)> = Vec::with_capacity(nstages - 1);
for _ in 0..nstages - 1 {
let mut fds = [0i32; 2];
if unsafe { libc::pipe(fds.as_mut_ptr()) } < 0 {
for (r, w) in &pipes {
unsafe {
libc::close(*r);
libc::close(*w);
}
}
return Value::Status(1);
}
pipes.push((fds[0], fds[1]));
}
// c:Src/exec.c:2916 — every async stage enters the subshell with
// ESUB_PGRP, so they all land in ONE new process group led by the
// first stage (c:Src/jobs.c:1582-1583 sets jn->gleader to the first
// proc's pid). Keeping them together is what makes `kill %1` reach
// the whole pipeline. Both parent and child set the pgid so neither
// side can lose the race.
let mut gleader: libc::pid_t = 0;
let mut procs: Vec<(libc::pid_t, String)> = Vec::with_capacity(nstages);
for (i, chunk) in chunks.iter().enumerate() {
match unsafe { libc::fork() } {
-1 => {
for (pid, _) in &procs {
unsafe { libc::kill(*pid, libc::SIGTERM) };
}
for (r, w) in &pipes {
unsafe {
libc::close(*r);
libc::close(*w);
}
}
return Value::Status(1);
}
0 => {
forked_child_subsh_levels(); // c:Src/exec.c:1221
EXECCMD_FORKED.with(|f| f.set(true)); // c:Src/exec.c:3063 `last1 = forked = 1`
// c:Src/exec.c:2916 — every async stage runs
// `entersubsh(ESUB_ASYNC|ESUB_PGRP)`: traps reset, MONITOR
// off, SIGINT/SIGQUIT ignored without job control, the
// interactive SIGTERM ignore dropped, job table cleared,
// subsh set. With job control it joins the job's group,
// led by the first stage (c:1149-1190); the port reads
// that leader from jobtab[thisjob], which zshrs fills in
// only after every fork, so join it here instead.
let monitor = crate::ported::zsh_h::isset(crate::ported::zsh_h::MONITOR);
crate::ported::exec::entersubsh(
crate::ported::exec::esub::ASYNC | crate::ported::exec::esub::PGRP,
None,
);
if monitor {
unsafe { libc::setpgid(0, gleader) };
}
// Mirrors the RUN_PIPELINE stage child: default SIGPIPE
// so a broken pipe kills the stage quietly, and drop the
// parent's EXIT trap (c:Src/exec.c:2917-2918).
unsafe { libc::signal(libc::SIGPIPE, libc::SIG_DFL) };
if let Ok(mut tt) = crate::ported::builtin::traps_table().lock() {
tt.remove("EXIT");
}
if let Ok(mut st) = crate::ported::signals::sigtrapped.lock() {
if let Some(slot) =
st.get_mut(crate::ported::signals_h::SIGEXIT as usize)
{
*slot = 0;
}
}
*crate::ported::jobs::THISJOB
.get_or_init(|| std::sync::Mutex::new(-1))
.lock()
.unwrap() = -1;
let in_fd = if i > 0 { pipes[i - 1].0 } else { -1 };
// Unlike a foreground pipeline (whose last stage runs
// inline in the shell), an async pipeline forks its last
// stage too, so that stage simply has no pipe on stdout.
let out_fd = if i + 1 < nstages { pipes[i].1 } else { -1 };
for (r, w) in &pipes {
unsafe {
if *r != in_fd && *r != out_fd {
libc::close(*r);
}
if *w != in_fd && *w != out_fd {
libc::close(*w);
}
}
}
stage_fds_park(in_fd, out_fd);
crate::fusevm_disasm::maybe_print_stdout(
&format!("background_job:stage:{i}"),
chunk,
);
let mut stage_vm = fusevm::VM::new(chunk.clone());
register_builtins(&mut stage_vm);
let _ = stage_vm.run();
let _ = std::io::stdout().flush();
let _ = std::io::stderr().flush();
std::process::exit(stage_vm.last_status);
}
pid => {
if gleader == 0 {
gleader = pid;
}
if crate::ported::zsh_h::isset(crate::ported::zsh_h::MONITOR) {
unsafe { libc::setpgid(pid, gleader) };
}
procs.push((pid, stages[i].1.clone()));
}
}
}
for (r, w) in &pipes {
unsafe {
libc::close(*r);
libc::close(*w);
}
}
// c:Src/exec.c:2891-2892 — `if (how & Z_ASYNC) lastpid = pid;` runs
// for EVERY stage as it is forked, so `$!` ends up holding the LAST
// stage's pid even though the job's group leader is the first.
if let Some((last, _)) = procs.last() {
crate::ported::modules::clone::lastpid
.store(*last, std::sync::atomic::Ordering::Relaxed);
}
{
use crate::ported::jobs;
use std::sync::Mutex;
let table = jobs::JOBTAB.get_or_init(|| Mutex::new(Vec::new()));
let idx = {
let mut tab = table.lock().unwrap_or_else(|e| e.into_inner());
let idx = jobs::initjob(&mut tab); // c:exec.c:1756
for (pid, text) in &procs {
// c:exec.c:2907 — one addproc per forked stage.
jobs::addproc(
&mut tab[idx],
*pid,
text,
false,
Some(std::time::Instant::now()),
-1,
-1,
);
}
tab[idx].stat |= crate::ported::zsh_h::STAT_NOSTTY; // c:exec.c:1803
idx
};
jobs::clearoldjobtab(); // c:exec.c:1798
if let Ok(mut tj) = jobs::THISJOB.get_or_init(|| Mutex::new(-1)).lock() {
*tj = idx as i32;
}
if disown {
// c:exec.c:1808-1811
{
let mut tab = table.lock().unwrap_or_else(|e| e.into_inner());
jobs::pipecleanfilelist(&mut tab[idx], false);
jobs::deletejob(&mut tab, idx, true);
}
if let Ok(mut tj) = jobs::THISJOB.get_or_init(|| Mutex::new(-1)).lock() {
*tj = -1;
}
} else {
jobs::spawnjob(); // c:exec.c:1814
}
}
with_executor(|exec| {
for (pid, text) in &procs {
exec.jobs.add_pid_job(*pid, text.clone(), JobState::Running);
}
});
return Value::Status(0);
}
let chunk = chunks.into_iter().next().unwrap();
let job_text = stages.into_iter().next().unwrap().1;
match unsafe { libc::fork() } {
-1 => Value::Status(1),
0 => {
forked_child_subsh_levels(); // c:Src/exec.c:1221
EXECCMD_FORKED.with(|f| f.set(true)); // c:Src/exec.c:3063 `last1 = forked = 1`
// c:Src/exec.c:2916 — an async command's child runs
// `entersubsh(ESUB_ASYNC|ESUB_PGRP)`: string traps reset,
// MONITOR off (no ESUB_JOB_CONTROL, c:1245-1246), SIGINT/
// SIGQUIT ignored without job control (c:1137-1140), its own
// process group with it (c:1149-1190), SIGTERM/SIGINT back to
// default in an interactive shell (c:1224-1230), subsh set. The old `setsid()` did none of
// that: the child kept MONITOR and the interactive SIGTERM
// ignore, so it put its own commands in fresh groups and
// `kill %N` reached nothing.
crate::ported::exec::entersubsh(
crate::ported::exec::esub::ASYNC | crate::ported::exec::esub::PGRP,
None,
);
// `$ZSH_SUBSHELL` itself is bumped by the chunk's leading
// BUILTIN_EXECCMD_FORKED_LEVEL, which knows whether the job
// is a `( … )` whose own subshell_begin is the one bump.
crate::fusevm_disasm::maybe_print_stdout("background_job", &chunk);
let mut bg_vm = fusevm::VM::new(chunk);
register_builtins(&mut bg_vm);
let _ = bg_vm.run();
let _ = std::io::stdout().flush();
let _ = std::io::stderr().flush();
std::process::exit(bg_vm.last_status);
}
pid => {
// c:Src/exec.c:2887-2890 — C's parent blocks on the synch
// pipe until the child has run entersubsh, so the child's
// own group exists before `kill %N` can target it. Set it
// from this side too (the async-pipeline arm above does the
// same) so neither side can lose the race.
if crate::ported::zsh_h::isset(crate::ported::zsh_h::MONITOR) {
unsafe { libc::setpgid(pid, pid) };
}
// Parent: record the PID into `$!` (most recent
// backgrounded job's pid). zsh exposes this for any
// script that needs `wait $!`. Also register the
// bare-pid job so a no-args `wait` can synchronize.
// c:Src/jobs.c:73 — `lastpid = pid;` after a
// background fork. zshrs's `$!` getter
// (params.rs::lookup_special_var "!") reads from
// the same atomic, so a single store here is the
// canonical writer.
crate::ported::modules::clone::lastpid
.store(pid, std::sync::atomic::Ordering::Relaxed);
// c:Src/exec.c:1700 — `thisjob = newjob = initjob()`:
// allocate the canonical jobtab slot. c:Src/exec.c:2950
// zfork path → addproc(pid, text, 0, &bgtime, ...) hangs
// the proc entry (with its display text) off the job.
// c:Src/exec.c:1744-1746 — `clearoldjobtab();
// jobtab[thisjob].stat |= STAT_NOSTTY;` then c:1758
// `spawnjob()` promotes it to curjob (top-level shell
// only), marks STAT_LOCKED and resets thisjob.
{
use crate::ported::jobs;
use std::sync::Mutex;
let table = jobs::JOBTAB.get_or_init(|| Mutex::new(Vec::new()));
let idx = {
let mut tab = table.lock().unwrap_or_else(|e| e.into_inner());
let idx = jobs::initjob(&mut tab); // c:exec.c:1700
jobs::addproc(
&mut tab[idx],
pid,
&job_text,
false,
Some(std::time::Instant::now()),
-1,
-1,
); // c:exec.c:2950 addproc
tab[idx].stat |= crate::ported::zsh_h::STAT_NOSTTY; // c:exec.c:1746
idx
};
jobs::clearoldjobtab(); // c:exec.c:1744
if let Ok(mut tj) = jobs::THISJOB.get_or_init(|| Mutex::new(-1)).lock() {
*tj = idx as i32;
}
if disown {
// c:exec.c:1752-1755 — `pipecleanfilelist(...);
// deletejob(jobtab + thisjob, 1); thisjob = -1;` — a
// disowned job leaves the table entirely, so neither
// spawnjob's `[N] pid` nor the later `[N] done` prints.
// This is what keeps zinit-turbo's `… &|` completion
// jobs silent (they load inside a `zle -F` handler).
{
let mut tab = table.lock().unwrap_or_else(|e| e.into_inner());
jobs::pipecleanfilelist(&mut tab[idx], false); // c:1753
jobs::deletejob(&mut tab, idx, true); // c:1754
}
if let Ok(mut tj) = jobs::THISJOB.get_or_init(|| Mutex::new(-1)).lock() {
*tj = -1; // c:1755
}
} else {
jobs::spawnjob(); // c:exec.c:1758
}
}
with_executor(|exec| {
exec.jobs
.add_pid_job(pid, job_text.clone(), JobState::Running);
});
Value::Status(0)
}
}
});
// ── Indexed-array storage ─────────────────────────────────────────────
//
// Stack: pushed values then name (LAST). `arr=(a b c)` → 4 args
// (a, b, c, arr). `arr=($(cmd))` → 2 args (FlatArray, arr).
//
// PURE PASSTHRU: pop name + values, dispatch to canonical
// `setaparam` / `sethparam` (C port of `Src/params.c:3595/3602`).
// assignaparam already handles PM_UNIQUE dedupe, type-flag flip,
// PM_NAMEREF rejection, ASSPM_AUGMENT prepend, and createparam
// for fresh names.
vm.register_builtin(BUILTIN_SET_ARRAY, |vm, argc| {
// `${~spec}` carrier: an assignment statement is a word-
// pipeline boundary too — restore the user's GLOB_SUBST
// before the NEXT word expands (`Z[d]=${~Z[d]}; print
// ${options[globsubst]}` must read the user value).
consume_tilde_globsubst_carrier();
let n = argc as usize;
let mut popped: Vec<Value> = Vec::with_capacity(n);
for _ in 0..n {
popped.push(vm.pop());
}
popped.reverse();
if popped.is_empty() {
return Value::Status(1);
}
let name = popped.pop().unwrap().to_str();
let mut values: Vec<String> = Vec::new();
for v in popped {
flatten_array_value(v, &mut values);
}
if array_assignment_expansion_failed() {
crate::ported::builtin::LASTVAL.store(1, std::sync::atomic::Ordering::Relaxed);
return Value::Status(1);
}
// Bash sparse: a full `a=(...)` reassign resets the array to dense
// (drops any prior holes from subscript-assign / unset).
if crate::dash_mode::sparse_arrays() {
crate::bash_arrays::clear(&name);
}
let blocked = with_executor(|exec| {
// c:Src/exec.c:4473-4509 save_params — an ARRAY prefix
// assignment (`z=(9 8 7) f`) is a WC_ASSIGN in the same chain
// as a scalar one, so it is snapshotted the same way and put
// back by restore_params when the command returns.
let prefix_restored = exec
.inline_env_stack
.last()
.is_some_and(|frame| frame.recording);
if prefix_restored {
save_inline_prefix_param(exec, &name);
}
// Assoc init `typeset -A m; m=(k v k v ...)` — route to
// canonical sethparam (Src/params.c:3602) which parses the
// flat (k,v) pair list internally.
if exec.assoc(&name).is_some() {
// `[k]=v` / `[k]+=v` elements arrive from the compiler
// as Marker / key / value triples (compile_zsh's port
// of keyvalpairelement, c:Src/subst.c:49-79).
let marker = crate::ported::zsh_h::Marker;
let values = if values.iter().any(|e| e.starts_with(marker)) {
// c:Src/params.c:3544-3560 — under ASSPM_KEY_VALUE
// assocs strictly enforce `[key]=value`: every
// stride-of-3 element must be a Marker. Mixing
// plain pairs with kv triads is an error.
let mut i = 0usize;
while i < values.len() {
if !values[i].starts_with(marker) {
crate::ported::utils::zerr(
"bad [key]=value syntax for associative array",
);
crate::ported::utils::errflag.fetch_or(
crate::ported::zsh_h::ERRFLAG_ERROR,
std::sync::atomic::Ordering::Relaxed,
);
exec.set_last_status(1);
return true;
}
i += 3;
}
if values.len() % 3 != 0 {
// c:Src/params.c:4124-4131 arrhashsetfn — a
// truncated triad leaves an odd non-Marker
// count → "bad set of key/value pairs".
crate::ported::utils::zerr(
"bad set of key/value pairs for associative array",
);
crate::ported::utils::errflag.fetch_or(
crate::ported::zsh_h::ERRFLAG_ERROR,
std::sync::atomic::Ordering::Relaxed,
);
exec.set_last_status(1);
return true;
}
// c:Src/params.c:4136-4168 arrhashsetfn — whole
// assignment builds a FRESH table; a `Marker +`
// triad (`[k]+=v`) appends to the value inserted
// EARLIER IN THIS SAME LITERAL (assignstrvalue
// with eltflags=ASSPM_AUGMENT against the new ht),
// so `h=([k]=a [k]+=b)` yields "ab". Resolve the
// appends here, then hand flat pairs to sethparam.
let mut order: Vec<String> = Vec::new();
let mut map: std::collections::HashMap<String, String> =
std::collections::HashMap::new();
for ch in values.chunks(3) {
let elt_append = ch[0].chars().nth(1) == Some('+');
let k = ch[1].clone();
let v = ch[2].clone();
let nv = if elt_append {
format!("{}{}", map.get(&k).cloned().unwrap_or_default(), v)
} else {
v
};
if !map.contains_key(&k) {
order.push(k.clone());
}
map.insert(k, nv);
}
order
.into_iter()
.flat_map(|k| {
let v = map.get(&k).cloned().unwrap_or_default();
[k, v]
})
.collect()
} else {
values
};
// Odd-count rejection lives in the canonical chain:
// sethparam → setarrvalue (c:3651/c:2920) →
// arrhashsetfn's zerr "bad set of key/value pairs"
// (Src/params.c:4128-4131). zerr sets ERRFLAG_ERROR,
// which aborts the remaining list at the next command
// boundary (BUILTIN_ERREXIT_CHECK trigger 4) —
// matching `zsh -fc 'typeset -A m; m=(odd); print x'`
// printing nothing after the error. Like C's sethparam
// (c:3652-3653 returns v->pm regardless), the Rust
// port returns Some on the odd-count path — the
// failure travels via errflag, so check BOTH.
let pre_err = crate::ported::utils::errflag
.load(std::sync::atomic::Ordering::Relaxed)
& crate::ported::zsh_h::ERRFLAG_ERROR;
let res = crate::ported::params::sethparam(&name, values.clone());
let now_err = crate::ported::utils::errflag
.load(std::sync::atomic::Ordering::Relaxed)
& crate::ported::zsh_h::ERRFLAG_ERROR;
if res.is_none() || (pre_err == 0 && now_err != 0) {
// c:Src/exec.c:2632-2633 addvars — `if
// (!assignaparam(name, arr, myflags)) lastval = 1;`
// — failed assignment sets lastval so the errflag
// abort exits 1 (init.c loop() breaks, zsh_main
// returns lastval).
exec.set_last_status(1);
return true;
}
#[cfg(feature = "recorder")]
if crate::recorder::is_enabled() && exec.local_scope_depth == 0 {
let ctx = exec.recorder_ctx();
let attrs = exec.recorder_attrs_for(&name);
let mut pairs: Vec<(String, String)> = Vec::with_capacity(values.len() / 2);
let mut iter = values.iter().cloned();
while let Some(k) = iter.next() {
if let Some(v) = iter.next() {
pairs.push((k, v));
}
}
crate::recorder::emit_assoc_assign(&name, pairs, attrs, false, ctx);
}
return false;
}
// Indexed-array: setaparam (Src/params.c:3766) wraps
// assignaparam with ASSPM_WARN — handles PM_UNIQUE dedupe,
// type-flag flip, PM_READONLY rejection.
//
// `[k]=v` elements arrive as Marker / key / value triples
// (compile_zsh's keyvalpairelement port). Mirror
// c:Src/exec.c:2552-2553 — `if (prefork_ret &
// PREFORK_KEY_VALUE) myflags |= ASSPM_KEY_VALUE;` — so
// assignaparam runs its kv-resolution block (sparse fill
// for PM_ARRAY, c:3447-3541; strict-triad enforcement for
// special PM_HASHED targets like `options`, c:3544-3560).
let values = values;
let has_kv = values
.iter()
.any(|e| e.starts_with(crate::ported::zsh_h::Marker));
// The tied-array mirror to a PM_TIED scalar
// (`typeset -T PATH path`) lives canonically in
// setarrvalue's dispatch in C zsh; until that wires
// through assignaparam, mirror here so PATH stays in sync
// after `path=(/x)`.
//
// The mirrored value must be the array AS STORED, which for a
// PM_UNIQUE tie means deduped. c:4066-4076 arrsetfn fixes the
// order:
// if (pm->node.flags & PM_UNIQUE) uniqarray(x);
// pm->u.arr = x;
// if (pm->ename && x) arrfixenv(pm->ename, x);
// — the dedupe happens FIRST, so the scalar publishes the same
// list the array holds and the two halves of a tie always agree.
// Mirroring the raw `values` broke exactly that:
// typeset -U path; path=(/a /b /a)
// $path → /a /b (right)
// $PATH → /a:/b:/a (wrong; zsh gives /a:/b)
// i.e. `typeset -U path`, the standard PATH-dedup idiom in
// essentially every .zshrc. assignaparam's own arrfixenv does not
// rescue it: that call is gated on the param having a gsu_a wired,
// and `path` has none.
//
// The dedupe is applied here rather than by reading the array back
// after assignaparam, because this mirror must stay BEFORE it.
// `exec.set_scalar` is heavier than C's arrfixenv — arrfixenv only
// rewrites the environment string, while set_scalar re-derives the
// ARRAY from the scalar. Running it afterwards makes `path=()`
// publish PATH="" and then re-split that back into a one-element
// `path=("")`, where zsh leaves 0 elements.
if let Some((scalar_name, sep)) = exec
.tied_array_to_scalar
.get(&name)
.cloned()
{
let uniq = crate::ported::params::paramtab()
.read()
.ok()
.and_then(|t| t.get(&name).map(|p| p.node.flags))
.map(|f| (f as u32 & crate::ported::zsh_h::PM_UNIQUE) != 0)
.unwrap_or(false);
let mirror = if uniq {
crate::ported::params::simple_arrayuniq(values.clone()) // c:4068
} else {
values.clone()
};
exec.set_scalar(scalar_name, mirror.join(&sep)); // c:4074-4075
}
// c:Src/exec.c:2632-2633 addvars — `if (!assignaparam(...))
// lastval = 1;` — a failed assignment (bad subscript, bad
// [key]=value syntax, readonly) exits 1 and the errflag
// abort stops the remaining list. Track errflag pre/post
// like the assoc branch above.
let kv_flag = if has_kv {
crate::ported::zsh_h::ASSPM_KEY_VALUE
} else {
0
};
let pre_err = crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed)
& crate::ported::zsh_h::ERRFLAG_ERROR;
// c:Src/exec.c:2573 — `flags = !(addflags & ADDVAR_RESTORE) ?
// ASSPM_WARN : 0;`: a prefix assignment that is put back after
// the command is implicitly scoped and never warns, the same rule
// the scalar arm applies.
let warn = if prefix_restored { 0 } else { crate::ported::zsh_h::ASSPM_WARN };
let res = crate::ported::params::assignaparam(&name, values.clone(), warn | kv_flag);
let now_err = crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed)
& crate::ported::zsh_h::ERRFLAG_ERROR;
if res.is_none() && pre_err == 0 && now_err != 0 {
exec.set_last_status(1);
return true;
}
// Bash sparse: an explicit-index array literal `a=([2]=x [5]=y)`
// leaves the un-indexed slots as HOLES (bash: count 2, indices
// {2,5}), not dense empties. assignaparam has already placed each
// value at its 0-based index; mark every OTHER slot a hole. Gated
// to a PURE indexed literal (every element a `[idx]=val` triple) —
// a mixed positional/indexed literal (`a=(x [3]=y z)`) needs the
// positional-counter replay we don't model, so it stays dense.
if crate::dash_mode::sparse_arrays() && has_kv {
let marker = crate::ported::zsh_h::Marker;
let pure_indexed = !values.is_empty()
&& values.len() % 3 == 0
&& values.chunks(3).all(|ch| ch[0].starts_with(marker));
if pure_indexed {
let mut explicit: std::collections::BTreeSet<usize> =
std::collections::BTreeSet::new();
for ch in values.chunks(3) {
if let Ok(i) = ch[1].trim().parse::<usize>() {
explicit.insert(i);
}
}
let len = exec.array(&name).map(|a| a.len()).unwrap_or(0);
crate::bash_arrays::note_holes_outside(&name, &explicit, len);
}
}
#[cfg(feature = "recorder")]
if crate::recorder::is_enabled() && exec.local_scope_depth == 0 {
let ctx = exec.recorder_ctx();
let attrs = exec.recorder_attrs_for(&name);
emit_path_or_assign(&name, &values, attrs, false, &ctx);
}
false
});
let status = if blocked { 1 } else { 0 };
// c:Src/jobs.c:1748-1757 waitonejob — in C an array-assignment
// simple command goes through execpline → waitjobs; with no
// procs the else-branch stores `pipestats[0] = lastval;
// numpipestats = 1`. Bare SCALAR assignments never create a
// job (no waitjobs), so this clobber is array/assoc-assignment
// specific: `false|true; x=(1 2); echo $pipestatus` → `0` in
// zsh while `x=1` preserves `1 0`. Bug #373.
crate::ported::builtin::LASTVAL.store(status, std::sync::atomic::Ordering::Relaxed);
crate::ported::jobs::waitonejob(-1);
Value::Status(status)
});
// `arr+=(d e f)` — array append. Same calling conventions as SET_ARRAY.
//
// PURE PASSTHRU shape: pop name + values, dispatch through the
// canonical assoc / array setter. assignaparam's ASSPM_AUGMENT
// flag handles the C-source-equivalent "preserve prior value"
// semantics; for now we read the current array, extend with
// new values, write through set_array (which routes to
// setaparam → assignaparam where PM_UNIQUE dedupe lands).
vm.register_builtin(BUILTIN_APPEND_ARRAY, |vm, argc| {
let n = argc as usize;
let mut popped: Vec<Value> = Vec::with_capacity(n);
for _ in 0..n {
popped.push(vm.pop());
}
popped.reverse();
if popped.is_empty() {
return Value::Status(1);
}
let name = popped.pop().unwrap().to_str();
let mut values: Vec<String> = Vec::new();
for v in popped {
flatten_array_value(v, &mut values);
}
if array_assignment_expansion_failed() {
crate::ported::builtin::LASTVAL.store(1, std::sync::atomic::Ordering::Relaxed);
return Value::Status(1);
}
let blocked = with_executor(|exec| -> bool {
// Assoc append `m+=(k1 v1 ...)`: merge the (k,v) pairs into
// the existing map and write back via canonical sethparam
// (Src/params.c:3602). The canonical C path would go
// assignaparam(ASSPM_AUGMENT) → arrhashsetfn(ASSPM_AUGMENT)
// at Src/params.c:3850, but the zshrs port of
// arrhashsetfn doesn't yet implement value-storage
// (pending Param.u_hash backend wireup) — until that
// lands, do the augment + write here so the storage
// actually mutates.
if exec.assoc(&name).is_some() {
// `[k]=v` / `[k]+=v` elements arrive as Marker / key /
// value triples (compile_zsh's port of
// keyvalpairelement, c:Src/subst.c:49-79).
let marker = crate::ported::zsh_h::Marker;
let mut map = exec.assoc(&name).unwrap_or_default();
if values.iter().any(|e| e.starts_with(marker)) {
// c:Src/params.c:3544-3560 — strict triad rule.
let mut i = 0usize;
while i < values.len() {
if !values[i].starts_with(marker) {
crate::ported::utils::zerr(
"bad [key]=value syntax for associative array",
);
crate::ported::utils::errflag.fetch_or(
crate::ported::zsh_h::ERRFLAG_ERROR,
std::sync::atomic::Ordering::Relaxed,
);
exec.set_last_status(1);
return true;
}
i += 3;
}
if values.len() % 3 != 0 {
// c:Src/params.c:4124-4131 — odd pair count.
crate::ported::utils::zerr(
"bad set of key/value pairs for associative array",
);
crate::ported::utils::errflag.fetch_or(
crate::ported::zsh_h::ERRFLAG_ERROR,
std::sync::atomic::Ordering::Relaxed,
);
exec.set_last_status(1);
return true;
}
// c:Src/params.c:4133-4168 arrhashsetfn with
// ASSPM_AUGMENT — ht = the EXISTING table, so
// `[k]+=v` appends to the current value
// (assignstrvalue eltflags=ASSPM_AUGMENT,
// c:4144-4150) and `[k]=v` overwrites.
for ch in values.chunks(3) {
let elt_append = ch[0].chars().nth(1) == Some('+');
let k = ch[1].clone();
let v = ch[2].clone();
let nv = if elt_append {
format!("{}{}", map.get(&k).cloned().unwrap_or_default(), v)
} else {
v
};
map.insert(k, nv);
}
} else {
// c:Src/params.c:4076-4085 arrhashsetfn — the SAME odd-count
// gate the non-augment form uses runs before ASSPM_AUGMENT
// merges anything:
// for (aptr = val; *aptr; ++aptr)
// if (**aptr != Marker) ++alen;
// if (alen % 2) { freearray(val);
// zerr("bad set of key/value pairs for associative
// array"); return; }
// c:4086 `if (flags & ASSPM_AUGMENT)` is reached only AFTER
// it, so `h+=(k2)` with a lone key is refused and the hash is
// left alone. The walk below just dropped the unpaired key
// (`if let Some(v) = it.next()`), so the append silently
// no-opped at status 0 where zsh errors and exits 1.
if values.len() % 2 != 0 {
crate::ported::utils::zerr(
"bad set of key/value pairs for associative array",
); // c:4083
crate::ported::utils::errflag.fetch_or(
crate::ported::zsh_h::ERRFLAG_ERROR,
std::sync::atomic::Ordering::Relaxed,
);
// c:Src/exec.c:2632-2633 — a failed assignment sets
// lastval 1, the same tail the triad form above uses.
exec.set_last_status(1);
return true;
}
let mut it = values.iter().cloned();
while let Some(k) = it.next() {
if let Some(v) = it.next() {
map.insert(k, v);
}
}
}
exec.set_assoc(name, map);
return false;
}
// Indexed-array append `arr+=(d e f)` — route directly
// through canonical assignaparam with ASSPM_AUGMENT
// (`Src/params.c:3570-3585` append-on-array branch).
// assignaparam reads the prior array internally and
// appends the new values, so the bridge no longer needs
// to pre-concat manually. Marker triples from `[k]=v`
// elements add ASSPM_KEY_VALUE (c:Src/exec.c:2552-2553)
// so the kv sparse-fill block (c:Src/params.c:3447-3541)
// resolves them against the existing elements.
let kv_flag = if values
.iter()
.any(|e| e.starts_with(crate::ported::zsh_h::Marker))
{
crate::ported::zsh_h::ASSPM_KEY_VALUE
} else {
0
};
let pre_err = crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed)
& crate::ported::zsh_h::ERRFLAG_ERROR;
let res = crate::ported::params::assignaparam(
&name,
values.clone(),
crate::ported::zsh_h::ASSPM_AUGMENT | kv_flag,
);
let now_err = crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed)
& crate::ported::zsh_h::ERRFLAG_ERROR;
if res.is_none() && pre_err == 0 && now_err != 0 {
// c:Src/exec.c:2632-2633 — failed assignment → lastval 1.
exec.set_last_status(1);
return true;
}
#[cfg(feature = "recorder")]
if crate::recorder::is_enabled() && exec.local_scope_depth == 0 {
let ctx = exec.recorder_ctx();
let attrs = exec.recorder_attrs_for(&name);
emit_path_or_assign(&name, &values, attrs, true, &ctx);
}
// Tied-scalar mirror — TODO faithful: should live in
// setarrvalue's gsu dispatch once boot_ paramtab wiring
// lands (Task #16). Re-read the canonical post-augment
// array so the joined scalar matches.
let tied_scalar = exec.tied_array_to_scalar.get(&name).cloned();
if let Some((scalar_name, sep)) = tied_scalar {
let merged = exec.array(&name).unwrap_or_default();
let joined = merged.join(&sep);
exec.set_scalar(scalar_name.clone(), joined.clone());
let _ = crate::ported::params::zputenv(&format!("{}={}", &scalar_name, &joined));
// c:Src/params.c:5354
}
false
});
// c:Src/jobs.c:1748-1757 waitonejob — `arr+=(...)` is an
// array-assignment simple command and clobbers pipestats to
// `[lastval]` exactly like `arr=(...)` above. Bug #373.
let status = if blocked { 1 } else { 0 };
crate::ported::builtin::LASTVAL.store(status, std::sync::atomic::Ordering::Relaxed);
crate::ported::jobs::waitonejob(-1);
Value::Status(status)
});
// `name[@]=(...)` / `name[*]=(...)` — whole-array SET with the assoc
// guard (c:Src/params.c:3324-3327). Stack: [v0..vn, name].
vm.register_builtin(BUILTIN_SET_ARRAY_AT, |vm, argc| {
let (name, values) = pop_array_args_with_name(vm, argc);
let status = with_executor(|exec| {
// c:Src/exec.c:4475-4478 (54941) — `a[@]=(…) f` saves `a`.
if exec.inline_env_stack.last().is_some_and(|frame| frame.recording) {
save_inline_prefix_param(exec, &name);
}
if exec.assoc(&name).is_some() {
// c:Src/params.c:3324-3327 — `[@]` (any slice) on a
// PM_HASHED target is an error.
crate::ported::utils::zerr(&format!(
"{}: attempt to set slice of associative array",
name
));
crate::ported::utils::errflag.fetch_or(
crate::ported::zsh_h::ERRFLAG_ERROR,
std::sync::atomic::Ordering::Relaxed,
);
exec.set_last_status(1);
return 1;
}
exec.set_array(name, values); // whole replace (c:3528 setarrvalue)
0
});
Value::Status(status)
});
// `name[@]+=(...)` / `name[*]+=(...)` — whole-array APPEND (push) with
// the same assoc guard.
vm.register_builtin(BUILTIN_APPEND_ARRAY_AT, |vm, argc| {
let (name, values) = pop_array_args_with_name(vm, argc);
let status = with_executor(|exec| {
// c:Src/exec.c:4475-4478 (54941) — `a[@]+=(…) f` saves `a`.
if exec.inline_env_stack.last().is_some_and(|frame| frame.recording) {
save_inline_prefix_param(exec, &name);
}
if exec.assoc(&name).is_some() {
crate::ported::utils::zerr(&format!(
"{}: attempt to set slice of associative array",
name
));
crate::ported::utils::errflag.fetch_or(
crate::ported::zsh_h::ERRFLAG_ERROR,
std::sync::atomic::Ordering::Relaxed,
);
exec.set_last_status(1);
return 1;
}
let mut cur = exec.array(&name).unwrap_or_default();
cur.extend(values);
exec.set_array(name, cur); // c:3511-3528 AUGMENT on array → push
0
});
Value::Status(status)
});
vm.register_builtin(BUILTIN_RUN_SELECT, |vm, argc| {
if argc < 2 {
return Value::Status(1);
}
let n = argc as usize;
let mut popped: Vec<Value> = Vec::with_capacity(n);
for _ in 0..n {
popped.push(vm.pop());
}
// popped: [sub_idx, name, word_N, ..., word_1] (popping from top)
let sub_idx_val = popped.remove(0);
let name_val = popped.remove(0);
// c:Src/loop.c — `select` flattens Array values (from `$@`,
// `${arr[@]}`, etc.) into the menu. Without per-element
// splice, `select x do ... done` (bare, iterating $@)
// collapsed all positionals into one joined entry.
let mut words: Vec<String> = Vec::new();
for v in popped.into_iter().rev() {
match v {
Value::Array(items) => {
for item in items.iter() {
words.push(item.to_str());
}
}
other => words.push(other.to_str()),
}
}
let sub_idx = sub_idx_val.to_int() as usize;
let name = name_val.to_str();
// c:Src/loop.c:250-255 — `execsubst(args); if (errflag) { state->pc =
// end; …; return 1; }`: a word list that failed to expand (a NOMATCH
// glob) ends the `select` with status 1, ahead of the empty-list 0.
if crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed) != 0 {
return Value::Status(1);
}
// c:Src/loop.c:248-252 — `if (!args || empty(args)) {
// state->pc = end; ... return 0; }`. An empty option list
// skips the body entirely; without this gate the prompt loop
// runs indefinitely (or twice on the EOF stdin case before
// exiting). Bug #401.
if words.is_empty() {
return Value::Status(0);
}
let chunk = match vm.chunk.sub_chunks.get(sub_idx).cloned() {
Some(c) => c,
None => return Value::Status(1),
};
let prompt =
with_executor(|exec| exec.scalar("PROMPT3").unwrap_or_else(|| "?# ".to_string()));
let stdin = std::io::stdin();
let mut reader = stdin.lock();
let mut last_status: i32 = 0;
// c:Src/loop.c:264 — `more = selectlist(args, 0);` renders the menu
// ONCE, BEFORE the selection loop. C reprints it ONLY when the user
// enters an EMPTY line (c:290, inside the inner read loop) — never per
// body iteration. This was a single conflated loop that re-rendered at
// the top of every pass, so `printf "1\n2\n" | select x in a b; do
// print $x; done` redrew the list before each prompt where zsh prints
// it once.
//
// (`selectlist` is also ported at src/ported/loop.rs:127, but that copy
// derives its row budget from adjustlines()/adjustcolumns() — an ioctl
// on fd 1 — and so renders nothing when stdout is not a tty, which is
// exactly this path. Keeping the working inline render here.)
let render_menu = || {
// Direct port of zsh's selectlist from
// src/zsh/Src/loop.c:347-409. Layout is column-major
// ("down columns, then across") — NOT row-major. With
// 6 items in 3 cols zsh produces:
// 1 3 5
// 2 4 6
// The previous Rust impl walked row-major which
// produced 1 2 3 / 4 5 6 (visually similar but wrong
// for prompts that mention ordering and breaks scripts
// that rely on column count == ceil(N/rows)).
//
// C variable mapping:
// ct -> word count (n)
// longest -> max item width + 1, then plus digits-of-ct
// fct -> column count
// fw -> per-column width
// colsz -> row count = ceil(ct / fct)
// t1 -> row index, walks 0..colsz
// ap -> item pointer; advances by colsz to step
// DOWN a column.
let term_width: usize = env::var("COLUMNS")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(80);
let ct = words.len();
// loop.c:354-363 — find longest item width.
let mut longest = 1usize;
for w in &words {
let aplen = w.chars().count();
if aplen > longest {
longest = aplen;
}
}
// loop.c:365-367 — `longest++` then add digits of `ct`.
longest += 1;
let mut t0 = ct;
while t0 > 0 {
t0 /= 10;
longest += 1;
}
// loop.c:369-373 — fct = (cols - 1) / (longest + 3); if
// 0, fct = 1; else fw = (cols - 1) / fct.
let raw_fct = (term_width.saturating_sub(1)) / (longest + 3);
let (fct, fw) = if raw_fct == 0 {
(1, longest + 3)
} else {
(raw_fct, (term_width.saturating_sub(1)) / raw_fct)
};
// loop.c:374 — colsz = (ct + fct - 1) / fct.
let colsz = ct.div_ceil(fct);
// loop.c:375-395 — for each row t1, walk down columns.
for t1 in 0..colsz {
let mut ap_idx = t1;
while ap_idx < ct {
let w = &words[ap_idx];
let n = ap_idx + 1;
let _ = write!(std::io::stderr(), "{}) {}", n, w);
let mut t2 = w.chars().count() + 2;
let mut t3 = n;
while t3 > 0 {
t2 += 1;
t3 /= 10;
}
// Pad to fw (loop.c:389-390).
while t2 < fw {
let _ = write!(std::io::stderr(), " ");
t2 += 1;
}
ap_idx += colsz;
}
let _ = writeln!(std::io::stderr());
}
};
render_menu(); // c:264 — once, before the loop
'select: loop {
// c:266-290 — inner read loop: prompt and read until a NON-EMPTY
// line arrives; each empty line reprints the menu and re-reads.
let trimmed = loop {
let _ = write!(std::io::stderr(), "{}", prompt);
let _ = std::io::stderr().flush();
let mut line = String::new();
match reader.read_line(&mut line) {
Ok(0) => {
// c:277-285 — EOF (user pressed Ctrl+D): REPLY="",
// a newline to stderr, then leave the construct.
with_executor(|exec| {
exec.set_scalar("REPLY".to_string(), String::new());
});
let _ = writeln!(std::io::stderr());
let _ = std::io::stderr().flush();
// !!! KORN-MODE (no C counterpart) !!! ksh93 and mksh end a
// `select` that hit EOF with status 1, whatever the body
// last returned (zsh keeps the last body status).
if crate::extensions::dash_mode::korn_mode() {
last_status = 1;
}
break 'select;
}
Ok(_) => {}
Err(_) => break 'select,
}
let t = line.trim_end_matches(['\n', '\r'][..].as_ref()).to_string();
// c:288-289 — `if (*str) break;`
if !t.is_empty() {
break t;
}
// c:290 — `more = selectlist(args, more);` on an empty line.
render_menu();
};
// c:291 `setsparam("REPLY", ztrdup(str));` — REPLY is set once the
// inner loop yields a non-empty line. An empty line never reaches
// here: c:290 reprints and re-reads instead.
with_executor(|exec| {
exec.set_scalar("REPLY".to_string(), trimmed.clone());
});
// c:293 `i = atoi(str);` — atoi(3) reads a LEADING integer:
// optional blanks, optional sign, then digits, ignoring whatever
// trails, and yields 0 when there are no digits at all.
// `parse::<usize>()` is strict and rejected `1 2` / `1abc` / `+2`
// / ` 1`, so a reply with anything after the number selected
// NOTHING where zsh selects the leading number's item.
let i: i64 = {
let b = trimmed.as_bytes();
let mut p = 0;
while p < b.len() && (b[p] == b' ' || b[p] == b'\t') {
p += 1;
}
let neg = p < b.len() && b[p] == b'-';
if p < b.len() && (b[p] == b'-' || b[p] == b'+') {
p += 1;
}
let mut v: i64 = 0;
while p < b.len() && b[p].is_ascii_digit() {
v = v.saturating_mul(10).saturating_add((b[p] - b'0') as i64);
p += 1;
}
if neg {
-v
} else {
v
}
};
// c:294-301 — `if (!i) str = "";` else walk i-1 nodes and take
// that word; running off the end leaves "". A NEGATIVE i walks
// until the list is exhausted (`n && i`), which also lands on "".
let chosen = if i <= 0 {
String::new()
} else {
words.get((i - 1) as usize).cloned().unwrap_or_default()
};
with_executor(|exec| {
exec.set_scalar(name.clone(), chosen);
});
// Reset canonical BREAKS/CONTFLAG before running the body
// so a stale value from a sibling construct doesn't leak in.
crate::ported::builtin::BREAKS.store(0, SeqCst);
crate::ported::builtin::CONTFLAG.store(0, SeqCst);
// c:Src/loop.c — `select` increments LOOPS for the body so
// `break` / `continue` inside the body see loops > 0 and
// don't emit `not in while, until, select, or repeat loop`.
// Mirrors execwhile/execrepeat's `LOOPS.fetch_add` pattern.
// The decrement happens after the body call so a body that
// explicitly returns / errors still leaves the counter
// balanced for the next iteration.
crate::ported::builtin::LOOPS.fetch_add(1, SeqCst);
crate::fusevm_disasm::maybe_print_stdout("select:body", &chunk);
let mut body_vm = fusevm::VM::new(chunk.clone());
register_builtins(&mut body_vm);
let _ = body_vm.run();
last_status = body_vm.last_status;
crate::ported::builtin::LOOPS.fetch_sub(1, SeqCst);
// Drain the canonical BREAKS/CONTFLAG counters. Mirrors
// loop.c:529-534's `if (breaks) { breaks--; if (breaks ||
// !contflag) break; contflag = 0; }` drain pattern.
// The legacy `BREAK_SELECT=1` env-var sentinel is still
// honored for backward compat.
let break_legacy = with_executor(|exec| {
let v = exec.scalar("BREAK_SELECT");
exec.unset_scalar("BREAK_SELECT");
v.map(|s| s != "0" && !s.is_empty()).unwrap_or(false)
});
use std::sync::atomic::Ordering::SeqCst;
let breaks = crate::ported::builtin::BREAKS.load(SeqCst);
if breaks > 0 {
let cont = crate::ported::builtin::CONTFLAG.load(SeqCst);
crate::ported::builtin::BREAKS.fetch_sub(1, SeqCst);
if breaks - 1 > 0 || cont == 0 {
break;
}
crate::ported::builtin::CONTFLAG.store(0, SeqCst);
continue;
}
if break_legacy {
break;
}
}
Value::Status(last_status)
});
// Magic special-parameter assoc lookup. Synthesizes values from
// shell state for zsh's shell-introspection assocs:
// commands, aliases, galiases, saliases, dis_aliases, dis_galiases,
// dis_saliases, functions, dis_functions, builtins, dis_builtins,
// reswords, options, parameters, jobtexts, jobdirs, jobstates,
// nameddirs, userdirs, modules.
// Returns None if `name` isn't a recognized magic name.
// `${arr[idx]}` — pop name, then idx_str. zsh is 1-based for positive
// indices; we honor that. `@`/`*` return the whole array as Value::Array
// so Op::Exec splice produces N argv slots. For `${foo[key]}` where foo
// is an assoc, the idx is a string key — we check assoc_arrays first
// when the idx isn't `@`/`*` and the name has an assoc binding.
// BUILTIN_ARRAY_INDEX — `${name[idx]}` paramsubst dispatch.
// PURE PASSTHRU: pops the idx + name, hands the canonical
// `${name[idx]}` form to `subst::paramsubst` (C port of
// `Src/subst.c::paramsubst`). All subscript-flag dispatch
// ((I)pat / (R)pat / (i)/(r)/(K)/(k), range slices `[N,M]`,
// negative indices, magic-assoc shape lookup, DQ-join collapse)
// lives inside paramsubst → fetchvalue → getarg in params.rs.
//
// Outer-flag dispatch (`(@)` / `(@k)` / `(v)NAME[(I)pat]` / etc.)
// routes through BUILTIN_BRIDGE_BRACE_ARRAY at the compile path
// (canonical paramsubst flag parser owns dispatch at Src/subst.c:2147+),
// so BUILTIN_ARRAY_INDEX receives clean name+key with no sentinel
// prefixes.
//
// argc contract: `3` means the caller is a `PREFORK_SINGLE` (`ssub`)
// context — a scalar assignment RHS (c:Src/exec.c:2603), a `case` WORD
// (c:Src/loop.c:611-612), a `[[ … ]]` operand (c:Src/cond.c:53) or the
// here-string word (c:Src/exec.c:4711). c:Src/subst.c:4226
// if (isarr && ssub) { val = sepjoin(aval, NULL, 1); isarr = 0; }
// so a RANGE subscript joins on `IFS[0]` and stops. `2` is every other
// caller, unchanged. The stack shape is the same either way (name, key) —
// the VM hands `argc` to the handler untouched and zshrs never sets
// `Chunk::builtin_argc_is_arity`.
vm.register_builtin(BUILTIN_ARRAY_INDEX, |vm, argc| {
let ssub = argc == 3;
let idx = vm.pop().to_str();
let name = vm.pop().to_str();
let v = array_index_lookup(&name, &idx, ssub);
// c:Src/subst.c:3912 — a RANGE subscript is array-shaped, so
// c:2916-2917 leaves `isarr` non-zero and the join-then-split block
// applies to it exactly as it does to a `[@]`/`[*]` splice or a bare
// array read. The single-element, assoc-key and search-flag shapes all
// come back as scalars (`isarr == 0`) and pass straight through.
//
// The gate: `ssub` joins at c:4226 and stops (c:3913 `force_split =
// !ssub && …`); `qt` clears `spbreak` at c:1707 and joins at c:3033;
// `sep` / `spsep` are the `(j:…:)` / `(s:…:)` separators, which take a
// flagged expansion to `paramsubst` rather than this fast path. So the
// only door in from here is SH_WORD_SPLIT, and the handler had no such
// block at all:
// setopt shwordsplit; a=('p:q' r); IFS=:; print -rl -- ${a[1,2]}
// zsh: `p` `q` `r` zshrs: `p:q` `r`
// setopt shwordsplit; a=(x '' y); IFS=:; print -rl -- ${a[1,2]}
// zsh: `x` `` zshrs: `x`
// The second is `sepsplit_c3932`'s `nulstring` rule (c:Src/subst.c:36),
// which c:186 keeps for an IFS-NON-whitespace separator.
if ssub || !crate::ported::zsh_h::isset(crate::ported::zsh_h::SHWORDSPLIT) {
return v;
}
let (ifs_opt, in_dq) = with_executor(|exec| (exec.scalar("IFS"), exec.in_dq_context > 0));
if in_dq {
return v; // c:1707 `!qt` — `spbreak` is 0, the block never opens
}
let Value::Array(items) = &v else {
// c:2916 `isarr == 0` — the single-element, assoc-key, scalar-slice
// and search-flag shapes. c:3914's join arm does not apply to them,
// but c:3931's `if (force_split && !isarr)` does, and it is the
// SAME `sepsplit`: `setopt shwordsplit; a=('p:q' r); IFS=:;
// print -rl -- ${a[1]}` is `p` `q` in zsh, and
// `typeset -A h=(k 'p:q'); … ${h[k]}` likewise.
return split_words_c3932(&v.to_str());
};
let elems: Vec<String> = items.iter().map(|x| x.to_str()).collect();
match join_c3914(elems, ifs_opt.as_deref()) {
// c:3914-3927 left `isarr` non-zero, so c:3931's `!isarr` keeps the
// split off too and the ORIGINAL elements are the answer.
JoinC3914::Elements(_) => v,
// c:3932 `sepsplit`, then c:3933-3938's 0/1/N result shape.
JoinC3914::Joined(val) => split_words_c3932(&val),
}
});
// BUILTIN_ARRAY_INDEX_UNBRACED — bare `$name[idx]` (no braces).
// Same subscript dispatch as BUILTIN_ARRAY_INDEX when KSHARRAYS
// is unset, but under KSHARRAYS the UNBRACED form does NOT
// subscript at all:
// c:Src/subst.c:2800-2802 — fetchvalue's bracket-parse arg is
// `(unset(KSHARRAYS) || inbrace) ? 1 : -1`; -1 inhibits
// subscript parsing for the bare form under KSHARRAYS.
// c:Src/subst.c:2867 — the bracket-consuming loop only runs
// `while (v || ((inbrace || (unset(KSHARRAYS) && vunset)) &&
// isbrack(*s)))` — bare + KSHARRAYS leaves `[...]` as literal
// trailing text.
// The bare `$name` expands (first element for identifier-named
// arrays per c:Src/params.c:2293-2296 `v->end = 1, v->isarr = 0`),
// the literal `[idx]` (+ any literal suffix) joins the last word,
// and the word undergoes filename generation: `[...]` is a glob
// char class, so unquoted it hits the c:Src/glob.c:1873-1886
// nomatch/nullglob dispatch (reused via exec.expand_glob).
// Operands: [name, idx, suffix, quoted] — `quoted` set when the
// word carries DQ markers (no filename generation in DQ; zsh 5.9:
// `setopt ksharrays; a=(x y z); print "$a[0]"` → `x[0]`).
// Verbatim zsh 5.9 ground truth for the unquoted form:
// `setopt ksharrays; a=(x y z); print -- $a[0]` →
// stderr `zsh:1: no matches found: x[0]`, rc=1, empty stdout.
vm.register_builtin(BUILTIN_ARRAY_INDEX_UNBRACED, |vm, _argc| {
let quoted = vm.pop().to_str() == "1";
let suffix = vm.pop().to_str();
let idx = vm.pop().to_str();
let name = vm.pop().to_str();
if !crate::ported::zsh_h::isset(crate::ported::zsh_h::KSHARRAYS) {
// The bare `$name[idx]` word is not itself a `singsub` caller
// shape the compiler tracks — it reaches this builtin from
// `compile_word_str`, which the `PREFORK_SINGLE` callers do not
// use. Pass `false` until a measured divergence says otherwise.
//
// c:Src/subst.c:1625 — paramsubst runs with `qt` set inside `"…"`;
// array_index_lookup reads it from in_dq_context. Without it the
// lookup ran unquoted and elided EMPTY elements before the join
// below: `a=("" b); "$a[1,2]"` gave `b` for ` b`, and a quoted
// SCANPM_ISVAR_AT selection (see isvar_at) lost its empty words
// (`set -- "" b; "$@[1,2]"` is two words).
let isvar_at = name == "@" || idx == "@";
if quoted {
with_executor(|exec| exec.in_dq_context += 1);
}
let v = array_index_lookup(&name, &idx, false);
if quoted {
with_executor(|exec| exec.in_dq_context -= 1);
}
// c:Src/subst.c:3033-3034 — `if (qt && !getlen && isarr > 0)
// { val = sepjoin(aval, sep, 1); isarr = 0; }`. Inside double
// quotes a subscript that selects an array (a range, or nothing
// at all) is joined into ONE word on IFS[0]; an empty selection
// joins to "" and still counts as a word. `array_index_lookup`
// rebuilds a flat `${name[idx]}` that carries no `qt`, so the
// unbraced form returned the raw array: `"$a[1]"` on an empty
// array vanished and `"$n[1,2]"` split into two words.
//
// `nojoin` (isarr = -1, c:3031-3032) spares a SCANPM_ISVAR_AT
// value, which c:Src/params.c:2251/2272 sets when the name is
// `@` and c:2049-2050 when the subscript is `[@]` (c:Src/subst.c:
// 2917 turns it into isarr = -1). So `"$@[2,3]"` stays one word
// per element, as `"${@[2,3]}"` does; `for 2 3 4 in "$@[7,-1]"`
// in Functions/Misc/regexp-replace depends on it.
let v = match v {
Value::Array(items) if quoted && !isvar_at => {
let strs: Vec<String> = items.iter().map(|x| x.to_str()).collect();
Value::str(crate::ported::utils::sepjoin(&strs, None)) // c:3034
}
other => other,
};
if suffix.is_empty() {
return v;
}
// Mirrors the previous compile-shape `ARRAY_INDEX +
// Op::Concat` exactly: Concat stringifies via as_str_cow
// (fusevm value.rs:132-146, arrays join with " ").
if let (true, Value::Array(items)) = (isvar_at, &v) {
let mut items: Vec<Value> = items.iter().cloned().collect();
// An unjoined `"$@[…]"` keeps its elements; the suffix
// glues onto the last one (c:Src/subst.c:4434
// `strcatsub(&y, aptr, aptr, x, xlen, fstr, …)`).
if let Some(last) = items.pop() {
items.push(Value::str(format!("{}{}", last.to_str(), suffix)));
return Value::array(items);
}
}
return Value::str(format!("{}{}", v.to_str(), suffix));
}
// KSHARRAYS bare form: no subscript. Bare-`$name` words +
// literal `[idx]suffix` glued onto the last word.
let mut words = ksharrays_bare_words(&name);
let last = format!("{}[{}]{}", words.pop().unwrap_or_default(), idx, suffix);
if quoted {
// DQ context — no filename generation, bracket text stays
// literal.
words.push(last);
return Value::str(words.join(" "));
}
// c:Src/glob.c:1873-1886 — expand_glob handles nullglob /
// NOMATCH (zerr "no matches found" + errflag + the
// current_command_glob_failed cell consumed at the command
// dispatch boundary) / literal passthrough for glob-free text.
let matches = with_executor(|exec| exec.expand_glob(&last));
let mut out: Vec<Value> = words.into_iter().map(Value::str).collect();
out.extend(matches.into_iter().map(Value::str));
if out.len() == 1 {
return out.pop().unwrap();
}
Value::array(out)
});
// BUILTIN_ASSOC_HAS_KEY — `${(k)assoc[name]}` key-existence query.
// Pops [assoc_name, key]; returns key (Str) if present in the
// assoc, empty Str otherwise. Mirrors zsh's `${(k)h[name]}`
// documented semantics in zshparam(1) "Parameter Expansion Flags".
// Distinct from BUILTIN_ARRAY_INDEX (which returns the VALUE) and
// from `${+h[name]}` (which returns "0"/"1"). Bug #145.
vm.register_builtin(BUILTIN_ASSOC_HAS_KEY, |vm, _argc| {
let key = vm.pop().to_str();
let name = vm.pop().to_str();
// c:Src/params.c getindex — the subscript text is substituted
// (singsub) before the lookup; `${(k)H[$k]}` must resolve $k.
// The compiler hands this opcode the RAW subscript text, so a
// dynamic key arrived literally ("$k") and matched nothing.
// singsub is identity for plain keys.
let key = if key.contains('$') || key.contains('`') || key.contains('\u{e18c}') {
crate::ported::subst::singsub(&key)
} else {
key
};
// c:Src/params.c:3131 gethkparam covers ordinary PM_HASHED
// paramtab entries only. Special/magic hashes (`parameters`,
// `options`, … — the zsh/parameter module's partab-backed
// params, Src/Modules/parameter.c) aren't in that storage, so
// a None here doesn't mean "no such assoc". Route those
// through paramsubst, whose assoc materialization handles the
// magic hashes and whose getarg port (c:Src/params.c:1591 +
// Src/subst.c:2922) returns the KEY for `(k)` on a plain
// subscript. zsh 5.9: `${(k)parameters[PATH]}` → "PATH".
// c:Src/params.c:1602-1612 — on a hash subscript C dispatches
// `ht->getnode(ht, s)`; it never enumerates. For the magic hashes that
// distinction is observable: `getfunction_source` (c:Src/Modules/
// parameter.c:549-566) answers for names its scan never lists, `mapfile`
// answers for any readable file, and the job trio calls `getjob(name,
// NULL)` whose `job not found` diagnostic (Src/jobs.c:2150-2151) must be
// emitted by the read. `gethkparam` answers Some(<enumerated keys>) for
// these names, which shortcut the dispatch entirely — `${(k)jobstates[x]}`
// stayed silent and `${(k)functions_source[x]}` returned "" where zsh
// returns the key. Send PARTAB names to paramsubst, which owns the
// getnode path (c:Src/subst.c:2923-2925 — key when set, "" when unset).
// Keys carrying `]`/`}` can't survive the flat rebuild (see
// array_index_lookup), so those keep the enumeration answer.
let magic_getnode = !key.contains(']')
&& !key.contains('}')
&& crate::ported::modules::parameter::PARTAB
.iter()
.any(|e_| e_.name == name);
match crate::ported::params::gethkparam(&name) {
Some(keys) if !magic_getnode => {
if keys.iter().any(|k| k == &key) {
Value::str(key)
} else {
Value::str("")
}
}
// c:2048 — `key` is already expanded, so an `@`/`*` here is a key,
// not the splat; see `expanded_subscript_text`.
_ => paramsubst_to_value(&format!(
"${{(k){}[{}]}}",
name,
expanded_subscript_text(&key)
)),
}
});
vm.register_builtin(BUILTIN_BRIDGE_BRACE_ARRAY, |vm, argc| {
// argc 2 = the compiler flagged this expansion as the VALUE of a
// scalar assignment (`x=…` / `local x=…` / `typeset x=…`), which C
// preforks with PREFORK_SINGLE|PREFORK_ASSIGN (c:Src/exec.c:2546).
// PREFORK_SINGLE is paramsubst's `ssub` (c:Src/subst.c:1759) and gates
// off c:3913's `force_split` — without it `r=${(s.c.)v[2,-1]}` split
// and re-joined on IFS (`b def`) where zsh keeps `bcdef`. Same
// operand contract as BUILTIN_PARAM_FLAG's argc-3 ssub. argc 1 =
// ordinary word, no ssub (kept for callers that predate the operand).
let ssub = if argc >= 2 {
vm.pop().to_int() != 0
} else {
false
};
// Inner body of `${(...)...}` (already stripped of `${`/`}` by
// the caller). The compiler optionally prefixes Qstring
// (\u{e18c}) to signal "expanded in DQ context" — strip it
// here and bump in_dq_context for the paramsubst call so the
// SUB_ZIP and other qt-aware paths fire.
let body = vm.pop().to_str();
let (dq, inner) = if let Some(rest) = body.strip_prefix('\u{e18c}') {
(true, rest.to_string())
} else {
(false, body)
};
if dq {
with_executor(|exec| exec.in_dq_context += 1);
}
let pf_flags = if ssub {
crate::ported::zsh_h::PREFORK_SINGLE // c:1759
} else {
0
};
let v = paramsubst_to_value_status(vm, &format!("${{{}}}", inner), pf_flags);
if dq {
with_executor(|exec| exec.in_dq_context -= 1);
}
v
});
// BUILTIN_PARAM_FLAG — `${(flags)name}` paramsubst dispatch.
// PURE PASSTHRU: pops sentinel-tagged flags + name, hands the
// canonical `${(flags)name}` form to `subst::paramsubst` (C port
// of `Src/subst.c::paramsubst`). The bridge does no flag
// walking, no DQ-context branching, no array/scalar shape
// selection — all of that lives inside paramsubst. Compile-time
// context (DQ / scalar-assign-RHS) flows through executor cells
// (in_dq_context, in_scalar_assign) bumped by BUILTIN_EXPAND_TEXT.
vm.register_builtin(BUILTIN_PARAM_FLAG, |vm, argc| {
// argc 3 = the compiler flagged this expansion as the VALUE of a
// scalar assignment (`x=…` / `local x=…`), which C preforks with
// PREFORK_SINGLE|PREFORK_ASSIGN (c:Src/exec.c:2603 / :4239-4241).
// PREFORK_SINGLE is paramsubst's `ssub` (c:Src/subst.c:1761) and
// gates off c:3913's `force_split`, so `(s::)` / `(f)` / `(0)` do
// not split there. argc 2 = ordinary word, no ssub.
let ssub = if argc >= 3 {
vm.pop().to_int() != 0
} else {
false
};
let flags = vm.pop().to_str();
let name = vm.pop().to_str();
let body = format!("${{({}){}}}", flags, name);
let pf_flags = if ssub {
crate::ported::zsh_h::PREFORK_SINGLE
} else {
0
};
paramsubst_to_value_status(vm, &body, pf_flags)
});
// `foo[key]=val` — single-key set on an assoc array. Stack: [name, key, value].
// PURE PASSTHRU: assignsparam with `name[key]` form (C port of
// `Src/params.c::assignsparam` subscript path at c:3210-3231)
// already does the indexed-array vs assoc decision, PM_HASHED
// auto-vivification, numeric-subscript bounds handling, and
// PM_READONLY rejection.
/// Assign `val` to one element of the PM_HASHED parameter `name`.
///
/// This is the tail of C's `assignsparam` for a subscripted target:
/// c:Src/params.c:3251 `getvalue(&vbuf, &t, 1)` (→ `fetchvalue` →
/// `getindex`) followed by c:3343 `assignstrvalue(v, val, flags)`.
///
/// C hands `getindex` the FLAT `"name[subscript]"` text, and that is
/// safe there because its subscript is still the SOURCE spelling: the
/// bracket walk at c:2008 `parse_subscript` runs BEFORE the
/// `parsestr`/`singsub` round at c:1585-1592, so a `]` that arrives by
/// expansion can never terminate it. zshrs expands a subscript before
/// this builtin runs, so re-flattening to `name[key]` and re-splitting
/// corrupts any key containing `]` (`k='x]y'; h[$k]=5` stored `x`). The
/// two halves therefore stay separate the whole way down:
///
/// * `sub` is the EXPANDED subscript — the key text.
/// * `sub_src` is the SOURCE subscript, used for ONE decision, the
/// one C makes at c:1410: `if (v->pm && (*s == '(' || *s == Inpar))`
/// — is there a flag block? Flags can only be literal (they are read
/// at c:1409, before any expansion), so `x='(r)v'; h[$x]=Z` has no
/// flag block and stores the literal key `(r)v`, while `h[(r)$x]=Z`
/// does have one and is a search.
///
/// With no flag block there is nothing for `getindex` to resolve beyond
/// the exact-key rebind at c:1596-1616, so the key goes straight to the
/// element store and never meets a parser. With one, `getindex` runs on
/// the EXPANDED text: its flag block is byte-identical to the source's
/// (flags are literal) and its pattern is already substituted, which is
/// what c:1585-1592 would have produced anyway.
fn assign_hash_element(name: &str, sub: &str, sub_src: &str, val: &str) -> i32 {
use crate::ported::zsh_h::{Inpar, PM_HASHED, PM_READONLY, SCANPM_ARRONLY};
let pm = crate::ported::params::paramtab()
.read()
.ok()
.and_then(|t| t.get(name).cloned());
// c:3216-3221 — `if (v->pm->node.flags & PM_READONLY)`.
if pm
.as_ref()
.is_some_and(|p| (p.node.flags as u32 & PM_READONLY) != 0)
{
crate::ported::utils::zerr(&format!("read-only variable: {}", name)); // c:3217
return 1; // c:3221
}
// c:3171 — `v->pm->node.flags &= ~PM_DEFAULTED;` on the parameter
// being subscripted: an element store makes a TYPESET_TO_UNSET
// declaration (`typeset -A h; h[k]=v`) a set parameter, so
// `typeset -p h` then prints its value.
if let Ok(mut tab) = crate::ported::params::paramtab().write() {
if let Some(p) = tab.get_mut(name) {
p.node.flags &= !(crate::ported::zsh_h::PM_DEFAULTED as i32); // c:3171
}
}
// c:1410 — `if (v->pm && (*s == '(' || *s == Inpar))`, read off the
// SOURCE spelling.
let has_flags = sub_src.starts_with('(') || sub_src.starts_with(Inpar);
if has_flags {
let mut v = crate::ported::zsh_h::value {
pm,
arr: Vec::new(),
// c:2274-2280 — fetchvalue promotes a PM_ARRAY/PM_HASHED
// value with no caller flags to SCANPM_ARRONLY; assignsparam
// arrives through `getvalue`, i.e. flags 0.
scanflags: SCANPM_ARRONLY as i32,
valflags: 0,
start: 0,
end: -1, // c:2279
};
let bracketed = format!("[{}]", sub); // c:2281 `*s == '['`
let mut sp: &str = &bracketed;
if crate::ported::params::getindex(&mut sp, &mut v, 0) != 0 {
// c:2020-2022 — `zerr("invalid subscript")` already reported.
return 1;
}
let elem_is_hash = v
.pm
.as_ref()
.is_some_and(|p| crate::ported::zsh_h::PM_TYPE(p.node.flags as u32) == PM_HASHED);
if elem_is_hash {
// A search subscript: the c:1596 exact-key rebind did not
// happen, so the value still refers to the whole association
// and c:3343 `assignstrvalue` reports it — either "attempt to
// set slice of associative array" (c:2701-2706, the scanflags
// survived the c:2179 clear) or "attempt to set associative
// array to scalar" (c:2831-2839, they did not and no member
// was found).
let pre = crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed);
crate::ported::params::assignstrvalue(
Some(&mut v),
Some(val.to_string()),
crate::ported::zsh_h::ASSPM_WARN,
); // c:3343
let post = crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed);
return if post != pre { 1 } else { 0 };
}
// c:1596-1616 — a non-search flag group (`(e)`, `(w)`, `(n:N:)`,
// `(p)`, or an unrecognised one, c:1498 `flagerr`): `v->pm` is now
// the ELEMENT and its name is the subscript with the group already
// consumed. That name IS the key.
let key =
v.pm.as_ref()
.map_or(sub, |p| p.node.nam.as_str())
.to_string();
return store_hash_element(name, &key, val);
}
// c:1596-1616 with no flag group at all — the subscript is the key
// verbatim. Nothing to parse, so an expanded `]` stays intact.
store_hash_element(name, sub, val)
}
/// c:Src/params.c:2841 — `foundparam->gsu.s->setfn(foundparam, val)`,
/// the write to one member of an association. This port keeps assoc
/// members as plain strings in `paramtab_hashed_storage` rather than as
/// Params carrying their own `strsetfn` (the same substitution
/// `arrhashsetfn` makes at c:4113), so the member write is a map insert.
fn store_hash_element(name: &str, key: &str, val: &str) -> i32 {
if let Ok(mut store) = crate::ported::params::paramtab_hashed_storage().lock() {
store
.entry(name.to_string())
.or_default()
.insert(key.to_string(), val.to_string()); // c:2841
}
0
}
vm.register_builtin(BUILTIN_SET_ASSOC, |vm, _argc| {
// `${~spec}` carrier: an assignment statement is a word-
// pipeline boundary too — restore the user's GLOB_SUBST
// before the NEXT word expands (`Z[d]=${~Z[d]}; print
// ${options[globsubst]}` must read the user value).
consume_tilde_globsubst_carrier();
// argc 4 = compile flagged the subscript as DYNAMIC (`H[$k]`):
// an EXPANDED-empty key is then a legal assoc key (C's
// assignsparam isident gate sees the raw `$k` text and the
// empty key stores at getindex time — zinit's
// ZINIT_SICE[$1…$2] relies on it). argc 3 = source-literal
// key; `H[]` stays the "not an identifier" error.
// Stack shapes (compile_zsh::compile_assign):
// argc 4 = [name, key, value, key_src] — literal key
// argc 5 = [name, key, value, key_src, dynamic] — expanded key
// `key_src` is the SOURCE spelling of the subscript, kept beside
// the expanded one so nothing downstream has to re-flatten
// `name[key]` and re-split it (c:Src/params.c:2008 parses the
// subscript BEFORE expansion; see `assign_hash_element`).
// argc 6 = [name, key, value, key_src, dynamic, append] — `+=`;
// value is the pre-concatenated read-modify-write.
let append = if _argc >= 6 {
vm.pop().to_int() != 0
} else {
false
};
let key_is_dynamic = if _argc >= 5 {
vm.pop().to_int() != 0
} else {
false
};
let key_src = if _argc >= 4 {
Some(vm.pop().to_str())
} else {
None
};
let value = vm.pop().to_str();
let key = vm.pop().to_str();
let name = vm.pop().to_str();
// c:Src/exec.c:4475-4478 (54941) — `A[k]=v cmd`: save_params cuts
// the assignment text at the subscript (`itype_end(s, INAMESPC, 0)`
// stopping at `[`) and snapshots the whole base parameter `A`, so
// the element assignment is undone after a builtin or shell
// function exactly as after a forked external (whose `addvars`
// runs in the child and never touches the parent's `A`).
with_executor(|exec| {
if exec
.inline_env_stack
.last()
.is_some_and(|frame| frame.recording)
{
save_inline_prefix_param(exec, &name);
}
});
// c:Src/params.c:3250-3266 — assignsparam ASSPM_AUGMENT on a
// subscripted integer/float:
// case PM_INTEGER: case PM_EFLOAT: case PM_FFLOAT:
// zsfree(val); unqueue_signals();
// zerr("attempt to add to slice of a numeric variable");
// return NULL;
if append {
let numeric = crate::ported::params::paramtab()
.read()
.ok()
.and_then(|t| t.get(&name).map(|pm| crate::ported::zsh_h::PM_TYPE(pm.node.flags as u32)))
.is_some_and(|t| {
t == crate::ported::zsh_h::PM_INTEGER
|| t == crate::ported::zsh_h::PM_EFLOAT
|| t == crate::ported::zsh_h::PM_FFLOAT
});
if numeric {
crate::ported::utils::zerr("attempt to add to slice of a numeric variable"); // c:3264
return Value::Status(1);
}
}
let key_src = key_src.unwrap_or_else(|| key.clone());
// c:Src/params.c:3203-3207 — `if (!isident(s)) { zerr("not an
// identifier: %s", s); errflag |= ERRFLAG_ERROR; return NULL; }`.
// Every subscripted assignment passes through that gate, and isident
// rejects an empty subscript at c:1334 `if (!(ss =
// parse_subscript(++ss, 1, ']'))) return 0;` — the LHS text is
// untokenized by then, so the `]` IS parse_subscript's literal endchar
// and c:Src/lex.c:1748 returns NULL. `m[]=z` / `A[]=z` / `s[]=z` are
// therefore all `not an identifier: NAME[]`, never a store.
// Only the SOURCE-LITERAL empty subscript is affected: with a dynamic
// key (`H[$k]=v`) C's isident sees the unexpanded `$k` text, passes,
// and getindex stores the expanded — possibly empty — key.
// The gate lives here because the PM_HASHED fast path and the numeric
// pre-resolve below both reach the store without calling assignsparam
// (the empty key resolved to "" for a hash and to math-0 for an
// indexed array, so `A[]=z` reported "assignment to invalid subscript
// range" instead). Route through assignsparam so the diagnostic and
// the errflag are the canonical ones.
if !key_is_dynamic && key.is_empty() {
crate::ported::params::assignsparam(
&format!("{}[]", name), // c:3203 — the LHS spelling zsh reports
&value,
crate::ported::zsh_h::ASSPM_WARN,
);
return Value::Status(1);
}
// Bash sparse-array tracking for `a[i]=v` (scalar single-index). A set
// that pads the dense Vec past its old end leaves old_len..i as holes;
// on an undefined array, `a[5]=q` leaves only index 5 (count 1). Only
// for INDEXED arrays (assoc keys are strings), bash mode, numeric key.
// Captured before the assign; applied after (on the array path).
let sparse_track: Option<(String, usize, usize)> =
if crate::dash_mode::sparse_arrays() && !key.contains(',') {
crate::dash_mode::sparse_subscript_index(&key).and_then(|i| {
with_executor(|exec| {
if !exec.has_assoc(&name) {
let old_len = exec.array(&name).map(|a| a.len()).unwrap_or(0);
Some((name.clone(), old_len, i))
} else {
None
}
})
})
} else {
None
};
if key_is_dynamic && key.is_empty() {
with_executor(|exec| {
let _ = exec;
});
// Mirror assignsparam's PM_HASHED tail directly (the
// textual `name[]` reconstruction can't pass isident).
if let Ok(mut store) = crate::ported::params::paramtab_hashed_storage().lock() {
let entry = store.entry(name.clone()).or_default();
let newval = if let Some(old) = entry.get("") {
// `+=` arrives pre-concatenated by the compile
// read-modify-write; plain `=` overwrites.
let _ = old;
value.clone()
} else {
value.clone()
};
entry.insert(String::new(), newval);
}
return Value::Status(0);
}
with_executor(|exec| {
#[cfg(feature = "recorder")]
if crate::recorder::is_enabled() && exec.local_scope_depth == 0 {
let ctx = exec.recorder_ctx();
let attrs = exec.recorder_attrs_for(&name);
crate::recorder::emit_assoc_assign(
&name,
vec![(key.clone(), value.clone())],
attrs,
true,
ctx,
);
}
let _ = exec;
});
// Build `name[key]=value` shape for assignsparam's subscript
// dispatch. Arith-evaluate numeric subscripts on an existing
// indexed array (`a[i+1]=v` form) before handing off — the
// canonical port currently only handles literal int / string
// keys, so pre-resolve here.
let resolved_key = with_executor(|exec| {
// Existence probes only — use the non-cloning `has_*`
// checks. `exec.assoc()` / `exec.array()` return owned
// clones of the whole map/vector, so probing `.is_some()`
// here copied the entire associative array on every
// `h[k]=v` (O(n) per store → O(n²) for a fill loop). The
// profiler flagged `ShellExecutor::assoc → IndexMap::clone`
// as the dominant cost.
let is_indexed = exec.has_array(&name);
let is_assoc = exec.has_assoc(&name);
let is_scalar = !is_indexed && !is_assoc && exec.has_scalar(&name);
// c:Src/params.c::getindex — `(i)pat` / `(I)pat` / `(R)pat`
// / `(r)pat` subscript flags on an indexed array LHS resolve
// to a numeric index (first / last match of pat). On a
// SCALAR LHS the same flags resolve to a CHAR position
// (1-based first/last match of pat in the scalar string)
// for the c:2748+ char-splice assignment. zshrs's
// read-form `${a[(i)pat]}` already implements both shapes;
// the LHS assignment path silently stored the literal
// "(i)pat" as an assoc key (for scalar: auto-vivified to
// PM_HASHED via the assignsparam unknown-subscript
// fallback). Bug #293 (array) / scalar sibling.
//
// Detect the `(flags)pat` shape and resolve to a numeric
// index before assignsparam.
if is_indexed || is_scalar {
if let Some(rest) = key.strip_prefix('(') {
if let Some(close) = rest.find(')') {
let flags = &rest[..close];
let pat = &rest[close + 1..];
if !flags.is_empty()
&& flags
.chars()
.all(|c| matches!(c, 'I' | 'R' | 'i' | 'r' | 'n' | 'e'))
{
// Resolve via the array's contents.
if let Some(arr) = exec.array(&name) {
let return_index = true; // LHS write — index needed
let down = flags.contains('I') || flags.contains('R');
let exact = flags.contains('e');
let iter: Box<dyn Iterator<Item = (usize, &String)>> = if down {
Box::new(arr.iter().enumerate().rev())
} else {
Box::new(arr.iter().enumerate())
};
let mut found: Option<usize> = None;
for (idx, elem) in iter {
let matched = if exact {
elem == pat
} else {
crate::ported::pattern::patcompile(
&{
let mut __pat_tok = (pat).to_string();
crate::ported::glob::tokenize(&mut __pat_tok);
__pat_tok
},
crate::ported::zsh_h::PAT_HEAPDUP as i32,
None,
)
.map_or(false, |p| crate::ported::pattern::pattry(&p, elem))
};
if matched {
found = Some(idx);
break;
}
}
let _ = return_index;
// (i)/(r) return 1-based index of match,
// arr.len()+1 (or 1 for I/R) on miss
// per zsh docs. We mirror the read-form
// semantics from subst.rs.
let idx_1based = match found {
Some(i) => (i + 1) as i64,
None => (arr.len() + 1) as i64,
};
return idx_1based.to_string();
}
// Scalar LHS — resolve to a CHAR position
// (1-based first/last match of pat in the
// string). c:Src/params.c:1411-1418 — the
// scalar path returns the char index from
// sliding-window pattern match against
// pm.u_str. Same algorithm as the read-form
// at subst.rs:5283-5306. Bug (scalar
// sibling of #293): `a=hello; a[(I)l]=X`
// previously auto-vivified `a` into
// PM_HASHED with key "(I)l" instead of
// splicing X at the last 'l' position
// (yielding "helXo").
if is_scalar {
let s = exec.scalar(&name).unwrap_or_default();
let s_chars: Vec<char> = s.chars().collect();
let n = s_chars.len();
let want_last = flags.contains('I') || flags.contains('R');
let exact = flags.contains('e');
let mut found: Option<usize> = None;
'outer: for start in 0..=n {
let lengths: Box<dyn Iterator<Item = usize>> = if want_last {
Box::new((1..=(n - start)).rev())
} else {
Box::new(1..=(n - start))
};
for len in lengths {
let cand: String =
s_chars[start..start + len].iter().collect();
let matched = if exact {
cand == pat
} else {
crate::ported::pattern::patcompile(
&{
let mut __pat_tok = (pat).to_string();
crate::ported::glob::tokenize(&mut __pat_tok);
__pat_tok
},
crate::ported::zsh_h::PAT_HEAPDUP as i32,
None,
)
.map_or(false, |p| {
crate::ported::pattern::pattry(&p, &cand)
})
};
if matched {
found = Some(start);
if !want_last {
break 'outer;
}
break;
}
}
}
// (I)/(R): scan again to find LAST.
if want_last {
let mut last_found: Option<usize> = found;
for start in (0..=n).rev() {
for len in 1..=(n - start) {
let cand: String =
s_chars[start..start + len].iter().collect();
let matched = if exact {
cand == pat
} else {
crate::ported::pattern::patcompile(
&{
let mut __pat_tok = (pat).to_string();
crate::ported::glob::tokenize(
&mut __pat_tok,
);
__pat_tok
},
crate::ported::zsh_h::PAT_HEAPDUP as i32,
None,
)
.map_or(false, |p| {
crate::ported::pattern::pattry(&p, &cand)
})
};
if matched {
last_found = Some(start);
break;
}
}
if last_found.is_some() && last_found.unwrap() >= start {
break;
}
}
found = last_found;
}
let idx_1based = match found {
Some(i) => (i + 1) as i64,
// (i) miss → len+1 (one past end).
None => (n + 1) as i64,
};
return idx_1based.to_string();
}
}
}
}
}
if is_indexed && key.trim().parse::<i64>().is_err() {
crate::ported::math::mathevali(&crate::ported::subst::singsub(&key))
.map(|n| n.to_string())
.unwrap_or(key.clone())
} else {
key.clone()
}
});
// c:Src/params.c getindex — C parses the subscript from the
// TOKENIZED source word, so a `]`/`}` that arrived via `$key`
// expansion is plain data and can never terminate the
// subscript. The textual `name[key]` rebuild below re-parses
// the FLAT string, where an expanded `]` splits the key at the
// first bracket (`c[$k]=5` with k='x]y' stored key "x" and
// spilled junk — zpwr expandstats died on the spill in a later
// math expr). For a PM_HASHED target the compile-time split
// already isolated the exact key: store it directly via the
// canonical hashed storage (same mechanism as the
// dynamic-empty-key arm above / assignsparam's PM_HASHED
// tail), with the readonly guard assignsparam would apply.
let target_flags = with_executor(|exec| exec.param_flags(&name));
// PM_SPECIAL exclusion: the zsh/parameter magic assocs
// (functions / aliases / galiases / saliases / options / …)
// have per-key setfns with SIDE EFFECTS — `functions[x]=body`
// must parse the body into shfunctab (Src/Modules/
// parameter.c:296 setfunction), `aliases[x]=v` must write
// aliastab. The direct hashed-storage store below silently
// swallowed those: zinit's tmp-subst wrappers
// (`functions[autoload]=':zinit-tmp-subst-autoload "$@";'`)
// never became real functions, so every
// `.zinit-tmp-subst-off` spammed `unfunction: no such hash
// table element: autoload/compdef/bindkey/…`. Route specials
// through assignsparam's canonical per-name arms instead.
if (target_flags as u32 & crate::ported::zsh_h::PM_HASHED) != 0
&& (target_flags as u32 & crate::ported::zsh_h::PM_SPECIAL) == 0
{
// c:3251 + c:3343 — run the real chain (getindex →
// assignstrvalue) instead of storing the subscript verbatim.
// Storing it verbatim is what made `h[(r)v]=Z` invent a key
// named `(r)v` where zsh reports a slice assignment, and it
// also skipped the c:2701 / c:2831 guards entirely.
let _ = &resolved_key;
return Value::Status(assign_hash_element(&name, &key, &key_src, &value));
}
let subscripted = format!("{}[{}]", name, resolved_key);
crate::ported::params::assignsparam(&subscripted, &value, crate::ported::zsh_h::ASSPM_WARN);
if let Some((nm, old_len, i)) = sparse_track {
crate::bash_arrays::note_subscript_set(&nm, old_len, i);
}
Value::Status(0)
});
// Brace expansion. Routes through executor.xpandbraces (already
// implemented for the pre-fusevm executor). Returns Value::Array.
// BUILTIN_ARRAY_DROP_EMPTY — filter out empty Value::Str entries
// from a Value::Array on the stack. Used by `for x in $@` /
// `for x in $*` unquoted forms which drop empty positionals
// (POSIX-like) but do NOT IFS-split each element internally
// (zsh-specific — scalar word splitting is off by default).
// Distinct from BUILTIN_WORD_SPLIT which routes through
// multsub PREFORK_SPLIT (full IFS-split). Bug #166.
vm.register_builtin(BUILTIN_ARRAY_DROP_EMPTY, |vm, argc| {
let v = vm.pop();
strip_nulstring_markers(drop_word_empties(v, argc))
});
// The c:183-186 decision of BUILTIN_ARRAY_DROP_EMPTY, before c:170's
// remnulargs (strip_nulstring_markers) runs on the survivors.
fn drop_word_empties(v: Value, argc: u8) -> Value {
// End of word: whatever `ARRAY_EMPTIES_ELIDABLE` was carrying is
// spent here even though this builtin drops unconditionally, so a
// following word starts from a clean bit.
let _ = take_array_empties_elidable();
// c:Src/subst.c:4387 / :4404 / :4426 — a QUOTED splat of two or more
// elements stored `nulstring` in its empty nodes, which c:183 finds
// NON-empty, so c:186's `uremnode` skips them and `remnulargs` (c:170)
// restores `""`. `a=(x '' y); PRE"${a[@]}"POST` is three words in zsh.
// See `QUOTED_SPLICE_KEEPS_EMPTIES` for the c:4261 element-count
// cut-off that makes this a run-time decision.
if take_quoted_splice_keeps_empties() {
return v;
}
match v {
Value::Array(items) => {
if argc & (WORD_DROP_KEEPS_FIRST | WORD_DROP_KEEPS_LAST) != 0 && plan9_active() {
// c:4341 — under plan9 the quoted-empty affix is glued to
// every element, so no node of the word is empty.
return Value::Array(items);
}
let last = items.len().saturating_sub(1);
let filtered: Vec<Value> = items
.iter()
.enumerate()
.filter(|(i, x)| word_drop_keeps(argc, *i, last) || !x.to_str().is_empty())
.map(|(_, x)| x.clone())
.collect();
Value::array(filtered)
}
Value::Str(s) if s.is_empty() => Value::array(Vec::new()),
other => other,
}
}
// Opens (argc 0) / closes (argc 1) a word whose literals the compiler
// attaches itself — see `BUILTIN_WORD_DEFER_EMPTIES`. Pushes nothing
// meaningful; the emitter pops the status.
vm.register_builtin(BUILTIN_WORD_DEFER_EMPTIES, |_vm, argc| {
if argc == 0 {
open_deferred_affix_word();
} else {
close_deferred_affix_word();
}
Value::Int(0)
});
// c:Src/subst.c:180-187 — prefork's final loop deletes a list node whose
// text is EMPTY: `} else if (!(flags & PREFORK_SINGLE) &&
// !(*ret_flags & PREFORK_KEY_VALUE) && !keep) uremnode(list, node);`.
// The compiler emits it once the word's segments have been folded, which
// is the ORDER c:183-186 has: the node text tested there is the finished
// word, prefix and suffix already attached by the array emit block
// (c:4245 onward — plan9 cross-product at c:4316-4365, the "simply join
// the first and last values" splice at c:4366-4437). So an element that
// is empty at read time is not yet an empty word: under plan9 a prefixed
// word cross-products (`setopt rcexpandparam; a=('' x);
// print -rl -- p$a` → `p`, `px`), and under the splice an affix lands on
// the boundary element (`a=(x y ""); print -rl -- ${a}POST` → `x`, `y`,
// `POST`).
//
// Applies only to the empties of a genuine ARRAY reference. A split field
// — SH_WORD_SPLIT (c:3919 `sepsplit`) or command substitution — is
// `nulstring` in C (c:36), non-empty at c:183, so it SURVIVES:
// `setopt shwordsplit; IFS=:; s='a::b'; print -rl -- P${s}S` is `Pa`,
// ``, `bS`. zshrs renders both as "", so the discriminator is the
// `ARRAY_EMPTIES_ELIDABLE` bit `get_var_impl` sets on the array read.
vm.register_builtin(BUILTIN_WORD_ELIDE_EMPTY, |vm, argc| {
let v = vm.pop();
strip_nulstring_markers(elide_word_empties(v, argc))
});
// The c:183-186 decision of BUILTIN_WORD_ELIDE_EMPTY, before c:170's
// remnulargs (strip_nulstring_markers) runs on the survivors.
fn elide_word_empties(v: Value, argc: u8) -> Value {
// `PARAMSUBST_EMPTIES_DEFERRED` is the same bit reported from the
// other direction: `paramsubst` skipped c:186 for a genuine array
// reference because this word opened with
// `BUILTIN_WORD_DEFER_EMPTIES`, so the removal is owed here. It is
// cleared by that marker's closing half, emitted just below this op.
let elidable = take_array_empties_elidable()
| crate::ported::subst::PARAMSUBST_EMPTIES_DEFERRED.with(|c| c.get());
// A quoted splat never reaches this arm (the compile site sends every
// splice-shaped word to `BUILTIN_ARRAY_DROP_EMPTY` instead), but the
// bit is word-scoped, so spend it here too rather than let it reach
// the next word's drop. See `QUOTED_SPLICE_KEEPS_EMPTIES`.
let _ = take_quoted_splice_keeps_empties();
// argc == 2 is the compiler's "this word carries a quoted-empty
// literal segment" bit (see the emit site). c:4341 — under plan9 that
// affix is glued to EVERY element, so no node of the word can be
// empty and c:186 removes nothing: `setopt rcexpandparam;
// a=("" y); print -rl -- $a''` is `` `y`.
if argc & 2 != 0 && plan9_active() {
return v;
}
// c:Src/subst.c:36 — a quoted-empty literal (`""`, `''`) leaves a
// nulstring in the word, so a SCALAR that expands to nothing around it
// (`$x""`, `""$x`, `$x"$x"`) is still one empty word, not zero.
if argc & 2 != 0 {
let nothing = match &v {
Value::Str(e) => e.is_empty(),
Value::Array(items) => items.is_empty(),
_ => false,
};
if nothing {
return Value::array(vec![Value::str("")]);
}
}
if !elidable {
return v;
}
match v {
Value::Array(items) => {
// `items` is an `Arc<Vec<Value>>`; borrow rather than move.
let last = items.len().saturating_sub(1);
let kept: Vec<Value> = items
.iter()
.enumerate()
.filter(|(i, x)| word_drop_keeps(argc, *i, last) || !x.to_str().is_empty())
.map(|(_, x)| x.clone())
.collect();
// c:4245 — an array reference that ends up empty is still an
// ARRAY for the plan9 word-removal rule, not a scalar.
if kept.is_empty() {
note_empty_is_scalar(false);
}
Value::array(kept)
}
other => other,
}
}
// zsh nofork command substitution (c:Src/subst.c:1904-2100) — and the
// ksh93 funsub / mksh valsub it subsumes. See the BUILTIN_KSH_FUNSUB
// doc comment.
vm.register_builtin(BUILTIN_KSH_FUNSUB, |vm, _argc| {
// 0 = unquoted, 1 = inside `"…"`, 2 = unquoted PREFORK_SINGLE (a
// scalar assignment RHS): trimmed like unquoted, never split.
let qt_code = vm.pop().to_int();
let single = qt_code == 2;
let mut qt = qt_code == 1;
let kind = vm.pop().to_int();
let rplyvar = vm.pop().to_str();
let body = vm.pop().to_str();
// !!! POSIX-FAMILY GATE !!! bash, dash and sh have no nofork
// command substitution — all three answer `bad substitution` and
// fail, measured on this host:
// bash -c 'printf "%s\\n" "${ printf inner; }"' -> rc 1
// dash -c 'printf "%s\\n" "${ printf inner; }"' -> rc 2
// sh -c 'printf "%s\\n" "${ printf inner; }"' -> rc 1
// The Korn family DOES have it (funsub/valsub) and so does zsh
// 5.10 (`${ … }` / `${| … }` / `${{VAR} … }`), so the gate is the
// bare bash/sh/dash drop-in only: `posix_faithful()` without the
// Korn leg. `--zsh` and native zshrs keep the substitution.
if crate::dash_mode::posix_faithful() && !crate::dash_mode::korn_mode() {
crate::ported::utils::zerr("bad substitution");
crate::ported::utils::errflag.fetch_or(
crate::ported::zsh_h::ERRFLAG_ERROR,
std::sync::atomic::Ordering::Relaxed,
);
with_executor(|exec| exec.set_last_status(1));
return Value::str("");
}
let live_status = vm.last_status;
// c:Src/subst.c:1625 — paramsubst's `qt` is "am I inside double
// quotes", which is a LEXICAL property of the whole word. The
// compiler can see it only when the substitution IS the entire
// word; `"${ print INNER } $?"` reaches here as a segment whose own
// text carries no quotes, so pick the enclosing quoting up from the
// executor's live DQ flag as well (D10nofork.ztst "return statement
// inside, part 1+": trim must NOT eat `print`'s newline there).
if !qt && with_executor(|exec| exec.in_dq_context) != 0 {
qt = true;
}
// c:Src/subst.c — the split decision is read BEFORE the body runs.
// D10nofork.ztst "test word splitting on result" pins that
// explicitly ("setting option inside is too late for that
// substitution"): a `setopt shwordsplit` executed by the body
// must not retroactively split the value it produced.
let split = !qt
&& !single
&& (crate::dash_mode::korn_mode()
|| crate::ported::zsh_h::isset(crate::ported::zsh_h::SHWORDSPLIT));
let out = with_executor(|exec| {
use std::sync::atomic::Ordering::Relaxed;
exec.set_last_status(live_status);
// c:2044 — `parse_string(cmdarg, 0)`: the body is parsed from the
// running line, not from 1.
let lineno: u64 = exec.scalar("LINENO").and_then(|s| s.parse().ok()).unwrap_or(0);
// c:1908 — `int trim = (!EMULATION(EMULATE_ZSH)) ? 2 : !qt;`
let trim: i32 = if crate::dash_mode::korn_mode()
|| !crate::ported::zsh_h::EMULATION(crate::ported::zsh_h::EMULATE_ZSH)
{
2
} else if qt {
0
} else {
1
};
// c:1993-2007 — `${ cmd }` takes advantage of the parameter
// scope and `$(<file)` semantics: the body runs in the CURRENT
// shell as `>| TMP {\nBODY\n;}` and the file is read back. The
// spelling is C's byte for byte; a body parse error's line
// number depends on it.
let rplytmp: Option<String> = if kind == 0 {
crate::ported::utils::gettempname(None, true) // c:1996
} else {
None
};
let cmdarg: String = match (kind, &rplytmp) {
(0, Some(t)) => format!(
">| {} {{\n{}\n;}}", // c:1993 outfmt
crate::ported::utils::quotestring(t, crate::ported::zsh_h::QT_BACKSLASH),
body
),
(0, None) => {
// c:2004-2007 — TMPPREFIX not writable: `cmdoutval =
// lastval; cmdarg = NULL;`.
crate::ported::exec::cmdoutval.store(live_status, Relaxed);
String::new()
}
_ => body.clone(),
};
// c:2016 — `startparamscope(); /* "local" behaves as if in a
// function */`, paired with c:2093 `endparamscope()`. All three
// forms take it (the C block is under `if (rplyvar)`), which is
// what makes `outer=GLOBAL; ${| local outer=LOCAL; … }` leave
// the outer value alone (D10nofork.ztst "local declaration
// inside").
crate::ported::utils::inc_locallevel(); // c:2016
// c:2018-2024 — `${| cmd }`: `rplypm = createparam("REPLY",
// PM_LOCAL|PM_UNSET|PM_HIDE)` inside the scope, so the body sees
// NO outer REPLY and the outer value is intact afterwards
// (D10nofork.ztst "Basic substitution and REPLY scoping"). mksh's
// valsub is identical, so one save/clear/restore serves both.
let saved_reply = if kind == 1 {
let saved = crate::ported::params::getsparam(&rplyvar);
crate::ported::params::unsetparam(&rplyvar);
saved
} else {
None
};
// c:2025-2031 — `${ cmd }` scopes its result under the reserved
// `.zsh.cmdsubst`: local, unset, hidden and PM_READONLY_SPECIAL,
// so the body cannot assign it (D10nofork.ztst "reserved
// parameter name").
if kind == 0 {
use crate::ported::zsh_h::{PM_HIDE, PM_LOCAL, PM_READONLY_SPECIAL, PM_UNSET};
crate::ported::params::createparam(
".zsh.cmdsubst",
(PM_LOCAL | PM_UNSET | PM_HIDE | PM_READONLY_SPECIAL) as i32,
); // c:2025-2027
if let Ok(mut tab) = crate::ported::params::paramtab().write() {
if let Some(pm) = tab.get_mut(".zsh.cmdsubst") {
pm.level = crate::ported::utils::locallevel(); // c:2029
}
}
}
if !cmdarg.trim().is_empty() {
// c:2039-2053 — `int obreaks = breaks; … cmdprog =
// parse_string(cmdarg, 0); if (cmdprog) { execode(cmdprog, 1,
// 0, "cmdsubst"); cmdoutval = lastval; if (retflag) { retflag
// = 0; breaks = obreaks; } } else errflag |= ERRFLAG_ERROR;`
// — `return` ends the body only; `exit` stays pending for the
// c:2094 zexit below; `break` keeps unwinding the loop around
// the command.
use crate::ported::builtin::{BREAKS, RETFLAG};
let obreaks = BREAKS.load(Relaxed); // c:2041
// The body's commands are not inside the word's quotes.
let saved_dq = std::mem::replace(&mut exec.in_dq_context, 0);
let saved_subexp =
crate::ported::subst::SUBEXP_SCALAR_CTX.with(|c| c.replace(0));
// c:Src/exec.c:4410 save_params records only the names in the
// prefix-assignment list (varspc); an assignment the body
// makes while `X=${| … } cmd` is being evaluated is not one
// of them. The inline-env frame records every SET_VAR while
// open (D10nofork.ztst "environment assignment" left REPLY
// unset), so park it for the body.
let frames = std::mem::take(&mut exec.inline_env_stack);
// c:Src/subst.c:2048 — execode pushes the "cmdsubst" context.
let ctx = crate::ported::exec::EvalContextFrame::push("cmdsubst");
let ran = exec.execute_string_at_lineno(&cmdarg, lineno);
drop(ctx);
exec.inline_env_stack = frames;
match ran {
Ok(st) => {
exec.set_last_status(st);
crate::ported::exec::cmdoutval.store(st, Relaxed); // c:2047
}
Err(_) => {
crate::ported::utils::errflag
.fetch_or(crate::ported::zsh_h::ERRFLAG_ERROR, Relaxed); // c:2053
}
}
crate::ported::subst::SUBEXP_SCALAR_CTX.with(|c| c.set(saved_subexp));
exec.in_dq_context = saved_dq;
if RETFLAG.load(Relaxed) != 0 {
RETFLAG.store(0, Relaxed); // c:2050
BREAKS.store(obreaks, Relaxed); // c:2051
}
}
let val = match kind {
1 => {
// c:2082-2083 — `val = dupstring(getsparam(rplyvar))`.
let reply = crate::ported::params::getsparam(&rplyvar).unwrap_or_default();
match saved_reply {
Some(v) => {
crate::ported::params::setsparam(&rplyvar, &v);
}
None => {
crate::ported::params::unsetparam(&rplyvar);
}
}
Value::str(reply)
}
2 => {
// c:2026-2033 — `${{VAR} cmd }`: VAR is the result
// parameter and gets NO local scope, so an assignment
// inside is global. c:2089-2091 then re-enters the
// ordinary parameter path with `s = dyncat(rplyvar, s)`,
// which is why an ARRAY result stays an array.
match exec.array(&rplyvar) {
Some(items) => {
Value::array(items.into_iter().map(Value::str).collect::<Vec<_>>())
}
None => Value::str(
crate::ported::params::getsparam(&rplyvar).unwrap_or_default(),
),
}
}
_ => {
// c:2056-2057 — `rplypm->node.flags &= ~PM_READONLY_SPECIAL;`
if let Ok(mut tab) = crate::ported::params::paramtab().write() {
if let Some(pm) = tab.get_mut(".zsh.cmdsubst") {
pm.node.flags &= !(crate::ported::zsh_h::PM_READONLY_SPECIAL as i32);
}
}
// c:2058-2075 — `if (rplytmp && !errflag) { noerrs = 2;
// rplylen = zstuff(&cmdarg, rplytmp); … }`: trim==2 strips
// EVERY trailing newline (ksh/bash), trim==1 exactly one,
// trim==0 none.
let mut b = String::new();
if let Some(t) = &rplytmp {
if crate::ported::utils::errflag.load(Relaxed) == 0 {
if let Ok((txt, _)) = crate::ported::input::zstuff(t) {
b = txt;
}
}
while trim > 0 && b.ends_with('\n') {
b.pop();
if trim == 1 {
break;
}
}
let _ = std::fs::remove_file(t); // c:2079-2080
}
Value::str(b)
}
};
crate::ported::params::endparamscope(); // c:2093
// c:2094-2103 — `if (exit_pending) { … stopmsg = 1; zexit(exit_val,
// ZEXIT_NORMAL); }`: an `exit` in the body ran in the CURRENT shell
// and was only deferred by the parameter scope; it ends the shell
// here, before the command around the substitution runs.
{
use crate::ported::builtin::{zexit, EXIT_PENDING, EXIT_VAL, STOPMSG};
use std::sync::atomic::Ordering::Relaxed;
if EXIT_PENDING.load(Relaxed) != 0 {
STOPMSG.store(1, Relaxed); // c:2100
zexit(EXIT_VAL.load(Relaxed), crate::ported::zsh_h::ZEXIT_NORMAL); // c:2101
// c:2103 `_exit(exit_val)` — back here only when zexit deferred
// for an in-process subshell (SUBSHELL_DEPTH): the forked child
// C runs would already be gone, so abort the command around
// the substitution and let the subshell unwind with the value.
crate::ported::utils::errflag
.fetch_or(crate::ported::zsh_h::ERRFLAG_ERROR, Relaxed);
}
}
val
});
// A nofork substitution IS a command substitution, so it publishes
// the body's exit the way `$( … )` does: `ksh -c 'v=${ false; };
// print "rc=$?"'` → `rc=1`. The body run above leaves it in the
// executor; the VM's own counter
// is what BUILTIN_SET_VAR hands back as the assignment's status
// (c:Src/exec.c:3396 `lastval = cmdoutval`), so mirror it here.
vm.last_status = with_executor(|exec| exec.last_status());
// An UNQUOTED substitution is word-split only when the shell splits
// ordinary expansions: always under ksh/mksh, and under zsh only
// with SH_WORD_SPLIT. `split` was decided above, before the body
// ran — see the comment there.
match out {
Value::Str(ref s) if split => {
let (_joined, parts, _isarr, _flags) =
crate::ported::subst::multsub(s, crate::ported::zsh_h::PREFORK_SPLIT);
Value::array(parts.into_iter().map(Value::str).collect::<Vec<_>>())
}
other => other,
}
});
// c:Src/subst.c:3032 `val = sepjoin(aval, sep, 1)` — see the
// BUILTIN_QUOTED_STAR_ONE_WORD doc comment.
vm.register_builtin(BUILTIN_QUOTED_STAR_ONE_WORD, |vm, _argc| match vm.pop() {
Value::Array(items) if items.is_empty() => Value::str(String::new()),
other => other,
});
// BUILTIN_QUOTEDZPUTS — re-wrap top-of-stack scalar via the
// canonical quotedzputs (Src/utils.c:6464). Non-printable bytes
// come back as `$'…'` C-string form so the cond xtrace prefix
// line preserves the source-quoting form for `[[ -n $'\C-[OP' ]]`
// instead of leaking raw ESC + "OP" bytes through the terminal.
vm.register_builtin(BUILTIN_QUOTEDZPUTS, |vm, _argc| {
let s = vm.pop().to_str();
Value::str(crate::ported::utils::quotedzputs(&s))
});
// BUILTIN_QUOTE_TOKENIZED_OUTPUT — char-aware mirror of
// c:Src/exec.c:2114 `quote_tokenized_output`. The canonical
// port at exec::quote_tokenized_output operates on bytes
// (zsh's metafied encoding); zshrs strings are UTF-8 so
// `\u{e187}` Star is `[0xC2, 0x87]`, and a byte walk writes
// 0xC2 raw (invalid UTF-8 lead → U+FFFD on lossy decode).
// Walk by char and dispatch the same switch the byte port
// uses, but with the token chars matching the UTF-8 form.
vm.register_builtin(BUILTIN_QUOTE_TOKENIZED_OUTPUT, |vm, _argc| {
let s = vm.pop().to_str();
let mut out = String::with_capacity(s.len());
let chars: Vec<char> = s.chars().collect();
let mut i = 0;
while i < chars.len() {
let c = chars[i];
// c:2120 — Meta-quoted byte: emit `*++s ^ 32`.
// In UTF-8 strings Meta is `\u{83}`; the next char is
// the metafied payload.
if c == '\u{83}' {
if let Some(&n) = chars.get(i + 1) {
if (n as u32) < 0x80 {
out.push(((n as u8) ^ 32) as char);
} else {
out.push(n);
}
i += 2;
continue;
}
i += 1;
continue;
}
// c:2124 — Nularg: skip.
if c == '\u{e1a1}' {
i += 1;
continue;
}
// c:2128-2143 — ASCII specials get backslash-prefixed
// then fall through to emit the literal char.
match c {
'\\' | '<' | '>' | '(' | '|' | ')' | '^' | '#' | '~' | '[' | ']' | '*' | '?'
| '$' | ' ' => {
out.push('\\');
out.push(c);
i += 1;
continue;
}
'\t' => {
out.push_str("$'\\t'");
i += 1;
continue;
}
'\n' => {
out.push_str("$'\\n'");
i += 1;
continue;
}
'\r' => {
out.push_str("$'\\r'");
i += 1;
continue;
}
'=' => {
if i == 0 {
out.push('\\');
}
out.push(c);
i += 1;
continue;
}
_ => {}
}
// c:2163 — `if (itok(*s)) putc(ztokens[*s - Pound]);`
// Map zsh token chars (`\u{e184}`..`\u{e1a1}` range, the
// ones the lexer emits for `#$^*()…`) back to their
// source ASCII via the `ztokens` table.
let cp = c as u32;
if (0xe184..=0xe1a1).contains(&cp) {
let idx = (cp - 0xe184) as usize;
let ztokens = crate::ported::lex::ztokens.as_bytes();
if idx < ztokens.len() {
out.push(ztokens[idx] as char);
i += 1;
continue;
}
}
out.push(c);
i += 1;
}
Value::str(out)
});
// BUILTIN_WORD_SPLIT — `${=var}` IFS-split runtime.
// PURE PASSTHRU: route through canonical `subst::multsub` with
// PREFORK_SPLIT flag (C port of `Src/subst.c::multsub` at c:544
// — the IFS-split walker with whitespace-vs-non-whitespace
// gating, quote-aware parsing, and empty-field handling).
vm.register_builtin(BUILTIN_WORD_SPLIT, |vm, _argc| {
let s = vm.pop().to_str();
let (_joined, parts, _isarr, _flags) =
crate::ported::subst::multsub(&s, crate::ported::zsh_h::PREFORK_SPLIT);
// Empty single-string special case → empty Array (drop empty arg).
// The Array is a carrier for "no argv word", not an array-SHAPED
// result: a single empty field came from an empty SCALAR (c:3922-3923
// `if (!aval || !aval[0]) val = dupstring("");`). Record that, or
// under RC_EXPAND_PARAM `concat_plan9` reads a stale bit and applies
// c:4362's `uremnode` to a word zsh keeps — `x$(true)y` and
// `v=""; x${=v}y` are each the single word `xy`, not zero words.
if parts.len() == 1 && parts[0].is_empty() {
note_empty_is_scalar(true);
return Value::array(Vec::new());
}
// Zero parts is the same story reached by a different route: an empty
// command substitution splits to nothing at all rather than to one
// empty field. `to_str()` above means this builtin's input is always
// a scalar, so an empty result here is never array-shaped.
restore_empty_shape(nodes_to_value(parts), true)
});
// BUILTIN_FORCE_SPLIT — `${=name}` / SH_WORD_SPLIT forced split.
// c:Src/subst.c:3920-3928 —
// if (force_split && !isarr) {
// aval = sepsplit(val, spsep, 0, 1);
// if (!aval || !aval[0]) val = dupstring("");
// else if (!aval[1]) val = aval[0];
// else isarr = nojoin ? 1 : 2;
// }
// with spsep == NULL for the `=` flag, so sepsplit falls through to
// Src/utils.c:3711 spacesplit(s, allownull=0). See BUILTIN_FORCE_SPLIT's
// doc comment for the empty-field rule and the argc contract.
vm.register_builtin(BUILTIN_FORCE_SPLIT, |vm, argc| {
// argc is a two-bit field, and there is exactly one emit site
// (compile_zsh.rs, the `${=…}` fast path):
// bit 0 keep_empties — the word has neighbouring text or `Dnull`
// markers to attach the empty leading/trailing fields to.
// bit 1 the operand is a `[@]`/`[*]` SPLICE, so c:3931's `!isarr`
// gate is live (see below).
let keep_empties = argc & 1 != 0;
let splice_operand = argc & 2 != 0;
let raw_val = vm.pop();
// c:Src/subst.c:3931 — `if (force_split && !isarr)`. The `${=NAME[*]}`
// / `${=NAME[@]}` splice fast paths hand this builtin whatever the
// c:3914-3927 join arm produced, and that arm can leave the expansion
// ARRAY-shaped: with `nojoin` set and IFS the EMPTY string, neither
// c:3916 nor c:3919 fires (c:3919 wants IFS UNSET, `!ifs`, not merely
// empty), so `isarr` is still -1 here and the split does not run at
// all. Only c:184-187's empty-word removal still applies.
//
// Gated on the SPLICE bit, not on the value's Rust type: a scalar
// `${=@}` reads through BUILTIN_GET_VAR_DQ, which also hands over a
// Value::Array, but there `isarr` was already collapsed by c:3033's
// quoted join and the split must still run over the joined text
// (`set -- 'a b' 'c d'; print -l $=@` is FOUR words).
if let (true, Value::Array(items)) = (splice_operand, &raw_val) {
let kept: Vec<Value> = items
.iter()
.filter(|x| keep_empties || !x.to_str().is_empty())
.cloned()
.collect();
return Value::array(kept);
}
let s = raw_val.to_str();
// c:3932 — `sepsplit(val, spsep, 0, 1)`; spsep NULL → spacesplit, plus
// c:184-187's empty-word removal. See `sepsplit_c3932` for the
// `nulstring`-vs-`""` rule that decides which empties survive.
// c:36 `nulstring` — inside a word whose end-of-word drop is still to
// run (BUILTIN_WORD_DEFER_EMPTIES opened it), an IFS-non-whitespace
// empty field keeps its Nularg so that drop can tell it from the
// IFS-whitespace edges it must delete (c:183-186), then removes the
// marker (c:170 remnulargs). `IFS=:; s=a::b; print -rl -- x${=s}y`
// is `xa` `` `by`.
let out = if keep_empties
&& crate::ported::subst::PARAMSUBST_AFFIXES_DEFERRED.with(|c| c.get()) > 0
{
crate::ported::utils::sepsplit(&s, None, false) // c:3932, Nularg kept
} else {
sepsplit_c3932(&s, keep_empties)
};
if out.is_empty() {
// c:3922-3923 — `if (!aval || !aval[0]) val = dupstring("");`:
// the split produced nothing, so the value is the empty SCALAR.
// Quoted, that is one empty word (c:4465 `if (qt && !*y) y =
// dupstring(nulstring);` → `a=( "${=v}" )` has one element);
// unquoted, prefork deletes it and the word vanishes.
if keep_empties {
return Value::str(String::new());
}
note_empty_is_scalar(true);
return Value::array(Vec::new());
}
if out.len() == 1 {
// c:3924 — `else if (!aval[1]) val = aval[0];` — a one-field
// split stays a SCALAR (this is why `${#${(f)v}}` counts
// characters when the split yields a single line).
return Value::str(out.into_iter().next().unwrap());
}
// c:3927 — `isarr = nojoin ? 1 : 2;`
Value::array(out.into_iter().map(Value::str).collect())
});
// See BUILTIN_BARE_SPBREAK's declaration for the argc contract.
vm.register_builtin(BUILTIN_BARE_SPBREAK, |vm, argc| {
// c:2567 / c:2562 — `${=…}` sets spbreak 2, `${==…}` clears it.
let spbreak = if argc & 1 != 0 { 2 } else { 0 };
let qt = argc & 2 != 0; // c:3033 `qt`
let name = vm.pop().to_str();
let (elems, is_arr, ifs_opt, in_dq) = with_executor(|exec| {
// c:Src/params.c:4745 `ifssetfn` — the C `ifs` global is NULL only
// when IFS is genuinely UNSET, and c:3920's `(!ifs && …)` turns on
// exactly that distinction, so carry the Option, not a defaulted
// string.
let ifs_opt = exec.scalar("IFS");
let in_dq = qt || exec.in_dq_context > 0; // c:3033 `qt`
let (elems, is_arr) = param_value_elems_c2916(exec, &name);
(elems, is_arr, ifs_opt, in_dq)
});
// c:3899-3906 — "treat a one-element array as a scalar for purposes of
// concatenation with surrounding text (some${param}thing) and
// rc_expand_param handling":
// } else if (isarr && aval && aval[0] && !aval[1]) {
// val = aval[0];
// isarr = 0;
// An EMPTY array fails `aval[0]` and keeps `isarr`.
let mut isarr: i32 = i32::from(is_arr && elems.len() != 1);
// c:1819 / c:2564 / c:2569 — `nojoin` for this spelling. `${==…}`
// clears it outright; `${=…}` recomputes it as `!(ifs && *ifs)` (and,
// unlike c:1819's SH_WORD_SPLIT form, with no `!qt` term).
let nojoin = spbreak != 0 && !matches!(ifs_opt.as_deref(), Some(s) if !s.is_empty());
// c:3030-3032 — `if (isarr) { if (nojoin) isarr = -1; }`.
if isarr != 0 && nojoin {
isarr = -1;
}
// c:3033-3036 — `if (qt && !getlen && isarr > 0) { val = sepjoin(aval,
// sep, 1); isarr = 0; }`. This is why `"${==a}"` with a non-empty IFS
// is ONE joined word while the unquoted form keeps its elements.
if in_dq && isarr > 0 {
return Value::str(crate::ported::utils::sepjoin(&elems, None));
}
// c:3912-3930 — the gate is open only for `${=…}` here (`ssub`,
// `spsep`, `sep` and the quoted-with-offset case never reach this
// spelling), and `force_split` is 1, so `join_c3914` is c:3916 and
// c:3919 exactly. c:3931's `sepsplit` is BUILTIN_FORCE_SPLIT at the
// compile site, which is why this stops at the join.
if spbreak != 0 && isarr != 0 {
return match join_c3914(elems, ifs_opt.as_deref()) {
JoinC3914::Joined(val) => Value::str(val), // c:3917 / c:3925
// Neither join arm fired (IFS set but EMPTY), so `isarr` is
// still non-zero at c:3931 and the split does not run either —
// BUILTIN_FORCE_SPLIT's splice bit passes the array through.
JoinC3914::Elements(kept) => {
Value::array(kept.into_iter().map(Value::str).collect())
}
};
}
if isarr != 0 {
// `${==NAME}` on an array: the block never ran, so the element
// vector is the answer. c:184-187's empty-word removal is the
// BUILTIN_ARRAY_DROP_EMPTY the compile site emits after this.
return Value::array(elems.into_iter().map(Value::str).collect());
}
// c:2927 / c:3904 — a scalar (or the one-element array c:3899
// collapsed): `isarr == 0`, so no join arm applies and c:3931 splits
// this text directly.
Value::str(elems.into_iter().next().unwrap_or_default())
});
vm.register_builtin(BUILTIN_BRACE_EXPAND, |vm, _argc| {
// c:Src/glob.c::xpandbraces — brace expansion runs per word.
// When the upstream produced an array (e.g. `${a:e}` splat),
// expand braces on each element separately so the splat
// survives. `pop().to_str()` would join with space and lose
// the array shape. Parity bug #28 cousin: the BRACE_EXPAND
// emit always fires for any word containing `{` (including
// `${...}` param-expansion braces), so its collapse hit even
// pure-paramsubst args.
let raw = vm.pop();
// Brace expansion runs BETWEEN the expansion builtin that produced
// this word and the concat that consumes it (`x${${P}}y` compiles to
// EXPAND_TEXT, BRACE_EXPAND, CONCAT_DISTRIBUTE). It cannot change
// whether an empty result was scalar- or array-SHAPED — c:Src/glob.c
// xpandbraces only ever rewrites the text of existing words. But both
// exits below funnel through `nodes_to_value`, which records
// `note_empty_is_scalar(false)` for an empty result, so the shape bit
// its producer set was being overwritten with "array" before
// `concat_plan9` could read it. Under RC_EXPAND_PARAM that deleted
// words zsh keeps: `unset P; x${${P}}y` and `x$(true)y` are each the
// single word `xy` (c:4438-4467 scalar arm), not zero words.
// Carry the incoming bit across an empty→empty pass-through.
let incoming_empty_is_scalar = empty_is_scalar();
// c:Src/options.c — `no_brace_expand` (negated braceexpand)
// disables brace expansion entirely. When set, `{a,b}` stays
// literal. Mirror by short-circuiting xpandbraces; pass the
// input through unchanged.
let brace_expand = opt_state_get("braceexpand").unwrap_or(true);
let brace_ccl = opt_state_get("braceccl").unwrap_or(false);
// c:Src/glob.c xpandbraces rewrites word TEXT; it never turns a
// scalar word into an array one. Remember the incoming shape so a
// scalar that brace-expands to exactly one word stays SCALAR:
// nodes_to_value collapses a lone EMPTY node to zero words unless
// in_dq_context > 0, and BUILTIN_EXPAND_TEXT has already decremented
// that by the time this runs — so a quoted word whose expansion came
// out empty, and which carries the Inbrace token so it reaches this
// builtin at all, lost its argument entirely.
let raw_was_scalar = !matches!(raw, Value::Array(_));
let inputs: Vec<String> = match raw {
Value::Array(items) => items.iter().map(|v| v.to_str()).collect(),
other => vec![other.to_str()],
};
if !brace_expand {
return restore_empty_shape(nodes_to_value(inputs), incoming_empty_is_scalar);
}
let mut out: Vec<String> = Vec::with_capacity(inputs.len());
for s in inputs {
for w in crate::ported::glob::xpandbraces(&s, brace_ccl) {
// bash: a brace alternative that comes out EMPTY and unquoted
// is a null word and is removed (`echo {,a}` -> `a`); zsh
// keeps it.
if w.is_empty() && crate::dash_mode::bash_mode() {
continue;
}
out.push(w);
}
}
if raw_was_scalar && out.len() == 1 {
let mut only = out.into_iter().next().unwrap();
crate::ported::glob::remnulargs(&mut only);
return Value::str(only);
}
restore_empty_shape(nodes_to_value(out), incoming_empty_is_scalar)
});
// `*(qual)` glob qualifier filter. Stack: [pattern, qualifier].
// Pattern is glob-expanded normally, then each result is filtered by the
// qualifier predicate. Common qualifiers:
// . — regular files only
// / — directories only
// @ — symlinks
// x — executable
// r/w/x — readable/writable/executable
// N — nullglob (no error if no match)
// L+N / L-N — size > N / size < N (in bytes)
// mh-N / mh+N — modified within N hours / older than N hours
// md-N / md+N — modified within N days / older than N days
// on/On — sort by name asc/desc (default)
// oL/OL — sort by length
// om/Om — sort by mtime
// Pop a scalar pattern, run expand_glob, push Value::Array. Used
// by the segment-concat compile path for `$D/*`-style words.
vm.register_builtin(BUILTIN_GLOB_EXPAND, |vm, _argc| {
// c:Src/glob.c:1872 — honour `setopt noglob` / `noglob CMD`
// precommand. When the option is on, the word stays literal
// (zsh skips the glob expansion entirely). Without this, the
// segment-fast-path BUILTIN_GLOB_EXPAND fired even after
// `noglob` set the option, so `noglob echo *.xyz` saw the
// NOMATCH error instead of the literal pass-through.
let raw = vm.pop();
let noglob =
opt_state_get("noglob").unwrap_or(false) || !opt_state_get("glob").unwrap_or(true);
glob_word_noting_errflag(raw, noglob)
});
// Redirect-target variant of BUILTIN_GLOB_EXPAND. c:Src/glob.c:
// 2161-2167 xpandredir — `prefork(&fake, isset(MULTIOS) ? 0 :
// PREFORK_SINGLE, NULL)` then "Globbing is only done for
// multios.": a redirect target word is only globbed when the
// MULTIOS option is set. With it unset, `echo hi > *.txt`
// creates the literal file `*.txt`, and `wc -c < *.txt` errors
// "no such file or directory: *.txt". Bug #36 follow-up in
// docs/BUGS.md.
vm.register_builtin(BUILTIN_REDIR_GLOB_EXPAND, |vm, _argc| {
let raw = vm.pop();
let noglob =
opt_state_get("noglob").unwrap_or(false) || !opt_state_get("glob").unwrap_or(true);
let multios = opt_state_get("multios").unwrap_or(true);
// c:Src/glob.c:2164-2166 — `in_expandredir = 1; globlist(&fake, 0);
// in_expandredir = 0;`. The flag is what lets `zglob`'s no-match
// dispatch (c:1888-1894) tell a redirect target apart from an
// ordinary word: under NULL_GLOB an ordinary word is dropped, but
// a redirect still needs exactly one target, so the empty result
// is `redirection failed (no match)` instead.
crate::ported::glob::IN_EXPANDREDIR.store(1, std::sync::atomic::Ordering::SeqCst); // c:2164
let out = glob_expand_word_value(raw, noglob || !multios); // c:2165
crate::ported::glob::IN_EXPANDREDIR.store(0, std::sync::atomic::Ordering::SeqCst); // c:2166
out
});
// Clear the default-word glob-pending carrier before the word's
// expansion runs, so a flag set by a prior word never leaks in.
vm.register_builtin(BUILTIN_DEFAULT_WORD_GLOB_RESET, |_vm, _argc| {
crate::ported::subst::DEFAULT_WORD_GLOB_PENDING.with(|c| c.set(false));
crate::ported::subst::DEFAULT_WORD_GLOBSUBST_OFF.with(|c| c.set(false));
crate::ported::subst::DEFAULT_WORD_GLOB_BARS.with(|b| b.borrow_mut().clear());
Value::Status(0)
});
// After the word is assembled, run filename generation ONLY if the
// default/alternate paramsubst arm flagged a source-glob default
// (DEFAULT_WORD_GLOB_PENDING). Otherwise pass the word through
// literally — a parameter VALUE must not glob. c:Src/subst.c globlist.
vm.register_builtin(BUILTIN_DEFAULT_WORD_GLOB, |vm, _argc| {
let raw = vm.pop();
let pending = crate::ported::subst::DEFAULT_WORD_GLOB_PENDING.with(|c| {
let v = c.get();
c.set(false); // read + clear
v
});
let bars = crate::ported::subst::DEFAULT_WORD_GLOB_BARS.with(|b| std::mem::take(&mut *b.borrow_mut()));
if !pending {
return raw;
}
let noglob =
opt_state_get("noglob").unwrap_or(false) || !opt_state_get("glob").unwrap_or(true);
if bars.is_empty() || noglob {
return glob_expand_word_value(raw, noglob);
}
// c:Src/lex.c:1000-1008 + c:Src/subst.c:3207-3228 — the default word's
// source `|` is a Bar token in the assembled word, so globlist reads a
// top-level alternation (`${x:-b|a}` matches the file `b`;
// `X${x:-b|a}` is the pattern `Xb` | `a`). Re-spell those `|`s from
// the carrier before globbing, and put them back to `|` in a word the
// glob hands back literally.
let rebar = |s: String| -> String {
let mut s = s;
for (plain, barred) in &bars {
if let Some(at) = s.find(plain.as_str()) {
s.replace_range(at..at + plain.len(), barred);
}
}
s
};
let barred = match raw {
Value::Array(items) => {
Value::array(items.iter().map(|v| Value::str(rebar(v.to_str()))).collect())
}
other => Value::str(rebar(other.to_str())),
};
match glob_expand_word_value(barred, false) {
Value::Array(items) => Value::array(
items
.iter()
.map(|v| Value::str(crate::ported::lex::untokenize(&v.to_str())))
.collect(),
),
other => Value::str(crate::ported::lex::untokenize(&other.to_str())),
}
});
// `break`/`continue` from a sub-VM body. The compile path emits
// these when the keyword appears at chunk top-level (no enclosing
// for/while in the current chunk's patch lists). Outer-loop
// builtins (BUILTIN_RUN_SELECT and any future loop-via-builtin
// construct) drain canonical BREAKS/CONTFLAG after each iteration.
//
// Writes match `bin_break`'s c:5836+ pattern:
// continue: contflag = 1; breaks++ (Src/builtin.c::bin_break)
// break: breaks++
vm.register_builtin(BUILTIN_SET_BREAK, |_vm, _argc| {
use std::sync::atomic::Ordering::SeqCst;
crate::ported::builtin::BREAKS.fetch_add(1, SeqCst);
Value::Status(0)
});
vm.register_builtin(BUILTIN_SET_CONTINUE, |_vm, _argc| {
use std::sync::atomic::Ordering::SeqCst;
crate::ported::builtin::CONTFLAG.store(1, SeqCst);
crate::ported::builtin::BREAKS.fetch_add(1, SeqCst);
Value::Status(0)
});
// `break N`/`continue N` with a RUNTIME level count. Pops [count,
// name]; math-evaluates count (c:builtin.c:5811 `mathevali`); on
// count <= 0 emits `argument is not positive: N` via zerrnam (sets
// errflag → abort, c:5813) and pushes Int(0) (matches no jump-table
// entry → control falls through to the errflag abort). Otherwise
// pushes Int(count) for the compiled jump table to dispatch on.
vm.register_builtin(BUILTIN_BREAK_COUNT_VALIDATE, |vm, _argc| {
let name = vm.pop().to_str();
let count_s = vm.pop().to_str();
// c:5816 — mathevali zerr's a bad expression itself; its errflag
// then suppresses the zerrnam below.
let count = match crate::ported::math::mathevali(&count_s) {
Ok(n) => n,
Err(msg) => {
crate::ported::utils::zerr(&msg);
0
}
};
if count <= 0 {
crate::ported::utils::zerrnam(&name, &format!("argument is not positive: {count}"));
return Value::Int(0);
}
Value::Int(count)
});
// `${arr[*]}` — join array elements with the first IFS char into
// a single string. Matches zsh: in DQ context this preserves the
// join; in array context too the result is one Value::Str.
// Set or clear a shell option directly. Used by `noglob CMD ...`
// precommand wrapping — the compiler emits SET_RAW_OPT to flip the
// option ON before compiling the inner words and OFF after, so glob
// expansion of the inner args sees the temporary state.
vm.register_builtin(BUILTIN_SET_RAW_OPT, |vm, _argc| {
let on = vm.pop().to_int() != 0;
let opt = vm.pop().to_str();
// Pure passthru: canonical port lives in
// src/ported/options.rs::opt_state_set_via_alias and
// handles negation-alias resolution per c:Src/options.c.
crate::ported::options::opt_state_set_via_alias(&opt, on);
Value::Status(0)
});
// c:Src/options.c GLOB_SUBST — runtime glob expansion of
// substituted words. Pop a Value (Str or Array); when
// GLOB_SUBST is ON, run expand_glob on each string element;
// when OFF, pass through unchanged. Bug #119 in docs/BUGS.md.
vm.register_builtin(BUILTIN_GLOB_SUBST_EXPAND, |vm, _argc| {
let raw = vm.pop();
// c:Src/subst.c:3231-3233 — after a default / alternate word C runs
// `if (globsubst != 2) globsubst = 0;`, so the finished expansion is
// not shtokenized and only glob tokens an UNQUOTED inner substitution
// produced survive into it. The paramsubst arm reports both halves
// (subst::DEFAULT_WORD_GLOBSUBST_OFF and DEFAULT_WORD_GLOB_PENDING);
// take them for this word: `setopt globsubst; foo='boring*'`
// `${foo+"$foo"}` stays `boring*`, `${foo+$foo}` still globs.
let default_off = crate::ported::subst::DEFAULT_WORD_GLOBSUBST_OFF.with(|c| c.replace(false));
let default_pending = default_off
&& crate::ported::subst::DEFAULT_WORD_GLOB_PENDING.with(|c| c.replace(false));
let glob_subst = crate::ported::zsh_h::isset(crate::ported::zsh_h::GLOBSUBST);
if !glob_subst || (default_off && !default_pending) {
return raw;
}
// Collect input strings (Str → vec![s]; Array → multiple).
let inputs: Vec<String> = match raw {
Value::Array(items) => items.iter().map(|v| v.to_str()).collect(),
other => vec![other.to_str()],
};
// Run expand_glob on each. Empty matches collapse to a
// single literal pass-through to mirror nullglob-off default.
let mut out: Vec<String> = Vec::with_capacity(inputs.len());
for pattern in inputs {
// c:Src/subst.c — GLOB_SUBST subjects the value to the FULL
// filename-generation pipeline: `filesub` (tilde/`=` expansion)
// BEFORE globbing (prefork runs filesub then globlist). zshrs
// globbed but skipped filesub, so `${~x}` / `setopt globsubst`
// left `~/foo` un-expanded. filesubstr matches the Tilde TOKEN,
// so shtokenize the value first (`~`→Tilde, glob metas active),
// run filesub, then untokenize the surviving glob metas back to
// raw for expand_glob (which re-tokenizes internally).
// c:178 — that filesub is prefork's SECOND pass, gated on
// `unset(SHFILEEXPANSION)`: with SH_FILE_EXPANSION the file
// expansion ran before substitution, so a substituted `~`/`=`
// stays literal.
let pattern = if (pattern.contains('~') || pattern.contains('='))
&& !crate::ported::zsh_h::isset(crate::ported::zsh_h::SHFILEEXPANSION)
{
let mut tok = pattern.clone();
crate::ported::glob::shtokenize(&mut tok);
let fs = crate::ported::subst::filesub(&tok, 0);
crate::ported::lex::untokenize(&fs)
} else {
pattern
};
// c:Src/glob.c:1872-1886 — `expand_glob` already owns the whole
// no-match dispatch: NULL_GLOB drops the word, NOMATCH errors, and
// only with both off does it hand the literal back. Pushing the
// literal again on an empty result undid NULL_GLOB and kept a
// word whose filesub had failed, so under `_expand`'s options
// `${~exp//…}` of `~[]` "expanded" to itself (Y01completion #10).
out.extend(with_executor(|exec| exec.expand_glob(&pattern)));
}
if out.len() == 1 {
Value::str(out.into_iter().next().unwrap())
} else {
Value::array(out.into_iter().map(Value::str).collect())
}
});
// c:Src/math.c:336-364 — `getmathparam` for ArithCompiler pre-load.
// Pop a variable name, return its math value.
//
// This used to be a second, smaller getmathparam: `getsparam` then
// `parse::<i64>` / `parse::<f64>` / `mathevali`. Two consequences,
// both invisible until you compared the two arithmetic backends on
// the same expression. It had no FORCEFLOAT coercion (c:359-362) and
// no `unset(UNSET)` diagnostic (c:345-346), so which of `setopt
// force_float` and `set -u` applied to `$(( x ))` depended on
// whether `compile_arith` had routed the expression to the
// ArithCompiler or to BUILTIN_ARITH_EVAL. And it re-derived a
// typed param's value from `getsparam`'s printed form, the same
// convbase round-trip c:2641 exists to avoid.
//
// There is one `getmathparam` in C; there is one here now.
vm.register_builtin(BUILTIN_GET_MATH_VAR, |vm, _argc| {
let name = vm.pop().to_str();
let n = crate::ported::math::getmathparam(&name); // c:337
if n.type_ == crate::ported::zsh_h::MN_FLOAT {
Value::Float(n.d)
} else {
Value::Int(n.l)
}
});
// ── Compiled-arithmetic runtime ops ───────────────────────────────
//
// c:Src/math.c:1156 `op(int what)` — the arms `Op::Div` / `Op::Mod` /
// `Op::Pow` cannot express, plus the two write-back / finish helpers
// the compiled `(( … ))` path needs. Each pops its operands in C's
// order: for `a OP b` the stack holds \[a, b\], so `b` pops first.
vm.register_builtin(BUILTIN_ARITH_DIV, |vm, _argc| {
let b = arith_pop_mnumber(vm);
let a = arith_pop_mnumber(vm);
arith_push(arith_div(a, b)) // c:1237-1257
});
vm.register_builtin(BUILTIN_ARITH_MOD, |vm, _argc| {
let b = arith_pop_mnumber(vm);
let a = arith_pop_mnumber(vm);
arith_push(arith_mod(a, b)) // c:1258-1272
});
vm.register_builtin(BUILTIN_ARITH_POW, |vm, _argc| {
let b = arith_pop_mnumber(vm);
let a = arith_pop_mnumber(vm);
arith_push(arith_pow(a, b)) // c:1335-1358
});
// c:Src/math.c:1200 — the `BOOL` operators yield an INTEGER 1/0
// whatever their operands were.
vm.register_builtin(BUILTIN_ARITH_LOGAND, |vm, _argc| {
let b = arith_pop_mnumber(vm);
let a = arith_pop_mnumber(vm);
Value::Int(i64::from(mn_is_true(a) && mn_is_true(b)))
});
vm.register_builtin(BUILTIN_ARITH_LOGOR, |vm, _argc| {
let b = arith_pop_mnumber(vm);
let a = arith_pop_mnumber(vm);
Value::Int(i64::from(mn_is_true(a) || mn_is_true(b)))
});
vm.register_builtin(BUILTIN_ARITH_LOGXOR, |vm, _argc| {
let b = arith_pop_mnumber(vm);
let a = arith_pop_mnumber(vm);
Value::Int(i64::from(mn_is_true(a) != mn_is_true(b)))
});
// c:Src/math.c:972 setmathvar — stack is \[name, value, pval\]; pval
// (argc 3) says the operator read the lvalue first (c:975-993).
vm.register_builtin(BUILTIN_SET_MATH_VAR, |vm, argc| {
let pval = argc >= 3 && vm.pop().to_int() != 0;
let value = arith_pop_mnumber(vm);
let name = vm.pop().to_str();
// c:Src/math.c:1161 — `op()` begins `if (errflag) return;`, so an
// assignment operator reached after a math error (`x %= 0`, the
// `y = 3` of `(( x = 5/0, y = 3 ))`) stores nothing.
if crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed) != 0 {
return arith_push(value);
}
// c:Src/math.c:395 `xstack = stack` / c:455 `stack = xstack` —
// `setmathvar` also memoises the value in the math-local read
// cache (`mptr->pval`, c:340-343), which in C belongs to the
// evaluation FRAME and dies with it. The compiled path has no
// such frame, so without this save/restore the entry outlives
// the expression: a later `sum=0` would update the parameter
// while `getmathparam` kept answering from the cache, and the
// next `(( sum += n ))` would resume from the stale total.
// Every setmathvar write goes through to the parameter table
// (`setnparam`, c:1005), so dropping the memo loses nothing but
// one paramtab read. Saving rather than clearing keeps the
// entries of an enclosing `matheval` frame intact, which is
// what c:455 restores.
let saved = crate::ported::math::m_variables_clone();
// c:Src/math.c:1370-1371 — `c = setmathvar(mvp, c); push(c, …)`:
// the stored value, converted to the parameter's type
// (c:1014-1030), is the value of the assignment.
let stored = crate::ported::math::setmathvar(&name, value, pval);
crate::ported::math::m_variables_set(saved);
arith_push(stored)
});
// c:Src/exec.c:5267 execarith tail + c:Src/math.c:1500 lastmathval.
vm.register_builtin(BUILTIN_ARITH_CMD_FINISH_VAL, |vm, _argc| {
use std::sync::atomic::Ordering;
let val = arith_pop_mnumber(vm);
// c:1500 `lastmathval = z` — recorded even when the value is
// only used for the exit status, because a `functions -M` math
// function returns whatever its last `(( … ))` left here
// (c:1115).
crate::ported::math::M_LASTMATHVAL.with(|c| c.set(val));
let live = crate::ported::utils::errflag.load(Ordering::Relaxed);
if live & crate::ported::zsh_h::ERRFLAG_ERROR != 0 {
// Same split as BUILTIN_ARITH_CMD_FINISH: a HARD error
// (`${v:?msg}`) must keep aborting the script, a soft math
// error is consumed here so the next statement still runs.
if live & crate::ported::zsh_h::ERRFLAG_HARD == 0 {
crate::ported::utils::errflag
.fetch_and(!crate::ported::zsh_h::ERRFLAG_ERROR, Ordering::Relaxed);
}
vm.last_status = 2;
return Value::Status(2);
}
// c:5267 — `(( 0 ))` is false, anything else is true.
let status = i32::from(!mn_is_true(val));
vm.last_status = status;
Value::Status(status)
});
// c:Src/subst.c:822/830 `if (glbsub) shtokenize(dest)` for the
// `${~spec}` / `$~spec` FLAG, where the compiler emits no
// GLOB_SUBST guard because the metas are meant to be active. Only
// the value's backslashes still need settling — c:Src/glob.c:3651
// leaves the ones before a non-`ztokens` char as data.
// See BUILTIN_PAT_DATA_BACKSLASH docs below for full rationale.
vm.register_builtin(BUILTIN_PAT_DATA_BACKSLASH, |vm, _argc| {
let p = vm.pop().to_str();
// The word arrives in EXPAND_TEXT mode 12's tokenized form (see the
// untokenize there). This leg wants every metacharacter ACTIVE anyway
// — `${~spec}` forced them — so both spellings collapse to the same
// raw character here, exactly as they did when mode 9 untokenized one
// step earlier.
let p = crate::lex::untokenize(&p);
let p = crate::pattern_data_escape::escape_data_backslashes(&p);
// c:Src/glob.c:3575-3580 + 3617-3620 — the `shtokenize` this
// builtin stands in for adds ZSHTOK_SHGLOB under SH_GLOB, and
// that flag makes `(`, `|` and `)` of the VALUE stay ordinary
// characters. Without this the value's parens reach patcompile
// as live metacharacters and `emulate ksh; p='-([AMO]*|[0CRSWnsw])';
// [[ "-s" = $~p ]]` becomes a bad pattern where zsh just fails
// to match.
if crate::pattern_data_escape::shglob_hides_parens() {
return Value::str(crate::pattern_data_escape::escape_shglob_parens(
&p,
crate::pattern_data_escape::dropin_keeps_ksh_groups(),
));
}
Value::str(p)
});
// c:Src/options.c GLOB_SUBST + Src/cond.c:552 cond_match.
// Pop pattern string; when GLOB_SUBST is OFF, escape every glob
// metachar with `\` so the downstream StrMatch + patcompile
// treat them as literals (matching C's tokenization-based
// gate). When GLOB_SUBST is ON, only the data-backslash respelling
// runs and the metas stay active.
// See BUILTIN_GLOB_SUBST_GUARD docs below for full rationale.
vm.register_builtin(BUILTIN_GLOB_SUBST_GUARD, |vm, argc| {
// argc 2 = a trailing "quoted" flag: the value came from a double-quoted
// substitution, which C never shtokenizes (c:Src/subst.c:822/830).
let force_literal = argc >= 2 && vm.pop().to_int() != 0;
let p = vm.pop().to_str();
let glob_subst =
!force_literal && crate::ported::zsh_h::isset(crate::ported::zsh_h::GLOBSUBST);
if glob_subst {
// c:Src/subst.c:822/830 `if (glbsub) shtokenize(dest)` — the
// value's metas go ACTIVE, but c:Src/glob.c:3651 still leaves a
// backslash before a non-`ztokens` char as ordinary data. Respell
// those in the normalizer's literal-backslash form; the ones
// `zshtokenize` WOULD fold into a quote are left alone.
// docs/BUGS.md #1090.
let p = crate::pattern_data_escape::escape_data_backslashes(&p);
// c:Src/glob.c:3575-3580 + 3617-3620 — same `shtokenize` call,
// so the ZSHTOK_SHGLOB suppression of `(` / `|` / `)` applies
// to the GLOB_SUBST leg exactly as it does to the `${~spec}`
// leg above.
if crate::pattern_data_escape::shglob_hides_parens() {
return Value::str(crate::pattern_data_escape::escape_shglob_parens(
&p,
crate::pattern_data_escape::dropin_keeps_ksh_groups(),
));
}
return Value::str(p);
}
// The metacharacters that have to be spelled `\X` to reach
// `ported::pattern`'s normalizer as ordinary characters.
//
// c:Src/lex.c:1390-1404 — `-` / `!` are Dash / Bang TOKENS only when
// the LEXER sees them unquoted; pattern.c's range parser (c:1483) and
// negation test look for the tokens, so a SUBSTITUTED `-` / `!` must
// stay an ordinary character with GLOB_SUBST off. Without those two,
// `cset='^a-z'; [[ - = ["$cset"] ]]` built a live `a-z` range out of
// substituted text.
fn is_pattern_meta(c: char) -> bool {
matches!(
c,
'*' | '?'
| '['
| ']'
| '('
| ')'
| '|'
| '<'
| '>'
| '#'
| '^'
| '~'
| '-'
| '!'
| '\\'
)
}
// The character an ACTIVE metacharacter token stands for, or None for
// anything that is not one.
//
// c:Src/glob.c:3640-3645 — `shtokenize` arms a metacharacter by
// rewriting it to `(t - ztokens) + Pound`; c:Src/lex.c:38 `ztokens` is
// the table that maps back. c:Src/zsh.h:159-183 is the metacharacter
// range (Pound 0x84 … Bang 0x9c); c:Src/zsh.h:193-206's Snull / Dnull /
// Bnull / Bnullkeep / Nularg are quote and null MARKERS, never
// metacharacters, so they are excluded here and travel with the
// literal run below — where `untokenize` gives them the same reading
// they had when it ran one step earlier (Bnull → `\`, which this pass
// then escapes to the normalizer's literal-backslash `\\`).
fn active_pattern_token(c: char) -> Option<char> {
let cu = c as u32;
if !(0xe184..=0xe19c).contains(&cu) {
return None;
}
let m = crate::ported::lex::ztokens
.chars()
.nth((cu - 0xe184) as usize)?;
is_pattern_meta(m).then_some(m)
}
// !!! RUST-ONLY HELPER — no C counterpart. C needs no such pass: its
// `patcompile` consumes the token encoding itself (c:Src/pattern.c:248
// — `zpc_chars` holds Star / Quest / Inbrack / …, so a RAW `*` never
// dispatches as ZPC_STAR and is literal by construction). zshrs's
// `ported::pattern` normalizer uses a raw-ASCII encoding whose literal
// form is `\X`, so C's one-byte ACTIVE-vs-DATA distinction has to be
// re-SPELLED: a metacharacter `shtokenize` armed becomes the bare
// character, a metacharacter that is a raw byte of a VALUE becomes
// `\X`. A pattern word holds both at once — c:Src/subst.c:1551-1552
// tokenizes the `(~j)` join SEPARATOR while the array ELEMENTS it joins
// keep their raw bytes — which is why escaping the word wholesale (or
// not at all) is wrong in both directions.
//
// Non-token text is untokenized in RUNS rather than per character, so
// `untokenize`'s multi-character decodes still see their whole input:
// the `Meta` pair (lex.rs's metafied high byte) and the
// `Qstring Snull` … `Snull` span of a `$'…'` literal
// (c:Src/subst.c:301-304).
fn flush_literal_run(lit: &mut String, out: &mut String) {
if lit.is_empty() {
return;
}
for c in crate::lex::untokenize(lit).chars() {
if is_pattern_meta(c) {
out.push('\\');
}
out.push(c);
}
lit.clear();
}
let mut out = String::with_capacity(p.len() * 2);
let mut lit = String::new();
let cs: Vec<char> = p.chars().collect();
let mut i = 0;
while i < cs.len() {
let c = cs[i];
// c:Src/glob.c:3593-3596 `case Meta: s++;` — `Meta` and the
// character after it are ONE unit and neither is a token.
if c as u32 == crate::ported::zsh_h::Meta as u32 && i + 1 < cs.len() {
lit.push(c);
lit.push(cs[i + 1]);
i += 2;
continue;
}
match active_pattern_token(c) {
Some(m) => {
flush_literal_run(&mut lit, &mut out);
out.push(m);
}
None => lit.push(c),
}
i += 1;
}
flush_literal_run(&mut lit, &mut out);
Value::str(out)
});
// argc contract — the caller names the `spbreak` (c:Src/subst.c:1707,
// :2563, :2567) its spelling implies, because c:3912's whole join/split
// block is gated on it:
//
// 0 plain `${NAME[*]}`, unquoted and not `ssub`. `spbreak` is
// SH_WORD_SPLIT, read at RUN time (the option can be set by an
// earlier statement in the same compiled unit).
// 1 "JOIN and STOP" — a PREFORK_SINGLE (`ssub`) context: a scalar
// assignment RHS (c:Src/exec.c:2603), a `typeset NAME=…` argument, a
// `case` word (c:Src/loop.c:611), a `[[ … ]]` operand
// (c:Src/cond.c:53) or the here-string word (c:Src/exec.c:4711).
// c:Src/subst.c:4226
// if (isarr && ssub) { val = sepjoin(aval, NULL, 1); isarr = 0; }
// "prefork() wants a scalar, so join no matter what else" — the join
// is the LAST thing that happens to the value, and `singsub`
// (c:Src/subst.c:514-525) never reaches `globlist`, so nothing splits
// it afterwards. c:3913's `force_split = !ssub && …` says the same.
// 2 `${==NAME[*]}` — c:2563 clears `spbreak`, so the gate stays SHUT
// whatever SH_WORD_SPLIT says and the element vector survives.
// 3 `${=NAME[*]}` / `${=NAME[@]}` — c:2567 sets `spbreak = 2`. c:3917
// joins and c:3932 `sepsplit` splits, but that split is
// BUILTIN_FORCE_SPLIT at the compile site, so this handler stops at
// the join rather than splitting twice. When c:3914-3927 leaves the
// value ARRAY-shaped it returns the array and FORCE_SPLIT's c:3931
// `!isarr` gate passes it through.
vm.register_builtin(BUILTIN_ARRAY_JOIN_STAR, |vm, argc| {
let join_no_split = argc == 1;
let name = vm.pop().to_str();
let (elems, joined, ifs_opt, in_dq) = with_executor(|exec| {
// c:Src/params.c — `"$*"` joins by IFS[0]. zsh
// distinguishes IFS=unset (→ default `" "`) from
// IFS="" (→ EMPTY separator → fields concatenate).
// chars().next() collapsed both into the default, so
// IFS="" was treated as IFS=" ".
// c:Src/params.c:4745 `ifssetfn` — the C `ifs` global is NULL only
// when IFS is genuinely UNSET, and c:3919's `(!ifs && …)` turns on
// exactly that distinction, so carry the Option, not a defaulted
// string.
let ifs_opt = exec.scalar("IFS");
let ifs_full = ifs_opt
.clone()
.unwrap_or_else(|| " \t\n".to_string());
let sep = ifs_full
.chars()
.next()
.map(|c| c.to_string())
.unwrap_or_default();
let in_dq = exec.in_dq_context > 0;
// c:Src/subst.c:3914 — the join at c:3917 is `sepjoin(aval, …)`,
// i.e. it runs on the ELEMENT vector, and c:3912's gate can leave
// that vector untouched. Keep both shapes: the joined scalar for
// the quoted / join-and-stop arms, and the elements for the plain
// command-argument arm that must not join at all.
let (elems, _) = param_value_elems_c2916(exec, &name);
let joined = elems.join(&sep);
(elems, joined, ifs_opt, in_dq)
});
// In QUOTED (`"${name[*]}"`) context the result IS a single scalar —
// c:Src/subst.c:3033 `if (qt && !getlen && isarr > 0) { val =
// sepjoin(aval, sep, 1); isarr = 0; }`. And argc 1 is the caller
// saying it wants the join without the split (see the contract above).
if in_dq || join_no_split {
return Value::str(joined);
}
// c:Src/subst.c:3912 — the join-then-split block is gated:
//
// if (ssub || spbreak || spsep || sep || quoted_array_with_offset) {
// int force_split = !ssub && (spbreak || spsep);
//
// `sep` / `spsep` are the `(j:…:)` / `(s:…:)` separators, which never
// reach this fast path (a flagged expansion goes to paramsubst), and
// the join-and-stop and quoted arms returned above. So the only way in
// left from here is `spbreak`, c:Src/subst.c:1707
// int spbreak = (pf_flags & PREFORK_SHWORDSPLIT)
// && !(pf_flags & PREFORK_SINGLE) && !qt;
// i.e. SH_WORD_SPLIT — or an explicit `${=…}` / `${==…}`, which the
// argc contract above hands down because c:2563/:2567 override the
// option. Without `spbreak` the block does not run at all and the
// expansion keeps its ARRAY shape untouched — `${a[*]}` unquoted is the
// same splat as `${a[@]}`, elements intact:
// a=("p:q" r); IFS=:; print -rl -- ${a[*]} -> `p:q` `r`
// a=("p q" r); print -rl -- ${a[*]} -> `p q` `r`
// a=(x y); IFS=; print -rl -- ${a[*]} -> `x` `y`
// This handler ran the join and the split unconditionally, so the
// first two came back as three words and the third — an EMPTY IFS
// joins with "" and then has no separator left to split on — as the
// single word `xy`.
//
// The empty-word removal below is c:Src/subst.c:184-187 `uremnode`,
// the same prefork pass the `[@]` splat gets from
// BUILTIN_ARRAY_DROP_EMPTY at its compile site; the joined+split path
// used to supply it as a side effect of its `filter`.
let spbreak = match argc {
// c:2563 — `${==NAME[*]}` clears spbreak whatever the option says.
2 => 0,
// c:2567 — `${=NAME[*]}` / `${=NAME[@]}` force it to 2.
3 => 2,
_ => i32::from(crate::ported::zsh_h::isset(crate::ported::zsh_h::SHWORDSPLIT)),
};
if spbreak == 0 {
return splice_words_value(prefork_c184_drop_empty(elems));
}
match join_c3914(elems, ifs_opt.as_deref()) {
// c:3914-3927 left `isarr` non-zero, so c:3931's `!isarr` keeps the
// split off as well and the ORIGINAL elements are the answer.
JoinC3914::Elements(kept) => {
if argc == 3 {
// BUILTIN_FORCE_SPLIT runs next; its c:3931 gate passes an
// array through and applies the empty-word removal itself.
return Value::array(kept.into_iter().map(Value::str).collect());
}
splice_words_value(prefork_c184_drop_empty(kept))
}
JoinC3914::Joined(val) => {
if argc == 3 {
// c:3932's `sepsplit` is BUILTIN_FORCE_SPLIT at the compile
// site — hand it the joined scalar rather than split twice.
return Value::str(val);
}
split_words_c3932(&val)
}
}
});
// argc contract — `0` and `1` are the historical callers (the bare
// `$@`/`$*`/`$argv` read, `${^NAME}`, a for-list `$NAME`, a QUOTED
// `"${NAME[@]}"`), which take the splat exactly as read. `2` and `3` are
// the `${NAME[@]}` / `${=NAME[@]}` splice fast paths asking for
// c:Src/subst.c:3912-3939 to run over the result — see
// BUILTIN_ARRAY_JOIN_STAR's contract, whose `0` and `3` these mirror.
// c:3030-3032 forces `isarr = -1` for a `[*]` splice whenever `nojoin` is
// set, so `[@]` and `[*]` need the SAME answer here and share the code.
vm.register_builtin(BUILTIN_ARRAY_ALL, |vm, argc| {
let name = vm.pop().to_str();
// c:Src/params.c:2027-2029 — a `[@]`/`[*]` subscript sets
// SCANPM_ISVAR_AT, i.e. `isarr != 0` (c:2915). An empty result is
// therefore an empty ARRAY, and plan9 deletes the whole word
// (c:4362) rather than keeping the surrounding text.
//
// The note describes the EMPTY value this expansion produces, so it
// must not survive a NON-empty one: the bit is read by concat_plan9
// when the word folds left-associatively, and a later non-empty
// segment overwriting it made `setopt rcexpandparam; e=''; a=(x y);
// print -rl -- ${e}${a}` delete the whole word instead of printing
// `x` and `y` (c:4437 keeps the surrounding text for a scalar
// empty; only c:4362's empty ARRAY deletes it). Restore the
// incoming bit whenever the result is not an empty array.
let saved_empty_is_scalar = empty_is_scalar();
note_empty_is_scalar(false);
let array_all = |vm: &mut fusevm::VM| -> Value {
let _ = &vm;
// bash `"${PIPESTATUS[@]}"` / `"${FUNCNAME[@]}"` / `"${BASH_VERSINFO[@]}"`
// splat — alias the zsh-native special. No-op in --zsh.
if let Some(v) = crate::dash_mode::bash_special_array(&name) {
return Value::array(v.into_iter().map(Value::str).collect());
}
with_executor(|exec| {
// Special positional names — splice the positional list.
if name == "@" || name == "*" || name == "argv" {
return Value::array(exec.pparams().iter().map(Value::str).collect());
}
// c:Src/Modules/parameter.c — funcstack/funcfiletrace/
// funcsourcetrace/functrace are PM_ARRAY|PM_READONLY
// specials backed by the canonical FUNCSTACK Vec.
// `${funcstack[@]}` inside a function call should splat
// the innermost-first names; without this branch the
// runtime fell to the scalar fallback (get_variable
// returns empty for these specials) and `[@]` came out
// empty. Bug #276 in docs/BUGS.md. Mirrors the parallel
// arrays_get handler at src/ported/subst.rs ~10685.
// c:Src/Modules/datetime.c:256 — `epochtime` PM_ARRAY|
// PM_READONLY backed by getcurrenttime(). Same parallel
// arrangement as the FUNCSTACK-backed specials below.
if name == "epochtime" {
// c:Src/params.c:589-594 getparamnode → c:563-585 loadparamnode —
// the `[@]` splat resolves the NAME, clearing PM_AUTOLOAD so
// paramtypestr (c:Src/Modules/parameter.c:48-50) reports the real
// type. Mirrors the arrays_get arm in src/ported/subst.rs.
if !crate::vm_helper::magic_special_shadowed(&name) {
crate::vm_helper::mark_module_param_used(&name);
}
let arr = crate::ported::modules::datetime::getcurrenttime();
return Value::array(arr.into_iter().map(Value::str).collect());
}
if matches!(
name.as_str(),
"funcstack" | "funcfiletrace" | "funcsourcetrace" | "functrace"
) {
// c:Src/params.c:589-594 — see the epochtime arm above.
if !crate::vm_helper::magic_special_shadowed(&name) {
crate::vm_helper::mark_module_param_used(&name);
}
// Route the three trace arrays through the canonical
// ported getfns (Src/Modules/parameter.c:648/:679/:711)
// — the previous inline copy emitted wrong shapes
// (bare filename for funcfiletrace, `name:lineno` for
// functrace instead of `caller:lineno`); same dedup as
// the parallel arrays_get handler in subst.rs.
let vals: Vec<String> = match name.as_str() {
"funcstack" => crate::ported::modules::parameter::FUNCSTACK
.lock()
.map(|f| f.iter().rev().map(|fs| fs.name.clone()).collect())
.unwrap_or_default(),
"funcfiletrace" => crate::ported::modules::parameter::funcfiletracegetfn(
std::ptr::null_mut(),
),
"funcsourcetrace" => {
crate::ported::modules::parameter::funcsourcetracegetfn(
std::ptr::null_mut(),
)
}
_ => {
crate::ported::modules::parameter::functracegetfn(std::ptr::null_mut())
}
};
return Value::array(vals.into_iter().map(Value::str).collect());
}
// c:Src/params.c — `${assoc[@]}` enumerates VALUES (per
// params.c:1696-1750 hashparam splat). Check assoc
// storage BEFORE the scalar fallback so an associative
// array named X resolves `${X[@]}` to the values, not
// empty. Bug #109 in docs/BUGS.md: `${h[@]}` on an
// assoc routed through BUILTIN_ARRAY_ALL, which only
// consulted `exec.array(name)` (the indexed-array map)
// — that lookup missed for assocs, fell through to
// `get_variable("h")` (also empty for an assoc-only
// name), and returned `Array(vec![])`. zsh's expected
// behavior is to enumerate values.
if let Some(assoc_map) = exec.assoc(&name) {
return Value::array(assoc_map.values().cloned().map(Value::str).collect());
}
match exec.array(&name) {
Some(v) => {
// bash sparse arrays: `"${a[@]}"` splats only LIVE
// elements, dropping hole slots (`a[5]=q` padding,
// `unset a[i]`). No-op in --zsh (no holes tracked).
let v = crate::bash_arrays::compact(&name, v);
Value::array(v.iter().map(Value::str).collect())
}
None => {
// c:Src/Modules/parameter.c:2235-2298 partab[] — the
// PM_HASHED magic assocs (aliases/functions/parameters/
// options/commands/builtins/modules/widgets/nameddirs/…)
// are real hash params in C, so `${aliases[@]}` takes the
// ordinary getvaluearr path and enumerates their VALUES.
// zshrs keeps them OUT of the executor's assoc storage
// (they are synthesized on demand by `subst::assoc_get`),
// so the `exec.assoc` probe above missed and this arm fell
// through to the scalar fallback, which returned an EMPTY
// array: `alias foo=bar; print -r -- "${aliases[@]}"` gave
// nothing where zsh gives `bar man whence`. Every other
// form already routed through paramsubst's own magic-assoc
// arms; only the flagless `[@]`/`[*]` splat compiles to
// BUILTIN_ARRAY_ALL and reached here.
//
// Placed in the `None` arm so a real indexed array or a
// user-defined assoc of the same name still wins, and so
// no ordinary array read pays for the PARTAB scan.
//
// Same gap on the PM_ARRAY side (c:2239-2291 partab[]
// rows: reswords/dis_reswords/patchars/dis_patchars/…):
// `getaparam` reads `pm->u.arr`, which is NULL on the
// placeholder node zshrs installs for a getfn-backed
// special, so `${reswords[@]}` splatted nothing. Route
// through the canonical `arrays_get` getfn dispatch.
if let Some(arr) = crate::ported::subst::arrays_get(&name) {
return Value::array(arr.into_iter().map(Value::str).collect());
}
if let Some(map) = crate::ported::subst::assoc_get(&name) {
return Value::array(map.values().cloned().map(Value::str).collect());
}
// Fall back to scalar lookup. zsh (unlike bash)
// does NOT IFS-split a scalar variable in a for
// list — `for w in $scalar` iterates ONCE with the
// scalar value. Word-splitting requires either
// sh_word_split option or explicit `${(s.,.)scalar}`.
let val = exec.get_variable(&name);
if val.is_empty() && !exec.has_scalar(&name) && env::var(&name).is_err() {
// c:Src/subst.c:3480-3485 — `${arr[@]}` on a genuinely
// UNSET parameter under NO_UNSET is a "parameter not set"
// error (vunset > 0 && unset(UNSET)), exactly like the
// scalar `$arr`, the `${arr[*]}` splat, and `${arr[1]}`
// — all of which already fire it via GET_VAR. The `[@]`
// splat path returned an empty array silently, so
// `setopt NO_UNSET; print "${arr[@]}"` exited 0 where zsh
// exits 1. A DECLARED-but-empty array (`arr=()`) resolves
// to `Some(vec![])` above and never reaches here, so it
// still splats to nothing without erroring — matching zsh.
if opt_state_get("nounset").unwrap_or(false) {
crate::ported::utils::zerr(&format!("{}: parameter not set", name));
crate::ported::utils::errflag.fetch_or(
crate::ported::zsh_h::ERRFLAG_ERROR,
std::sync::atomic::Ordering::Relaxed,
);
exec.set_last_status(1);
}
// c:Src/subst.c:3480-3485 — an UNSET parameter takes the
// `vunset` arm: `val = dupstring("")` with isarr left at
// 0. That is a SCALAR empty, so plan9 keeps the
// surrounding text (`setopt rcexpandparam;
// print -r -- "[${unset[@]}]"` → `[]`), unlike a
// DECLARED-but-empty array (`arr=()`, matched by the
// `Some(vec![])` arm above), which sets isarr and gets
// the word deleted at c:4362.
note_empty_is_scalar(true);
// c:Src/subst.c:3603-3610 — an UNSET parameter leaves `isarr` at 0
// and yields `val = ""`, i.e. a SCALAR empty, so a quoted
// `"${u[@]}"` is ONE empty word (`f "${u[@]}"` → $# == 1) while
// `"${empty_array[@]}"` is zero. Returning an empty ARRAY here
// collapsed both to zero words. The unquoted form still drops it:
// the compiler emits BUILTIN_ARRAY_DROP_EMPTY after this call for
// non-DQ splices (compile_zsh.rs:6149), and that builtin maps an
// empty Str to an empty array.
Value::str(String::new())
} else if opt_state_get("shwordsplit").unwrap_or(false)
// c:Src/subst.c:1707-1708 — `spbreak = (pf_flags &
// PREFORK_SHWORDSPLIT) && … && !qt`: a quoted
// `"${scalar[@]}"` (argc 4, see below) is never split.
&& argc != 4
{
// c:3921 `aval = sepsplit(val, spsep, 0, 1)` — same
// splitter as `${=name}` (Src/utils.c:3711 spacesplit),
// not a naive `split().filter(non-empty)`: only the
// IFS-WHITESPACE-derived empty fields are elided; the
// `nulstring` ones an IFS-NON-whitespace separator makes
// survive (c:Src/subst.c:36).
let nulstring = crate::ported::zsh_h::Nularg.to_string();
let parts: Vec<Value> =
crate::ported::utils::sepsplit(&val, None, false)
.into_iter()
.filter_map(|w| {
if w == nulstring {
Some(Value::str(String::new()))
} else if w.is_empty() {
None // c:184-187 prefork uremnode
} else {
Some(Value::str(w))
}
})
.collect();
Value::array(parts)
} else {
Value::array(vec![Value::str(val)])
}
}
}
})
};
let result = array_all(vm);
if !matches!(&result, Value::Array(a) if a.is_empty()) {
note_empty_is_scalar(saved_empty_is_scalar);
}
// argc 4 is the compile site's "this `[@]` splat is QUOTED" bit
// (`compile_zsh.rs`, the `${NAME[@]}` fast path). c:Src/subst.c:4387
// `if (qt && !*y && isarr != 2) y = dupstring(nulstring)` then keeps
// this read's empty elements alive through c:186 — but only above
// c:4261's two-element cut-off, which is why the count is applied here
// and not at the compile site. See `QUOTED_SPLICE_KEEPS_EMPTIES`.
// Every other argc is an UNQUOTED (or `ssub`-joined) read, so it must
// CLEAR the bit rather than leave a previous word's set: a whole-word
// `"${a[@]}"` emits no end-of-word drop, so nothing else spends it.
let quoted_splat_elems = match &result {
Value::Array(items) if argc == 4 => items.len(),
_ => 0,
};
note_quoted_splice_elems(quoted_splat_elems);
// c:Src/subst.c:3912-3939 for the `${NAME[@]}` splice fast paths. Only
// an ARRAY-shaped result reaches the block (c:3914 `if (isarr || …)`);
// the scalar arms above — an unset parameter (c:3480-3485), the
// scalar-fallback read — leave `isarr` at 0 and pass straight through.
if !matches!(argc, 2 | 3) {
return result;
}
let Value::Array(items) = &result else {
return result;
};
let elems: Vec<String> = items.iter().map(|v| v.to_str()).collect();
// c:1707 / :2567 — `spbreak` is SH_WORD_SPLIT for a plain `${NAME[@]}`
// (argc 2), forced to 2 by the `=` flag (argc 3).
let spbreak = if argc == 3 {
2
} else {
i32::from(crate::ported::zsh_h::isset(crate::ported::zsh_h::SHWORDSPLIT))
};
// The gate never opens / neither join arm fires: no join, no split,
// only c:184-187's empty-word removal — which the compile site used to
// append as a separate BUILTIN_ARRAY_DROP_EMPTY, and that builtin
// always returned an ARRAY. Keep that exact shape so nothing
// downstream (concat, plan9, argv splice) sees a one-element splat turn
// into a scalar.
// c:Src/subst.c:4366-4437 then c:183-186 — the removal tests the
// FINISHED node, after the word's text is glued onto the first and
// last elements. When this read is a segment of such a word
// (BUILTIN_WORD_DEFER_EMPTIES opened it) the word's own end-of-word
// drop runs that test; removing the empty elements here, before the
// concat, dropped the ones the affixes land on:
// `a=(x y ""); print -rl -- p${a[@]}q` is `px` `y` `q` in zsh.
let defer_to_word = crate::ported::subst::PARAMSUBST_AFFIXES_DEFERRED.with(|c| c.get()) > 0;
let untouched = |e: Vec<String>| {
let e = if defer_to_word { e } else { prefork_c184_drop_empty(e) };
Value::array(e.into_iter().map(Value::str).collect())
};
if spbreak == 0 {
return untouched(elems);
}
let ifs_opt = with_executor(|exec| exec.scalar("IFS"));
match join_c3914(elems, ifs_opt.as_deref()) {
JoinC3914::Elements(kept) => {
if argc == 3 {
Value::array(kept.into_iter().map(Value::str).collect())
} else {
untouched(kept)
}
}
JoinC3914::Joined(val) => {
if argc == 3 {
// BUILTIN_FORCE_SPLIT is c:3932 at the compile site.
Value::str(val)
} else if defer_to_word {
// c:3932 sepsplit, then c:184-187 on the FINISHED word: the
// enclosing word's end-of-word drop removes the truly empty
// edge fields after its text is glued on and strips the c:36
// `nulstring` markers. `setopt shwordsplit; IFS=:; a=(a ""
// b); print -rl -- x${a[@]}y` is `xa` `` `by`.
Value::array(
crate::ported::utils::sepsplit(&val, None, false)
.into_iter()
.map(Value::str)
.collect(),
)
} else {
splice_words_value(sepsplit_c3932(&val, false))
}
}
}
});
// BUILTIN_ARRAY_FLATTEN(N): pops N values, flattens one level of Array
// nesting, pushes the resulting Array AND its length as a separate Int.
// The two-value return shape lets the caller (for-loop compile path)
// SetSlot the length before SetSlot'ing the array, without re-deriving
// the length from the array via a second builtin call.
// `coproc [name] { body }` — bidirectional pipe to backgrounded body.
// Stack discipline (top first): [name (str, "" for default), sub_idx (int)].
// On success: parent's `executor.arrays[name]` becomes [write_fd, read_fd]
// and Status(0) is returned. The caller writes to the child's stdin via
// write_fd, reads its stdout via read_fd, and closes both when done.
//
// Bash's coproc convention is `${NAME[0]}` = read_fd, `${NAME[1]}` =
// write_fd. We follow that: arrays[name] = [read_fd_str, write_fd_str].
vm.register_builtin(BUILTIN_RUN_COPROC, |vm, _argc| {
let sub_idx = vm.pop().to_int() as usize;
let job_text = vm.pop().to_str();
let raw_name = vm.pop().to_str();
let name = if raw_name.is_empty() {
"COPROC".to_string()
} else {
raw_name
};
let chunk = match vm.chunk.sub_chunks.get(sub_idx).cloned() {
Some(c) => c,
None => return Value::Status(1),
};
// c:Src/exec.c:1760 — `thisjob = newjob = initjob()` comes BEFORE the
// old coproc's fds are closed (c:1768-1772), so that coproc, which
// only starts exiting once they close, still holds its job slot and
// the new one gets the next number: `coproc cat; …; coproc cat; jobs`
// lists `[2]`. Taking the slot after the fork raced the reaper.
let newjob = {
let table = crate::ported::jobs::JOBTAB
.get_or_init(|| std::sync::Mutex::new(Vec::new()));
let mut tab = table.lock().unwrap_or_else(|e| e.into_inner());
crate::ported::jobs::initjob(&mut tab)
};
// A coproc that never starts gives the slot back.
let release_newjob = || {
if let Some(table) = crate::ported::jobs::JOBTAB.get() {
let mut tab = table.lock().unwrap_or_else(|e| e.into_inner());
tab[newjob].stat = 0;
}
};
// c:Src/exec.c:1710-1712 — starting a new coproc closes the
// previous one's fds FIRST:
// if (coprocin >= 0) { zclose(coprocin); zclose(coprocout); }
// The old coproc child then sees EOF on its stdin and exits on
// its own schedule (its job-table entry stays until it's
// reaped) — zsh does NOT deletejob it here. This is also what
// makes the `exec 4<&p; coproc exit; read -u4` EOF idiom work:
// the replacement coproc closes the shell's write end to the
// old one.
{
use std::sync::atomic::Ordering;
let old_in = crate::ported::modules::clone::coprocin.load(Ordering::Relaxed);
if old_in >= 0 {
let old_out = crate::ported::modules::clone::coprocout.load(Ordering::Relaxed);
unsafe {
libc::close(old_in);
if old_out >= 0 {
libc::close(old_out);
}
}
crate::ported::modules::clone::coprocin.store(-1, Ordering::Relaxed);
crate::ported::modules::clone::coprocout.store(-1, Ordering::Relaxed);
}
}
// (parent_read ← child_stdout)
let mut p2c = [0i32; 2]; // parent writes, child reads
let mut c2p = [0i32; 2]; // child writes, parent reads
if unsafe { libc::pipe(p2c.as_mut_ptr()) } < 0 {
release_newjob();
return Value::Status(1);
}
if unsafe { libc::pipe(c2p.as_mut_ptr()) } < 0 {
unsafe {
libc::close(p2c[0]);
libc::close(p2c[1]);
}
release_newjob();
return Value::Status(1);
}
// c:Src/exec.c:5160 mpipe — both pipes' fds are moved above
// the user-visible range (movefd → F_DUPFD ≥ 10) so the
// coproc fds never collide with explicit user fds like
// `exec 3>&p`.
for fd in p2c.iter_mut().chain(c2p.iter_mut()) {
*fd = crate::ported::utils::movefd(*fd);
}
// c:Src/exec.c:1748/1815 — a coproc is spawned by execpline's
// Z_ASYNC arm, inside the same `child_block()` span as `cmd &`.
#[cfg(unix)]
let _child_block = ChildBlockSpan::enter();
match unsafe { libc::fork() } {
-1 => {
unsafe {
libc::close(p2c[0]);
libc::close(p2c[1]);
libc::close(c2p[0]);
libc::close(c2p[1]);
}
release_newjob();
Value::Status(1)
}
0 => {
forked_child_subsh_levels(); // c:Src/exec.c:1221
EXECCMD_FORKED.with(|f| f.set(true)); // c:Src/exec.c:3063 `last1 = forked = 1`
// Child: stdin from p2c[0], stdout to c2p[1]. Close all
// unused fds. setsid so SIGINT to fg doesn't hit us.
unsafe {
libc::dup2(p2c[0], libc::STDIN_FILENO);
libc::dup2(c2p[1], libc::STDOUT_FILENO);
libc::close(p2c[0]);
libc::close(p2c[1]);
libc::close(c2p[0]);
libc::close(c2p[1]);
libc::setsid();
}
crate::fusevm_disasm::maybe_print_stdout("coproc:child", &chunk);
let mut co_vm = fusevm::VM::new(chunk);
register_builtins(&mut co_vm);
let _ = co_vm.run();
let _ = std::io::stdout().flush();
let _ = std::io::stderr().flush();
std::process::exit(co_vm.last_status);
}
pid => {
// Parent: close child ends, store [read_fd, write_fd] in NAME.
unsafe {
libc::close(p2c[0]);
libc::close(c2p[1]);
}
let read_fd = c2p[0];
let write_fd = p2c[1];
// bash(1) `coproc`: the child's pid is published as NAME_PID.
if crate::dash_mode::bash_mode() {
crate::ported::params::setsparam(&format!("{name}_PID"), &pid.to_string());
}
with_executor(|exec| {
exec.unset_scalar(&name);
exec.set_array(name, vec![read_fd.to_string(), write_fd.to_string()]);
});
// c:Src/exec.c — `coprocin`/`coprocout` are the
// canonical globals that bin_read's `-p` arm
// (Src/builtin.c:6510) and bin_print's `-p` arm
// (Src/builtin.c:4827) read to find the
// coprocess fds. The Rust port has the atomic
// declarations at src/ported/modules/clone.rs:262
// but the coproc-launch path never updated them,
// so `read -p` / `print -p` always errored with
// "-p: no coprocess" even when a coproc was
// running. Bug #388 in docs/BUGS.md. Update them
// here so the canonical builtins find the live
// pipe.
crate::ported::modules::clone::coprocin
.store(read_fd, std::sync::atomic::Ordering::Relaxed);
crate::ported::modules::clone::coprocout
.store(write_fd, std::sync::atomic::Ordering::Relaxed);
// c:Src/exec.c:1725 — `fdtable[coprocin] =
// fdtable[coprocout] = FDT_UNUSED;`: the two kept ends
// are user-reachable (via `>&p` / `<&p`), so they drop
// the FDT_INTERNAL mark movefd gave them.
crate::ported::utils::fdtable_set(read_fd, crate::ported::zsh_h::FDT_UNUSED);
crate::ported::utils::fdtable_set(write_fd, crate::ported::zsh_h::FDT_UNUSED);
// c:Src/exec.c:2837 — `lastpid = (zlong) pid;`. zsh
// sets the `$!` global to the coproc child's PID so
// subsequent `$!` reads return it. The Rust port at
// exec.rs:6773 mirrors this for regular background
// jobs but the coproc launch path was missing the
// assignment, leaving `$!` at 0 after `coproc cmd`.
crate::ported::modules::clone::lastpid
.store(pid, std::sync::atomic::Ordering::Relaxed);
// c:Src/exec.c:1700-1758 — the coproc rides the SAME
// Z_ASYNC job-table path as `cmd &`: `thisjob = newjob
// = initjob()` (c:1700), addproc hangs the pid+text
// proc entry off the job, `jobtab[thisjob].stat |=
// STAT_NOSTTY` (c:1746), `clearoldjobtab()` (c:1744)
// and `spawnjob()` (c:1758) promote it to curjob. This
// is what makes `jobs` list the coproc as
// `[1] + running cat` and `kill %1` resolve it.
// Mirrors the BUILTIN_RUN_BG parent arm exactly.
{
use crate::ported::jobs;
use std::sync::Mutex;
let table = jobs::JOBTAB.get_or_init(|| Mutex::new(Vec::new()));
let idx = {
let mut tab = table.lock().unwrap_or_else(|e| e.into_inner());
let idx = newjob; // c:exec.c:1760, reserved above
jobs::addproc(
&mut tab[idx],
pid,
&job_text,
false,
Some(std::time::Instant::now()),
-1,
-1,
);
tab[idx].stat |= crate::ported::zsh_h::STAT_NOSTTY; // c:exec.c:1746
idx
};
jobs::clearoldjobtab(); // c:exec.c:1744
if let Ok(mut tj) = jobs::THISJOB.get_or_init(|| Mutex::new(-1)).lock() {
*tj = idx as i32;
}
jobs::spawnjob(); // c:exec.c:1758
}
with_executor(|exec| {
exec.jobs
.add_pid_job(pid, job_text.clone(), JobState::Running);
});
Value::Status(0)
}
}
});
vm.register_builtin(BUILTIN_ARRAY_FLATTEN, |vm, argc| {
// `${~spec}` carrier: a `for`/`select` WORD LIST is a word-
// pipeline boundary too. In C the `globsubst` flag is a
// paramsubst-LOCAL int (Src/subst.c:1671 `int globsubst =
// isset(GLOBSUBST);`, forced to 2 by `${~…}` at
// Src/subst.c:2603) whose only lasting effect is the
// `shtokenize` of that substitution's own result — it never
// reaches the option table, so `execfor`'s list prefork
// (Src/loop.c:196-235) cannot leak it into the loop BODY.
// zshrs carries the flag through the global option table so
// the compile-emitted glob ops of the SAME word can see it
// (documented deviation at subst.rs:3190), and restores it at
// command-dispatch boundaries — but a `for` list has no
// trailing dispatch of its own, so `for i in "${a:#${~p}*}"`
// left GLOB_SUBST ON and filename-generated the FIRST body
// command's words (`_parameters:34` → `ary+=($i:"$v")` glob-
// erroring "bad pattern: HISTCHARS:!^#", which aborted the
// whole `pr<TAB>` completion). This builtin ends EVERY for/
// select list expansion and runs AFTER each word's
// GLOB_SUBST_EXPAND op, so the carrier has been read by then.
consume_tilde_globsubst_carrier();
let n = argc as usize;
let start = vm.stack.len().saturating_sub(n);
let raw: Vec<Value> = vm.stack.drain(start..).collect();
let mut flat: Vec<Value> = Vec::with_capacity(raw.len());
for v in raw {
match v {
Value::Array(items) => flat.extend(items.iter().cloned()),
other => flat.push(other),
}
}
let len = flat.len() as i64;
// Push the array first; the Int(len) becomes the builtin's return
// value (which CallBuiltin already pushes). Caller consumes in
// reverse: SetSlot(len_slot) pops Int, SetSlot(arr_slot) pops Array.
vm.push(Value::array(flat));
Value::Int(len)
});
// Shell variable get/set — routes through executor.variables so nested
// VMs (function calls) and tree-walker callers see the same storage.
// GET_VAR / GET_VAR_DQ share one body via `get_var_impl`; the only
// difference is `force_dq`, which the compiler sets for QUOTED simple
// reads (`"$name"`) so an array's empty elements are preserved (the
// `in_dq_context` runtime flag is 0 for these compiler-direct reads).
fn get_var_impl(vm: &mut fusevm::VM, argc: u8, force_dq: bool) -> Value {
let args = pop_args(vm, argc);
let name = args.into_iter().next().unwrap_or_default();
let live_status = vm.last_status;
// `$@` and `$*` need splice semantics — return Value::Array of
// positional params so for-loop's BUILTIN_ARRAY_FLATTEN spreads them
// and pop_args splits them into argv slots. zsh's `"$@"` bslashquote-each-
// word semantics matches: each pos-param becomes its own arg.
// Same for arrays accessed by name (e.g. `$arr` in some contexts).
//
// vm.last_status is authoritative: `subshell_end` now returns
// Some(status) and fusevm's `Op::SubshellEnd` writes it into
// vm.last_status, so a deferred subshell `exit N` is visible
// here. Suppressing this sync (as an older revision did, back
// when the host hook returned nothing) made LASTVAL win over
// any status the VM set AFTER SubshellEnd — which dropped the
// `!` negation of `Src/exec.c:1979-1980`
// if ((slflags & WC_SUBLIST_NOT) && !errflag && !retflag)
// lastval = !lastval;
// for `! (exit 7)` (emit_negate_status' SetStatus updated
// vm.last_status, then `$?` read the stale LASTVAL=7).
let sync_status = |exec: &mut ShellExecutor| {
exec.set_last_status(live_status);
};
if name == "@" || name == "*" {
// Quoting decides empty-word retention (c:Src/subst.c:
// 184-187): the COMPILE site knows it and emits
// BUILTIN_ARRAY_DROP_EMPTY after this read for the
// unquoted form only — in_dq_context is NOT a valid
// discriminator here (the quoted "$@" fast path emits
// GET_VAR directly without an EXPAND_TEXT wrapper).
let pp = with_executor(|exec| {
sync_status(exec);
exec.pparams()
});
// c:Src/subst.c:1817 — `int nojoin = (pf_flags &
// PREFORK_SHWORDSPLIT) ? !(ifs && *ifs) && !qt : 0;`
// c:Src/subst.c:3908-3911 — `if (nojoin == 0 || sep) { val =
// sepjoin(aval, sep, 1); isarr = 0; }`
// c:Src/subst.c:3919-3921 — `if (force_split && !isarr) { aval =
// sepsplit(val, spsep, 0, 1); … }`
//
// So under SH_WORD_SPLIT an UNQUOTED `$@`/`$*` with a NON-EMPTY
// `$IFS` is first JOINED on `$IFS[1]` and then re-split on `$IFS`
// — which is why `setopt shwordsplit; set -- one:two b:c; IFS=:;
// print -l $@` is four words in zsh (and in bash, and in ksh).
// The port returned the raw positional list, so an element
// carrying an IFS byte was never broken up
// (D04parameter.ztst "Splitting of $@ on IFS: single element";
// `zshrs --bash -c 'set -- "a b" c; printf "[%s]\n" $@'` printed
// `[a b]` where bash prints `[a]` `[b]`).
//
// The gates are C's, verbatim: `!force_dq` is `!qt`, an UNSET or
// EMPTY `$IFS` leaves `nojoin` at 1 (no join, no split), and the
// whole rule is inert without SH_WORD_SPLIT (`nojoin = 0` there,
// but `force_split` at c:3913 is `!ssub && (spbreak || spsep)`,
// all clear, so neither branch runs).
if !force_dq && crate::ported::zsh_h::isset(crate::ported::zsh_h::SHWORDSPLIT) {
// c:1817 — carry the Option: an UNSET `$IFS` (`!ifs`) joins on
// " " and splits at c:3919-3925 (`(!ifs && isarr < 0)`), unlike an
// EMPTY one. `join_c3914` encodes both arms.
let ifs_opt = with_executor(|exec| exec.scalar("IFS"));
if let JoinC3914::Joined(joined) = join_c3914(pp.clone(), ifs_opt.as_deref()) {
// c:3919 `sepsplit(val, spsep, 0, 1)` with spsep NULL →
// spacesplit (c:Src/utils.c:3711), then c:184-187. The
// IFS-whitespace edge fields are truly empty and c:186
// deletes them only from the FINISHED word, after the
// word's text is glued on (c:4366-4437): `setopt
// shwordsplit; set -- "" x ""; print -rl -- p$@q` is `p`
// `x` `q`. So inside a word that defers that removal
// (BUILTIN_WORD_DEFER_EMPTIES) the fields go out raw, the
// c:36 `nulstring` markers included, exactly as
// BUILTIN_FORCE_SPLIT hands them over; a whole word gets
// the removal from the compile site's BUILTIN_ARRAY_DROP_EMPTY,
// which also strips the markers (c:170). multsub's
// PREFORK_SPLIT walker, used before, dropped the edge fields
// outright and folded `nulstring` to "" (`IFS=:; set -- a::b;
// print -rl -- $@` lost its middle field).
let parts = crate::ported::utils::sepsplit(&joined, None, false); // c:3919, Nularg kept
return Value::array(parts.into_iter().map(Value::str).collect());
}
}
// c:Src/subst.c:4387 — `"$@"` is the quoted splat of the positional
// list, so its empty elements become `nulstring` and survive
// c:186: `set -- x '' y; PRE"$@"POST` is three words in zsh. `*` is
// excluded because c:3032's quoted `sepjoin` has already collapsed
// it to one scalar (the compile site routes `"$*"` through
// BUILTIN_EXPAND_TEXT and discards this value). c:4261's
// element-count cut-off is applied by `note_quoted_splice_elems`.
// An UNQUOTED `$@` passes 0, which CLEARS the bit: a preceding
// whole-word `"${a[@]}"` emits no end-of-word drop, so its bit is
// still standing and this word's drop must not honour it.
let quoted_at_elems = if force_dq && name == "@" { pp.len() } else { 0 };
note_quoted_splice_elems(quoted_at_elems);
return Value::array(pp.iter().map(Value::str).collect());
}
// RC_EXPAND_PARAM: when the option is set and `name` refers to
// an array, return Value::Array so the enclosing word's
// BUILTIN_CONCAT_DISTRIBUTE distributes element-wise. Without
// the option, arrays still join to a space-separated scalar
// (zsh's default unquoted-array-as-scalar semantics).
// `isset` is the single atomic load C's `isset(RCEXPANDPARAM)` is
// (c:Src/zsh.h:2557); `opt_state_get` re-resolved the name through the
// option table under a lock on every parameter read.
let rc_expand = isset(crate::ported::zsh_h::RCEXPANDPARAM);
// c:Src/subst.c — under KSHARRAYS a bare `$name` (no [@]/[*] subscript;
// this GET_VAR path only handles the bare form) is element 1 ONLY — a
// scalar. RC_EXPAND_PARAM then has a single value to distribute, so
// `$acc` → "p1", NOT the whole array. Skip the whole-array rc_expand
// shortcut when KSHARRAYS is set and fall through to the normal path,
// which applies the element-1 collapse. Without this gate,
// `setopt KSH_ARRAYS rc_expand_param; print -r -- $acc` splatted every
// element while zsh prints just "p1".
let ksh_arrays = crate::ported::zsh_h::isset(crate::ported::zsh_h::KSHARRAYS);
// c:Src/subst.c:4245 `if (isarr)` gates the whole plan9 block
// (c:4316), and TWO earlier arms have already zeroed `isarr` for a
// bare array read that is quoted or scalar-substituted:
// c:3032 `if (qt && !getlen && isarr > 0) { val = sepjoin(aval,
// sep, 1); isarr = 0; }` — DQ context
// c:3905 `if (nojoin == 0 || sep) { val = sepjoin(aval, sep, 1);
// isarr = 0; }` under `if (ssub || …)` at c:3901
// — PREFORK_SINGLE (scalar
// assignment RHS)
// So RC_EXPAND_PARAM never cross-products a plain `"$a"` / `b=$a`;
// the array collapses to one IFS-joined scalar first. `force_dq` is
// exactly the compiler's flag for those two contexts (it is set for
// `in_dq || scalar_assign_depth > 0 || assign_builtin_arg_depth > 0`),
// Without this gate `setopt rcexpandparam; a=(x y); print -rl -- "$a"Z`
// emitted `xZ` / `yZ` instead of zsh's single `x yZ` — which is how
// `_sqlite`'s `"($exclusive)"$^dashes'-header[…]'` reached
// `comparguments` as five words starting `(-noheader`.
//
// Only the compile-time flag is consulted. The runtime
// `in_dq_context` counter stays set while a `$(…)` INSIDE double
// quotes runs its body, so reading it here would join an unquoted
// `$a` in `"$(print -l -- $a)"`.
if rc_expand && !ksh_arrays && !force_dq {
let arr_val = with_executor(|exec| {
sync_status(exec);
exec.array(&name)
});
if let Some(arr) = arr_val {
// c:4245 — a real array reference (`isarr != 0`). An empty one
// takes plan9's word-removal path (c:4362), so clear the
// scalar bit; a preceding empty-SCALAR expansion in the same
// word would otherwise leave it set and keep the word alive
// (`empty=''; e=(); a=("$empty"); print -rl -- x$e y`).
// Only an EMPTY array may clear it: a non-empty one carries
// no emptiness of its own, and clearing on it wiped the bit a
// preceding empty SCALAR had set — `setopt rcexpandparam;
// e=''; a=(x y); print -rl -- $e$a` lost the whole word.
if arr.is_empty() {
note_empty_is_scalar(false);
}
// A genuine array reference, so an empty element that
// survives the plan9 cross-product IS an empty word:
// `setopt rcexpandparam; a=('' x); print -rl -- ${a}`
// is one word (`x`) in zsh. See `ARRAY_EMPTIES_ELIDABLE`.
note_array_empties_elidable();
return Value::array(arr.into_iter().map(Value::str).collect());
}
}
// Magic-assoc fallback FIRST — `${aliases}` / `${functions}`
// / `${commands}` / etc. should return the value list per
// zsh's bare-assoc semantics. Without this, those names fell
// through to `get_variable` which is empty (they live in
// separate executor tables, not `assoc_arrays`). Return as
// a Value::Array so `arr=(${aliases})` distributes into
// multiple elements, matching zsh's array-context word
// splitting for assoc-bare references.
// Only a name that is a special hash or array row, or a module
// parameter that autoloads, can answer here. For every other name
// `partab_array_get` / `partab_scan_keys` return None after their
// shadow check, module gate and bookkeeping insert — work that cost
// about a third of each parameter read in compinit. The AUTOLOAD
// check keeps `mark_module_param_used`'s first-touch load for those.
let partab_candidate = crate::ported::modules::parameter::PARTAB
.iter()
.any(|e| e.name == name.as_str())
|| crate::ported::modules::parameter::PARTAB_ARRAY
.iter()
.any(|e| e.name == name.as_str())
|| crate::vm_helper::AUTOLOAD_PARAMS.iter().any(|(p, _)| *p == name.as_str());
let magic_vals = if !partab_candidate {
None
} else {
with_executor(|exec| {
sync_status(exec);
// Canonical PARTAB dispatch (Src/Modules/parameter.c:2235-
// 2298 + SPECIALPMDEFs in mapfile/terminfo/termcap/system/
// zleparameter): PARTAB_ARRAY entries → whole-array getfn;
// PARTAB entries → scan keys + per-key getpm/scanpm fn
// pointers.
let _ = exec;
if let Some(values) = partab_array_get(&name) {
Some(values)
} else if let Some(keys) = partab_scan_keys(&name) {
Some(
keys.iter()
.map(|k| partab_get(&name, k).unwrap_or_default())
.collect::<Vec<_>>(),
)
} else {
None
}
})
};
if let Some(vals) = magic_vals {
// Distinguish "name IS a magic-assoc with no entries"
// (return Array(empty)) from "name is unknown — fall
// through to get_variable".
// c:Src/params.c:2293-2296 — KSHARRAYS bare reference
// collapses to the FIRST element in scan order
// (`v->end = 1, v->isarr = 0`). For `options` the scan
// order is optiontab bucket order (OPTIONTAB), so zsh 5.9
// prints `off` (posixargzero) for
// `setopt ksharrays; print $options`.
if isset(crate::ported::zsh_h::KSHARRAYS) {
// c:Src/params.c:2342-2350 — a PM_HASHED special takes the
// same `!v->scanflags && EMULATION(EMULATE_KSH)` arm as a
// plain association: `s = "[0]"; getindex(...)`, i.e. the
// value under key "0" through the special's getfn, empty
// when absent. PARTAB_ARRAY rows are PM_ARRAY and keep the
// first element.
if crate::ported::zsh_h::EMULATION(crate::ported::zsh_h::EMULATE_KSH)
&& partab_array_get(&name).is_none()
{
return Value::str(partab_get(&name, "0").unwrap_or_default());
}
return Value::str(vals.into_iter().next().unwrap_or_default());
}
// Same array reference shape as the indexed-array arm below.
if !force_dq {
note_array_empties_elidable();
}
return Value::array(vals.into_iter().map(Value::str).collect());
}
// Indexed-array path: return Value::Array so pop_args splats
// each element into its own argv slot. Direct port of zsh's
// unquoted `$arr` semantics — each element becomes a separate
// word in command-arg position.
//
// DQ context exception: inside `"...$arr..."`, zsh joins with
// the first char of $IFS (default space) so the DQ word stays
// a single argv slot. Detect via in_dq_context (bumped by
// BUILTIN_EXPAND_TEXT mode 1) and return the joined scalar.
// Direct port of Src/subst.c:1759-1813 nojoin/sepjoin: in DQ
// (qt=1) without explicit `(@)`, sepjoin runs and the result
// is one word.
let arr_assoc_data = with_executor(|exec| {
sync_status(exec);
let in_dq = force_dq || exec.in_dq_context > 0;
// KSH_ARRAYS: bare `$arr` returns ONLY arr[0] (zero-
// based first-element-only semantics). Direct port of
// Src/params.c getstrvalue's KSH_ARRAYS gate which
// returns aval[0] instead of the whole array.
let ksh_arrays = isset(crate::ported::zsh_h::KSHARRAYS);
if let Some(arr) = exec.array(&name) {
if ksh_arrays {
return Some((vec![arr.first().cloned().unwrap_or_default()], in_dq));
}
return Some((arr, in_dq));
}
// Existence only: `exec.assoc()` cloned the whole map to answer it.
if exec.has_assoc(&name) {
// c:Src/params.c:2351-2358 — under KSH EMULATION a bare
// `$assoc` is `${assoc[0]}` (a KEY-"0" lookup), so it is
// EMPTY unless the hash actually has a key "0". This is
// EMULATION-gated, not KSHARRAYS-option-gated: `emulate -L
// ksh; typeset -A h=(a 1 b 2); print $h` is empty, whereas
// `setopt ksharrays; …; print $h` collapses to the bucket-
// first value below.
// bash(1): "Referencing an array variable without a subscript is
// equivalent to referencing the array with a subscript of 0".
if crate::ported::zsh_h::EMULATION(crate::ported::zsh_h::EMULATE_KSH)
|| crate::dash_mode::bash_mode()
{
let v = crate::ported::subst::assoc_get(&name)
.and_then(|m| m.get("0").cloned())
.unwrap_or_default();
return Some((vec![v], in_dq));
}
// c:Src/hashtable.c scanhashtable — a bare `$assoc` joins its
// VALUES in zsh hash-BUCKET order (the same order `(k)`/`(v)`
// enumerate), NOT sorted or insertion order. `assoc_get`
// rebuilds zsh's bucket layout; use it so `$as` matches
// `${(v)as}` (`as=(zebra 9 apple 1)` → `9 1`, not the
// alphabetical `1 9`). Under KSHARRAYS the bare form collapses
// to the bucket-FIRST value (`9`), matching zsh.
let values: Vec<String> = crate::ported::subst::assoc_get(&name)
.map(|m| m.values().cloned().collect())
.unwrap_or_default();
if ksh_arrays {
return Some((vec![values.into_iter().next().unwrap_or_default()], in_dq));
}
return Some((values, in_dq));
}
None
});
if let Some((items, in_dq)) = arr_assoc_data {
if in_dq {
// c:Src/utils.c:3936-3945 sepjoin default-sep rule:
// set-but-empty IFS joins with "" (`IFS=""; echo
// "$arr"` concatenates); only unset / space-leading
// IFS yields " ". The previous get_variable read
// couldn't distinguish unset from set-empty.
return Value::str(crate::ported::utils::sepjoin(&items, None));
}
// c:Src/subst.c:3912 — the join-then-split block:
//
// if (ssub || spbreak || spsep || sep || quoted_array_with_offset) {
// int force_split = !ssub && (spbreak || spsep);
// if (isarr || quoted_array_with_offset) {
//
// A BARE `$NAME` / `${NAME}` read of an ARRAY is `isarr != 0`, so it
// takes the same block the `${NAME[@]}` / `${NAME[*]}` splice does
// (BUILTIN_ARRAY_ALL / BUILTIN_ARRAY_JOIN_STAR above) — c:3030-3032
// makes the three spellings indistinguishable once inside it. The
// only door in from HERE is `spbreak`, c:Src/subst.c:1707
// int spbreak = (pf_flags & PREFORK_SHWORDSPLIT)
// && !(pf_flags & PREFORK_SINGLE) && !qt;
// — SH_WORD_SPLIT. `qt` and PREFORK_SINGLE both reach this handler
// as `force_dq` (the compile site emits GET_VAR_DQ for either), and
// that arm returned above, so getting here already means `!qt` and
// `!ssub`; the explicit `${=…}` / `${==…}` spellings have their own
// fast path. `sep` / `spsep` are the `(j:…:)` / `(s:…:)` separators,
// which never reach a compiler fast path.
//
// This handler had no such block at all: it returned the element
// vector whatever the option said, so an element carrying an IFS
// byte was never broken up —
// setopt shwordsplit; a=('p:q' r); IFS=:; print -rl -- $a
// zsh: `p` `q` `r` zshrs: `p:q` `r`
// setopt shwordsplit; a=('p q' r); unset IFS; print -rl -- ${a}
// zsh: `p` `q` `r` zshrs: `p q` `r`
// setopt shwordsplit; a=(x '' y); IFS=:; print -rl -- $a
// zsh: `x` `` `y` zshrs: `x` `y`
// The last is `sepsplit_c3932`'s `nulstring` rule: the join makes
// `x::y`, and an empty field delimited by IFS-NON-whitespace comes
// back as c:Src/subst.c:36's one-byte `nulstring`, which c:186 KEEPS.
//
// Only the JOINED outcome changes shape. When c:3914-3927 leaves the
// vector alone (an IFS that is set but EMPTY: c:1819 `nojoin` is 1
// and c:3919's second arm needs `!ifs`, which a set-empty IFS fails)
// c:3931's `!isarr` closes the split too, and the answer is the
// untouched array the code below already returns.
if crate::ported::zsh_h::isset(crate::ported::zsh_h::SHWORDSPLIT) {
let ifs_opt = with_executor(|exec| exec.scalar("IFS"));
if let JoinC3914::Joined(val) = join_c3914(items.clone(), ifs_opt.as_deref()) {
// c:3932 `aval = sepsplit(val, spsep, 0, 1)`, then
// c:3933-3938's 0/1/N result shape.
return split_words_c3932(&val);
}
}
// c:Src/subst.c:184-187 — prefork's `else if (!keep)
// uremnode(list, node)`: UNQUOTED expansion drops empty
// list nodes before they reach argv, so `a=(y '' x);
// print -- $a` passes TWO args in zsh (`y x`), while the
// quoted "${a[@]}" splat keeps the empty slot.
//
// The removal must NOT happen HERE. c:186 deletes an
// assembled list NODE — it runs after stringsubst has
// concatenated the word's surrounding text onto the
// elements (the array emit block is c:4245 onward, the
// non-plan9 prefix/suffix attach c:4366-4437), so an
// element that is empty at READ time can still finish as a
// non-empty WORD. Filtering on the way out of the read cost
// exactly that: `a=(x y ""); print -rl -- ${a}POST` dropped
// the slot the suffix was going to land on and printed
// `x` `yPOST` where zsh prints `x` `y` `POST`. The elision
// now lives at the end of word assembly
// (`BUILTIN_WORD_ELIDE_EMPTY`, emitted by compile_zsh once
// the word's segments are folded); flag the value so that
// builtin can tell a genuine array's empty element from a
// split field's `nulstring` (see `ARRAY_EMPTIES_ELIDABLE`).
note_array_empties_elidable();
// c:4245 — a real array reference: `isarr != 0`, so an empty
// one takes plan9's word-removal path, not the scalar path.
// Only note it when the array IS empty — see the rc_expand arm
// above for why a non-empty read must not touch the bit.
if items.is_empty() {
note_empty_is_scalar(false);
}
return Value::array(items.into_iter().map(Value::str).collect());
}
let (val, in_dq, is_known) = with_executor(|exec| {
sync_status(exec);
let v = exec.get_variable(&name);
// For nounset detection: a name is "known" when it has a
// paramtab/array/assoc/env entry. Special chars ($?, $#,
// $@, $*, $-, $$, $!, $_, $0) always count as known
// regardless of value. Pure-digit positional params
// count as known iff index <= $# (set -- has populated
// that slot). c:Src/subst.c:1689 — NOUNSET fires on
// unset positional param too: `set --; echo "$1"` with
// nounset must diagnose.
let is_special_single = name.len() == 1
&& matches!(
name.chars().next().unwrap(),
'?' | '#' | '@' | '*' | '-' | '$' | '!' | '_' | '0'
);
let is_pure_digit = !name.is_empty() && name.chars().all(|c| c.is_ascii_digit());
let positional_known = if is_pure_digit {
let idx: usize = name.parse().unwrap_or(0);
if idx == 0 {
true // $0 always set
} else {
idx <= exec.pparams().len()
}
} else {
false
};
let known = !v.is_empty()
|| name.is_empty()
|| is_special_single
|| positional_known
|| crate::ported::params::paramtab()
.read()
.ok()
.map(|t| t.contains_key(&name))
.unwrap_or(false)
|| env::var(&name).is_ok();
(v, force_dq || exec.in_dq_context > 0, known)
});
// c:Src/subst.c:1689 — NO_UNSET / nounset: reading an unset
// parameter fires "parameter not set" diagnostic and aborts
// the substitution. Direct port of the noerrs gate at c:1689
// (zerr + errflag). Matches `set -u` POSIX semantics.
// `nounset` is the negated alias of UNSET (c:Src/options.c optns), so
// this is C's `unset(UNSET)`: one atomic load, not a name lookup.
if !is_known && !isset(crate::ported::zsh_h::UNSET) {
crate::ported::utils::zerr(&format!("{}: parameter not set", name));
crate::ported::utils::errflag.fetch_or(
crate::ported::zsh_h::ERRFLAG_ERROR,
std::sync::atomic::Ordering::Relaxed,
);
with_executor(|exec| exec.set_last_status(1));
return Value::str("");
}
// Empty unquoted scalar → drop the arg (zsh "remove empty
// unquoted words" rule). Returning empty Value::Array makes
// pop_args contribute zero items. DQ context keeps the empty
// string so "$a" stays a single empty arg. Direct port of
// subst.c's elide-empty pass.
if val.is_empty() && !in_dq {
// c:1650-1656 / c:4437 — a SCALAR parameter has `isarr == 0`,
// so it never reaches plan9's word-removal at c:4362. Flag the
// empty Array below as a scalar so `setopt rcexpandparam;
// v=; print -rl -- x$v y` still emits `x` (only an empty
// ARRAY deletes the word).
note_empty_is_scalar(true);
return Value::array(Vec::new());
}
// c:Src/subst.c:1759 SH_WORD_SPLIT — when shwordsplit is set and
// we're in unquoted command-arg position (not DQ), split scalar
// value on IFS into multiple words. Matches BUILTIN_ARRAY_ALL's
// shwordsplit arm (fusevm_bridge.rs:2200). Without this, bare
// `$s` in `print $s` stayed a single arg even with the option
// set, breaking POSIX-style scalar word-splitting.
if !in_dq && isset(crate::ported::zsh_h::SHWORDSPLIT) {
// c:Src/subst.c:318-324 → c:1707 `spbreak`, c:3921 `sepsplit`, then
// c:4366-4437 attach the word's affixes BEFORE c:184-187 deletes the
// empty nodes. `spacesplit` (c:Src/utils.c:3730-3760, allownull 0)
// gives a leading/trailing run of IFS-whitespace a real `""` node,
// which survives only once text is glued onto it:
// setopt shwordsplit; s=' foo bar '; print -rl -- x${s}y
// zsh: x / foo / bar / y (the edges became `x` and `y`)
// while an IFS-non-whitespace empty field is `nulstring` and always
// survives. This read cannot see the affixes, and dropping every
// truly-empty field here made that `xfoo` / `bary`. paramsubst
// already carries both rules (PARAMSUBST_AFFIXES_DEFERRED leaves the
// removal to the word's end-of-word drop), and it is the same
// expansion C runs, so hand it the `${name}` spelling.
return paramsubst_to_value(&format!("${{{}}}", name));
}
Value::str(val)
}
// Provenance: BUILTIN_GET_VAR / _DQ are the bytecode-level parameter
// READ ops, so this is the tap that hands a tracked parameter's
// lineage to the value the read produced. The name is peeked off the
// stack before `get_var_impl` consumes it.
fn get_var_prov(vm: &mut fusevm::VM, argc: u8, force_dq: bool) -> Value {
if !crate::provenance::active() {
return get_var_impl(vm, argc, force_dq);
}
let name = vm.peek().to_str();
let value = get_var_impl(vm, argc, force_dq);
crate::provenance::on_param_read(&name, &value);
value
}
vm.register_builtin(BUILTIN_GET_VAR, |vm, argc| get_var_prov(vm, argc, false));
vm.register_builtin(BUILTIN_GET_VAR_DQ, |vm, argc| get_var_prov(vm, argc, true));
// `name+=val` (no parens) — runtime dispatch:
// - if `name` is in `arrays` → push `val` as new element
// - if `name` is in `assoc_arrays` → refuse (zsh errors here)
// - else → scalar concat (existing behavior)
// Stack: [name, value].
vm.register_builtin(BUILTIN_APPEND_SCALAR_OR_PUSH, |vm, argc| {
let args = pop_args(vm, argc);
let mut iter = args.into_iter();
let name = iter.next().unwrap_or_default();
let value = iter.next().unwrap_or_default();
with_executor(|exec| {
// Array form: `arr+=elem` pushes a single element.
// Routes through canonical assignaparam(name, [value],
// ASSPM_AUGMENT) — Src/params.c:3357 c:3402-3412 augment
// path prepends prior scalar / appends to existing array.
// Existence probe uses the non-cloning `has_array` — the
// owning `exec.array()` clone here made `arr+=x` in a loop
// O(n²) (see the assoc-store fix above).
if exec.has_array(&name) {
// c:Src/params.c — under KSHARRAYS a bare array name
// addresses element 0 (ksh), so `a+=X` (scalar augment)
// CONCATENATES onto the first element ("firstlast second"),
// it does NOT push a new element. C routes scalar `+=`
// through assignsparam (which targets the elem-0 value);
// zshrs's APPEND_SCALAR_OR_PUSH would otherwise push.
if crate::ported::zsh_h::isset(crate::ported::zsh_h::KSHARRAYS) {
let mut arr = exec.array(&name).unwrap_or_default();
if arr.is_empty() {
arr.push(value.clone());
} else {
arr[0] = format!("{}{}", arr[0], value);
}
exec.set_array(name.clone(), arr);
#[cfg(feature = "recorder")]
if crate::recorder::is_enabled() && exec.local_scope_depth == 0 {
let ctx = exec.recorder_ctx();
let attrs = exec.recorder_attrs_for(&name);
emit_path_or_assign(&name, std::slice::from_ref(&value), attrs, true, &ctx);
}
return;
}
let _ = crate::ported::params::assignaparam(
&name,
vec![value.clone()],
crate::ported::zsh_h::ASSPM_AUGMENT
| crate::ported::zsh_h::ASSPM_WARN, // c:Src/exec.c:2573
);
#[cfg(feature = "recorder")]
if crate::recorder::is_enabled() && exec.local_scope_depth == 0 {
let ctx = exec.recorder_ctx();
let attrs = exec.recorder_attrs_for(&name);
emit_path_or_assign(&name, std::slice::from_ref(&value), attrs, true, &ctx);
}
return;
}
// An association falls through too: c:Src/params.c:3178-3192
// `resetparam(v->pm, PM_SCALAR)`s a non-special PM_HASHED
// target (unset KSHARRAYS) and the augment then appends to the
// fresh empty scalar, so `typeset -A h; h+=x` leaves h="x".
// Scalar / integer / float form: route through canonical
// assignsparam(name, value, ASSPM_AUGMENT) which
// dispatches PM_TYPE — PM_SCALAR concats, PM_INTEGER
// arith-adds (c:2775-2778), PM_FLOAT float-adds.
let _ = crate::ported::params::assignsparam(
&name,
&value,
crate::ported::zsh_h::ASSPM_AUGMENT | crate::ported::zsh_h::ASSPM_WARN, // c:Src/exec.c:2573 addvars
);
#[cfg(feature = "recorder")]
if crate::recorder::is_enabled() && exec.local_scope_depth == 0 {
let ctx = exec.recorder_ctx();
let attrs = exec.recorder_attrs_for(&name);
// Re-read the canonical value via get_variable for the
// recorder bundle (assignsparam may have transformed it
// through integer/float arithmetic).
let final_val = exec.get_variable(&name);
let lower = name.to_ascii_lowercase();
if matches!(
lower.as_str(),
"path" | "fpath" | "manpath" | "module_path" | "cdpath"
) {
emit_path_or_assign(&name, std::slice::from_ref(&final_val), attrs, true, &ctx);
} else {
crate::recorder::emit_assign_typed(&name, &final_val, attrs, ctx);
}
}
});
Value::Status(0)
});
// BUILTIN_SET_VAR — `name=value` runtime scalar assignment.
// PURE PASSTHRU: hand to canonical `setsparam` (C port of
// `Src/params.c::setsparam`). That walks assignsparam →
// assignstrvalue which already does:
// - readonly rejection (zerr + errflag at c:2701)
// - PM_INTEGER math evaluation (mathevali at c:3590)
// - PM_EFLOAT / PM_FFLOAT float coercion (c:3608)
// - PM_LOWER / PM_UPPER case fold (via setstrvalue)
// - GSU special-param dispatch (homesetfn / ifssetfn / etc.)
// - allexport env mirror via the PM_EXPORTED setfn
//
// Bridge-only concerns kept here:
// - inline_env_stack (zsh `X=foo cmd` scoped env)
// - recorder emission (PFA-SMR)
// - vm.last_status propagation for `a=$(cmd)` exit-code chaining
// Sets the GLOB_ASSIGN-eligibility flag consumed by the NEXT BUILTIN_SET_VAR.
// Emitted only when a scalar-assign RHS had an unquoted glob token. Takes no
// args; its pushed return is discarded by a following Op::Pop.
vm.register_builtin(BUILTIN_MARK_GLOB_ELIGIBLE, |_vm, _argc| {
SET_VAR_GLOB_ELIGIBLE.with(|c| c.set(true));
fusevm::Value::Int(0)
});
vm.register_builtin(BUILTIN_SET_VAR, |vm, argc| {
// `${~spec}` carrier: an assignment statement is a word-
// pipeline boundary too — restore the user's GLOB_SUBST
// before the NEXT word expands (`Z[d]=${~Z[d]}; print
// ${options[globsubst]}` must read the user value).
consume_tilde_globsubst_carrier();
// Snapshot the raw Values BEFORE pop_args's to_str
// flattening — needed to distinguish Int (arith assignment,
// integer-typed param) from Str (scalar assignment).
let mut raw_values: Vec<fusevm::Value> = Vec::with_capacity(argc as usize);
for _ in 0..argc {
raw_values.push(vm.pop());
}
raw_values.reverse();
let name = raw_values.first().map(|v| v.to_str()).unwrap_or_default();
let value_raw = raw_values.get(1).cloned();
let value = value_raw.as_ref().map(|v| v.to_str()).unwrap_or_default();
// c:Src/params.c — when the bytecode hands us an Int value
// (only the arith assignment paths emit this — `(( X = N ))`
// is the canonical site), route through setiparam so the
// param ends up PM_INTEGER + inherits the math layer's
// `lastbase` for display formatting (`(( X = 16#ff ));
// echo \$X` → `16#FF`). Scalar `X=val` and `$((expr))`
// assignments still take the setsparam path below.
let int_assign = matches!(value_raw, Some(fusevm::Value::Int(_)));
let float_assign = matches!(value_raw, Some(fusevm::Value::Float(_)));
let mut assign_failed = false;
with_executor(|exec| {
// c:Src/params.c assignsparam — PM_READONLY rejection
// BEFORE any env mutation. The inline-env-prefix path
// (`X=2 env`) called env::set_var unconditionally before
// the readonly check fired in setsparam, so the OS env
// got X=2 even though the assignment errored. env then
// inherited the polluted env from fork, leaking the
// attempted override past the readonly guard. Mirror
// C's order: readonly check → zerr → bail; only mutate
// env when the assignment is admissible. Bug #551
// (security-relevant).
if exec.is_readonly_param(&name) {
crate::ported::utils::zerr(&format!("read-only variable: {}", name));
return;
}
// c:Src/params.c:2539-2543 — a PM_RESTRICTED parameter (PATH, IFS,
// UID, ...) cannot be assigned under RESTRICTED.
if crate::ported::zsh_h::isset(crate::ported::zsh_h::RESTRICTED)
&& (exec.param_flags(name.split('[').next().unwrap_or(&name)) as u32
& crate::ported::zsh_h::PM_RESTRICTED)
!= 0
{
crate::ported::utils::zerr(&format!("{}: restricted", name));
return;
}
// Inline-assignment frame tracking (`X=foo cmd` reverts on
// command return). Only the PREFIX assignments belong in
// the frame: c:Src/exec.c:4410 save_params snapshots the
// parsed WC_ASSIGN chain and nothing else. The frame stays
// on the stack while the command runs, so gate on
// `recording` (cleared by SEAL_INLINE_ENV once the prefix
// assignments have committed) — otherwise every assignment
// the command itself makes gets recorded and then reverted
// (`X=y . file` wiped every global the file defined).
let prefix_restored = exec
.inline_env_stack
.last()
.is_some_and(|frame| frame.recording);
if prefix_restored {
save_inline_prefix_param(exec, &name);
let _ = crate::ported::params::zputenv(&format!("{}={}", &name, &value));
// c:Src/params.c:5354
}
// c:Src/exec.c:2641 —
// if ((addflags & ADDVAR_EXPORT) && !strchr(name, '[')) {
// ...
// allexp = opts[ALLEXPORT];
// opts[ALLEXPORT] = 1;
// if (isset(KSHARRAYS))
// unsetparam(name);
// pm = assignsparam(name, val, myflags);
// opts[ALLEXPORT] = allexp;
// } else
// pm = assignsparam(name, val, myflags);
// The assignment itself is what has to run under ALLEXPORT —
// `createparam` ORs in PM_EXPORTED for a name that did not
// exist (c:Src/params.c:1170-1171) and `assignstrvalue`'s tail
// calls `export_param` for one that did (c:2836-2841) — so the
// flip wraps the setsparam/setiparam/setnparam dispatch and the
// env mirror below, and nothing else. Doing it any other way
// would be special-casing the `${(t)}` readout instead of
// marking the parameter.
//
// !!! NOT PORTED — the STTY leg (c:2642-2645 `STTYval =
// ztrdup(val)`). `execute` consumes STTYval on the next
// external command (exec.rs:4081) and C drops it again at
// c:4310 / c:4400-4401 when the prefixed command finishes;
// the bridge has no counterpart for those clears, so capturing
// it here would apply `STTY=… cmd`'s settings to whatever
// command ran next instead.
let addvar_export = exec
.inline_env_stack
.last()
.is_some_and(|frame| frame.recording && frame.export)
&& !name.contains('['); // c:2641
let saved_allexport = if addvar_export {
let allexp = isset(crate::ported::zsh_h::ALLEXPORT); // c:2646
crate::ported::options::opt_state_set("allexport", true); // c:2647
if isset(crate::ported::zsh_h::KSHARRAYS) {
// c:2648 — force the name to be recreated by the scalar
// assignment rather than written into the array that is
// already there: `setopt ksharrays; A=(1 2); A=x f`
// reports `scalar-export` inside the call in zsh.
crate::ported::params::unsetparam(&name); // c:2649
}
Some(allexp)
} else {
None
};
// c:Src/exec.c:2573 — `flags = !(addflags & ADDVAR_RESTORE) ?
// ASSPM_WARN : 0;`, with the comment "Don't do this if there is a
// list of variables marked to be restored after the command, since
// then the assignment is implicitly scoped." A prefix assignment
// recorded into the open inline-env frame is exactly that: it is
// put back by restore_params when the command returns (c:4144-4145
// `if (restorelist) flags |= ADDVAR_RESTORE;`, and c:4346-4347 for
// an external's forked child). The non-recording arms (POSIX
// special builtins, the do_save = 0 case) and plain assignments
// keep the warning.
let asg_flags = if prefix_restored {
0
} else {
crate::ported::zsh_h::ASSPM_WARN as i32
};
// Canonical setsparam handles readonly, integer math, case
// fold, GSU dispatch. For Int values (arith assigns) route
// through setiparam so the param is PM_INTEGER + inherits
// the math layer's lastbase for display formatting. For
// Float (arith assigns producing MN_FLOAT) route through
// setnparam so the param is PM_FFLOAT — `(( b = a * 2 ))`
// with scalar `a="3.14"` should create b as typeset -F,
// not a scalar holding "6.28".
if int_assign {
if let Some(fusevm::Value::Int(i)) = value_raw {
crate::ported::params::assigniparam(&name, i, asg_flags);
} else {
assign_failed = crate::ported::params::assignsparam(&name, &value, asg_flags).is_none();
}
} else if float_assign {
if let Some(fusevm::Value::Float(f)) = value_raw {
// ArithCompiler returns Value::Float whenever any
// operand came through Str (BUILTIN_GET_VAR yields
// Value::Str even for integer-shaped scalars). To
// avoid forcing every `(( b = a + 3 ))` to PM_FFLOAT
// when `a="5"` (integer-shaped), detect integer-
// valued floats and route through setiparam instead.
// True floats (non-integral) reach setnparam →
// PM_FFLOAT so `typeset -p b` shows `typeset -F …`.
if f.fract() == 0.0 && f.is_finite() && f.abs() <= i64::MAX as f64 {
crate::ported::params::assigniparam(&name, f as i64, asg_flags);
} else {
let mnval = crate::ported::math::mnumber {
l: 0,
d: f,
type_: crate::ported::math::MN_FLOAT,
};
crate::ported::params::assignnparam(&name, mnval, asg_flags);
}
} else {
assign_failed = crate::ported::params::assignsparam(&name, &value, asg_flags).is_none();
}
} else {
// c:Src/exec.c:2554-2567 — GLOB_ASSIGN. When the
// `globassign` option is on and the scalar RHS is a glob
// pattern, glob it and recreate the parameter as a scalar
// (≤1 match) or array (>1) — csh-style assignment. The
// bridge hands `value` UNTOKENIZED, so re-tokenize
// (shtokenize) before haswilds/globlist; zsh's wordcode
// value arrives pre-tokenized via `htok`. The
// `isset(GLOBASSIGN)` gate is first and cheap (option off
// by default), so the common path is unchanged.
let mut globbed = false;
// Only glob the RHS when the compiler flagged an UNQUOTED glob
// token in the literal wordcode (SET_VAR_GLOB_ELIGIBLE). zsh's
// GLOB_ASSIGN (Src/exec.c:2554) globs literal patterns only —
// `x="/tmp/*"`, `x='/tmp/*'`, `x=$param`, `x=$(cmd)` all assign
// verbatim. The value arrives here untokenized (DQ-wrapped by
// the compiler), so this compile-time flag is the only surviving
// signal of whether the pattern was quote-protected.
let glob_eligible = SET_VAR_GLOB_ELIGIBLE.with(|c| c.replace(false));
if glob_eligible && crate::ported::zsh_h::isset(crate::ported::zsh_h::GLOBASSIGN) {
let mut tv = value.clone();
crate::ported::glob::shtokenize(&mut tv);
if crate::ported::pattern::haswilds(&tv) {
// Committed to the glob path: never fall back to
// assigning the literal pattern (zsh errors on
// no-match instead).
globbed = true;
// globlist tokenizes its input internally (for
// haswilds + glob_path) and prints the ORIGINAL
// string verbatim in its "no matches found" error,
// so feed it the UNtokenized value — passing the
// tokenized form would leak the Star/Quest token
// bytes into the error message.
let mut ll: crate::ported::linklist::LinkList<String> = Default::default();
ll.push_back(value.clone());
crate::ported::subst::globlist(&mut ll, 0); // c:2556
if crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed)
== 0
{
let matches: Vec<String> = ll
.nodes
.iter()
.map(|s| crate::ported::lex::untokenize(s).to_string())
.collect();
crate::ported::params::unsetparam(&name); // c:2562
if matches.len() <= 1 {
let v = matches.into_iter().next().unwrap_or_default();
assign_failed =
crate::ported::params::assignsparam(&name, &v, asg_flags).is_none();
} else {
crate::ported::params::assignaparam(&name, matches, asg_flags);
}
}
// errflag set → globlist already reported
// "no matches found"; leave the param unassigned
// to match zsh's abort.
}
}
// c:Src/exec.c addvars — a NULL return from
// assignsparam (e.g. nameref resolving out of scope,
// createparam refusal at c:1108-1118) fails the
// assignment with status 1.
if !globbed {
assign_failed = crate::ported::params::assignsparam(&name, &value, asg_flags).is_none();
}
}
// PM_EXPORTED / allexport env mirror — read AFTER setsparam
// so the flag bit reflects any GSU setfn side-effects.
let allexport = opt_state_get("allexport").unwrap_or(false);
let already_exported =
(exec.param_flags(&name) as u32 & crate::ported::zsh_h::PM_EXPORTED) != 0;
if allexport || already_exported {
// c:Src/params.c:3024 — the env mirror is `addenv(pm, value)`,
// and addenv builds its string with `mkenvstr(nam, value,
// pm->flags)` (c:5463) so `copyenvstr` (c:5434) can apply the
// PM_LOWER / PM_UPPER fold. Formatting `name=value` by hand
// skipped that: `typeset -lx v; v=HeLLo` exported `HeLLo`
// where zsh exports `hello`. The fold has to happen HERE
// because the paramtab now stores the value verbatim.
let envstr = crate::ported::params::mkenvstr(
&name,
&value,
exec.param_flags(&name), // c:5463 pm->flags
);
let _ = crate::ported::params::zputenv(&envstr); // c:Src/params.c:5354
}
// c:2651 — `opts[ALLEXPORT] = allexp;`
if let Some(allexp) = saved_allexport {
crate::ported::options::opt_state_set("allexport", allexp);
}
#[cfg(feature = "recorder")]
if crate::recorder::is_enabled()
&& exec.local_scope_depth == 0
&& !matches!(
name.as_str(),
"PPID" | "LINENO" | "ZSH_ARGZERO" | "argv0" | "ARGC" | "?" | "_" | "RANDOM"
)
{
let ctx = exec.recorder_ctx();
let attrs = exec.recorder_attrs_for(&name);
crate::recorder::emit_assign_typed(&name, &value, attrs, ctx);
}
// c:Src/exec.c:1367-1370 — `if (code == WC_ASSIGN) { cmdoutval = 0;
// addvars(state, state->pc - 1, 0); setunderscore(""); … }`. A
// simple command consisting ONLY of scalar assignments clears `$_`;
// it never goes through execcmd's c:3545-3547
// `setunderscore(lastnode(args))`. src/ported/exec.rs:6946-6950
// already ports that arm, but the WC_ASSIGN wordcode never
// executes under fusevm — a bare `x=1` arrives here as
// BUILTIN_SET_VAR, so `$_` kept the PREVIOUS command's last
// argument. Symptom: in the `unset <TAB>` listing (the user's
// `_parameters` override runs `maxLen=50` right before the
// `$parameters` walk) zsh shows `_` empty while zshrs showed the
// completion-internal `^a*` — `_parameters -g '^a*'`'s last arg.
//
// Two exclusions, both verified against zsh 5.9.2
// (`true aa; <form>; print -r -- "[$_]"`):
// * PREFIX assignments (`x=1 true dd` → `dd`) are part of a
// command, so c:3545-3547 owns `$_`. They are exactly the
// assignments recorded into an open inline-env frame above.
// * `(( q = 1 ))` (→ `aa`, unchanged) is WC_ARITH, not
// WC_ASSIGN; the arith paths are the only ones that hand this
// builtin an Int/Float `Value` (see the `int_assign` note).
if !int_assign
&& !float_assign
&& !exec
.inline_env_stack
.last()
.is_some_and(|frame| frame.recording)
{
// c:1369 — assignment-only command clears `$_`. The
// former DUAL-STATE note here is obsolete: `set_zunderscore`
// and the ported `setunderscore` now write the SAME
// `init::zunderscore` global (params.rs `zunderscore_lock`
// points at it), matching C's single store, so this one call
// is the whole effect.
crate::ported::exec::setunderscore(""); // c:1369
}
});
// c:Src/exec.c:2654-2663 — `if (!pm) { lastval = 1; ... if
// (!cmdoutval) cmdoutval = 1; }`; BUILTIN_ASSIGN_ONLY_STATUS
// reads the flag back as the command's status.
if assign_failed {
ASSIGN_FAILED_FLAG.store(true, std::sync::atomic::Ordering::Relaxed);
}
Value::Status(vm.last_status)
});
// c:Src/exec.c execfor → Src/params.c:6362 setloopvar — the
// for-loop variable bind. Distinct from BUILTIN_SET_VAR because a
// PM_NAMEREF loop variable REBINDS (new refname) instead of
// assigning through the resolved chain.
vm.register_builtin(BUILTIN_SET_LOOP_VAR, |vm, argc| {
let args = pop_args(vm, argc);
let name = args.first().cloned().unwrap_or_default();
let value = args.get(1).cloned().unwrap_or_default();
if crate::vm_helper::is_nameref(&name) {
let ef_before =
crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed);
crate::ported::params::setloopvar(&name, &value); // c:6362
let ef_after = crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed);
if (ef_after & crate::ported::utils::ERRFLAG_ERROR) != 0 && ef_after != ef_before {
// zerr fired (read-only reference / invalid self
// reference) — abort the loop, status 1 (C errflag).
vm.last_status = 1;
return Value::Bool(false);
}
return Value::Bool(true);
}
// Plain loop var — canonical scalar path (same shape as
// BUILTIN_SET_VAR's setsparam arm).
with_executor(|exec| {
if exec.is_readonly_param(&name) {
crate::ported::utils::zerr(&format!("read-only variable: {}", name));
return;
}
// c:Src/params.c:2539-2543 — a PM_RESTRICTED parameter (PATH, IFS,
// UID, ...) cannot be assigned under RESTRICTED.
if crate::ported::zsh_h::isset(crate::ported::zsh_h::RESTRICTED)
&& (exec.param_flags(name.split('[').next().unwrap_or(&name)) as u32
& crate::ported::zsh_h::PM_RESTRICTED)
!= 0
{
crate::ported::utils::zerr(&format!("{}: restricted", name));
return;
}
crate::ported::params::setsparam(&name, &value);
let allexport = opt_state_get("allexport").unwrap_or(false);
let already_exported =
(exec.param_flags(&name) as u32 & crate::ported::zsh_h::PM_EXPORTED) != 0;
if allexport || already_exported {
// c:Src/params.c:3024 — the env mirror is `addenv(pm, value)`,
// and addenv builds its string with `mkenvstr(nam, value,
// pm->flags)` (c:5463) so `copyenvstr` (c:5434) can apply the
// PM_LOWER / PM_UPPER fold. Formatting `name=value` by hand
// skipped that: `typeset -lx v; v=HeLLo` exported `HeLLo`
// where zsh exports `hello`. The fold has to happen HERE
// because the paramtab now stores the value verbatim.
let envstr = crate::ported::params::mkenvstr(
&name,
&value,
exec.param_flags(&name), // c:5463 pm->flags
);
let _ = crate::ported::params::zputenv(&envstr); // c:Src/params.c:5354
}
});
Value::Bool(true)
});
// Pre-compiled function registration — used by compile_zsh.rs's
// FuncDef path. Stack: [name, base64-bincode-of-Chunk]. We decode
// the base64, deserialize the Chunk, and store directly in
// executor.functions_compiled. Bypasses the ShellCommand JSON layer.
// BUILTIN_VAR_EXISTS — `[[ -v name ]]` set-test.
// PURE PASSTHRU: build `${+name}` and route through canonical
// `subst::paramsubst` which returns "1" for set / "0" for unset
// (C port of `Src/subst.c::paramsubst` plus-prefix arm).
// paramsubst handles all the shapes the 48-line hand-roll did:
// - bare scalar / array / assoc
// - subscripted `a[N]` / `h[key]`
// - positional params (any digit-only name)
// - env-var fallback (`HOME` set via getsparam → lookup_special_var)
vm.register_builtin(BUILTIN_VAR_EXISTS, |vm, _argc| {
let name = vm.pop().to_str();
// c:Src/cond.c:361 `case 'v': return !issetvar(left)`. `-v` is
// NOT `${+name}` — issetvar (params.c:751) additionally rejects
// trailing chars after the parsed name/subscript (`arr[3]extra`,
// nested `arr[2][1]`) and validates array-slice bounds (an
// out-of-range `(i)`-not-found index is "unset"). `${+}` is
// lenient and reported those as set.
Value::Bool(crate::ported::params::issetvar(&name) != 0)
});
// `time { compound; ... }` — runs the sub-chunk and prints elapsed
// wall-clock time. zsh's full `time` also tracks user/system CPU via
// getrusage on the *child*; we approximate via wall-time only since
// the sub-chunk runs in-process (no fork). Output format matches
// `time simple-cmd` (already implemented elsewhere via exectime).
vm.register_builtin(BUILTIN_TIME_SUBLIST, |vm, argc| {
// A negative sub-chunk index is the compiler's marker for the BARE
// `time` keyword, which has no body to run.
// c:Src/exec.c:5331-5334 exectime:
// if (WC_TIMED_TYPE(state->pc[-1]) == WC_TIMED_EMPTY) {
// shelltime(NULL,NULL,NULL,0);
// return 0;
// }
// `shelltime(NULL, NULL, NULL, 0)` is the ONE call that prints the
// shell/children pair: with delta==0 and both pointers NULL, both
// `!delta == !shell` (c:Src/jobs.c:1964) and `!delta == !kids`
// (c:1985) hold. Verified: `zsh -fc 'time'` prints
// shell 0.00s user 0.00s system … / children 0.00s user …
// while every `time <body>` form prints nothing (see the is_cursh
// note below). zshrs previously compiled bare `time` to a plain
// `status = 0` and printed nothing at all.
let sub_idx_raw = vm.pop().to_int();
let sub_idx = sub_idx_raw as usize;
// c:Src/jobs.c:1028-1029 — `pn->text` arg to printtime. argc==2
// means the compiler also pushed a desc string (bug #66 fix);
// older callers with argc==1 push only sub_idx and we synthesize
// an empty desc for backward compat with cached bytecode that
// predates the desc-threading patch.
let desc = if argc >= 2 {
vm.pop().to_str().to_string()
} else {
String::new()
};
// c:Src/exec.c:3536-3538 — `if (!text && (!sfcontext && (jobbing ||
// (how & Z_TIMED)))) text = getjobtext(…)`: inside a shell function
// (sfcontext = SFC_DIRECT, c:5632-5633) no job text is taken, so the
// report's %J is empty: `f(){ time /bin/sleep 0 }; f` prints
// ` 0.00s user …` with no command.
let desc = if crate::ported::exec::sfcontext.load(std::sync::atomic::Ordering::Relaxed)
!= crate::ported::zsh_h::SFC_NONE
{
String::new()
} else {
desc
};
// c:Src/exec.c:3690 — the compiler's `is_cursh` verdict for the
// timed body (see compile_zsh.rs `time_cursh_hint`): 1 = current
// shell, 0 = forked job, 2 = decide from the command name below.
// argc < 4 means bytecode cached before this operand pair existed;
// fall back to the old fork-counter heuristic in that case.
let (cursh_hint, cursh_name) = if argc >= 4 {
let hint = vm.pop().to_int();
let name = vm.pop().to_str().to_string();
(hint, name)
} else {
(-1, String::new())
};
// c:Src/jobs.c:1029-1037 dumptime — a timed multi-stage pipeline
// arrives with its per-stage texts and the last stage's is_cursh
// verdict (compile_zsh.rs Time arm): [texts…, last_hint, last_name, n].
let timed_pipeline = if argc > 4 {
let n = vm.pop().to_int().max(0) as usize;
let last_name = vm.pop().to_str().to_string();
let last_hint = vm.pop().to_int();
let mut texts: Vec<String> = (0..n).map(|_| vm.pop().to_str().to_string()).collect();
texts.reverse();
Some(TimedPipeline {
texts,
last_forks: !time_body_is_cursh(last_hint, &last_name),
procs: Vec::new(),
})
} else {
None
};
if sub_idx_raw < 0 {
crate::ported::jobs::shelltime(None, None, None, 0); // c:5333
return Value::Status(0); // c:5334
}
let chunk_opt = vm.chunk.sub_chunks.get(sub_idx).cloned();
let Some(chunk) = chunk_opt else {
return Value::Status(0);
};
// c:Src/jobs.c:1968 — `getrusage(RUSAGE_CHILDREN, &ti)` before
// and after the timed sublist gives accurate per-stage user/sys
// CPU. Wall-time-only approximation (0.7×/0.1× fudge factors)
// produced bogus user/sys columns and ignored TIMEFMT. Bug #66
// in docs/BUGS.md.
let ru_before: libc::rusage = unsafe {
let mut r: libc::rusage = std::mem::zeroed();
libc::getrusage(libc::RUSAGE_CHILDREN, &mut r);
r
};
// c:Src/jobs.c — zsh's `time` reports only for JOBS (forked
// work). Builtins/brace-groups/functions run in the shell
// process with no job, so `zsh -fc 'time true'` emits NOTHING.
// Snapshot the fork-event counter; report only if the timed
// body forked (external command or subshell).
let forks_before = crate::vm_helper::FORK_EVENTS.load(std::sync::atomic::Ordering::Relaxed);
// c:Src/jobs.c:1943 — `getrusage(RUSAGE_SELF, &ti)` — shelltime's
// "shell" line reports the SHELL PROCESS's own CPU delta, which is
// where a current-shell (`is_cursh`) body's work lands.
let ru_self_before: libc::rusage = unsafe {
let mut r: libc::rusage = std::mem::zeroed();
libc::getrusage(libc::RUSAGE_SELF, &mut r);
r
};
let start = Instant::now();
crate::fusevm_disasm::maybe_print_stdout("time_sublist", &chunk);
let mut sub_vm = fusevm::VM::new(chunk);
register_builtins(&mut sub_vm);
let outer_timed = TIMED_PIPELINE.with(|t| t.replace(timed_pipeline));
let _ = sub_vm.run();
let timed_pipeline = TIMED_PIPELINE.with(|t| t.replace(outer_timed));
let status = sub_vm.last_status;
let elapsed = start.elapsed();
let ru_self_after: libc::rusage = unsafe {
let mut r: libc::rusage = std::mem::zeroed();
libc::getrusage(libc::RUSAGE_SELF, &mut r);
r
};
let ru_after: libc::rusage = unsafe {
let mut r: libc::rusage = std::mem::zeroed();
libc::getrusage(libc::RUSAGE_CHILDREN, &mut r);
r
};
// Delta children rusage = timed work's CPU.
let mut delta = ru_after;
let sub = timeval_sub;
delta.ru_utime = sub(ru_after.ru_utime, ru_before.ru_utime);
delta.ru_stime = sub(ru_after.ru_stime, ru_before.ru_stime);
let ti = crate::ported::zsh_h::timeinfo::from_rusage(&delta);
// c:Src/jobs.c:808-809 — `s = getsparam("TIMEFMT"); s ||
// DEFAULT_TIMEFMT`. Honor user-set TIMEFMT, fall back to the
// canonical default.
let fmt = crate::ported::params::getsparam("TIMEFMT")
.unwrap_or_else(|| crate::ported::zsh_system_h::DEFAULT_TIMEFMT.to_string());
// c:Src/jobs.c:768 `desc` arg — for the `time { sublist }` /
// `time simple-cmd` keyword path, zsh passes the sublist's
// source text (used by %J via printtime). The compiler now
// threads the rendered source text through as the desc operand
// (compile_zsh.rs Time arm, argc==2 form). Bug #66.
// c:Src/exec.c:3690 — resolve the compiler's verdict. Hint 2 means
// "a simple command whose head word decides it": `is_builtin ||
// is_shfunc`. A reserved-word / builtin / function head runs in the
// current shell; anything else forks and becomes a job.
let is_cursh = match cursh_hint {
1 => true,
0 => false,
2 => time_body_is_cursh(2, &cursh_name),
// Bytecode cached before the hint operands existed: keep the
// historical fork-counter heuristic (report only if something
// forked) so a stale cache doesn't start emitting shell/children
// lines for every builtin.
_ => {
let forked = crate::vm_helper::FORK_EVENTS
.load(std::sync::atomic::Ordering::Relaxed)
!= forks_before;
if forked {
let line =
crate::ported::jobs::printtime(elapsed.as_secs_f64(), &ti, &fmt, &desc);
eprintln!("{}", line);
}
return Value::Status(status);
}
};
let _ = forks_before;
// c:Src/exec.c:1699 — execpline hands `how` (Z_TIMED included) to
// the pipeline's last stage, and a last stage that runs in the
// current shell reaches the c:4443 shelltime call below just as a
// timed builtin does: `time /bin/echo a | read x` prints the shell
// and children lines before dumptime's line for the forked stage.
let last_stage_cursh = timed_pipeline.as_ref().is_some_and(|t| !t.last_forks);
if is_cursh || last_stage_cursh {
// c:Src/exec.c:4443-4444 — `if ((is_cursh || do_exec) && (how &
// Z_TIMED)) shelltime(&shti, &chti, &then, 1);`
//
// c:Src/jobs.c:1933-1993 shelltime(shell, kids, then, delta=1):
// getrusage(RUSAGE_SELF, &ti); dtime_tv(… shell delta …);
// dtime_ts(&dtimespec, then, &now);
// if (!delta == !shell) printtime(&dtimespec, &ti, "shell");
// getrusage(RUSAGE_CHILDREN, &ti); dtime_tv(… kids delta …);
// if (!delta == !kids) printtime(&dtimespec, &ti, "children");
// With delta=1 and both pointers non-NULL, BOTH lines print.
//
// !!! DO NOT "FIX" THIS TO PRINT NOTHING !!!
// The locally-installed `zsh` may print nothing here and look
// like the oracle. It is not: this behaviour was ADDED by
// upstream 53088 (ChangeLog 2024-09-14, Bart Schaefer) —
// "Src/exec.c, Src/jobs.c, Test/A01grammar.ztst,
// Test/A08time.ztst: enable `time' on builtins, assignments,
// and other current-shell actions, including failed commands."
// — which also ADDED Test/A08time.ztst chunks 8-15, the ones
// that assert `shell*` / `children*` for `time x=1`,
// `time echo $(…)`, `time for ((…))`, `time builtin nonesuch`
// and `time false`. zsh 5.9 (2022-05) predates 53088, so a 5.9.x
// binary is silent for every one of those shapes while both
// vendored C trees (src/zsh 5.9.0.3-test and 5.9.999.3-test)
// carry the c:4443 call. Corpus + C source are the spec here.
let mut d_self = ru_self_after;
d_self.ru_utime = sub(ru_self_after.ru_utime, ru_self_before.ru_utime); // c:1954
d_self.ru_stime = sub(ru_self_after.ru_stime, ru_self_before.ru_stime); // c:1955
let ti_self = crate::ported::zsh_h::timeinfo::from_rusage(&d_self);
// c:1972 — `printtime(&dtimespec, &ti, "shell");`
eprintln!(
"{}",
crate::ported::jobs::printtime(elapsed.as_secs_f64(), &ti_self, &fmt, "shell")
);
// c:1993 — `printtime(&dtimespec, &ti, "children");`
eprintln!(
"{}",
crate::ported::jobs::printtime(elapsed.as_secs_f64(), &ti, &fmt, "children")
);
}
if is_cursh {
// A current-shell body is no job: nothing more to report.
} else if let Some(report) = timed_pipeline.filter(|t| !t.procs.is_empty()).and_then(|t| {
// c:Src/jobs.c:1029-1037 — `for (pn = jn->procs; pn; pn = pn->next)
// printtime(dtime_ts(…, &pn->bgtime, &pn->endtime), &pn->ti,
// pn->text);` — one line per process the pipeline forked.
let jn = crate::ported::zsh_h::job {
procs: t.procs,
..Default::default()
};
crate::ported::jobs::dumptime(&jn)
}) {
eprintln!("{}", report);
} else if !last_stage_cursh {
// c:Src/jobs.c:1037 — the forked job's own printtime line, with
// `pn->text` (the command source) as %J.
let line = crate::ported::jobs::printtime(elapsed.as_secs_f64(), &ti, &fmt, &desc);
eprintln!("{}", line);
}
Value::Status(status)
});
// `{name}>file` / `{name}<file` / `{name}>>file` — named-fd allocator.
// Stack: [path, varid, op_byte]. Opens path with the appropriate mode
// and stores the resulting fd number in $varid as a string. We use
// a high starting fd (10+) by allocating then dup'ing — matches zsh's
// "fresh fd >= 10" promise so subsequent commands don't collide on
// stdin/out/err.
vm.register_builtin(BUILTIN_OPEN_NAMED_FD, |vm, _argc| {
use std::sync::atomic::Ordering;
let op_byte = vm.pop().to_int() as u8;
let varid = vm.pop().to_str();
let path = vm.pop().to_str();
// Param introspection used by both the open and close forms.
// c:Src/exec.c:2188 `getvalue(&vbuf, &s, 0)` reaches the node through
// realparamtab->getnode, which is getprivatenode once zsh/param/private
// is set up (Src/Modules/param_private.c:678): a private from an
// enclosing scope is not this parameter.
let param_flags = crate::ported::params::paramtab().read().ok().and_then(|t| {
t.get(&varid).and_then(|p| {
let vis = crate::ported::modules::param_private::getprivatenode(&**p as *const _);
(!vis.is_null()).then(|| unsafe { (*vis).node.flags })
})
});
let param_readonly = param_flags
.map(|f| (f & crate::ported::zsh_h::PM_READONLY as i32) != 0)
.unwrap_or(false);
// `{varid}>&-` / `{varid}<&-` — REDIR_CLOSE with varid.
// Direct port of Src/exec.c:3805-3850.
if matches!(
op_byte,
b if b == fusevm::op::redirect_op::DUP_WRITE
|| b == fusevm::op::redirect_op::DUP_READ
) {
let n = path.trim_start_matches('&');
if n == "-" {
let val = with_executor(|exec| exec.scalar(&varid)).unwrap_or_default();
let fd1 = val.parse::<i32>();
// c:3811-3816 — bad=1: parameter doesn't contain an fd.
let Ok(fd1) = fd1 else {
crate::ported::utils::zwarn(&format!(
"parameter {} does not contain a file descriptor",
varid
));
with_executor(|exec| exec.redirect_failed = true);
return Value::Status(1);
};
// c:3813-3814 — bad=2: readonly parameter.
if param_readonly {
crate::ported::utils::zwarn(&format!(
"can't close file descriptor from readonly parameter {}",
varid
));
with_executor(|exec| exec.redirect_failed = true);
return Value::Status(1);
}
// c:3830-3835 — bad=3: fd >= 10 marked FDT_INTERNAL.
if fd1 >= 10
&& fd1 <= crate::ported::utils::MAX_ZSH_FD.load(Ordering::Relaxed)
&& crate::ported::utils::fdtable_get(fd1) == crate::ported::zsh_h::FDT_INTERNAL
{
crate::ported::utils::zwarn(&format!(
"file descriptor {} used by shell, not closed",
fd1
));
with_executor(|exec| exec.redirect_failed = true);
return Value::Status(1);
}
// c:3870-3873 — close; report failure (varid form
// always reports, unlike bare `N>&-`).
// In an in-process subshell only the body's copy closes.
crate::ported::exec::SubshFdFrame::touch(fd1);
if crate::ported::utils::zclose(fd1) < 0 {
crate::ported::utils::zwarn(&format!(
"failed to close file descriptor {}: {}",
fd1,
crate::ported::utils::zsh_errno_msg(
std::io::Error::last_os_error().raw_os_error().unwrap_or(0)
) // c:Src/exec.c:3929 `%e`
));
return Value::Status(1);
}
return Value::Status(0);
}
// `{varid}>&N` — dup N to a fresh fd >= 10, store in varid.
if let Ok(src) = n.parse::<i32>() {
if param_readonly {
crate::ported::utils::zwarn(&format!(
"can't allocate file descriptor to readonly parameter {}",
varid
));
with_executor(|exec| exec.redirect_failed = true);
return Value::Status(1);
}
let dup = unsafe { libc::fcntl(src, libc::F_DUPFD, 10) };
if dup < 0 {
crate::ported::utils::zwarn(&format!("{}: bad file descriptor", src));
with_executor(|exec| exec.redirect_failed = true);
return Value::Status(1);
}
// c:2404-2412 addfd varid arm — movefd + FDT_EXTERNAL.
let final_fd = crate::ported::utils::movefd(dup);
crate::ported::utils::fdtable_set(final_fd, crate::ported::zsh_h::FDT_EXTERNAL);
// In an in-process subshell the descriptor dies with the body.
crate::ported::exec::SubshFdFrame::opened(final_fd);
with_executor(|exec| {
#[cfg(feature = "recorder")]
crate::recorder::note_descriptor_param(&varid);
exec.set_scalar(varid, final_fd.to_string());
});
return Value::Status(0);
}
return Value::Status(1);
}
// `{varid}<<HERE` (op byte 255) / `{varid}<<<str` (op byte
// 254) — zshrs-side contract with compile_redir; fusevm's
// redirect_op stops at 8. C path: gethere/getherestr write the
// body to a temp file (Src/exec.c:4660-4682), then addfd's
// varid arm moves the read fd >= 10, marks FDT_EXTERNAL and
// sets the param (c:2402-2412). `path` carries the BODY text
// here.
//
// The two markers ARE the `REDIRF_FROM_HEREDOC` distinction of
// c:Src/exec.c:4671-4672 (flag set at c:Src/parse.c:2970-2971):
// 255 is the here-DOCUMENT spelling, whose body reaches the
// consumer byte-for-byte, and 254 the genuine here-STRING,
// which gains one trailing newline "as if the string given was
// a complete command line" (c:4665-4666).
if op_byte == 255 || op_byte == 254 {
let from_heredoc = op_byte == 255;
if param_readonly {
crate::ported::utils::zwarn(&format!(
"can't allocate file descriptor to readonly parameter {}",
varid
));
with_executor(|exec| exec.redirect_failed = true);
return Value::Status(1);
}
// c:4671-4672 — `trim_end_matches('\n')` + unconditional
// append was lossy in both directions: `exec {f}<<EOF`
// with two trailing blank lines produced "hello\n" where
// zsh produces "hello\n\n\n".
let body = if from_heredoc {
path
} else {
format!("{}\n", path)
};
let mut tmpl: Vec<u8> = b"/tmp/zshrs_hd_XXXXXX\0".to_vec();
let write_fd = unsafe { libc::mkstemp(tmpl.as_mut_ptr() as *mut libc::c_char) };
if write_fd < 0 {
crate::ported::utils::zwarn(&format!(
"can't create temp file for here document: {}",
crate::ported::utils::zsh_errno_msg(
std::io::Error::last_os_error().raw_os_error().unwrap_or(0)
) // c:Src/exec.c:3828 `%e`
));
return Value::Status(1);
}
let bytes = body.as_bytes();
let mut off = 0;
while off < bytes.len() {
let n = unsafe {
libc::write(
write_fd,
bytes[off..].as_ptr() as *const libc::c_void,
bytes.len() - off,
)
};
if n <= 0 {
unsafe { libc::close(write_fd) };
return Value::Status(1);
}
off += n as usize;
}
unsafe { libc::close(write_fd) };
let read_fd =
unsafe { libc::open(tmpl.as_ptr() as *const libc::c_char, libc::O_RDONLY) };
unsafe { libc::unlink(tmpl.as_ptr() as *const libc::c_char) };
if read_fd < 0 {
return Value::Status(1);
}
let final_fd = crate::ported::utils::movefd(read_fd);
if final_fd < 0 {
return Value::Status(1);
}
crate::ported::utils::fdtable_set(final_fd, crate::ported::zsh_h::FDT_EXTERNAL);
// In an in-process subshell the descriptor dies with the body.
crate::ported::exec::SubshFdFrame::opened(final_fd);
with_executor(|exec| {
#[cfg(feature = "recorder")]
crate::recorder::note_descriptor_param(&varid);
exec.set_scalar(varid, final_fd.to_string());
});
return Value::Status(0);
}
// Open form: `{varid}>file` etc.
// c:Src/exec.c:2177-2215 checkclobberparam — gate BEFORE open.
if param_readonly {
// c:2191-2197
crate::ported::utils::zwarn(&format!(
"can't allocate file descriptor to readonly parameter {}",
varid
));
with_executor(|exec| exec.redirect_failed = true);
return Value::Status(1);
}
// c:2199-2213 — NO_CLOBBER refuses to overwrite a parameter
// already holding an OPEN fd (decimal value, fdtable says
// FDT_EXTERNAL).
if !isset(crate::ported::zsh_h::CLOBBER) && op_byte != fusevm::op::redirect_op::CLOBBER {
if let Some(val) = with_executor(|exec| exec.scalar(&varid)) {
if let Ok(fd) = val.parse::<i32>() {
if fd >= 0
&& fd <= crate::ported::utils::MAX_ZSH_FD.load(Ordering::Relaxed)
&& crate::ported::utils::fdtable_get(fd)
== crate::ported::zsh_h::FDT_EXTERNAL
{
crate::ported::utils::zwarn(&format!(
"can't clobber parameter {} containing file descriptor {}",
varid, fd
));
with_executor(|exec| exec.redirect_failed = true);
return Value::Status(1);
}
}
}
}
let path_c = match CString::new(path.clone()) {
Ok(c) => c,
Err(_) => return Value::Status(1),
};
let flags = match op_byte {
b if b == fusevm::op::redirect_op::READ => libc::O_RDONLY,
b if b == fusevm::op::redirect_op::WRITE || b == fusevm::op::redirect_op::CLOBBER => {
libc::O_WRONLY | libc::O_CREAT | libc::O_TRUNC
}
b if b == fusevm::op::redirect_op::APPEND => {
libc::O_WRONLY | libc::O_CREAT | libc::O_APPEND
}
b if b == fusevm::op::redirect_op::READ_WRITE => libc::O_RDWR | libc::O_CREAT,
_ => return Value::Status(1),
};
let fd = unsafe { libc::open(path_c.as_ptr(), flags, 0o666) };
if fd < 0 {
// c:Src/exec.c:3790-3795 — report the open failure and mark the
// redirect failed so the command is SKIPPED, matching the numeric-fd
// (`3< file`) and non-varid (`< file`) paths. Previously this
// silently returned Status(1) with no diagnostic and no
// redirect_failed flag, so `{fd}< /nonexistent` ran the command
// anyway with exit 0 (zsh errors "no such file or directory" +
// skips the command). `%e: %s` = strerror(errno) : filename.
let e = std::io::Error::last_os_error();
let msg = redir_errno_msg(&e);
crate::ported::utils::zwarn(&format!("{}: {}", msg, path));
with_executor(|exec| exec.redirect_failed = true);
return Value::Status(1);
}
// c:2404-2412 addfd varid arm — `fd1 = movefd(fd2);
// fdtable[fd1] = FDT_EXTERNAL; setiparam(varid, fd1);`.
// FDT_EXTERNAL (not INTERNAL): the user owns this fd — the
// NO_CLOBBER gate above and `{fd}>&-` close both key off it.
let final_fd = crate::ported::utils::movefd(fd);
if final_fd < 0 {
crate::ported::utils::zerr(&format!(
"cannot move fd {}: {}",
fd,
crate::ported::utils::zsh_errno_msg(
std::io::Error::last_os_error().raw_os_error().unwrap_or(0)
) // c:Src/exec.c:2463 `%e`
));
return Value::Status(1);
}
crate::ported::utils::fdtable_set(final_fd, crate::ported::zsh_h::FDT_EXTERNAL);
// In an in-process subshell the descriptor dies with the body.
crate::ported::exec::SubshFdFrame::opened(final_fd);
let _ = Ordering::Relaxed;
with_executor(|exec| {
#[cfg(feature = "recorder")]
crate::recorder::note_descriptor_param(&varid);
exec.set_scalar(varid, final_fd.to_string());
});
Value::Status(0)
});
// BUILTIN_SET_TRY_BLOCK_ERROR — capture the try-block's exit
// status into `__zshrs_try_block_saved_status` (a scratch
// scalar) so the always-arm can later restore it. Also set
// `TRY_BLOCK_ERROR` per zsh semantics: it stays at -1 unless
// the try-block fired an explicit error (errflag), per
// c:Src/exec.c execlist's WC_TRYBLOCK arm.
vm.register_builtin(BUILTIN_SET_TRY_BLOCK_ERROR, |vm, _argc| {
use std::sync::atomic::Ordering;
let vm_status = vm.last_status;
// c:Src/exec.c WC_TRYBLOCK — the always-arm runs with a
// clean escape state. Snapshot RETFLAG / BREAKS / CONTFLAG /
// EXIT_PENDING here and clear them; RESTORE_TRY_BLOCK_STATUS
// re-applies them at always-arm exit so the propagation jump
// emitted by compile_zsh fires correctly.
let ret_save = crate::ported::builtin::RETFLAG.swap(0, Ordering::Relaxed); // c:769-770
let brk_save = crate::ported::builtin::BREAKS.swap(0, Ordering::Relaxed); // c:771-772
let cont_save = crate::ported::builtin::CONTFLAG.swap(0, Ordering::Relaxed); // c:773-774
let exit_save = crate::ported::builtin::EXIT_PENDING.swap(0, Ordering::Relaxed);
// c:Src/loop.c:762-763 — `save_try_errflag = try_errflag;
// save_try_interrupt = try_interrupt;`. Restored at c:778-779
// by RESTORE_TRY_BLOCK_STATUS so a nested try block doesn't
// clobber the enclosing one's `$TRY_BLOCK_ERROR`.
let try_err_save = crate::ported::r#loop::try_errflag.load(Ordering::Relaxed); // c:762
let try_int_save = crate::ported::r#loop::try_interrupt.load(Ordering::Relaxed); // c:763
TRY_ESCAPE_SAVE.with(|s| {
s.borrow_mut().push((
ret_save,
brk_save,
cont_save,
exit_save,
try_err_save,
try_int_save,
));
});
// c:Src/loop.c:764-766 — `try_errflag = (zlong)(errflag &
// ERRFLAG_ERROR); try_interrupt = (zlong)((errflag &
// ERRFLAG_INT) ? 1 : 0);`. Both are the RAW FLAG BITS, not the
// try-list's exit status: ERRFLAG_ERROR is 1 (zsh.h:2972), so
// `$TRY_BLOCK_ERROR` is 1-or-0 in zsh regardless of what the
// failing command's `$?` was. The try-list's status is carried
// separately in `__zshrs_try_block_saved_status`.
let live_errflag = crate::ported::utils::errflag.load(Ordering::Relaxed);
let try_err = (live_errflag & crate::ported::zsh_h::ERRFLAG_ERROR) as i64; // c:765
let try_int = if (live_errflag & crate::ported::zsh_h::ERRFLAG_INT) != 0 {
1i64
} else {
0i64
}; // c:766
crate::ported::r#loop::try_errflag.store(try_err, Ordering::Relaxed); // c:765
crate::ported::r#loop::try_interrupt.store(try_int, Ordering::Relaxed); // c:766
// c:Src/loop.c:755 — `endval = lastval ? lastval : errflag;`.
// The status of the WHOLE `{…} always {…}` construct, captured
// BEFORE the always-list runs (exectry returns it at c:801) and
// deliberately including the errflag fallback: a try-list that
// failed with `lastval == 0` but raised errflag still reports 1.
let endval = if vm_status != 0 {
vm_status
} else {
live_errflag
}; // c:755
with_executor(|exec| {
// flags=0 (not setsparam's ASSPM_WARN): VM-internal scratch —
// must never surface as a WARN_CREATE_GLOBAL diagnostic inside
// a user function running `{...} always {...}` (f-sy-h's
// `_zsh_highlight` does exactly that under warncreateglobal).
crate::ported::params::assignsparam(
"__zshrs_try_block_saved_status",
&endval.to_string(),
0,
);
let _ = exec;
// Mirror into paramtab so `${parameters[TRY_BLOCK_ERROR]}`
// and the PM_INTEGER `u_val` shadow agree with the atomic
// the special-var getter reads. (setsparam → intsetfn's
// TRY_BLOCK_ERROR arm re-stores the same value.)
exec.set_scalar("TRY_BLOCK_ERROR".to_string(), try_err.to_string());
exec.set_scalar("TRY_BLOCK_INTERRUPT".to_string(), try_int.to_string());
});
// c:Src/loop.c:768 — `errflag = 0;` ("We need to reset all
// errors to allow the block to execute"). C clears the WHOLE
// word, not just ERRFLAG_ERROR.
crate::ported::utils::errflag.store(0, Ordering::Relaxed); // c:768
Value::Status(0)
});
// BUILTIN_BEGIN_INLINE_ENV / END_INLINE_ENV — wrap an
// inline-assignment-prefixed command (`X=foo Y=bar cmd`):
// BEGIN pushes a save frame; SET_VAR fires for each assign and
// ALSO env::set_var's the value (visible to cmd's child); the
// command runs; END pops the frame and restores both shell-var
// and process-env state. Direct port of zsh's addvars() →
// execute_simple → restore-after-exec contract.
vm.register_builtin(BUILTIN_BEGIN_INLINE_ENV, |vm, argc| {
// c:Src/exec.c:4114-4126 — whether the frame RECORDS anything is
// `do_save`:
// if (isset(POSIXBUILTINS)) {
// if (is_shfunc || (hn->flags & (BINF_PSPECIAL|BINF_ASSIGN)))
// do_save = (orig_cflags & BINF_COMMAND);
// else
// do_save = 1;
// } else { ... }
// if (do_save && varspc) save_params(...);
// A frame is pushed either way so BEGIN/END stay balanced; an
// empty save list simply restores nothing, which IS the
// assignment persisting. POSIX.1-2017 XCU 2.9.1: "If the command
// name is a special built-in utility, variable assignments shall
// affect the current execution environment." Verified:
// `dash|ksh|mksh -c 'v=0; v=1 :; printf "[%s]\n" "$v"'` → `[1]`,
// and `v=2 true` → `[1]` because `true` is NOT special.
//
// The name arrives as a compile-time constant (empty when the
// command word is an expansion, which takes the save arm).
let name = if argc >= 1 {
vm.pop().to_str()
} else {
String::new()
};
let mut frame = crate::vm_helper::InlineEnvFrame::new();
// !!! bash EXCEPTION — bash(1), "POSIX Mode": "Assignment
// statements preceding POSIX special builtins persist in the shell
// environment after the builtin completes." bash does this ONLY in
// posix mode, so default `--bash` keeps zsh's save/restore
// (`bash -c 'v=0; v=1 :; printf "[%s]\n" "$v"'` → `[0]`, while
// dash / ksh93 / mksh / bash-as-sh all print `[1]`). zshrs tracks
// bash's `set -o posix` in dash_mode::BASH_ONLY_OPTS, so honor it.
let bash_suppresses =
crate::dash_mode::bash_mode() && !crate::dash_mode::bash_set_o_get("posix");
if crate::ported::zsh_h::isset(crate::ported::zsh_h::POSIXBUILTINS)
&& !name.is_empty()
&& !bash_suppresses
{
// c:4123 `do_save = (orig_cflags & BINF_COMMAND)` — the
// `command` prefix is BINF_COMMAND (c:Src/builtin.c:44
// `BIN_PREFIX("command", BINF_COMMAND)`) and resets the
// behavior, so it keeps the save.
let is_command_prefix = name == "command";
// !!! dash / pdksh EXCEPTION — C's `is_shfunc` leg is not
// universal. `f(){ :; }; v=0; v=4 f` leaves `v` at 0 in dash,
// ash AND mksh, while ksh93 and bash-as-sh (the `--sh`
// reference) leave it at 4. Only the builtin legs are shared.
let is_shfunc = !crate::dash_mode::dash_strict()
&& !crate::dash_mode::pdksh_family()
&& crate::ported::hashtable::shfunctab_lock()
.read()
.map(|t| t.get(&name).is_some())
.unwrap_or(false);
if !is_command_prefix
&& (is_shfunc || builtin_is_pspecial(&name) || builtin_is_assign_family(&name))
{
frame.recording = false; // c:4122-4123 do_save = 0
}
}
// c:4137-4147 — the OTHER decision the command word drives, and the
// one that has nothing to do with POSIX_BUILTINS:
// /* Export this if the command is a shell function,
// * but not if it's a builtin.
// */
// int flags = 0;
// if (is_shfunc)
// flags |= ADDVAR_EXPORT;
// ...
// addvars(state, varspc, flags);
// `addvars` turns that bit into `opts[ALLEXPORT] = 1` around the
// assignment (c:2641-2651), so `X=y shellfn` leaves `X` EXPORTED —
// `${(t)X}` reads `scalar-export` inside the call and `export -p`
// lists it — while `X=y eval …` leaves a plain `scalar`. Verified
// against /opt/homebrew/bin/zsh: `f(){ print ${(t)Q} }; Q=y f` →
// `scalar-export`, `Q=y eval 'print ${(t)Q}'` → `scalar`.
//
// The external-command leg (c:4343-4348 sets ADDVAR_EXPORT
// unconditionally) runs in the FORKED child, after which nothing
// reads the child's parameter table; the value reaches the child's
// environment through the `zputenv` the set-var builtin already
// does either way, so only the shell-function leg is observable and
// only it is mirrored here.
//
// !!! KNOWN GAP — an EXPANDED command word (`c=f; X=y $c`) has no
// compile-time literal, so `name` is the unexpanded text and the
// lookup misses: the prefix assignment stays unexported where zsh
// exports it. Same limitation, same cause as the POSIX_BUILTINS
// `do_save` decision above (compile_zsh.rs:2133-2137) — C resolves
// `hn` at runtime from the expanded word and the bridge is handed a
// constant.
frame.export = crate::ported::hashtable::shfunctab_lock()
.read()
.map(|t| t.get(&name).is_some())
.unwrap_or(false); // c:4142-4143
with_executor(|exec| {
exec.inline_env_stack.push(frame);
});
Value::Status(0)
});
// Closes the frame's save list — see BUILTIN_SEAL_INLINE_ENV.
vm.register_builtin(BUILTIN_SEAL_INLINE_ENV, |_vm, _argc| {
with_executor(|exec| {
if let Some(frame) = exec.inline_env_stack.last_mut() {
frame.recording = false;
}
});
// c:Src/exec.c:4147-4148 — `addvars(state, varspc, flags); if
// (errflag) {` — see PREFIX_ASSIGN_FAILED.
let failed = (crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed)
& crate::ported::zsh_h::ERRFLAG_ERROR)
!= 0;
PREFIX_ASSIGN_FAILED.with(|c| c.set(failed));
// The command word is known now unless it is an expansion, which
// BUILTIN_EXEC_DYNAMIC settles.
if let Some(name) = PREFIX_ASSIGN_CMD.with(|c| c.borrow_mut().take()) {
if !name.is_empty() {
settle_prefix_assign_exit(&name);
}
}
Value::Status(0)
});
// See BUILTIN_PREFIX_ASSIGNS_START.
vm.register_builtin(BUILTIN_PREFIX_ASSIGNS_START, |vm, argc| {
let name = if argc >= 1 { vm.pop().to_str() } else { String::new() };
PREFIX_ASSIGN_CMD.with(|c| *c.borrow_mut() = Some(name));
PREFIX_ASSIGN_EXIT_PENDING.with(|c| c.set(false));
Value::Status(0)
});
vm.register_builtin(BUILTIN_END_INLINE_ENV, |_vm, _argc| {
PREFIX_ASSIGN_FAILED.with(|c| c.set(false));
// No dispatch resolved the command: the assignments ran in the shell.
if PREFIX_ASSIGN_EXIT_PENDING.with(|c| c.get()) {
settle_prefix_assign_exit("");
}
with_executor(|exec| {
if let Some(frame) = exec.inline_env_stack.pop() {
frame.restore(); // c:Src/exec.c:4519 restore_params
}
});
Value::Status(0)
});
// c:Src/exec.c:3969-3976 — bare-exec assignment epilogue: see the
// const's doc block. POSIX_BUILTINS → assignments persist (pop the
// frame, discard the saved state); otherwise → restore_params
// (same walk as END_INLINE_ENV).
vm.register_builtin(BUILTIN_EXEC_INLINE_ENV_DONE, |_vm, _argc| {
let persist = isset(crate::ported::zsh_h::POSIXBUILTINS);
with_executor(|exec| {
if let Some(frame) = exec.inline_env_stack.pop() {
if persist {
return; // c:3971 — no save/restore under POSIX_BUILTINS
}
frame.restore(); // c:Src/exec.c:4519 restore_params
}
});
Value::Status(0)
});
// BUILTIN_RESTORE_TRY_BLOCK_STATUS — emitted at the end of an
// `always` arm. Per zshmisc, the exit status of the entire
// `{ try } always { finally }` construct is the try-list's
// status, regardless of what happens in the always-list (the
// exception is `return`/`exit` inside always, which short-
// circuits and the cleanup is the only thing that runs). So
// restore TRY_BLOCK_ERROR unconditionally — the always-list's
// exit status is discarded for the construct.
vm.register_builtin(BUILTIN_RESTORE_TRY_BLOCK_STATUS, |_vm, _argc| {
use std::sync::atomic::Ordering;
// c:Src/loop.c:801 — `return endval;`. The construct's exit
// status is the try-list's (captured at c:755 by
// SET_TRY_BLOCK_ERROR), never the always-list's.
let saved = with_executor(|exec| {
exec.scalar("__zshrs_try_block_saved_status")
.and_then(|s| s.parse::<i32>().ok())
.unwrap_or(0)
});
// c:Src/exec.c:1375 — `lastval = lv;` on the exectry return.
// The always-list's own commands left their status in LASTVAL
// (`always { : }` → 0); without this store the errflag re-raise
// below aborts the shell with the always-list's 0 instead of
// the try-list's failure status.
crate::ported::builtin::LASTVAL.store(saved, Ordering::Relaxed); // c:1375
// c:Src/loop.c:774-777 — the error RE-RAISE. This is the
// whole point of TRY_BLOCK_ERROR being writable:
//
// if (try_errflag) errflag |= ERRFLAG_ERROR;
// else errflag &= ~ERRFLAG_ERROR;
// if (try_interrupt) errflag |= ERRFLAG_INT;
// else errflag &= ~ERRFLAG_INT;
//
// SET_TRY_BLOCK_ERROR cleared errflag (c:768) so the always-arm
// could run; the try-block's error is PARKED in `try_errflag`
// and re-raised HERE unless the always-arm zeroed it
// (`TRY_BLOCK_ERROR=0`, the documented swallow idiom — routed
// to the atomic by intsetfn's IPDEF6 arm, params.rs).
//
// zshrs used to just drop the parked error, so
// `f() { { typeset -r ro=1; ro=2 } always { … }; print reached }`
// kept running and exited 0, where zsh aborts f with status 1.
let te = crate::ported::r#loop::try_errflag.load(Ordering::Relaxed); // c:774
let ti = crate::ported::r#loop::try_interrupt.load(Ordering::Relaxed); // c:776
if te != 0 {
crate::ported::utils::errflag
.fetch_or(crate::ported::zsh_h::ERRFLAG_ERROR, Ordering::Relaxed);
// c:775
} else {
crate::ported::utils::errflag
.fetch_and(!crate::ported::zsh_h::ERRFLAG_ERROR, Ordering::Relaxed);
// c:777
}
if ti != 0 {
crate::ported::utils::errflag
.fetch_or(crate::ported::zsh_h::ERRFLAG_INT, Ordering::Relaxed);
// c:779
} else {
crate::ported::utils::errflag
.fetch_and(!crate::ported::zsh_h::ERRFLAG_INT, Ordering::Relaxed);
// c:781
}
// Re-apply the escape flags captured by SET_TRY_BLOCK_ERROR.
// If the always-arm itself fired return/break/continue/exit,
// its handler already overwrote the canonical atomics; let
// those win — the always-arm's own escape always takes
// priority over the try-block's deferred one.
if let Some((ret, brk, cont, exit_p, try_err_save, try_int_save)) =
TRY_ESCAPE_SAVE.with(|s| s.borrow_mut().pop())
{
// c:Src/loop.c:782-783 — `try_errflag = save_try_errflag;
// try_interrupt = save_try_interrupt;`
crate::ported::r#loop::try_errflag.store(try_err_save, Ordering::Relaxed); // c:782
crate::ported::r#loop::try_interrupt.store(try_int_save, Ordering::Relaxed);
// c:783
if crate::ported::builtin::RETFLAG.load(Ordering::Relaxed) == 0 {
crate::ported::builtin::RETFLAG.store(ret, Ordering::Relaxed);
}
if crate::ported::builtin::BREAKS.load(Ordering::Relaxed) == 0 {
crate::ported::builtin::BREAKS.store(brk, Ordering::Relaxed);
}
if crate::ported::builtin::CONTFLAG.load(Ordering::Relaxed) == 0 {
crate::ported::builtin::CONTFLAG.store(cont, Ordering::Relaxed);
}
if crate::ported::builtin::EXIT_PENDING.load(Ordering::Relaxed) == 0 {
crate::ported::builtin::EXIT_PENDING.store(exit_p, Ordering::Relaxed);
}
}
Value::Status(saved)
});
// `[[ -r/-w/-x file ]]` — the cond path must use access(2) (the
// C-faithful doaccess), NOT fusevm's generic Op::TestFile which only
// checks existence for -r/-w (so a `chmod 000` file read as readable;
// C02cond.ztst:13). Stack: [path, mode]; mode is the access(2) bit
// (R_OK=4, W_OK=2, X_OK=1). Mirrors cond.rs:232/238/267 `doaccess`.
vm.register_builtin(BUILTIN_COND_ACCESS, |vm, _argc| {
let mode = vm.pop().to_int() as i32;
let path = vm.pop().to_str();
Value::Bool(crate::ported::cond::doaccess(&path, mode) != 0)
});
// `[[ -prefix PAT ]]` / `-suffix` / `-after` / `-between` module condition.
// Stack (pushed by the ModCond compile arm): arg0 … argN-1, then the
// operator word last. argc = N+1.
// c:Src/subst.c:4419-4420 `if (globsubst) shtokenize(y)` — see the
// BUILTIN_COND_SHTOKENIZE doc for why a module condition needs it.
vm.register_builtin(BUILTIN_COND_SHTOKENIZE, |vm, _argc| {
let mut s = vm.pop().to_str();
crate::ported::glob::shtokenize(&mut s);
Value::str(s)
});
vm.register_builtin(BUILTIN_COND_MOD, |vm, argc| {
use crate::ported::zle::complete::{cond_psfix, cond_range, CVT_PREPAT, CVT_SUFPAT};
let op = vm.pop().to_str(); // operator word (pushed last → popped first)
let n = (argc as usize).saturating_sub(1);
let mut args: Vec<String> = Vec::with_capacity(n);
for _ in 0..n {
args.push(vm.pop().to_str());
}
args.reverse(); // restore arg0 … argN-1 order
// Dispatch the module/completion condition (C evalcond COND_MOD path:
// condtab lookup + arity check, cond.c:149-185, over the four cotab[]
// entries at complete.c:1697-1702). Handlers return 1=match/true.
let name: String = op
.trim_start_matches(|c: char| c == '-' || c == '\u{e19b}')
.to_string();
// c:Src/cond.c:149-150 — `cd = getconddef((ctype == COND_MODI),
// name + 1, 1)`. The `autol = 1` argument is what makes an
// autoloadable condition LOAD its module: `getconddef`
// (Src/module.c:647) sees the `c:`-stub's `p->module` and calls
// `ensurefeature(p->module, "c:", name)`, then re-looks-up the
// now-real definition that `zsh/complete`'s cotab installed.
// Without this call zshrs answered `[[ -prefix … ]]` straight
// from the compiled-in handler table and left `zsh/complete`
// unloaded, where `zsh -f` reports it loaded after the first use.
// `try_lock`: every other MODULESTAB caller holds the same mutex
// for a moment and the load chain re-enters it; falling through
// to the compiled-in table is the safe outcome, not a deadlock.
let cd = match crate::ported::module::MODULESTAB.try_lock() {
Ok(mut tab) => crate::ported::module::getconddef(0, &name, 1, &mut tab), // c:150
Err(_) => None,
};
// c:151-155 — arity check against the conddef's own min/max
// (`if (l < cd->min || (cd->max >= 0 && l > cd->max))`). The
// fallback pins the same numbers the cotab rows carry
// (complete.c:1698-1701) for the window before zsh/complete is
// loaded, when `getconddef` has only the module-less stub.
let (min, max): (usize, usize) = match cd.as_ref() {
Some(c) if c.max >= 0 => (c.min.max(0) as usize, c.max as usize), // c:152
// !!! KORN-MODE EXTENSION (no C counterpart) !!! ksh93 `[[ -R NAME ]]`
// is true when NAME is a nameref.
_ if name == "R" && args.len() == 1 && crate::extensions::dash_mode::ksh93_mode() => {
return Value::Bool(crate::ported::params::is_nameref(&args[0]));
}
_ => match name.as_str() {
"prefix" | "suffix" => (1, 2), // c:1700-1701
"after" => (1, 1), // c:1698
"between" => (2, 2), // c:1699
_ => {
// c:Src/cond.c:186-193 — no conddef matched, so C falls out
// of both `getconddef` arms to `zwarnnam(fromtest, "unknown
// condition: %s", errname)` and then `return 2;` (the
// "module not found, error" exit). Status 2 — not 1 — is
// what `evalcond` hands back, and c:Src/exec.c:5216-5221
// turns a 2 into a shell error. Arm the same carrier
// BUILTIN_COND_UNKNOWN uses so the shared
// BUILTIN_COND_STATUS_FROM_BOOL tail emits 2 and aborts;
// returning a bare Bool(false) collapsed it to 1, so
// `[[ -zz a ]]` exited 1 where zsh exits 2.
COND_BAD_PATTERN.with(|c| c.set(true)); // c:193
crate::ported::utils::zerr(&format!(
"unknown condition: {}",
op.replace('\u{e19b}', "-")
));
return Value::Bool(false);
}
},
};
if args.len() < min || args.len() > max {
// c:Src/cond.c:177-181 — `if (l < cd->min || (cd->max >= 0 &&
// l > cd->max)) { zwarnnam(fromtest, "unknown condition: %s",
// errname); return 2; }`. Status 2, same as the module-not-found
// arm above.
//
// This arm previously refused to arm the carrier because the
// PARSER turned a zero-operand `-word` into a ModCond, so
// `[[ -prefix ]]` would have exited 2 where zsh exits 0. That
// parser bug is fixed (src/ported/parse.rs par_cond_2: a
// multi-char `-word` with no operand now takes c:2590's
// `par_cond_double("-n", s1)` string-test arm, and a two-char
// one takes c:2592's `par_cond_multi(s1, newlinklist())`), so
// the only way to reach here is a genuine arity violation —
// `[[ -between a ]]`, which zsh answers 2.
COND_BAD_PATTERN.with(|c| c.set(true)); // c:180
crate::ported::utils::zerr(&format!(
"unknown condition: {}",
op.replace('\u{e19b}', "-")
));
return Value::Bool(false);
}
// c:158 — `return !cd->handler(strs, cd->condid);`
let r = match cd.as_ref().and_then(|c| c.handler.map(|h| (h, c.condid))) {
Some((handler, condid)) => handler(&args, condid),
// Pre-load window: zsh/complete's cotab is not installed yet,
// so dispatch through the compiled-in handlers directly.
None => match name.as_str() {
"prefix" => cond_psfix(&args, CVT_PREPAT),
"suffix" => cond_psfix(&args, CVT_SUFPAT),
"after" => cond_range(&args, 0),
"between" => cond_range(&args, 1),
_ => 0,
},
};
Value::Bool(r == 1)
});
vm.register_builtin(BUILTIN_IS_TTY, |vm, _argc| {
let fd_str = vm.pop().to_str();
let fd: i32 = fd_str.trim().parse().unwrap_or(-1);
let is_tty = if fd < 0 {
false
} else {
unsafe { libc::isatty(fd) != 0 }
};
Value::Bool(is_tty)
});
// c:Src/exec.c:4918/5040/5069 — a process substitution used inside a
// `[[ … ]]` cond operand errors "process substitution %s cannot be
// used here" (getoutputfile/getproc run with thisjob == -1). Emitted
// by the compiler in place of ProcessSubIn/Out when in_cond_operand.
vm.register_builtin(BUILTIN_PROCSUB_COND_ERROR, |_vm, _argc| {
let cmd = _vm.pop().to_str();
crate::ported::utils::zerr(&format!("process substitution {} cannot be used here", cmd));
// c:getoutputfile returns NULL with errflag set → the enclosing
// statement aborts (empty stdout, exit 1), rather than the cond
// merely evaluating false.
crate::ported::utils::errflag.fetch_or(
crate::ported::zsh_h::ERRFLAG_ERROR,
std::sync::atomic::Ordering::Relaxed,
);
with_executor(|exec| exec.set_last_status(1));
_vm.last_status = 1;
Value::str("")
});
// Set $LINENO before executing the next statement. Direct
// port of zsh's `lineno` global tracking from Src/input.c
// (`if ((inbufflags & INP_LINENO) || !strin) && c == '\n')
// lineno++;`). The compiler emits one of these before each
// top-level pipe in `compile_sublist`, carrying the line
// number captured by the parser at `ZshPipe.lineno`. Pops
// [n], updates `$LINENO` in the variable table.
vm.register_builtin(BUILTIN_SET_LINENO, |vm, _argc| {
let n = vm.pop().to_int();
set_lineno_impl(n)
});
// Direct port of Src/prompt.c:1623 cmdpush. Token is a `CS_*`
// value (zsh.h:2775-2806) emitted by compile_zsh around each
// compound command (if/while/[[…]]/((…))/$(…)) and consumed by
// `%_` in PS4 / prompt expansion.
vm.register_builtin(BUILTIN_CMD_PUSH, |vm, _argc| {
let token = vm.pop().to_int() as u8;
// Route through canonical cmdpush (Src/prompt.c:1623). The
// prompt expander reads from the file-static `CMDSTACK` at
// `prompt.rs:2006`, not `exec.cmd_stack` — without this,
// `%_` in PS4 saw an empty stack during xtrace.
if (token as i32) < crate::ported::zsh_h::CS_COUNT {
crate::ported::prompt::cmdpush(token);
}
Value::Status(0)
});
// Direct port of Src/prompt.c:1631 cmdpop.
vm.register_builtin(BUILTIN_CMD_POP, |_vm, _argc| {
crate::ported::prompt::cmdpop();
Value::Status(0)
});
vm.register_builtin(BUILTIN_OPTION_SET, |vm, _argc| {
let name = vm.pop().to_str();
// Direct port of `optison(char *name, char *s)` at Src/cond.c:502 — `[[ -o NAME ]]`
// reads through the same `opts[]` array that `setopt NAME`
// writes via `dosetopt`. Earlier code read a duplicate Executor
// HashMap which never saw `bin_setopt`'s writes (those land in
// `OPTS_LIVE` via `opt_state_set`). Routing through the canonical
// C port restores the single-store invariant: one `opts[]`,
// shared between setopt/unsetopt and `[[ -o ]]`.
let r = crate::ported::cond::optison(None, &name); // c:cond.c:502 (fromtest=NULL for [[ -o ]])
match r {
0 => Value::Bool(true), // c:cond.c:520 set
1 => Value::Bool(false), // c:cond.c:518/520 unset
_ => {
// c:cond.c:514 — unknown option. optison already emitted the
// diagnostic (via zwarn, now that fromtest=NULL for
// `[[ -o ]]`); re-printing here double-emitted for
// `[[ ! -o bad ]]` / `[[ -o a || -o b ]]`.
Value::Bool(false)
}
}
});
// Tri-state `-o` for compile_cond's direct status path. Returns
// 0 / 1 / 3 as a Value::Int that compile_cond consumes via
// Op::SetStatus. Mirrors zsh's `[[ -o invalid ]]` returning $?=3.
vm.register_builtin(BUILTIN_OPTION_CHECK_TRISTATE, |vm, _argc| {
let name = vm.pop().to_str();
let r = crate::ported::cond::optison(None, &name); // c:cond.c:502 (fromtest=NULL for [[ -o ]])
// optison itself prints the diagnostic via zwarnnam when r=3
// and POSIXBUILTINS is unset (the canonical path). Don't
// double-emit here. r is already 0/1/3.
Value::Int(r as i64)
});
// BUILTIN_PARAM_FILTER — `${var:#pat}` / `${var:|name}` etc.
// PURE PASSTHRU: rebuild `${name:#pat}` and route to paramsubst.
vm.register_builtin(BUILTIN_PARAM_FILTER, |vm, argc| {
// c:Src/subst.c:1761 — the word's PREFORK_SINGLE bit, pushed last by
// compile_zsh::emit_param_modifier (see the note there).
let pf_flags = if argc as usize > 2 && vm.pop().to_int() != 0 {
crate::ported::zsh_h::PREFORK_SINGLE
} else {
0
};
let pattern = vm.pop().to_str();
let name = vm.pop().to_str();
let body = format!("${{{}:#{}}}", name, pattern);
paramsubst_to_value_status(vm, &body, pf_flags)
});
// `a[i]=(elements)` / `a[i,j]=(elements)` / `a[i]=()`
// — subscripted-array assign with array RHS. Stack pushed by
// compile_assign as: [elem0, elem1, …, elemN-1, name, key].
vm.register_builtin(BUILTIN_SET_SUBSCRIPT_RANGE, |vm, argc| {
let n = argc as usize;
let mut popped: Vec<Value> = Vec::with_capacity(n);
for _ in 0..n {
popped.push(vm.pop());
}
popped.reverse();
if popped.len() < 3 {
return Value::Status(1);
}
// c:Src/params.c:3511-3526 — trailing append flag. The ARRAY
// subscript path (`a[N]+=(v)` / `a[lo,hi]+=(v)`) sets it so the
// AUGMENT transform below collapses the range to an empty range
// after the slice end and inserts ONLY the new value. The scalar
// path pre-concats the old slice (ARRAY_INDEX+Concat) and passes
// 0, so it keeps plain-replace semantics.
// The trailing marker is 0/1 for the ARRAY-RHS emitter and 2 for
// the SCALAR-RHS comma emitter (compile_zsh::compile_assign),
// which also pushes the SOURCE subscript just below it. The
// scalar form is the one C does NOT necessarily treat as a
// range: c:Src/params.c:1515 `(c != Outbrack && (ishash || c !=
// ','))` stops the comma from separating subscripts when the
// parameter is a hash, so `h[1,2]=Z` is the ordinary key `1,2`.
// The compile-time split cannot know the type, so it defers here.
let marker = popped.pop().map_or(String::new(), |v| v.to_str());
// Marker 3 is the scalar-RHS form of `+=` (old slice already
// concatenated in, like 2); it differs only for a numeric target.
let scalar_append = marker == "3";
let scalar_rhs = marker == "2" || scalar_append; // c:1515 deferral
let key_src = if scalar_rhs {
popped.pop().map(|v| v.to_str())
} else {
None
};
let append = marker == "1";
let key = popped.pop().unwrap().to_str();
let name = popped.pop().unwrap().to_str();
// c:Src/exec.c:4475-4478 (54941) — a subscripted prefix assignment
// (`H[2,4]=oo f`) saves its base parameter for restore_params.
with_executor(|exec| {
if exec
.inline_env_stack
.last()
.is_some_and(|frame| frame.recording)
{
save_inline_prefix_param(exec, &name);
}
});
// c:Src/params.c:1585-1592 — `if (needtok) { parsestr(&s);
// singsub(&s); }`: the subscript body is parameter-substituted
// BEFORE it is read, whether it goes on to `mathevalarg`
// (c:1601, the array/scalar range bounds) or straight into the
// hash as a key (c:1596-1616). The ARRAY-RHS emitter pre-expands
// its subscript at word-compile time, but the SCALAR-RHS comma
// emitter hands over the raw source, so this round has to happen
// here: `mathevali("$n")` is 0, which silently turned
// `a=abcdef; n=3; a[$n,-1]=X` into a whole-string overwrite
// (`X` instead of `abX`), and it is why the fzf-tab
// `t[$#MATCH/2+1,-1]=""` form still lost its bound.
//
// Only for a source-level LIVE expansion: an escaped `\$`
// reached `parsestr` as the Bnull marker and `singsub` leaves it
// alone, so `h[\$x,y]` keys on the literal `$x,y`.
let key = if scalar_rhs
&& key_src.as_deref().is_some_and(|src| {
let b = src.as_bytes();
(0..b.len())
.any(|i| (b[i] == b'$' || b[i] == b'`') && (i == 0 || b[i - 1] != b'\\'))
}) {
crate::ported::subst::singsub(&key) // c:1592
} else {
key
};
let mut values: Vec<String> = Vec::new();
for v in popped {
match v {
Value::Array(items) => {
for it in items.iter() {
values.push(it.to_str());
}
}
other => values.push(other.to_str()),
}
}
// c:Src/params.c:3316/3365 — assignaparam's subscript arm finds the
// parameter through getvalue/fetchvalue, whose getparamnode
// (c:570-575) follows a PM_NAMEREF chain to its endpoint, so
// `ptr[2,4]=(x y)` splices the array `ptr` names. Everything below
// looks `name` up directly and spliced the reference itself ("ptr:
// attempt to assign array value to non-array"). A chain ending on a
// visible parameter is that parameter's name; any other outcome
// (subscripted refname, hidden binding, placeholder, loop) goes to
// the ported assignaparam, which resolves the chain itself.
let name = if crate::ported::params::is_nameref(&name) {
use crate::ported::params::nameref_resolution as NR;
let visible = |t: &str, level: i32, has_pm: bool| {
!has_pm
|| crate::ported::params::paramtab()
.read()
.ok()
.and_then(|tb| tb.get(t).map(|p| p.level))
== Some(level)
};
match crate::ported::params::resolve_nameref_name(&name, None) {
NR::Target { name: t, subscript: None, pm, level } if visible(&t, level, pm.is_some()) => t,
_ if !scalar_rhs => {
let asspm = if append { crate::ported::zsh_h::ASSPM_AUGMENT } else { 0 };
let done =
crate::ported::params::assignaparam(&format!("{name}[{key}]"), values, asspm);
return Value::Status(if done.is_some() { 0 } else { 1 });
}
_ => name,
}
} else {
name
};
// Bash sparse-array tracking: a single-index `a[i]=v` that pads the
// dense Vec past its old end leaves indices old_len..i as HOLES (not
// real elements), so `${#a[@]}`/`${!a[@]}` skip them like bash. Only
// in bash mode, only for a plain non-append single index (0-based
// under ksharrays). Captured before the assign; applied after.
let sparse_track: Option<(String, usize, usize)> =
if crate::dash_mode::sparse_arrays() && !append && !key.contains(',') {
crate::dash_mode::sparse_subscript_index(&key)
.filter(|_| !with_executor(|exec| exec.has_assoc(&name)))
.map(|i| {
let old_len =
with_executor(|exec| exec.array(&name).map(|a| a.len()).unwrap_or(0));
(name.clone(), old_len, i)
})
} else {
None
};
// c:Src/params.c:3383-3389 — a subscripted ARRAY assignment to an
// associative array is an error, whatever the subscript looks like:
// if (v && PM_TYPE(v->pm->node.flags) == PM_HASHED) {
// unqueue_signals();
// zerr("%s: attempt to set slice of associative array",
// v->pm->node.nam);
// freearray(val);
// errflag |= ERRFLAG_ERROR;
// return NULL;
// }
// assignaparam (params.rs) ports this, but a single-key `h[k]=(1 2)`
// never reaches it: the VM lowers subscripted assignment to this
// builtin instead. The comma form `h[a,b]=(1 2)` DID error — it takes a
// different route — so the gap looked like a subscript-parsing quirk
// when it was really "the check lives on a path this form doesn't
// take". Untreated, the assignment was SILENTLY DISCARDED: rc=0 and
// `${h[k]}` still read its old value.
//
// Only array-valued assignment is rejected; `h[k]=x` is a scalar
// element store and stays legal.
{
let is_hashed = crate::ported::params::paramtab()
.read()
.ok()
.and_then(|t| {
t.get(&name).map(|pm| {
crate::ported::zsh_h::PM_TYPE(pm.node.flags as u32)
== crate::ported::zsh_h::PM_HASHED
})
})
.unwrap_or(false);
if is_hashed {
if scalar_rhs {
// c:1515 — for a hash the comma is not a subscript
// separator, so this was never a range: hand the
// WHOLE subscript to the element path. `h[1,2]=Z`
// keys on `1,2` in zsh; rejecting it here was the
// compile-time range split leaking through.
let src = key_src.unwrap_or_else(|| key.clone());
let val = values.first().cloned().unwrap_or_default();
return Value::Status(assign_hash_element(&name, &key, &src, &val));
}
crate::ported::utils::zerr(&format!(
"{name}: attempt to set slice of associative array" // c:3385
));
crate::ported::utils::errflag.fetch_or(
crate::ported::zsh_h::ERRFLAG_ERROR,
std::sync::atomic::Ordering::Relaxed,
); // c:3387
return Value::Status(1); // c:3388
}
}
with_executor(|exec| {
// Parse subscript: slice `lo,hi` or single index `i`.
// setarrvalue (Src/params.c:2895) expects 1-based start/
// end inclusive where start==end means replace one
// element. Negative bounds translate to len+n+1 (1-based).
//
// c:Src/params.c — the END side accepts 0 as a valid value
// that signals "insert BEFORE start position" (the canonical
// `a[N,N-1]=val` prepend / mid-insert idiom). Bug #275 in
// docs/BUGS.md: the previous Rust port clamped end up to 1,
// collapsing `a[1,0]=(X Y)` into `a[1,1]=(X Y)` which
// OVERWRITES position 1 instead of prepending. Provide two
// translators — start_translate clamps to 1 (1-based);
// end_translate keeps 0 intact so the splice in
// setarrvalue (start_idx=0..end_idx=0) inserts at the front.
// Bug #589: for scalars (no array), use the scalar's char
// count as `len` so negative-index translation (`a[2,-1]`)
// computes against the actual string length, not 0.
let len = exec
.array(&name)
.map(|a| a.len() as i64)
.or_else(|| {
crate::ported::params::paramtab().read().ok().and_then(|t| {
t.get(&name).and_then(|pm| {
if crate::ported::zsh_h::PM_TYPE(pm.node.flags as u32)
== crate::ported::zsh_h::PM_SCALAR
{
pm.u_str.as_ref().map(|s| s.chars().count() as i64)
} else {
None
}
})
})
})
.unwrap_or(0);
let start_translate = |raw: i64| -> i32 {
if raw < 0 {
(len + raw + 1).max(1) as i32
} else {
raw.max(1) as i32
}
};
let end_translate = |raw: i64| -> i32 {
if raw < 0 {
(len + raw + 1).max(0) as i32
} else {
raw.max(0) as i32
}
};
// c:Src/params.c — KSH_ARRAYS option flips array subscripts
// from 1-based to 0-based. setarrvalue expects 1-based
// inclusive bounds, so under KSH_ARRAYS we shift positive
// inputs by +1 before translation. Negative bounds left
// alone (count from end). Sibling of #610/#611/#612.
// Bug #613.
let ksh_arrays = crate::ported::zsh_h::isset(crate::ported::zsh_h::KSHARRAYS);
let ksh_shift = |raw: i64| -> i64 {
if ksh_arrays && raw >= 0 {
raw + 1
} else {
raw
}
};
// c:Src/params.c getindex — subscript bounds are MATH
// expressions, not bare integers: `a[(( ${#a}+1 ))]=(x)`,
// `a[n+1]=(x)`. Plain `parse::<i64>()` returned 0 on any
// arithmetic subscript, which the `i == 0` guard turned into
// a silent no-op (computed-index append never landed). Parse
// the literal fast-path first, then fall back to mathevali
// (which handles `(( ))` grouping, var refs, and operators).
// c:Src/params.c:2036 + c:2118 — getindex resolves EACH range
// bound with `getarg`, not with mathevalarg directly, so a bound
// may be a `(r)`/`(R)`/`(i)`/`(I)`/`(k)`/`(K)` SEARCH rather than
// an arithmetic expression. On an array getarg's search arm
// (c:1672-1719) returns the 1-BASED INDEX `r` of the match — the
// value-vs-index distinction only sets `*inv`, which getindex
// rejects for a range START (c:2121) and otherwise ignores. So map
// the VALUE-returning direction letters onto their INDEX twins and
// read the position back. Without this both bounds evaluated to 0
// through mathevali and `array[(R)nomatch,(r)nomatch]=(…)` became
// a front INSERT instead of the whole-array replace zsh performs.
let cur_arr: Vec<String> = exec.array(&name).unwrap_or_default();
let eval_bound = |s: &str| -> i64 {
let t = s.trim();
if let Some(rest) = t.strip_prefix('(') {
if let Some(close) = rest.find(')') {
let grp = &rest[..close];
if !grp.is_empty()
&& grp
.chars()
.all(|c| matches!(c, 'r' | 'R' | 'i' | 'I' | 'k' | 'K' | 'e'))
{
// c:1394-1410 — r/k select the FIRST match, R/K the
// LAST; i/I are the same searches returning the index.
let mapped: String = grp
.chars()
.map(|c| match c {
'r' | 'k' => 'i',
'R' | 'K' => 'I',
other => other,
})
.collect();
let expr = format!("({}){}", mapped, &rest[close + 1..]);
if let Some(crate::ported::params::getarg_out::Value(v)) =
crate::ported::params::getarg(&expr, Some(&cur_arr), None, None)
{
return v.to_str().trim().parse::<i64>().unwrap_or(0);
}
}
}
}
t.parse::<i64>()
.ok()
.or_else(|| crate::ported::math::mathevali(t).ok())
.unwrap_or(0)
};
let (raw_start, raw_end) = if let Some((s_str, e_str)) = key.split_once(',') {
(ksh_shift(eval_bound(s_str)), ksh_shift(eval_bound(e_str)))
} else {
let i = ksh_shift(eval_bound(&key));
(i, i)
};
// c:Src/params.c:2124-2151 (getindex) — `start == 0 && end == 0`
// is the range entirely off the START of the index range. With
// KSH_ZERO_SUBSCRIPT it degrades to "the first element"
// (`end = startnextlen;` c:2140, i.e. the 0-based range [0,1)).
// Without it the range is flagged VALFLAG_EMPTY (c:2148) and
// setarrvalue (c:2910) rejects the assignment with
// "assignment to invalid subscript range". zshrs silently
// returned for `a[0]=(x)` and front-INSERTED for `a[0,0]=(x)`.
let mut valflags = 0i32;
let (raw_start, raw_end) = if raw_start == 0 && raw_end == 0 {
if crate::ported::zsh_h::isset(crate::ported::zsh_h::KSHZEROSUBSCRIPT) {
(1, 1) // c:2140 — first element, in the 1-based convention below
} else {
valflags |= crate::ported::zsh_h::VALFLAG_EMPTY; // c:2148
(-1, 0) // c:2149 — bounds unused; setarrvalue errors first
}
} else {
(raw_start, raw_end)
};
// c:Src/params.c:2114 (getindex) — a SINGLE subscript is the
// range `[i, i]`: `end = we ? we : start;` sets BOTH bounds to
// the same RAW user index, and only the START is then shifted
// down by one (`if (start > 0) start -= startprevlen;` c:2120).
// setarrvalue (c:2944-2953) afterwards resolves each bound
// INDEPENDENTLY — `start += len` clamped at 0, `end += len + 1`
// clamped at 0 — so an out-of-range negative index such as
// `a[-10]` on a 3-element array yields start==end==0, an EMPTY
// range at the front that INSERTS. Running the end bound of a
// single subscript through `start_translate` (which floors at 1)
// instead collapsed that to [0,1) and OVERWROTE element 1:
// `a=(some sunny day); a[-10]=(we'll meet again)` dropped "some"
// (Test/D04parameter.ztst:1420 "Out of range negative array
// subscripts"). Both forms therefore share one translator pair.
let (start, end) = (start_translate(raw_start), end_translate(raw_end));
// c:Src/params.c:3518-3520 (assignaparam ASSPM_AUGMENT) — a
// subscripted `+=` to an array does NOT prepend the old slice;
// it collapses the range to an EMPTY range positioned right
// AFTER the slice end (`v->start = v->end--`) and splices in
// ONLY the new value: `a[2]+=(d)` on (a b c) → (a b d c);
// `a[2,3]+=(x)` on (1 2 3 4) → (1 2 3 x 4). In setarrvalue's
// 1-based convention here that means start = end+1 (so
// start_idx == end_idx == end → splice arr[end..end]).
let (start, end) = if append && end > 0 {
(end + 1, end)
} else {
(start, end)
};
// c:Src/params.c:392-430 IPDEF9("argv"/"@"/"*", &pparams) —
// the positional parameters live in the `pparams` vector, NOT
// paramtab, so a subscript splice (`argv[2]=(X Y Z)`,
// `2=(X Y Z)`) must read/write pparams. Splice a synthetic
// array param holding the current positionals via the
// canonical setarrvalue, then store the result back to
// pparams — mirroring assignaparam's argv/@/* special-case
// (params.rs:6937) for the whole-array form.
if name == "argv" || name == "@" || name == "*" {
let mut pm = {
crate::ported::params::createparam(
&name,
crate::ported::zsh_h::PM_ARRAY as i32,
);
crate::ported::params::paramtab()
.write()
.ok()
.and_then(|mut t| t.remove(&name))
};
if let Some(ref mut p) = pm {
p.u_arr = Some(exec.pparams());
}
let mut v = crate::ported::zsh_h::value {
pm,
arr: Vec::new(),
scanflags: 0,
valflags,
start,
end,
};
crate::ported::params::setarrvalue(&mut v, values);
let result = v.pm.and_then(|p| p.u_arr).unwrap_or_default();
exec.set_pparams(result);
return;
}
// Route through canonical setarrvalue (Src/params.c:2895).
// It handles PM_READONLY rejection, PM_HASHED slice-error,
// PM_ARRAY splice + bounds clamp + padding (c:2980+).
let taken = match crate::ported::params::paramtab().write() {
Ok(mut tab) => tab.remove(&name),
Err(_) => None,
};
// c:Src/exec.c:2640 / getvalue(…, 1) — a subscript assignment to
// a NONEXISTENT parameter auto-creates it. getindex/fetchvalue
// with the create flag calls createparam(name, PM_ARRAY) so the
// splice has an array to write into; `unset u; u[1,2]=(a z)`
// then yields the array (a z). Without this, setarrvalue saw
// v.pm == None and silently stored nothing. The single-index
// scalar-value path (SET_ASSOC/SET_ARRAY_AT) already vivifies;
// this brings the range/array-value path to parity.
let taken = taken.or_else(|| {
crate::ported::params::createparam(&name, crate::ported::zsh_h::PM_ARRAY as i32);
crate::ported::params::paramtab()
.write()
.ok()
.and_then(|mut t| t.remove(&name))
});
// c:Src/params.c:2748+ — PM_SCALAR with subscript range
// SPLICES the value into the scalar's char string. Bug
// #589: zshrs's slice handler always called setarrvalue,
// erroring "attempt to assign array value to non-array"
// for `a=hello; a[2,3]=XYZ`. Detect PM_SCALAR and route
// through assignstrvalue (which does scalar splice via
// the PM_SCALAR arm at params.rs:3709-3789).
//
// Only a SCALAR RHS takes that route: it is assignsparam
// (c:Src/params.c:3183), whose assignstrvalue also covers an
// integer/float target (c:2777 — the whole value is replaced,
// `integer i=5; i[1,2]=3` gives 3). An ARRAY RHS is assignaparam
// → setarrvalue, which rejects every non-array target
// (c:2896-2900 "attempt to assign array value to non-array":
// `s=abc; s[2]=(x y)`).
let target_type = taken
.as_ref()
.map(|pm| crate::ported::zsh_h::PM_TYPE(pm.node.flags as u32));
let is_scalar = scalar_rhs
&& target_type.is_some_and(|t| {
t & (crate::ported::zsh_h::PM_ARRAY | crate::ported::zsh_h::PM_HASHED) == 0
});
// c:Src/params.c:3250-3266 — `+=` on a subscripted integer/float:
// case PM_INTEGER: case PM_EFLOAT: case PM_FFLOAT:
// zsfree(val); unqueue_signals();
// zerr("attempt to add to slice of a numeric variable");
// return NULL;
if scalar_append
&& target_type.is_some_and(|t| {
t == crate::ported::zsh_h::PM_INTEGER
|| t == crate::ported::zsh_h::PM_EFLOAT
|| t == crate::ported::zsh_h::PM_FFLOAT
})
{
if let (Some(pm), Ok(mut tab)) = (taken, crate::ported::params::paramtab().write()) {
tab.insert(name, pm);
}
crate::ported::utils::zerr("attempt to add to slice of a numeric variable"); // c:3264
return;
}
let mut v = crate::ported::zsh_h::value {
pm: taken,
arr: Vec::new(),
scanflags: 0,
valflags,
start,
end,
};
if is_scalar {
// Scalar splice — concat values, route through
// assignstrvalue which dispatches by PM_TYPE.
// start_translate returns 1-based positions; assignstrvalue's
// PM_SCALAR arm at params.rs:3735+ expects 0-based start
// (chars before start are kept) and 0-based end-exclusive
// (chars from end are kept). Convert: start-=1.
if v.start > 0 {
v.start -= 1;
}
let val: String = values.join("");
crate::ported::params::assignstrvalue(Some(&mut v), Some(val), 0);
} else {
crate::ported::params::setarrvalue(&mut v, values);
}
// Write the mutated Param back to paramtab — setarrvalue
// mutated v.pm in-place; the prior `tab.remove(&name)` at
// the top of this handler took ownership, so we re-insert
// here. setarrvalue + this re-insert IS the canonical
// store (Src/params.c:2895). No further mirror needed.
if let Some(pm) = v.pm {
if let Ok(mut tab) = crate::ported::params::paramtab().write() {
tab.insert(name, pm);
}
}
});
if let Some((nm, old_len, i)) = sparse_track {
crate::bash_arrays::note_subscript_set(&nm, old_len, i);
}
Value::Status(0)
});
// BUILTIN_CONCAT_SPLICE — word-segment concat for an expansion whose
// ARRAY shape survives into the word (`${arr[@]}`, `$@`, `${(@)a}`,
// `${=v}`, slices). c:Src/subst.c:4245 `if (isarr)` gates the two
// emit shapes and c:1663 `int plan9 = isset(RCEXPANDPARAM);` picks
// between them at RUNTIME — so the option, not the compile-time
// segment shape, decides splice-vs-cross-product here.
vm.register_builtin(BUILTIN_CONCAT_SPLICE, |vm, _argc| {
let rhs = vm.pop();
let lhs = vm.pop();
if plan9_active() {
return concat_plan9_prov(lhs, rhs);
}
concat_splice_prov(lhs, rhs)
});
// BUILTIN_CONCAT_DISTRIBUTE — word-segment concat. With
// rcexpandparam (zsh option), distributes element-wise (cartesian
// product). Default mode: joins arrays with IFS first char to a
// single scalar before concat, matching zsh's default unquoted
// and DQ semantics. Direct port of Src/subst.c sepjoin path
// (line ~1813) which gates element-vs-join on the rc_expand_param
// option, defaulting to join.
// BUILTIN_CONCAT_DISTRIBUTE_FORCED — same shape as
// CONCAT_DISTRIBUTE, but always cartesian-distributes when one
// side is Array. Used for compile-time-detected explicit
// distribution forms (`${^arr}` etc.) where the source flag
// overrides the rcexpandparam option default.
// `${^arr}` — RC_EXPAND_PARAM forced on by the flag. concat_plan9 carries
// both halves of C's plan9 block: the c:4316-4350 cartesian emit AND the
// c:4362 `uremnode` word deletion for an empty array. The DISTRIBUTE_FORCED
// handler below cannot be reused: it is shared with `${(@)a}` / `${(f)v}` /
// `${a[@]}`, which KEEP the word on empty (`x${(@)a}y` → `xy`).
vm.register_builtin(BUILTIN_CONCAT_PLAN9, |vm, _argc| {
let rhs = vm.pop();
let lhs = vm.pop();
concat_plan9_prov(lhs, rhs)
});
// `${^^arr}` — RC_EXPAND_PARAM forced OFF (c:2553-2555 `plan9 = 0`). Every
// other concat builtin re-checks plan9_active(), which is the OPTION, so
// under `setopt rcexpandparam` they cross-product regardless of the flag.
// Go straight to concat_splice — C's non-plan9 path (c:4366-4437).
vm.register_builtin(BUILTIN_CONCAT_SPLICE_NOPLAN9, |vm, _argc| {
let rhs = vm.pop();
let lhs = vm.pop();
concat_splice_prov(lhs, rhs)
});
vm.register_builtin(BUILTIN_CONCAT_DISTRIBUTE_FORCED, |vm, _argc| {
let rhs = vm.pop();
let lhs = vm.pop();
match (lhs, rhs) {
(Value::Array(la), Value::Array(ra)) => {
if ra.is_empty() {
return Value::Array(la);
}
if la.is_empty() {
return Value::Array(ra);
}
let mut out = Vec::with_capacity(la.len() * ra.len());
for a in la.iter() {
let a_s = a.as_str_cow();
for b in ra.iter() {
let b_s = b.as_str_cow();
let mut s = String::with_capacity(a_s.len() + b_s.len());
s.push_str(&a_s);
s.push_str(&b_s);
out.push(Value::str(s));
}
}
Value::array(out)
}
(Value::Array(la), rhs_scalar) => {
// An EMPTY array contributes nothing to a concatenated
// word — the surrounding scalar text survives. zsh:
// `x${^a}y` (a=()) / `x${(P)scalar-empty}y` → "xy", NOT
// a dropped word. Without this, a `(P)` indirect to an
// unset/empty scalar (which nodes_to_value collapses to
// Value::Array([]) for standalone-removal semantics)
// cartesian-dropped the whole word — p10k's
// `typeset -g _$2=${(P)2}` then arrived as a bare
// `typeset` and dumped every parameter (~217× → 19 MB
// terminal flood → startup hang).
if la.is_empty() {
return rhs_scalar;
}
let r = rhs_scalar.as_str_cow();
let out: Vec<Value> = la
.iter()
.map(|a| {
let a_s = a.as_str_cow();
let mut s = String::with_capacity(a_s.len() + r.len());
s.push_str(&a_s);
s.push_str(&r);
Value::str(s)
})
.collect();
Value::array(out)
}
(lhs_scalar, Value::Array(ra)) => {
// Symmetric empty-array-contributes-nothing rule; see
// the (Array, scalar) arm above.
if ra.is_empty() {
return lhs_scalar;
}
let l = lhs_scalar.as_str_cow();
let out: Vec<Value> = ra
.iter()
.map(|b| {
let b_s = b.as_str_cow();
let mut s = String::with_capacity(l.len() + b_s.len());
s.push_str(&l);
s.push_str(&b_s);
Value::str(s)
})
.collect();
Value::array(out)
}
(lhs_s, rhs_s) => {
let l = lhs_s.as_str_cow();
let r = rhs_s.as_str_cow();
let mut s = String::with_capacity(l.len() + r.len());
s.push_str(&l);
s.push_str(&r);
Value::str(s)
}
}
});
vm.register_builtin(BUILTIN_CONCAT_DISTRIBUTE, |vm, argc| {
let rhs = vm.pop();
let lhs = vm.pop();
// c:Src/subst.c:4245 `if (isarr)` — an unquoted array embedded
// in a word ALWAYS emits one word per element, never a scalar
// join. The shape (splice vs plan9 cross-product) is chosen at
// RUNTIME by c:1663 `int plan9 = isset(RCEXPANDPARAM);`, exactly
// as BUILTIN_CONCAT_SPLICE does. The only extra case DISTRIBUTE
// handles is the DQ context: the compiler emits
// CallBuiltin(BUILTIN_CONCAT_DISTRIBUTE, 1) when the parent word
// is DQ-wrapped (compile_zsh.rs parent_is_dq), and inside DQ
// `"pre${arr}post"` joins via $IFS[0] to a single scalar
// regardless of the option (c:Src/subst.c:1650-1656 isarr
// comment). The default UNQUOTED path emits argc=2 (lhs + rhs).
// Bug #246 in docs/BUGS.md.
if argc == 1 {
// DQ context: join any Array side to scalar via sepjoin's
// IFS default. c:Src/utils.c:3936-3945 — set-but-empty IFS
// joins with "" (`IFS=""; echo "x$*y"` → `xabcy`); only
// unset / space-leading IFS yields " ".
let join_arr = |arr: &[Value]| -> String {
let strs: Vec<String> = arr.iter().map(|v| v.as_str_cow().into_owned()).collect();
crate::ported::utils::sepjoin(&strs, None)
};
// Provenance: the DQ-join arm consumes both operands, so
// capture them first (Arc clones, only while armed).
let prov_operands = crate::provenance::active().then(|| (lhs.clone(), rhs.clone()));
let l = match lhs {
Value::Array(a) => join_arr(&a),
other => other.as_str_cow().into_owned(),
};
let r = match rhs {
Value::Array(a) => join_arr(&a),
other => other.as_str_cow().into_owned(),
};
let mut s = String::with_capacity(l.len() + r.len());
s.push_str(&l);
s.push_str(&r);
let out = Value::str(s);
if let Some((pl, pr)) = prov_operands {
crate::provenance::on_concat(&pl, &pr, &out);
}
return out;
}
// Unquoted plain `${arr}`: same runtime dispatch as
// BUILTIN_CONCAT_SPLICE — c:4245 `if (isarr)` always distributes
// one word per element; c:1663 picks splice (default, first/last
// sticking, c:4366-4437) vs plan9 cross-product (c:4316-4365).
// concat_splice / concat_plan9 both honor EMPTY_EXPANSION_IS_SCALAR
// so the p10k `${(P)2}` empty-array word-removal semantics survive.
if plan9_active() {
return concat_plan9_prov(lhs, rhs);
}
concat_splice_prov(lhs, rhs)
});
// See BUILTIN_WORD_ASSEMBLE_PLAN9's doc comment for the stack contract.
vm.register_builtin(BUILTIN_WORD_ASSEMBLE_PLAN9, |vm, argc| {
// Pop argc values: descriptor was pushed FIRST (bottom), segments
// after it, so popping top-first then reversing yields
// [descriptor, seg0, …, seg(n-1)].
let mut popped: Vec<Value> = Vec::with_capacity(argc as usize);
for _ in 0..argc {
popped.push(vm.pop());
}
popped.reverse();
let mut it = popped.into_iter();
let descriptor = it.next().map(|v| v.to_str()).unwrap_or_default();
let plan9_flags: Vec<bool> = descriptor.chars().map(|c| c == '1').collect();
let segments: Vec<Value> = it.collect();
word_assemble_plan9(&segments, &plan9_flags)
});
// `[[ a -ef b ]]` — same-inode test. Resolves both paths via fs::metadata
// (follows symlinks the way zsh's -ef does) and compares (dev, inode).
// Returns false on any I/O error (path missing, permission denied, etc.).
vm.register_builtin(BUILTIN_SAME_FILE, |vm, _argc| {
let b = vm.pop().to_str();
let a = vm.pop().to_str();
let same = match (fs::metadata(&a), fs::metadata(&b)) {
(Ok(ma), Ok(mb)) => ma.dev() == mb.dev() && ma.ino() == mb.ino(),
_ => false,
};
Value::Bool(same)
});
// `[[ -c path ]]` — character device.
vm.register_builtin(BUILTIN_IS_CHARDEV, |vm, _argc| {
let path = vm.pop().to_str();
let result = fs::metadata(&path)
.map(|m| m.file_type().is_char_device())
.unwrap_or(false);
Value::Bool(result)
});
// `[[ -b path ]]` — block device.
vm.register_builtin(BUILTIN_IS_BLOCKDEV, |vm, _argc| {
let path = vm.pop().to_str();
let result = fs::metadata(&path)
.map(|m| m.file_type().is_block_device())
.unwrap_or(false);
Value::Bool(result)
});
// `[[ -p path ]]` — FIFO (named pipe).
vm.register_builtin(BUILTIN_IS_FIFO, |vm, _argc| {
let path = vm.pop().to_str();
let result = fs::metadata(&path)
.map(|m| m.file_type().is_fifo())
.unwrap_or(false);
Value::Bool(result)
});
// `[[ -S path ]]` — socket.
vm.register_builtin(BUILTIN_IS_SOCKET, |vm, _argc| {
let path = vm.pop().to_str();
let result = fs::symlink_metadata(&path)
.map(|m| m.file_type().is_socket())
.unwrap_or(false);
Value::Bool(result)
});
// `[[ -k path ]]` / `-u` / `-g` — sticky / setuid / setgid bit.
vm.register_builtin(BUILTIN_HAS_STICKY, |vm, _argc| {
let path = vm.pop().to_str();
let result = fs::metadata(&path)
.map(|m| m.permissions().mode() & libc::S_ISVTX as u32 != 0)
.unwrap_or(false);
Value::Bool(result)
});
vm.register_builtin(BUILTIN_HAS_SETUID, |vm, _argc| {
let path = vm.pop().to_str();
let result = fs::metadata(&path)
.map(|m| m.permissions().mode() & libc::S_ISUID as u32 != 0)
.unwrap_or(false);
Value::Bool(result)
});
vm.register_builtin(BUILTIN_HAS_SETGID, |vm, _argc| {
let path = vm.pop().to_str();
let result = fs::metadata(&path)
.map(|m| m.permissions().mode() & libc::S_ISGID as u32 != 0)
.unwrap_or(false);
Value::Bool(result)
});
vm.register_builtin(BUILTIN_OWNED_BY_USER, |vm, _argc| {
let path = vm.pop().to_str();
let euid = unsafe { libc::geteuid() };
let result = fs::metadata(&path)
.map(|m| m.uid() == euid)
.unwrap_or(false);
Value::Bool(result)
});
vm.register_builtin(BUILTIN_OWNED_BY_GROUP, |vm, _argc| {
let path = vm.pop().to_str();
let egid = unsafe { libc::getegid() };
let result = fs::metadata(&path)
.map(|m| m.gid() == egid)
.unwrap_or(false);
Value::Bool(result)
});
// `[[ -N path ]]` — file's access time is NOT newer than its
// modification time (zsh man: "true if file exists and its
// access time is not newer than its modification time"). Used
// by zsh's mailbox-watching code. The semantic is `atime <=
// mtime` (equivalent to `mtime >= atime`) — equal counts as
// true, which a strict `mtime > atime` check missed for newly
// created files where both stamps are identical.
vm.register_builtin(BUILTIN_FILE_MODIFIED_SINCE_ACCESS, |vm, _argc| {
let path = vm.pop().to_str();
let result = fs::metadata(&path)
.map(|m| m.atime() <= m.mtime())
.unwrap_or(false);
Value::Bool(result)
});
// `[[ a -nt b ]]` — true if `a`'s mtime is strictly later than `b`'s.
// BOTH files must exist; if either is missing the result is false.
// (Earlier behavior was bash's "missing == infinitely-old"; zsh
// strictly requires both files to exist.)
vm.register_builtin(BUILTIN_FILE_NEWER, |vm, _argc| {
let b = vm.pop().to_str();
let a = vm.pop().to_str();
// Use SystemTime modified() for nanosecond precision —
// MetadataExt::mtime() returns seconds only, so two files
// touched within the same second compared equal even when
// 500ms apart. zsh tracks ns and uses `>=` for ties (touching
// a then b in quick succession should still report b newer).
let ta = fs::metadata(&a).and_then(|m| m.modified()).ok();
let tb = fs::metadata(&b).and_then(|m| m.modified()).ok();
let result = match (ta, tb) {
(Some(ta), Some(tb)) => ta > tb,
// bash, ksh93 and mksh: a missing right operand is infinitely old.
(Some(_), None) => crate::dash_mode::bash_mode() || crate::dash_mode::korn_mode(),
_ => false,
};
Value::Bool(result)
});
// `[[ a -ot b ]]` — mirror of -nt. Same both-must-exist contract.
vm.register_builtin(BUILTIN_FILE_OLDER, |vm, _argc| {
let b = vm.pop().to_str();
let a = vm.pop().to_str();
let ta = fs::metadata(&a).and_then(|m| m.modified()).ok();
let tb = fs::metadata(&b).and_then(|m| m.modified()).ok();
let result = match (ta, tb) {
(Some(ta), Some(tb)) => ta < tb,
// bash, ksh93 and mksh: a missing left operand is infinitely old.
(None, Some(_)) => crate::dash_mode::bash_mode() || crate::dash_mode::korn_mode(),
_ => false,
};
Value::Bool(result)
});
// `set -e` / `setopt errexit` post-command check. Compiler emits
// this after each top-level command's SetStatus (skipped inside
// conditionals/pipelines/&&||/`!`). If errexit is on AND the last
// command exited non-zero AND it's not a `return` from a function,
// exit the shell with that status.
// `set -x` / `setopt xtrace` — print each command before it runs.
// The compiler emits this BEFORE the actual builtin/external call
// with the command's literal text as a single string arg. We
// print to stderr if xtrace is on. Honors `$PS4` (default `+ `).
//
// ── XTRACE flow control ────────────────────────────────────────
// Mirror of C zsh's `doneps4` flag in execcmd_exec (Src/exec.c).
// When an assignment trace fires (XTRACE_ASSIGN), it emits PS4
// and sets this flag so the subsequent XTRACE_ARGS skips its own
// PS4 emission — the assignment + command end up on the SAME
// line: `<PS4>a=1 echo hello\n`. XTRACE_ARGS / XTRACE_NEWLINE
// reset the flag after emitting the trailing `\n`.
vm.register_builtin(BUILTIN_XTRACE_IS_ON, |_vm, _argc| {
// Push live xtrace state. Caller pairs this with JumpIfFalse
// to skip the trace-string-building block when xtrace is off,
// avoiding side-effectful operand re-evaluation. Bug #159 in
// docs/BUGS.md.
let on = crate::ported::zsh_h::isset(crate::ported::zsh_h::XTRACE);
Value::Int(if on { 1 } else { 0 })
});
vm.register_builtin(BUILTIN_XTRACE_LINE, |vm, _argc| {
// Keep the Value; `to_str()` allocates a String, and this handler
// runs on EVERY `(( … ))` / `[[ … ]]` / loop-head evaluation, where
// xtrace is off essentially always. Defer the allocation to the
// `on` branch below.
let cmd_val = vm.pop();
// Sync exec.last_status with the live vm.last_status BEFORE
// the next command runs. Direct port of the zsh exec.c
// contract — `$?` reads the exit status of the *most recent*
// command. XTRACE_LINE is emitted by the compiler BEFORE
// every simple command, so it's the natural sync point.
let live = vm.last_status;
with_executor(|exec| {
exec.set_last_status(live);
});
// C zsh emits xtrace for `(( … ))` / `[[ … ]]` / `case` /
// `if/while/until/for/repeat` head expressions via
// `printprompt4(); fprintf(xtrerr, "%s\n", expr)` at
// Src/exec.c:5240 (math), c:5286 (cond), c:4117 (for), etc.
// The compiler emits BUILTIN_XTRACE_LINE only at those
// construct boundaries (compile_arith / compile_cond /
// compile_if / compile_while / compile_for / compile_case);
// simple commands route to BUILTIN_XTRACE_ARGS instead. So
// this handler always emits when xtrace is on — no prefix-
// string heuristic.
let on = crate::ported::zsh_h::isset(crate::ported::zsh_h::XTRACE);
if on {
let already = XTRACE_DONE_PS4.with(|f| f.get());
if !already {
printprompt4();
}
// c:exec.c:5240/5286 — `fprintf(xtrerr, "%s\n", expr)`. Buffer
// the line + newline, flush once (single write).
xtrerr_fputs(&cmd_val.to_str());
xtrerr_fputs("\n");
xtrerr_flush();
XTRACE_DONE_PS4.with(|f| f.set(false));
}
Value::Status(0)
});
// BUILTIN_XTRACE_ARRAY_LINE — xtrace line for an `arr=(...)` / `arr+=(...)`
// assignment. Stack on entry: [array, prefix] (argc = 2); pops prefix
// ("name=( " / "name+=( "), then the whole assembled Value::Array. Direct
// port of c:Src/exec.c::addvars:2624-2632, guarded on the live xtrace
// state like C's `if (xtr)`: prints `prefix qz(e0) qz(e1) … ) ` with each
// element shell-quoted (quotedzputs). Replaces the former one-VM-slot-per-
// element trace, which overflowed next_slot (u16) on large literals.
vm.register_builtin(BUILTIN_XTRACE_ARRAY_LINE, |vm, _argc| {
let prefix = vm.pop().to_str();
let arr = vm.pop();
let live = vm.last_status;
with_executor(|exec| {
exec.set_last_status(live);
});
let on = crate::ported::zsh_h::isset(crate::ported::zsh_h::XTRACE);
if on {
let already = XTRACE_DONE_PS4.with(|f| f.get());
if !already {
printprompt4();
}
let mut line = String::with_capacity(prefix.len() + 16);
line.push_str(&prefix);
if let Value::Array(items) = arr {
for it in items.iter() {
line.push_str(&crate::ported::utils::quotedzputs(&it.to_str()));
line.push(' ');
}
}
line.push_str(") ");
line.push('\n');
xtrerr_fputs(&line);
xtrerr_flush();
XTRACE_DONE_PS4.with(|f| f.set(false));
}
Value::Status(0)
});
// BUILTIN_MAKE_ARRAY_COUNTED — pop a count Int (top), then pop that many
// values below it, and push them as one Value::Array (bottom-of-group
// first). Same result as Op::MakeArray(N) but N comes from the stack as an
// i64, dodging MakeArray's u16 operand cap. The compiler emits this only
// when a literal `arr=(...)` has more than u16::MAX elements.
vm.register_builtin(BUILTIN_MAKE_ARRAY_COUNTED, |vm, _argc| {
let count = vm.pop().to_int().max(0) as usize;
let mut items: Vec<Value> = Vec::with_capacity(count);
for _ in 0..count {
items.push(vm.pop());
}
items.reverse();
Value::array(items)
});
// BUILTIN_ARGV_RFLATTEN — recursively flatten a MakeArray-packed argv
// bundle so a >255-arg Call/CallFunction/CallBuiltin (dispatched with
// argc=1 over the single packed Array) recovers every positional arg. The
// call ops flatten only one level; a brace/glob/`$arr` word contributes a
// nested Array that would otherwise stringify. See the const doc.
vm.register_builtin(BUILTIN_ARGV_RFLATTEN, |vm, _argc| {
let v = vm.pop();
let mut out: Vec<String> = Vec::new();
flatten_array_value(v, &mut out);
Value::array(out.into_iter().map(Value::str).collect())
});
// Like XTRACE_LINE but reads the top `argc - 1` values from the
// VM stack WITHOUT consuming them (peek), then pops a prefix
// string at the top. Joins prefix + peeked args with spaces using
// zsh's quotedzputs-equivalent quoting. Direct port of
// Src/exec.c:2055-2066 — emit AFTER expansion, with each arg
// shell-quoted, so `for i in a b; echo for $i` traces as
// `echo for a` / `echo for b`, not `echo for $i`.
//
// Stack contract on entry: [arg1, arg2, ..., argN, prefix].
// Pops prefix; peeks argN..arg1 below. argc = N + 1.
vm.register_builtin(BUILTIN_XTRACE_ARGS, |vm, argc| {
let prefix = vm.pop().to_str();
let live = vm.last_status;
with_executor(|exec| {
exec.set_last_status(live);
});
let on = crate::ported::zsh_h::isset(crate::ported::zsh_h::XTRACE);
if on {
let n_args = argc.saturating_sub(1) as usize;
let len = vm.stack.len();
// c:Src/exec.c:2055 — argv is the POST-expansion word
// list, so an arg that expanded to multiple words splats
// into multiple trace tokens AND an arg that expanded to
// zero words (empty unquoted `${UNSET}`) emits nothing.
// pop_args (line 6243) already does this splat for the
// real handler; mirror the same Array → splat / empty →
// drop logic here so xtrace renders `echo ${UNSET}` as
// `echo` (zsh) instead of `echo ''` (the previous
// single-arg stringify path returned "" and then
// quotedzputs wrapped it in `''`).
let arg_strs: Vec<String> = if n_args > 0 && len >= n_args {
let mut out = Vec::new();
for v in &vm.stack[len - n_args..] {
match v {
Value::Array(items) => {
for item in items.iter() {
out.push(quotedzputs(&item.to_str()));
}
}
other => out.push(quotedzputs(&other.to_str())),
}
}
out
} else {
Vec::new()
};
// Builtins dispatch through `execbuiltin` (Src/builtin.c:442)
// which emits its own PS4 + name + args xtrace. To avoid
// double-emission, skip our emission here when the first
// arg is a known builtin with a registered HandlerFunc —
// those go through execbuiltin and will trace themselves.
// Externals + builtins-not-yet-routed-through-execbuiltin
// keep our emission as a stand-in.
let goes_through_execbuiltin = crate::ported::builtin::BUILTINS
.iter()
.any(|b| b.node.nam == prefix && b.handlerfunc.is_some());
if !goes_through_execbuiltin {
let line = if arg_strs.is_empty() {
prefix
} else {
format!("{} {}", prefix, arg_strs.join(" "))
};
// Mirrors Src/exec.c:2055 xtrace emission. C does:
// if (!doneps4) printprompt4();
// ... emit args + spaces ...
// fputc('\n', xtrerr); fflush(xtrerr);
// printprompt4 + the args + `\n` all land in the xtrerr
// buffer; the single fflush below writes the whole line in
// one syscall so concurrent pipeline stages never
// interleave (c:makecline:2122-2123).
let already_ps4 = XTRACE_DONE_PS4.with(|f| f.get());
if !already_ps4 {
printprompt4();
}
xtrerr_fputs(&line);
xtrerr_fputs("\n"); // c:2122 fputc('\n', xtrerr)
xtrerr_flush(); // c:2123 fflush(xtrerr)
}
XTRACE_DONE_PS4.with(|f| f.set(false));
}
Value::Status(0)
});
// BUILTIN_XTRACE_ASSIGN — direct port of the per-assignment
// trace block at Src/exec.c:2517-2582. C body excerpt:
// xtr = isset(XTRACE);
// if (xtr) { printprompt4(); doneps4 = 1; }
// while (assign) {
// if (xtr) fprintf(xtrerr, "%s+=" or "%s=", name);
// ... eval value into `val` ...
// if (xtr) { quotedzputs(val, xtrerr); fputc(' ', xtrerr); }
// ...
// }
//
// Stack on entry: [..., name, value]. PEEKS both (they're left
// on stack for SET_VAR to pop). Emits `name=<quoted-val> ` with
// no newline; trailing `\n` comes from XTRACE_ARGS (cmd path)
// or XTRACE_NEWLINE (assignment-only path).
vm.register_builtin(BUILTIN_XTRACE_ASSIGN, |vm, _argc| {
let on = crate::ported::zsh_h::isset(crate::ported::zsh_h::XTRACE);
if on {
// PEEK [..., name, value] — argc==2 by contract.
let len = vm.stack.len();
if len >= 2 {
let name = vm.stack[len - 2].to_str();
let value = vm.stack[len - 1].to_str();
let already_ps4 = XTRACE_DONE_PS4.with(|f| f.get());
if !already_ps4 {
printprompt4();
XTRACE_DONE_PS4.with(|f| f.set(true));
}
// C: `fprintf(xtrerr, "%s=", name)` then `quotedzputs
// (val); fputc(' ', xtrerr);`. Append to the xtrerr buffer
// (no newline / no flush — the line continues with the
// command via XTRACE_ARGS, or ends at XTRACE_NEWLINE).
xtrerr_fputs(&format!("{}={} ", name, quotedzputs(&value)));
}
}
Value::Status(0)
});
// BUILTIN_XTRACE_NEWLINE — emit trailing `\n` + flush iff a
// prior XTRACE_ASSIGN this line already emitted PS4. Mirrors
// C's `fputc('\n', xtrerr); fflush(xtrerr);` at exec.c:3398
// (the assignment-only path through execcmd_exec).
vm.register_builtin(BUILTIN_XTRACE_NEWLINE, |_vm, _argc| {
let on = crate::ported::zsh_h::isset(crate::ported::zsh_h::XTRACE);
if on {
let already_ps4 = XTRACE_DONE_PS4.with(|f| f.get());
if already_ps4 {
xtrerr_fputs("\n"); // c:3398 fputc('\n', xtrerr)
xtrerr_flush(); // c:3398 fflush(xtrerr)
XTRACE_DONE_PS4.with(|f| f.set(false));
}
}
Value::Status(0)
});
// c:Src/exec.c WC_TRYBLOCK — post-always re-jump probes. Each
// returns 1 + consumes the atomic when the corresponding
// escape flag is set; the try-block compile pairs each with
// a JumpIfFalse + Jump → outer scope's return / break /
// continue patches.
vm.register_builtin(BUILTIN_RETFLAG_CHECK, |_vm, _argc| {
use std::sync::atomic::Ordering;
let r = crate::ported::builtin::RETFLAG.load(Ordering::Relaxed);
if r != 0 {
// Don't clear here — doshfunc owns the clear at c:6047
// when the function unwinds. Leaving it set propagates
// through nested `eval`/`source` callers correctly.
Value::Int(1)
} else {
Value::Int(0)
}
});
vm.register_builtin(BUILTIN_BREAKS_CHECK, |_vm, _argc| {
use std::sync::atomic::Ordering;
let b = crate::ported::builtin::BREAKS.load(Ordering::Relaxed);
let c = crate::ported::builtin::CONTFLAG.load(Ordering::Relaxed);
// `break` sets BREAKS but NOT CONTFLAG; `continue` sets both.
// Filter out the continue path here so the two checks are
// mutually exclusive.
if b != 0 && c == 0 {
// Consume BREAKS so the outer loop's break_patches
// landing doesn't double-decrement.
crate::ported::builtin::BREAKS.store(0, Ordering::Relaxed);
Value::Int(1)
} else {
Value::Int(0)
}
});
vm.register_builtin(BUILTIN_CONTFLAG_CHECK, |_vm, _argc| {
use std::sync::atomic::Ordering;
let c = crate::ported::builtin::CONTFLAG.load(Ordering::Relaxed);
if c != 0 {
crate::ported::builtin::CONTFLAG.store(0, Ordering::Relaxed);
crate::ported::builtin::BREAKS.store(0, Ordering::Relaxed);
Value::Int(1)
} else {
Value::Int(0)
}
});
// c:Src/loop.c — `loops++` / `loops--` bracket every iterative
// construct: execfor c:114/188, execwhile c:427/491, execrepeat
// c:523/546. `loops` is a GLOBAL, not a per-frame counter, and
// `bin_break` reads it (`if (!loops)`) to decide whether `break` /
// `continue` is legal. Because doshfunc does NOT reset it (only
// restores it under LOCAL_LOOPS, c:6104-6112), a function called
// from inside a loop sees the CALLER's count and its `break` ends
// the caller's loop. zshrs's compiled for/while/until/repeat lower
// to raw jumps, so without these two ops the counter stayed 0 and
// every such `break` errored out instead.
vm.register_builtin(BUILTIN_LOOP_ENTER, |_vm, _argc| {
crate::ported::builtin::LOOPS.fetch_add(1, std::sync::atomic::Ordering::SeqCst); // c:114
Value::Int(0)
});
// c:Src/loop.c:141-145 + :199-203 (execfor), :478-481 (execwhile),
// :534-537 (execrepeat) — every loop that abandons its body because
// `errflag` is set FORCES the escaping status first:
// if (errflag) { if (breaks) breaks--; lastval = 1; break; }
// so a fatal error inside a loop leaves 1, not whatever the failing
// command set. `setopt extendedglob; for i in 1 2; do [[ abc == [ ]]; done`
// exits 1 in zsh while the bare `[[ abc == [ ]]` exits 2; zshrs's compiled
// loops jumped straight to the chunk-end landing and carried the cond's 2
// out. `execselect` has no such assignment (c:217+), which is why
// `compile_select` does not bump `open_loop_depth` and never emits this.
// c:Src/loop.c:479-482 — `if (errflag) { lastval = 1; break; }`, the
// guard every C loop runs AFTER its body. Without it a completer whose
// loop body raises an error spins forever in an interactive shell: the
// errflag makes the prologue skip every statement, but the loop's exit
// test reads a residual `$? == 0` and loops again. Reproduced at 98% CPU
// with `_files -g "*(-.):t:source files" -g "(a:t:directories"` behind a
// `#compdef` — `while _next_label …; do` (Completion/Unix/Type/_files
// sh:121) never terminated, so `<cmd> <TAB>` produced nothing, ever.
// lldb pinned three samples at the same loop head in the `_files` chunk.
//
// C tests the WHOLE errflag word here (ERRFLAG_INT included), exactly as
// the list loop does at c:Src/exec.c:1443.
vm.register_builtin(BUILTIN_LOOP_ERRFLAG_BREAK, |vm, _argc| {
if crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed) == 0 {
return Value::Int(0);
}
vm.last_status = 1; // c:481/201/536
with_executor(|exec| exec.set_last_status(1)); // c:481/201/536
Value::Int(1) // c:482/202/537 — break
});
vm.register_builtin(BUILTIN_LOOP_ERRFLAG_STATUS, |vm, _argc| {
// The `if (errflag)` half of the C guard is re-tested HERE, not at
// compile time: the same abort edge also carries an ERREXIT
// (`set -e`) exit, which in C leaves execlist via `zexit(lastval)`
// and never reaches the loop's `if (errflag)` arm — so that status
// must survive untouched.
if (crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed)
& crate::ported::zsh_h::ERRFLAG_ERROR)
!= 0
{
vm.last_status = 1; // c:144/201/480/536
with_executor(|exec| exec.set_last_status(1)); // c:144/201/480/536
}
Value::Int(0)
});
vm.register_builtin(BUILTIN_LOOP_EXIT, |_vm, _argc| {
use std::sync::atomic::Ordering::SeqCst;
// Saturating: a chunk aborted mid-loop (errflag, `return`)
// unwinds through `run_chunk`'s restore rather than this op, so
// never let a stray decrement drive the count negative.
let _ = crate::ported::builtin::LOOPS
.fetch_update(SeqCst, SeqCst, |n| Some(if n > 0 { n - 1 } else { 0 })); // c:188
Value::Int(0)
});
// c:Src/loop.c:529-534 (execwhile), :180-185 (execfor), :540-545
// (execrepeat) — the identical post-body drain every loop runs:
// if (breaks) {
// breaks--;
// if (breaks || !contflag) break;
// contflag = 0;
// }
// Returns Int(1) when this loop must terminate, Int(0) when it
// should proceed to the next iteration. Only a `break`/`continue`
// executed in a DIFFERENT chunk (a called function, `eval`, a
// sourced file) reaches here — an in-chunk `break` compiles to a
// direct jump and never touches the counter.
vm.register_builtin(BUILTIN_LOOP_BREAK_DRAIN, |_vm, _argc| {
use std::sync::atomic::Ordering::SeqCst;
let breaks = crate::ported::builtin::BREAKS.load(SeqCst);
if breaks == 0 {
return Value::Int(0);
}
let remaining = breaks - 1;
crate::ported::builtin::BREAKS.store(remaining, SeqCst); // c:530
let contflag = crate::ported::builtin::CONTFLAG.load(SeqCst);
if remaining != 0 || contflag == 0 {
return Value::Int(1); // c:532 — `break`
}
crate::ported::builtin::CONTFLAG.store(0, SeqCst); // c:533
Value::Int(0)
});
// c:Src/exec.c:1370 execlist — `while (wc_code(code) == WC_LIST &&
// !breaks && !retflag && !errflag)`. A pending `breaks` stops the
// CURRENT list at the next statement boundary WITHOUT consuming it,
// so the flag keeps travelling outward until a loop's drain eats it.
// Non-consuming by design: the drain above is the only consumer.
vm.register_builtin(BUILTIN_BREAKS_PENDING, |_vm, _argc| {
let b = crate::ported::builtin::BREAKS.load(std::sync::atomic::Ordering::SeqCst);
Value::Int(if b != 0 { 1 } else { 0 })
});
vm.register_builtin(BUILTIN_NOEXEC_CHECK, |vm, _argc| {
// c:Src/exec.c:1390 — `set -n` / `noexec` option: parse but
// don't execute. Returns Int(1) when noexec is set so the
// emit-side JumpIfTrue skips the statement body.
//
// Arg: 1 when every command of the sublist is a simple command
// with a command word. c:Src/parse.c:1928 marks those cmplx, so C
// never takes execsimple's `if (!isset(EXECOPT)) return lastval =
// 0;` (c:Src/exec.c:1351) for them: execcmd_exec expands the words
// first and skips only the execution (c:4051). Those commands
// carry their own BUILTIN_NOEXEC_CMD_GATE, so noexec must not
// skip them here.
let gated_in_command = vm.pop().to_int() != 0;
if !gated_in_command && opt_state_get("noexec").unwrap_or(false) {
return Value::Int(1);
}
// c:Src/exec.c:1390 — execlist's list-loop gate:
// `while (wc_code(code) == WC_LIST && !breaks && !retflag
// && !errflag)`
// — once errflag is set, the NEXT sublist never starts, so
// lastval survives untouched to the shell exit. Without this
// prologue gate the follow-up statement RAN, its dispatch
// saw errflag, returned 1, and SetStatus clobbered lastval —
// `[[ x == [a- ]]; print rc=$?` exited 1 instead of zsh's 2
// (the cond syntax error set lastval=2 per exec.c:5216-5221).
if (crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed)
& crate::ported::zsh_h::ERRFLAG_ERROR)
!= 0
{
return Value::Int(1);
}
Value::Int(0)
});
// See BUILTIN_NOEXEC_CMD_GATE.
vm.register_builtin(BUILTIN_NOEXEC_CMD_GATE, |vm, _argc| {
if !opt_state_get("noexec").unwrap_or(false) {
return Value::Int(0);
}
// c:Src/exec.c:3760-3763 — `if (errflag) { lastval = 1; goto err; }`
// runs after globlist and before the EXECOPT test, so an expansion
// error still sets the status under NO_EXEC.
if (crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed)
& crate::ported::zsh_h::ERRFLAG_ERROR)
!= 0
{
vm.last_status = 1; // c:3761 `lastval = 1;`
crate::ported::builtin::LASTVAL.store(1, std::sync::atomic::Ordering::Relaxed);
}
Value::Int(1) // c:4051 — the execution branch is not taken
});
// c:Src/exec.c:1536-1538 —
// /* suppress errexit for commands before && and || and after ! */
// if (isandor || isnot)
// noerrexit |= NOERREXIT_EXIT | NOERREXIT_RETURN;
// The bits live on the PROCESS-GLOBAL `noerrexit`, so they are still
// in force inside a shell function called from that position (doshfunc
// clears only NOERREXIT_RETURN, c:5930). zshrs suppressed the check
// purely at COMPILE time (`errexit_suppress_depth`), which cannot
// reach a separately-compiled function body — so
// TRAPZERR(){ print E }; f(){ print f; false; }; f && t
// fired the ZERR trap from inside `f` where zsh stays silent
// (C03traps:14, E01options:18,19,21).
vm.register_builtin(BUILTIN_NOERREXIT_SUPPRESS, |_vm, _argc| {
use std::sync::atomic::Ordering;
let old = crate::ported::exec::noerrexit.load(Ordering::Relaxed); // c:1417
NOERREXIT_SAVES.with(|st| st.borrow_mut().push(old));
crate::ported::exec::noerrexit.store(
old | crate::ported::zsh_h::NOERREXIT_EXIT | crate::ported::zsh_h::NOERREXIT_RETURN,
Ordering::Relaxed,
); // c:1538
Value::Int(0)
});
// c:Src/exec.c:1621 / c:1626 — `noerrexit = oldnoerrexit;`
vm.register_builtin(BUILTIN_NOERREXIT_RESTORE, |_vm, _argc| {
use std::sync::atomic::Ordering;
if let Some(old) = NOERREXIT_SAVES.with(|st| st.borrow_mut().pop()) {
crate::ported::exec::noerrexit.store(old, Ordering::Relaxed); // c:1621
}
Value::Int(0)
});
vm.register_builtin(BUILTIN_DONETRAP_RESET, |_vm, _argc| {
donetrap_reset_impl()
});
// See BUILTIN_FORKED_REDIRS.
vm.register_builtin(BUILTIN_FORKED_REDIRS, |vm, _argc| {
if FORKED_REDIR_VM.with(|f| f.replace(0)) == vm as *const fusevm::VM as usize {
// The next op is the command's WithRedirectsBegin.
let depth = with_executor(|exec| exec.redirect_scope_stack.len()) + 1;
FORKED_REDIR_SCOPE.with(|c| c.set(depth));
}
Value::Int(0)
});
vm.register_builtin(BUILTIN_EXECCMD_FORKED_LEVEL, |vm, _argc| {
let is_subsh = vm.pop().to_int() != 0;
execcmd_forked_level(is_subsh, vm as *const fusevm::VM as usize);
Value::Int(0)
});
vm.register_builtin(BUILTIN_EXITING_EXIT_TRAP, |_vm, _argc| {
use crate::ported::signals_h::SIGEXIT;
use std::sync::atomic::Ordering;
// `trap '…' EXIT` bodies live in traps_table, TRAPEXIT in sigtrapped.
let trapped = crate::ported::signals::sigtrapped.lock().ok().is_some_and(|st| st.get(SIGEXIT as usize).is_some_and(|&s| s != 0))
|| crate::ported::builtin::traps_table().lock().ok().is_some_and(|t| t.contains_key("EXIT"));
if trapped {
let eflag = crate::ported::utils::errflag.load(Ordering::Relaxed); // c:1701
crate::ported::utils::errflag.store(0, Ordering::Relaxed); // c:1702
crate::ported::signals::dotrap(SIGEXIT); // c:1703
// c:1705 — `sigtrapped[SIGEXIT] = 0;`
if let Ok(mut st) = crate::ported::signals::sigtrapped.lock() {
if let Some(slot) = st.get_mut(SIGEXIT as usize) {
*slot = 0;
}
}
if let Ok(mut t) = crate::ported::builtin::traps_table().lock() {
t.remove("EXIT");
}
crate::ported::utils::errflag.store(eflag, Ordering::Relaxed); // c:1706
}
Value::Int(0)
});
// c:Src/exec.c:1451/1455/1476/1390 — see BUILTIN_STMT_PROLOGUE_FAST.
vm.register_builtin(BUILTIN_STMT_PROLOGUE_FAST, |vm, _argc| {
use std::sync::atomic::Ordering;
let line = vm.pop().to_int();
SUBLIST_SERIAL.with(|c| c.set(c.get().wrapping_add(1)));
GLOB_WORD_ERRFLAG.with(|c| c.set(false));
PREFORK_CUT.with(|c| c.set(false));
if line >= 0 {
set_lineno_impl(line); // c:1451
}
donetrap_reset_impl(); // c:1455
// c:1390 — `set -n`, and execlist's own `!errflag` list gate.
if opt_state_get("noexec").unwrap_or(false)
|| (crate::ported::utils::errflag.load(Ordering::Relaxed)
& crate::ported::zsh_h::ERRFLAG_ERROR)
!= 0
{
return Value::Bool(false);
}
// c:1423 `sigtrapped[SIGDEBUG]` — checked through both
// registries because `settrap` and `bin_trap` populate
// different ones (signals.rs:1481-1511 dotrap).
let sig_debug = crate::ported::signals_h::SIGDEBUG as usize;
let debug_trapped = crate::ported::signals::sigtrapped
.lock()
.map(|v| v.get(sig_debug).copied().unwrap_or(0))
.unwrap_or(0);
if debug_trapped != 0 {
return Value::Bool(false);
}
let debug_in_table = crate::ported::builtin::traps_table()
.lock()
.map(|t| t.contains_key("DEBUG"))
.unwrap_or(false);
Value::Bool(!debug_in_table)
});
vm.register_builtin(BUILTIN_SUBLIST_FINISH, |vm, _argc| {
// c:Src/jobs.c:1754 — `pipestats[0] = lastval;`. C has ONE
// `lastval` global (c:Src/exec.c:120), so `waitonejob` reads
// exactly the status the finished sublist just produced.
//
// zshrs splits that global in two: the fusevm status cell that
// `Op::SetStatus`/`Op::GetStatus` and therefore `$?` use, and
// the `builtin::LASTVAL` mirror that the ported `waitonejob`
// reads. The compound-command compilers (compile_if,
// compile_while, compile_for, compile_case, …) settle their
// result with `Op::SetStatus` alone, so LASTVAL still holds
// whatever the last dispatched BUILTIN returned — the loop
// condition, typically. `if [[ -z x ]]; then :; fi` and
// `while false; do :; done` both end with `$? == 0` and a
// stale LASTVAL of 1.
//
// compile_sublist pushes `Op::GetStatus` ahead of this call so
// the authoritative status arrives as an argument; republish it
// through LASTVAL to reunify the two before the ported
// waitonejob reads it, exactly as the single-command dispatch
// sites at c:Src/exec.c:4367 do.
let status = vm.pop().to_int() as i32;
crate::ported::builtin::LASTVAL.store(status, std::sync::atomic::Ordering::Relaxed);
// c:Src/jobs.c:1750-1756 — `compile_sublist` only emits this
// marker for a cmplx sublist element that is not a multi-stage
// pipeline, i.e. exactly the case where C's job carries no
// procs, so drive the canonical port with a procs-less job the
// same way the single-command sites do.
crate::ported::jobs::waitonejob(-1);
Value::Status(0)
});
// `[[ -z X ]]` / `[[ -n X ]]` — pop one Value and apply the empty /
// non-empty test evalcond's `-z` / `-n` arms perform (cond.rs).
//
// The Array→words conversion lives at the bridge. For
// `"${arr[@]}"` in DQ context the splice yields `Value::Array`
// — an empty array still expands to one implicit empty word
// (per zsh's "${arr[@]}" splat preserving at least one slot
// in cond context), so:
// - Array(0) → ["-z", ""] → 0 (true)
// - Array(1) → ["-z", word] → 0/1
// - Array(2+) → ["-z", w1, w2, ...] → 2 (parse
// error: too many ops)
// → coerced to false
// - Str(s) → ["-z", s] → 0/1
//
// Bug #185 in docs/BUGS.md.
fn run_cond_str_empty(v: Value, op: &str) -> Value {
let words: Vec<String> = match v {
Value::Array(arr) => arr.iter().map(|x| x.to_str()).collect(),
Value::Str(s) => vec![s.to_string()],
other => vec![other.to_str()],
};
// c:Src/cond.c:62-66 — `evalcond` returns 0=true, 1=false,
// 2=syntax-error. Coerce error to false (observable behavior
// in zsh: `[[ -z a b ]]` errors and the test as a whole
// returns non-zero).
// c:Src/cond.c — evalcond's `-n` arm is `!strlen(left)` negated and its
// `-z` arm `strlen(left)`; a single operand needs no wordcode. Two or
// more words are the syntax error (2) the wordcode parser reports
// for `-z a b`. No word at all is the implicit empty operand.
let ret = if words.len() > 1 {
2
} else {
let empty = words.first().map_or(true, |w| w.is_empty());
((op == "-z") != empty) as i32
};
Value::Int(if ret == 0 { 1 } else { 0 })
}
vm.register_builtin(BUILTIN_COND_STR_EMPTY, |vm, _argc| {
let v = vm.pop();
run_cond_str_empty(v, "-z")
});
vm.register_builtin(BUILTIN_COND_STR_NONEMPTY, |vm, _argc| {
let v = vm.pop();
run_cond_str_empty(v, "-n")
});
// `exec N<<<"str"` — herestring redirect to explicit fd, applied
// permanently. Direct port of `Src/exec.c:4655 getherestr` +
// `addfd(forked, save, mfds, fn->fd1, fil, 0, ...)` at c:3766-
// 3780 for the nullexec=1 bare-exec-redir path. Bug #205 in
// docs/BUGS.md.
// c:Src/exec.c:4671-4672 — a here-string DERIVED FROM a here-doc
// gets no appended newline. See BUILTIN_HEREDOC_BODY_SINK.
vm.register_builtin(BUILTIN_HEREDOC_BODY_SINK, |vm, _argc| {
let body = vm.pop().to_str();
if crate::provenance::active() {
crate::provenance::on_heredoc("heredoc", &body);
}
with_executor(|exec| exec.host_set_pending_stdin(body));
Value::Int(0)
});
vm.register_builtin(BUILTIN_EXEC_HERESTR_FD, |vm, _argc| {
// Stack (pushed by compile_redir): [content, fd, from_heredoc].
let from_heredoc = vm.pop().to_int() != 0;
let fd = vm.pop().to_int() as i32;
let content = vm.pop().to_str();
// c:Src/exec.c:4671-4672 — `getherestr` appends the newline
// only for a REAL here-string:
// if (!(fn->flags & REDIRF_FROM_HEREDOC))
// t[len++] = '\n';
// The `REDIRF_FROM_HEREDOC` flag is set by
// c:Src/parse.c:2970-2971 when the redirection was written as
// `<<WORD` and the parser turned the collected body into a
// here-string. This helper serves BOTH spellings — `exec
// 3<<<str` (append) and `exec 3<<EOF` (verbatim) — so the flag
// has to be threaded in rather than assumed. It used to
// unconditionally append, and the here-doc call site
// compensated with `trim_end_matches('\n')`, which collapsed
// N trailing blank lines to one and added a newline to a body
// that ended without one.
let body = if from_heredoc {
content
} else {
format!("{}\n", content)
};
// c:Src/exec.c:3779 `addfd(forked, save, mfds, fn->fd1, fil, 0,
// NULL)` → c:2421-2443: park the OLD contents of fd1 so
// `fixfds` (c:4530) can put them back at the end of the
// command; a bare `exec` (nullexec==1, c:3978-3986) skips it
// and the redirection persists. This runs BEFORE the temp
// file is opened on purpose: C reads fd1's pre-redirect state
// too, and taking it afterwards would dup the here-document
// itself and "restore" fd N to the body at scope end.
with_executor(|exec| exec.save_fd_for_scope(fd));
// c:4673-4679 — gettempfile → write_loop → close → reopen
// read-only → unlink. Rust equivalent via tempfile crate or
// explicit O_TMPFILE; use mkstemp + unlink-immediately to
// mirror C exactly.
use std::ffi::CString;
let mut tmpl: Vec<u8> = b"/tmp/zshrs_hs_XXXXXX\0".to_vec();
let write_fd = unsafe { libc::mkstemp(tmpl.as_mut_ptr() as *mut libc::c_char) };
if write_fd < 0 {
crate::ported::utils::zwarn(&format!(
"can't create temp file for here document: {}",
crate::ported::utils::zsh_errno_msg(
std::io::Error::last_os_error().raw_os_error().unwrap_or(0)
) // c:Src/exec.c:3828 `%e`
));
return Value::Status(1);
}
// c:4675 — write_loop(fd, t, len)
let bytes = body.as_bytes();
let mut off = 0;
while off < bytes.len() {
let n = unsafe {
libc::write(
write_fd,
bytes[off..].as_ptr() as *const libc::c_void,
bytes.len() - off,
)
};
if n <= 0 {
unsafe { libc::close(write_fd) };
return Value::Status(1);
}
off += n as usize;
}
unsafe { libc::close(write_fd) }; // c:4676
// Path null-terminated by mkstemp; reopen for reading.
let read_fd = unsafe { libc::open(tmpl.as_ptr() as *const libc::c_char, libc::O_RDONLY) };
// c:4678 — unlink immediately so the file disappears on
// close, leaving only the fd reference.
unsafe { libc::unlink(tmpl.as_ptr() as *const libc::c_char) };
if read_fd < 0 {
return Value::Status(1);
}
// c:Src/utils.c:2047-2065 `redup(x, y)` — the `zclose(x)` lives
// INSIDE the `else if (x != y)` arm:
// if(x < 0) zclose(y);
// else if (x != y) { dup2(x, y); …; zclose(x); }
// When x == y, redup is a NO-OP. This helper closed `read_fd`
// unconditionally, and `read_fd == fd` is the COMMON case for
// `exec 3<<…`: mkstemp takes the lowest free fd (3), closes it
// at c:4676, then `open` reclaims the same 3, so `dup2(3, 3)`
// returned 3 and the very next `close(3)` threw the redirect
// away. Every `exec N<<…` / `exec N<<<…` left N closed, and
// `cat <&N` reported "N: bad file descriptor".
if read_fd != fd {
let r = unsafe { libc::dup2(read_fd, fd) };
unsafe { libc::close(read_fd) };
if r < 0 {
return Value::Status(1);
}
}
Value::Status(0)
});
// c:Src/exec.c:2418 + addfd splice — MULTIOS fan-out. Stack
// layout pushed by compile_zsh's coalescing pass:
// [target_1, op_byte_1, target_2, op_byte_2, …, target_N,
// op_byte_N, fd]
// argc = 2N + 1. Pops, opens every target, sets up a pipe +
// splitter thread that reads pipe → writes every chunk to
// every opened target, dup2's pipe-write-end onto fd. The
// splitter is closed + joined by host_redirect_scope_end.
// Bug #36 in docs/BUGS.md.
vm.register_builtin(BUILTIN_MULTIOS_REDIRECT, |vm, argc| {
if argc < 3 || argc % 2 == 0 {
// Bad shape — bail.
return Value::Status(1);
}
// Pop fd first (top of stack).
let fd = vm.pop().to_int() as i32;
// Then pop (op, target) pairs in reverse compile order. Keep
// targets as Values — a glob-bearing target arrives as a
// Value::Array of matches.
let n_targets = ((argc - 1) / 2) as usize;
let mut pairs: Vec<(u8, Value)> = Vec::with_capacity(n_targets);
for _ in 0..n_targets {
let op_byte = vm.pop().to_int() as u8;
let target = vm.pop();
pairs.push((op_byte, target));
}
// Restore compile order (target_1 first).
pairs.reverse();
// c:Src/exec.c:3785-3796 — an errflag from expanding a target fails
// the redirection (see redir_target_expansion_failed).
if with_executor(redir_target_expansion_failed) {
return Value::Status(1);
}
// c:Src/glob.c:2195-2203 xpandredir — "Loop over matches,
// duplicating the redirection for each file found": a glob
// target with N matches becomes N members of the same multio
// (`echo hi > *.txt` with two matches writes both files).
let mut entries: Vec<(u8, String)> = Vec::with_capacity(pairs.len());
for (op_byte, target) in pairs {
match target {
// c:Src/glob.c:2161 — without MULTIOS the word is preforked
// PREFORK_SINGLE: one word, an array joined by sepjoin.
Value::Array(items) if !opt_state_get("multios").unwrap_or(true) => {
let words: Vec<String> = items.iter().map(|v| v.to_str()).collect();
entries.push((op_byte, crate::ported::utils::sepjoin(&words, None)));
}
Value::Array(items) => {
for item in items.iter() {
entries.push((op_byte, item.to_str()));
}
}
other => entries.push((op_byte, other.to_str())),
}
}
if entries.is_empty() {
return Value::Status(1);
}
// c:Src/exec.c:2418 — `else if (!mfds[fd1] || unset(MULTIOS))`:
// with MULTIOS unset every redirect takes the REPLACE path in
// script order — each target is still opened (created /
// truncated) and dup2'd over the fd, so the LAST one wins and
// earlier files end up empty (`unsetopt multios; print x > a
// > b` leaves `a` empty, `x` in `b`). host_apply_redirect is
// exactly one replace step, noclobber gate included.
let multios_on = opt_state_get("multios").unwrap_or(true);
if !multios_on {
with_executor(|exec| {
for (op_byte, target) in &entries {
exec.host_apply_redirect(fd as u8, *op_byte, target);
if exec.redirect_failed {
// c:Src/exec.c execerr — abort the remaining
// redirect list on failure.
break;
}
}
});
return Value::Status(0);
}
if entries.len() == 1 {
// Single member after splicing — a plain replace
// (c:2418 new-multio arm). Route through
// host_apply_redirect so the noclobber gate, the
// pipeline-output split partial, and error handling all
// apply exactly as for an un-bagged redirect.
let (op_byte, target) = &entries[0];
with_executor(|exec| {
exec.host_apply_redirect(fd as u8, *op_byte, target);
});
return Value::Status(0);
}
// c:Src/exec.c:3722-3724 — when this command's stdout IS the
// pipeline output, C seeds mfds[1] with the pipe BEFORE
// walking the redirect list, so the pipe is the multio's
// first member (`print x >&1 > f | cat` sends `x` down the
// pipe TWICE: once for the seed, once for the `>&1` dup).
let pipe_seed = fd == 1
&& with_executor(|exec| {
exec.pipe_output_scope
.is_some_and(|d| d + 1 == exec.redirect_scope_stack.len())
});
// Save current fd state for scope-end restoration — BEFORE
// the first member's replace dup2 below.
// c:Src/exec.c:2425 — `int fdN = movefd(fd1); save[fd1] = fdN;`. A SAVED
// descriptor is shell state and must live above the script's fd range:
// plain dup() returns the LOWEST free fd, which parked the saved stdout
// on fd 3, so `print -u 3 -r -- X 2>/dev/null` wrote into the shell's own
// saved descriptor and reported success where zsh says `bad file number`.
// F_DUPFD with a floor of 10 is exactly what movefd does.
// c:Src/exec.c:3978-3986 — a bare `exec`'s redirections (nullexec==1)
// are permanent: the saved copy is closed, not restored, and the
// tee process outlives this command (see the closemn arm below).
let permanent = with_executor(|exec| exec.exec_redirs_permanent);
if permanent {
// Inside an in-process `( … )` / `$( … )` the change is permanent
// only for the subshell (see SubshFdFrame), as for a single target.
crate::ported::exec::SubshFdFrame::touch(fd);
}
// c:2478 — `if (!forked && save[fd1] == -2)`.
let forked = with_executor(|exec| redir_scope_forked(exec.redirect_scope_stack.len()));
let saved = if forked {
-1
} else {
unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, 10) }
};
// c:2426-2437 — "fd1 may already be closed here, so ignore bad
// file descriptor error": `save[fd1] = fdN` stores -1 for a closed
// fd, and the scope-end restore (c:Src/utils.c:2047 `if (x < 0)
// zclose(y)`) then CLOSES it. Without that slot the splitter's pipe
// write end stayed dup'd on the fd, the splitter never saw EOF and
// the scope-end join hung: `print -u3 x 3>a 3>b` never returned.
// A forked child parks no copy, but the splitter's pipe write end
// on `fd` must still go at scope end or its join never sees EOF;
// the -1 slot closes it there, as the child's exit does in C.
let saved_slot = if forked {
Some(-1)
} else if saved >= 0 {
Some(saved)
} else if std::io::Error::last_os_error().raw_os_error() == Some(libc::EBADF) {
Some(-1)
} else {
None
};
if permanent {
// c:4038-4040 — `for (i = 0; i < 10; i++) if (save[i] != -2)
// zclose(save[i]);`
if saved >= 0 {
unsafe { libc::close(saved) };
}
} else if let Some(saved) = saved_slot {
with_executor(|exec| {
if let Some(top) = exec.redirect_scope_stack.last_mut() {
top.push((fd, saved));
mark_saved_fd(saved);
} else if saved >= 0 {
unsafe { libc::close(saved) };
}
});
}
// Accumulate member fds in redirect order. c:Src/exec.c:
// 2447-2480 addfd — the FIRST member REPLACES the fd
// (c:2448-2450 `mfds[fd1]->ct=1; mfds[fd1]->fds[0]=fd1;`), so
// a later numeric `>&N` self-dup resolves against the fd's
// value at that point in the sequence: `print x > f >&1`
// writes f TWICE; `print x >&1 > f` writes the ORIGINAL
// stdout + f.
let mut target_fds: Vec<i32> = Vec::with_capacity(entries.len() + 1);
if pipe_seed {
let p = unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, 10) };
if p >= 0 {
target_fds.push(p);
}
}
let noclobber = opt_state_get("noclobber").unwrap_or(false)
|| !opt_state_get("clobber").unwrap_or(true);
for (i, (op_byte, target)) in entries.iter().enumerate() {
let open_result: std::io::Result<i32> = match *op_byte {
r::DUP_WRITE | r::DUP_READ => {
// Numeric `>&N` — dup the LIVE fd N (after any
// earlier member's replace).
match target.trim_start_matches('&').parse::<i32>() {
Ok(src) => {
let d = unsafe { libc::fcntl(src, libc::F_DUPFD_CLOEXEC, 10) };
if d >= 0 {
Ok(d)
} else {
Err(std::io::Error::last_os_error())
}
}
Err(_) => Err(std::io::Error::from_raw_os_error(libc::EBADF)),
}
}
r::WRITE => {
// c:Src/exec.c clobber_open — noclobber applies
// to multio file targets too; failure aborts the
// remaining redirect list (execerr), so `setopt
// noclobber; touch a; print x > a > b` errors on
// `a` and never creates `b`.
let target_meta = std::fs::metadata(target).ok();
let target_is_regular_file = target_meta
.as_ref()
.map(|m| m.file_type().is_file())
.unwrap_or(false);
// c:Src/exec.c:2313 clobber_open — CLOBBER_EMPTY re-uses
// an empty regular file under noclobber (same allowance
// as the single-redirect path).
let clobber_empty_ok = opt_state_get("clobberempty").unwrap_or(false)
&& target_meta.as_ref().map(|m| m.len() == 0).unwrap_or(false);
if noclobber && target_is_regular_file && !clobber_empty_ok {
eprintln!(
"{}:{}: file exists: {}",
shname(),
crate::ported::lex::lineno(),
target
);
for prev in &target_fds {
unsafe {
libc::close(*prev);
}
}
with_executor(|exec| {
exec.redirect_failed = true;
});
// Sink the upcoming command's output (mirrors
// the single-redirect noclobber arm in
// host_apply_redirect).
if let Ok(file) = fs::OpenOptions::new().write(true).open("/dev/null") {
let new_fd = file.into_raw_fd();
unsafe {
libc::dup2(new_fd, fd);
libc::close(new_fd);
}
}
return Value::Status(1);
}
fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(target)
.map(|f| f.into_raw_fd())
}
r::APPEND => fs::OpenOptions::new()
.write(true)
.create(true)
.append(true)
.open(target)
.map(|f| f.into_raw_fd()),
_ => fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(target)
.map(|f| f.into_raw_fd()),
};
match open_result {
Ok(tfd) => {
// c:2463-2470 / c:2481 — every member of a split stream
// is `movefd`'d above the script's fd range. A file opened
// while the target fd is closed comes back AS that fd
// (`print -u3 x 3>a 3>b`: `a` opens on 3), and the pipe
// dup2 below then replaced the member with the splitter's
// own write end — `a` stayed empty and the splitter fed
// its output back into itself.
let tfd = crate::ported::utils::movefd(tfd);
if i == 0 && !pipe_seed {
// c:2448-2450 — first member replaces the fd.
unsafe {
libc::dup2(tfd, fd);
}
}
target_fds.push(tfd);
}
Err(e) => {
// c:Src/exec.c:3741 — `zwarn("%e: %s", errno, fname)`:
// zwarning supplies the `name:LINE:` prefix with the
// REAL current lineno; redir_errno_msg builds the `%e`
// errno message (was a hardcoded ErrorKind match that
// showed generic "redirect failed" for EROFS/etc.).
let msg = redir_errno_msg(&e);
crate::ported::utils::zwarn(&format!("{}: {}", msg, target));
// Close already-opened fds to avoid leaks.
for prev in &target_fds {
unsafe {
libc::close(*prev);
}
}
with_executor(|exec| {
exec.redirect_failed = true;
});
return Value::Status(1);
}
}
}
// Create the splitter pipe.
let (read_end, write_end) = match os_pipe::pipe() {
Ok(p) => p,
Err(_) => {
for f in &target_fds {
unsafe {
libc::close(*f);
}
}
return Value::Status(1);
}
};
// c:Src/exec.c:5222 — `pp[0] = movefd(pp[0]);` in `mpipe()`.
// c:Src/utils.c:1990-2012 movefd — "if(fd != -1 && fd < 10)"
// dup into the >=10 range and zclose the low copy, then mark
// the result FDT_INTERNAL. Every shell-internal fd goes
// through this so it can never share a number with the
// user-visible `>&N` range that the redirect bookkeeping
// opens/dups/closes. This splitter kept the raw (low) pipe
// read end, so an unrelated close of that number shut it
// under the splitter thread and dropping the owned
// PipeReader aborted the process with std's "IO Safety
// violation: owned file descriptor already closed"
// (E01options.ztst:46 `( echo hello ) >a >b`, ~2 runs in 3).
let read_end = unsafe {
<os_pipe::PipeReader as std::os::unix::io::FromRawFd>::from_raw_fd(
crate::extensions::fds::movefd(read_end.into_raw_fd()),
)
};
let pipe_write_raw = AsRawFd::as_raw_fd(&write_end);
if permanent && (0..10).contains(&fd) {
// c:Src/exec.c:4014-4016 — "We are done with redirection. close
// the mnodes, spawning tee/cat processes as necessary." A bare
// `exec 3>&1 3>&2` keeps the multio for the rest of the shell's
// life, so the scope-bound splitter thread below (drained and
// joined at scope end) cannot serve it: nothing ever ends the
// scope, and the thread dies with the process before it copies
// what the last command wrote. closemn forks the tee process C
// uses for every multio; it reads until the shell's last copy
// of the pipe write end closes, i.e. after the shell exits.
// c:4045 — "We're done with this job, no need to wait for it."
let write_dup = unsafe { libc::fcntl(pipe_write_raw, libc::F_DUPFD_CLOEXEC, 10) };
drop(write_end);
if write_dup < 0 {
for f in &target_fds {
unsafe { libc::close(*f) };
}
return Value::Status(1);
}
unsafe {
libc::dup2(write_dup, fd);
libc::close(write_dup);
}
let mn = crate::ported::zsh_h::multio {
ct: target_fds.len() as i32,
rflag: 1, // c:2462 — output multio: a tee, not a cat
pipe: std::os::unix::io::IntoRawFd::into_raw_fd(read_end),
fds: target_fds,
};
let mut mfds: [Option<Box<crate::ported::zsh_h::multio>>; 10] = Default::default();
mfds[fd as usize] = Some(Box::new(mn));
crate::ported::exec::closemn(&mut mfds, fd, crate::ported::zsh_h::REDIR_CLOSE);
return Value::Status(0);
}
// Spawn the splitter thread: read pipe → write every chunk
// to every target fd. Each write inside the thread uses
// libc::write directly on the raw fd (no Rust File ownership
// so the splitter can close after EOF without racing main).
let target_fds_for_thread = target_fds.clone();
let handle = crate::signal_thread::spawn(move || {
let mut r = read_end;
let mut buf = [0u8; 8192];
loop {
match std::io::Read::read(&mut r, &mut buf) {
Ok(0) => break,
Ok(n) => {
for &tfd in &target_fds_for_thread {
let mut off = 0;
while off < n {
let w = unsafe {
libc::write(
tfd,
buf[off..n].as_ptr() as *const libc::c_void,
n - off,
)
};
if w <= 0 {
break;
}
off += w as usize;
}
}
}
Err(_) => break,
}
}
// Close every target so file contents flush.
for tfd in target_fds_for_thread {
unsafe {
libc::close(tfd);
}
}
});
// Dup the pipe write-end onto the target fd; close the
// original write_end so EOF arrives when host_redirect_scope_end
// closes our tracked pipe_write_fd.
let write_dup = unsafe { libc::fcntl(pipe_write_raw, libc::F_DUPFD_CLOEXEC, 10) };
drop(write_end);
if write_dup < 0 {
return Value::Status(1);
}
unsafe {
libc::dup2(write_dup, fd);
libc::close(write_dup);
}
// Track the running splitter so scope-end can drain + join.
// The "write_fd" we store is the user-visible fd (e.g. 1).
// Closing that fd at scope-end isn't quite right; we need a
// way to send EOF. Solution: track the write_dup we just
// closed; instead keep a second dup for the close-on-end.
// Shell-internal bookkeeping fd — above the script's range (movefd).
let close_on_end = unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, 10) };
with_executor(|exec| {
if let Some(top) = exec.multios_scope_stack.last_mut() {
top.push((close_on_end, handle));
} else {
// No scope — leak the dup; thread will keep running
// until process exit. Should not happen because
// host_redirect_scope_begin pushed a frame.
unsafe { libc::close(close_on_end) };
}
});
Value::Status(0)
});
// c:Src/exec.c:2418 input-arm — MULTIOS read fan-in. Stack
// layout pushed by compile_zsh (mirrors the write side):
// [source_1, op_1, source_2, op_2, …, source_N, op_N, fd]
// argc = 2N + 1; op distinguishes file opens (READ) from numeric
// `<&N` dups (DUP_READ); a glob source arrives as Value::Array
// and splices into one member per match (c:Src/glob.c:2195-2203).
// Opens every source, sets up a pipe + producer thread that
// reads each source in order and writes to the pipe write-end,
// then closes its write-end so the consumer gets EOF. dup2 the
// pipe read-end onto fd. Bug #36 input side in docs/BUGS.md.
vm.register_builtin(BUILTIN_MULTIOS_READ, |vm, argc| {
if argc < 3 || argc % 2 == 0 {
return Value::Status(1);
}
let fd = vm.pop().to_int() as i32;
let n_sources = ((argc - 1) / 2) as usize;
let mut pairs: Vec<(u8, Value)> = Vec::with_capacity(n_sources);
for _ in 0..n_sources {
let op_byte = vm.pop().to_int() as u8;
let source = vm.pop();
pairs.push((op_byte, source));
}
pairs.reverse();
// c:Src/exec.c:3785-3796 — an errflag from expanding a target fails
// the redirection (see redir_target_expansion_failed).
if with_executor(redir_target_expansion_failed) {
return Value::Status(1);
}
// Splice glob match arrays (c:Src/glob.c:2195-2203).
let mut entries: Vec<(u8, String)> = Vec::with_capacity(pairs.len());
for (op_byte, source) in pairs {
match source {
// c:Src/glob.c:2161 — without MULTIOS the word is preforked
// PREFORK_SINGLE: one word, an array joined by sepjoin.
Value::Array(items) if !opt_state_get("multios").unwrap_or(true) => {
let words: Vec<String> = items.iter().map(|v| v.to_str()).collect();
entries.push((op_byte, crate::ported::utils::sepjoin(&words, None)));
}
Value::Array(items) => {
for item in items.iter() {
entries.push((op_byte, item.to_str()));
}
}
other => entries.push((op_byte, other.to_str())),
}
}
if entries.is_empty() {
return Value::Status(1);
}
// c:Src/exec.c:2418 — `unset(MULTIOS)`: sequential replace,
// last source wins (`unsetopt multios; cat < a < b` reads
// only b; a is still opened — and errors still surface).
let multios_on = opt_state_get("multios").unwrap_or(true);
if !multios_on {
with_executor(|exec| {
for (op_byte, source) in &entries {
multios_apply_member(exec, fd, *op_byte, source);
if exec.redirect_failed {
break;
}
}
});
return Value::Status(0);
}
// c:Src/exec.c:3775-3777 — a pipeline stage's input pipe is already
// mfds[0]'s first member, so even one source concatenates.
let pipe_seed = with_executor(|exec| take_pipe_input_seed(exec, fd));
if entries.len() == 1 && pipe_seed.is_none() {
// Single member after splicing — plain replace.
let (op_byte, source) = &entries[0];
with_executor(|exec| {
multios_apply_member(exec, fd, *op_byte, source);
});
return Value::Status(0);
}
// Save current fd state for scope-end restoration — BEFORE
// the first member's replace dup2 below.
// c:Src/exec.c:2425 — `int fdN = movefd(fd1); save[fd1] = fdN;`. A SAVED
// descriptor is shell state and must live above the script's fd range:
// plain dup() returns the LOWEST free fd, which parked the saved stdout
// on fd 3, so `print -u 3 -r -- X 2>/dev/null` wrote into the shell's own
// saved descriptor and reported success where zsh says `bad file number`.
// F_DUPFD with a floor of 10 is exactly what movefd does.
// c:2478 — `if (!forked && save[fd1] == -2)`.
let forked = with_executor(|exec| redir_scope_forked(exec.redirect_scope_stack.len()));
let saved = if forked {
-1
} else {
unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, 10) }
};
// c:2426-2437 — a closed fd saves -1, restored by closing it (see
// the write-side multio above).
// A forked child parks no copy, but the pipe read end on `fd` must
// still go at scope end or a splitter blocked on a full pipe never
// finishes its join; the -1 slot closes it there, as the child's
// exit does in C.
let saved_slot = if forked {
Some(-1)
} else if saved >= 0 {
Some(saved)
} else if std::io::Error::last_os_error().raw_os_error() == Some(libc::EBADF) {
Some(-1)
} else {
None
};
if let Some(saved) = saved_slot {
with_executor(|exec| {
if let Some(top) = exec.redirect_scope_stack.last_mut() {
top.push((fd, saved));
mark_saved_fd(saved);
} else if saved >= 0 {
unsafe { libc::close(saved) };
}
});
}
// Open every source in redirect order; numeric `<&N` dups
// resolve against the LIVE fd table. First member replaces
// the fd (c:2448-2450) so later self-dups see it.
let mut source_fds: Vec<i32> = Vec::with_capacity(entries.len() + 1);
source_fds.extend(pipe_seed);
for (i, (op_byte, source)) in entries.iter().enumerate() {
let open_result: std::io::Result<i32> = match *op_byte {
r::DUP_READ | r::DUP_WRITE => match source.trim_start_matches('&').parse::<i32>() {
Ok(src) => {
let d = unsafe { libc::fcntl(src, libc::F_DUPFD_CLOEXEC, 10) };
if d >= 0 {
Ok(d)
} else {
Err(std::io::Error::last_os_error())
}
}
Err(_) => Err(std::io::Error::from_raw_os_error(libc::EBADF)),
},
// c:Src/exec.c:3821-3835 — `fil = getherestr(fn);`
MULTIOS_OP_HERESTR_BODY | MULTIOS_OP_HEREDOC_BODY => {
multios_body_fd(source, *op_byte == MULTIOS_OP_HERESTR_BODY)
}
_ => fs::File::open(source).map(|f| f.into_raw_fd()),
};
match open_result {
Ok(opened) => {
// c:Src/exec.c:2458-2465 — addfd moves every multio member
// out of the script's fd range (`fdN = movefd(fd1)`,
// `fdN = movefd(fd2)`). A member opened by `open` gets the
// LOWEST free descriptor, which for `cat 3<o1 3<o2 <&3` is
// 3 itself: the `dup2` of the concatenator pipe onto fd 3
// below then closed o1, the producer read its own empty
// pipe instead, and the command hung.
let tfd = crate::ported::utils::movefd(opened);
if i == 0 {
unsafe {
libc::dup2(tfd, fd);
}
}
source_fds.push(tfd);
}
Err(e) => {
let msg = match e.kind() {
std::io::ErrorKind::PermissionDenied => "permission denied",
std::io::ErrorKind::NotFound => "no such file or directory",
_ => "open failed",
};
// c:Src/exec.c:3741 — zwarn with real lineno prefix.
crate::ported::utils::zwarn(&format!("{}: {}", msg, source));
for prev in &source_fds {
unsafe {
libc::close(*prev);
}
}
with_executor(|exec| {
exec.redirect_failed = true;
});
return Value::Status(1);
}
}
}
// Create the concatenator pipe.
if !with_executor(|exec| multios_read_concat(exec, fd, source_fds)) {
return Value::Status(1);
}
Value::Status(0)
});
// c:Src/exec.c:3978-3986 — nullexec==1 marker. See the const's
// doc block. Arg: 1 = entering a bare-exec redirect, 0 = leaving.
vm.register_builtin(BUILTIN_EXEC_PERM_REDIRS, |vm, _argc| {
let on = vm.pop().to_int() != 0;
with_executor(|exec| exec.exec_redirs_permanent = on);
Value::Status(0)
});
// Bare-exec redirect epilogue — see the const's doc block.
// c:Src/exec.c:252-259 (execerr) + c:4367-4386 (done: POSIX gate).
vm.register_builtin(BUILTIN_EXEC_REDIR_DONE, |vm, _argc| {
use std::sync::atomic::Ordering;
let failed = with_executor(|exec| {
let f = exec.redirect_failed;
exec.redirect_failed = false;
f
});
if !failed {
// c:Src/exec.c:4032 — `lastval = errflag ? errflag : cmdoutval;`
// cmdoutval is NOT reset by a command without assignments, so
// a `$(...)` from an earlier command (`x=$(false); exec 3>f`)
// still decides this status.
let ef = crate::ported::utils::errflag.load(Ordering::Relaxed);
return Value::Status(if ef != 0 { ef } else { crate::ported::exec::cmdoutval.load(Ordering::Relaxed) });
}
// c:255 — `redir_err = lastval = 1` (dash: 2, see fatal_error_status).
let redir_st = crate::extensions::dash_mode::fatal_error_status().unwrap_or(1);
vm.last_status = redir_st;
if isset(crate::ported::zsh_h::POSIXBUILTINS) && !isset(crate::ported::zsh_h::INTERACTIVE) {
// c:4379-4383 — non-interactive POSIX fatal: exit(1).
// In-process equivalent: arm EXIT_PENDING/EXIT_VAL so the
// next BUILTIN_ERREXIT_CHECK (trigger 2) unwinds the
// script with status 1 — same deferred-exit shape the
// `exit` builtin uses inside subshell contexts.
crate::ported::builtin::EXIT_VAL.store(1, Ordering::Relaxed);
crate::ported::builtin::EXIT_PENDING.store(1, Ordering::Relaxed);
}
Value::Status(redir_st)
});
// c:Src/exec.c:3722-3724 — see the const's doc block. No args.
// BUILTIN_XTRERR_COPY — c:Src/exec.c:3765-3773, emitted right before a
// simple command's WithRedirectsBegin. No args.
vm.register_builtin(BUILTIN_XTRERR_COPY, |_vm, _argc| {
xtrerr_flush(); // c:3766 fflush(xtrerr)
if isset(crate::ported::zsh_h::XTRACE)
&& crate::ported::utils::xtrerr.load(std::sync::atomic::Ordering::Relaxed) == libc::STDERR_FILENO
{
// c:3767-3769
let fd = crate::ported::utils::movefd(unsafe { libc::dup(libc::STDERR_FILENO) });
if fd >= 0 {
// c:Src/exec.c:779 `closem(FDT_XTRACE, 0)` closes this fd in a
// child before it execs; zshrs's spawns run no closem, so
// close-on-exec stands in for it.
unsafe { libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC) };
crate::ported::utils::xtrerr.store(fd, std::sync::atomic::Ordering::Relaxed); // c:3770
crate::ported::utils::fdtable_set(fd, crate::ported::zsh_h::FDT_XTRACE); // c:3771
let depth = with_executor(|exec| exec.redirect_scope_stack.len()) + 1;
XTRERR_COPIES.with(|v| v.borrow_mut().push((depth, fd)));
}
}
Value::Status(0)
});
vm.register_builtin(BUILTIN_PIPE_OUTPUT_MARK, |_vm, _argc| {
with_executor(|exec| exec.pipe_output_pending = true);
Value::Status(0)
});
// c:Src/exec.c:3710-3724 — install this pipeline stage's fds.
// /* Make a copy of stderr for xtrace output before redirecting */
// fflush(xtrerr);
// ...
// /* Add pipeline input/output to mnodes */
// if (input) addfd(forked, save, mfds, 0, input, 0, NULL);
// if (output) addfd(forked, save, mfds, 1, output, 1, NULL);
// Emitted into the stage chunk by compile_zsh.rs (after the arg
// words' expansion ops, before the redirect scope), and fed by
// BUILTIN_RUN_PIPELINE via `stage_fds_park`. Doing the dup2 HERE
// rather than before the chunk runs is what makes a `$(...)` in a
// stage's arguments see the shell's fd 0 instead of the pipe.
vm.register_builtin(BUILTIN_PIPE_FDS_INSTALL, |vm, argc| {
// Arg: `|&` merge-stderr flag (compile_zsh always passes it).
let merge_stderr = pop_args(vm, argc)
.first()
.map(|s| s != "0" && !s.is_empty())
.unwrap_or(false);
let (in_fd, out_fd) = stage_fds_take();
if in_fd < 0 && out_fd < 0 {
return Value::Status(0);
}
// c:3711 `fflush(xtrerr)` — flush before the fds move, so
// anything buffered from the expansion phase lands on the
// ORIGINAL fd, not on the pipe.
let _ = std::io::stdout().flush();
let _ = std::io::stderr().flush();
unsafe {
if in_fd >= 0 {
libc::dup2(in_fd, libc::STDIN_FILENO);
if in_fd != libc::STDIN_FILENO {
libc::close(in_fd);
}
// c:3775-3776 — the pipe is mfds[0]'s first member.
PIPE_INPUT_INSTALLED.with(|c| c.set(Some(SUBLIST_SERIAL.with(|s| s.get()))));
}
if out_fd >= 0 {
libc::dup2(out_fd, libc::STDOUT_FILENO);
if out_fd != libc::STDOUT_FILENO {
libc::close(out_fd);
}
// `cmd |& next`: the `2>&1` C appends to cmd's redirect
// list (walked at c:3730+, i.e. after this addfd), so
// stderr follows the pipe, not the shell's stdout.
if merge_stderr {
libc::dup2(libc::STDOUT_FILENO, libc::STDERR_FILENO);
}
}
}
Value::Status(0)
});
// c:Src/exec.c — block-level redirect-failure gate. When a
// compound command (`{ … } < file`, `( … ) > file`, etc.) has a
// failing redirect (e.g. `< /nonexistent`), zsh skips the entire
// body AND sets lastval to 1. The simple-command path's
// redirect_failed check (line 215-221 above) only catches the
// failure when a builtin dispatches and is consumed by that
// single builtin call — so a multi-statement block kept running
// its remaining statements after the redir error. Emit-side at
// compile_zsh.rs::compile_command's Redirected arm pairs this
// with a JumpIfTrue → WithRedirectsEnd to abandon the body.
vm.register_builtin(BUILTIN_REDIRECT_FAILED_CHECK, |vm, _argc| {
let failed = with_executor(|exec| {
let f = exec.redirect_failed;
exec.redirect_failed = false;
f
});
if failed {
vm.last_status = crate::extensions::dash_mode::fatal_error_status().unwrap_or(1);
Value::Int(1)
} else {
Value::Int(0)
}
});
// c:Src/exec.c — drop-in replacement for fusevm's Op::Exec used by
// the dynamic-first-word path (`$cmd`, `$(cmd)`, glob-named cmds).
// fusevm's Op::Exec returns Value::Status(0) when post-expansion
// argv is empty (vm.rs:1722) — that clobbers \$? for the
// `\$(exit 1); echo \$?` case where the cmd-subst left
// last_status = 1 but the empty expansion gets exec'd to 0.
// Mirror C zsh: when the word list is empty after expansion,
// \$? becomes whatever the inner cmd-subst's last_status is
// (preserved here by returning Value::Status(last_status)).
// c:Src/cond.c:308-316 — `if (!(pprog = patcompile(right, ...)))
// { zwarnnam(fromtest, "bad pattern: %s", right); return 2; }`.
// The cond path must NOT use str_match/glob_match_static: the
// case-statement consumer of those follows Src/loop.c:667 zerr
// semantics (errflag abort), while cond is a zwarn + status-2
// soft failure. COND_BAD_PATTERN carries the 2 across the
// Bool-shaped stack contract (so `!=`'s LogNot can't lose it).
thread_local! {
static COND_BAD_PATTERN: std::cell::Cell<bool> =
const { std::cell::Cell::new(false) };
}
vm.register_builtin(BUILTIN_COND_STRMATCH, |vm, _argc| {
let pat = pattern_filesub(&vm.pop().to_str());
let s = vm.pop().to_str();
// bash `shopt -s nocasematch` → case-insensitive `[[ == ]]` / `[[ != ]]`.
// Lowercase BOTH sides for the match decision (glob metacharacters are
// not letters, so the pattern's `*`/`?`/`[…]` structure is preserved).
// No-op unless the bash shopt is active. --zsh unaffected.
let (s, pat) = if crate::dash_mode::nocasematch() {
(s.to_lowercase(), pat.to_lowercase())
} else {
(s, pat)
};
// !!! BASH-MODE (no C counterpart) !!! bash enables extglob while parsing
// `[[ … ]]` (bash(1) `shopt` extglob: "the extended pattern matching
// ksh93 `~(options)pat` prefixes (`~(i)`, `~(E)`, `~(F)`, `~(G)`).
if let Some(m) = crate::pattern_data_escape::ksh93_flagged_match(&s, &pat) {
return Value::Bool(m);
}
// operators are enabled within [[ ]]"), so `[[ abc == @(a|x)bc ]]` matches
// with the shopt off. Hold KSHGLOB on for this one match.
let _extglob_in_dbracket = BashDbracketExtglob::enter(&pat);
// A bare POSIX-family drop-in reads a source-level `(` by its own
// rules, not by zsh's parse-time tokenization — see
// `dropin_source_pattern_parens_literal`.
let pat_eff = if crate::pattern_data_escape::dropin_source_pattern_parens_literal() {
crate::pattern_data_escape::escape_shglob_parens(
&pat,
crate::pattern_data_escape::dropin_keeps_ksh_groups(),
)
} else {
pat.clone()
};
let mut pat_tok = pat_eff.clone();
crate::ported::glob::tokenize(&mut pat_tok);
if crate::ported::pattern::patcompile(
&pat_tok,
crate::ported::zsh_h::PAT_STATIC as i32,
None,
)
.is_none()
{
// c:314 — zwarnnam(fromtest, "bad pattern: %s", right).
crate::ported::utils::zwarn(&format!("bad pattern: {}", pat));
COND_BAD_PATTERN.with(|c| c.set(true));
return Value::Bool(false);
}
// Match via the shared engine so `(#b)`/`(#m)` backref and
// MATCH-variable population stays in one place.
Value::Bool(crate::vm_helper::glob_match_static(&s, &pat_eff))
});
// See BUILTIN_RM_STAR_CHECK.
vm.register_builtin(BUILTIN_RM_STAR_CHECK, |vm, argc| {
use crate::ported::zsh_h::{interact, isset, ERRFLAG_ERROR, RMSTARSILENT, SHINSTDIN, Star};
use std::sync::atomic::Ordering;
let mask = vm.pop().to_int() as u64;
let n = (argc as usize).saturating_sub(1);
let mut words: Vec<Value> = (0..n).map(|_| vm.pop()).collect();
words.reverse();
// c:3549-3551 — `type == WC_SIMPLE && interact && unset(RMSTARSILENT)
// && isset(SHINSTDIN)` and at least one argument after `rm`.
if interact() && !isset(RMSTARSILENT) && isset(SHINSTDIN) && n > 0 {
let is_star = |c: char| c == Star || c == '*';
for (i, word) in words.iter().enumerate() {
// c:3554 — `node && !errflag`
if crate::ported::utils::errflag.load(Ordering::Relaxed) != 0 {
break;
}
if i >= 64 || mask & (1u64 << i) == 0 {
continue;
}
let s: Vec<char> = word.to_str().chars().collect();
let l = s.len();
let rmall = if l == 1 && is_star(s[0]) {
// c:3559-3560 — `checkrmall(pwd)`
let pwd = crate::ported::params::getsparam("PWD").unwrap_or_default();
crate::ported::utils::checkrmall(&pwd)
} else if l >= 2 && s[l - 2] == '/' && is_star(s[l - 1]) {
// c:3564-3570 — the word up to the `/`, or `/` itself.
let dir: String = if l == 2 { "/".to_string() } else { s[..l - 2].iter().collect() };
crate::ported::utils::checkrmall(&dir)
} else {
true
};
if !rmall {
crate::ported::utils::errflag.fetch_or(ERRFLAG_ERROR, Ordering::Relaxed); // c:3561 / c:3573
break;
}
}
}
for w in words {
vm.push(w);
}
Value::Int(0)
});
// c:Src/cond.c:122-193, the COND_MODI arm: `[[ a -op b ]]` with an `-op`
// that is not one of get_cond_num's (Src/parse.c:2697-2701). See
// BUILTIN_COND_MODI.
vm.register_builtin(BUILTIN_COND_MODI, |vm, _argc| {
let is_dash = |s: &str| s.starts_with('-') || s.starts_with(crate::ported::zsh_h::Dash);
let mut name = vm.pop().to_str(); // c:130 — the operator word
let right = vm.pop().to_str();
let left = vm.pop().to_str();
let mut strs = vec![left, right]; // c:136-141
let l: i32 = 2; // c:141
// c:143-148
let errname = if is_dash(&name) {
crate::lex::untokenize(&name)
} else if is_dash(&strs[0]) {
crate::lex::untokenize(&strs[0])
} else {
"<null>".to_string()
};
let lookup = |inf: i32, word: &str| {
let cond = word.chars().skip(1).collect::<String>(); // `name + 1`
match crate::ported::module::MODULESTAB.try_lock() {
Ok(mut tab) => crate::ported::module::getconddef(inf, &cond, 1, &mut tab),
Err(_) => None,
}
};
// c:149-150
let mut cd = if is_dash(&name) { lookup(1, &name) } else { None };
if cd.is_none() {
// c:161-174 — retry as a prefix condition on the left word, with
// the operator word moved into its place.
let s = std::mem::replace(&mut strs[0], name); // c:173
name = s; // c:174
cd = if is_dash(&name) { lookup(0, &name) } else { None }; // c:176-177
match cd.as_ref() {
Some(c) if l < c.min || (c.max >= 0 && l > c.max) => {
// c:178-181
crate::ported::utils::zerr(&format!("unknown condition: {}", errname));
COND_BAD_PATTERN.with(|c| c.set(true));
return Value::Bool(false);
}
Some(_) => {}
None => {
// c:186-192 — `zwarnnam(…, "unknown condition: %s",
// errname)` then `return 2;`, the status the shared
// BUILTIN_COND_STATUS_FROM_BOOL tail turns into an error.
crate::ported::utils::zerr(&format!("unknown condition: {}", errname));
COND_BAD_PATTERN.with(|c| c.set(true));
return Value::Bool(false);
}
}
}
// c:158 / c:185 — `return !cd->handler(strs, cd->condid);`
let r = cd
.and_then(|c| c.handler.map(|h| h(&strs, c.condid)))
.unwrap_or(0);
Value::Bool(r != 0)
});
vm.register_builtin(BUILTIN_COND_UNKNOWN, |vm, _argc| {
// c:Src/cond.c:150-188 — `zwarnnam(fromtest, "unknown condition: %s",
// name)` for a `-X` op with no matching cond module. Like a cond
// syntax error it yields status 2 and aborts: arm COND_BAD_PATTERN so
// the downstream BUILTIN_COND_STATUS_FROM_BOOL carries the 2 across the
// Bool-shaped stack and runs the shared errflag+set_last_status(2)+abort
// path (c:Src/exec.c:5216-5221). Returns Bool(false) as the operand.
let op = vm.pop().to_str();
crate::ported::utils::zerr(&format!("unknown condition: {}", op));
COND_BAD_PATTERN.with(|c| c.set(true));
Value::Bool(false)
});
vm.register_builtin(BUILTIN_COND_STATUS_FROM_BOOL, |vm, _argc| {
// `${~pat}` / `${(P)~pat}` inside a `[[ … ]]` operand flips
// GLOB_SUBST on via the tilde carrier so the pattern match sees
// active metacharacters. In C that flag is prefork-scoped and
// gone once the operand is consumed; zshrs restores it at the
// next command-dispatch boundary, but a bare `[[ … ]]` has no
// trailing assignment to trigger that — so globsubst leaked ON
// into the NEXT command's word expansion, filename-generating a
// scalar value it should not (p10k `_p9k_set_prompt`: line 45
// `[[ … != ${(P)~disabled} ]]` leaked into line 46's
// `local val=$arr[idx]`, whose glob-char-laden value then hit
// "no matches found" and aborted the whole prompt build →
// garbled 25-line prompt / interactive hang). Consume the
// carrier here: this builtin ends EVERY `[[ … ]]`, and runs
// after the operands (and their pattern match) are done.
consume_tilde_globsubst_carrier();
let ok = vm.pop().to_int() != 0;
let bad = COND_BAD_PATTERN.with(|c| {
let b = c.get();
c.set(false);
b
});
if bad {
// c:Src/exec.c:5216-5221 — `stat = evalcond(...);
// /* 2 indicates a syntax error. For compatibility,
// turn this into a shell error. */
// if (stat == 2) errflag |= ERRFLAG_ERROR;`
// The errflag abort exits the script with lastval (2),
// matching `zsh -fc '[[ x == [a- ]]; print rc=$?'`
// printing nothing after the diagnostic and exiting 2.
crate::ported::utils::errflag.fetch_or(
crate::ported::zsh_h::ERRFLAG_ERROR,
std::sync::atomic::Ordering::Relaxed,
);
with_executor(|exec| exec.set_last_status(2));
return Value::Int(2); // c:Src/cond.c:316 `return 2;`
}
let status: i32 = if ok { 0 } else { 1 };
// c:Src/exec.c:5216 — `lastval = evalcond(...)`: the conditional's
// result IS the command's lastval, and c:Src/cond.c's evalcond
// never inspects errflag while evaluating. So when a `[[ … ]]`
// operand raised errflag (e.g. a nounset "parameter not set" zerr
// on `${arr[99]}` under NO_UNSET), zsh STILL completes the test and
// exits with the cond result; the errflag only aborts the FOLLOWING
// commands. Sync the result to the executor's live lastval HERE —
// the nounset site left it at a transient 1, and the next
// BUILTIN_ERREXIT_CHECK reads the executor (not vm.last_status), so
// without this sync `setopt NO_UNSET; [[ -z ${arr[99]} ]]` exited 1
// instead of 0. The Op::SetStatus that follows sets vm.last_status;
// this keeps the executor coherent with it before the abort check.
with_executor(|exec| exec.set_last_status(status));
Value::Int(status as i64)
});
// c:Src/exec.c:2796 (execcmd_analyse) / c:1368 (execsimple) — a simple
// command that carries assignments starts with `cmdoutval = 0;`.
vm.register_builtin(BUILTIN_CMDOUTVAL_RESET, |_vm, _argc| {
crate::ported::exec::cmdoutval.store(0, std::sync::atomic::Ordering::Relaxed);
Value::Status(0)
});
vm.register_builtin(BUILTIN_USE_CMDOUTVAL_RESET, |_vm, _argc| {
crate::ported::exec::use_cmdoutval.store(0, std::sync::atomic::Ordering::Relaxed);
Value::Status(0)
});
// See BUILTIN_COND_PCRE_MATCH.
vm.register_builtin(BUILTIN_COND_PCRE_MATCH, |vm, _argc| {
let re = crate::lex::untokenize(&vm.pop().to_str());
let subject = crate::lex::untokenize(&vm.pop().to_str());
let hit = crate::ported::modules::pcre::cond_pcre_match(
&[subject, re],
crate::ported::modules::pcre::CPCRE_PLAIN,
) != 0;
Value::Bool(hit)
});
// See BUILTIN_AUTOCONTINUE_FORCE.
vm.register_builtin(BUILTIN_AUTOCONTINUE_FORCE, |vm, _argc| {
thread_local! {
static SAVED: std::cell::RefCell<Vec<bool>> = const { std::cell::RefCell::new(Vec::new()) };
}
if vm.pop().to_int() != 0 {
let old = opt_state_get("autocontinue").unwrap_or(false); // c:3021 oautocont
SAVED.with(|s| s.borrow_mut().push(old));
crate::ported::options::opt_state_set_via_alias("autocontinue", true); // c:3022
} else if let Some(old) = SAVED.with(|s| s.borrow_mut().pop()) {
crate::ported::options::opt_state_set_via_alias("autocontinue", old);
}
Value::Int(0)
});
// See BUILTIN_CMD_NAME_GLOB_MARK.
vm.register_builtin(BUILTIN_CMD_NAME_GLOB_MARK, |vm, _argc| {
let more_words = vm.pop().to_int() != 0;
// A NOMATCH / bad pattern zerrs (errflag set); a CSH_NULL_GLOB drop is
// silent and leaves the word list to carry on.
let failed = with_executor(|exec| exec.current_command_glob_failed.get())
&& crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed)
& crate::ported::zsh_h::ERRFLAG_ERROR
!= 0;
// A CSH_NULL_GLOB drop of the name leaves the other words to the
// globlist at c:Src/exec.c:3757, which restarts the badcshglob count
// (c:Src/subst.c:498): the dropped name must not later read as
// "every glob of this command failed".
if !failed && more_words {
crate::ported::glob::BADCSHGLOB.store(0, std::sync::atomic::Ordering::Relaxed);
}
CMD_NAME_GLOB_FAILED.with(|c| c.set(failed));
Value::Int(0)
});
// See BUILTIN_MARK_CURSH.
vm.register_builtin(BUILTIN_MARK_CURSH, |_vm, _argc| {
crate::exec_jobs::mark_thisjob_cursh(true); // c:Src/exec.c:3674-3682
Value::Int(0)
});
// See BUILTIN_EXEC_DYNAMIC_REDIRS.
vm.register_builtin(BUILTIN_EXEC_DYNAMIC_REDIRS, |_vm, _argc| {
EXEC_DYNAMIC_REDIRS.with(|c| c.set(true));
Value::Int(0)
});
vm.register_builtin(BUILTIN_EXEC_DYNAMIC, |vm, argc| {
let raw = pop_args(vm, argc);
// Taken first so every return path below clears it.
let had_redirs = EXEC_DYNAMIC_REDIRS.with(|c| c.replace(false));
// Flatten Array entries into argv slots (matches fusevm
// Op::Exec's flatten at vm.rs:1660-1665) so `${arr[@]}` /
// splice expansions produce one argv slot per element.
let args: Vec<String> = raw.into_iter().collect();
// c:Src/subst.c paramsubst — when `${var:?msg}` or
// `${var?msg}` set errflag, the expansion may produce empty
// argv[0] which would fall into the EACCES/permission-denied
// path below, masking the real paramsubst diagnostic with a
// spurious "permission denied:" line and rc=126. Honour
// errflag so the simple command ends with the paramsubst
// error as the sole diagnostic, rc=1. Bug #86.
if (crate::ported::utils::errflag.load(std::sync::atomic::Ordering::SeqCst)
& crate::ported::zsh_h::ERRFLAG_ERROR)
!= 0
{
if PREFIX_ASSIGN_EXIT_PENDING.with(|c| c.get()) {
settle_prefix_assign_exit(args.first().map(String::as_str).unwrap_or(""));
}
// c:Src/exec.c:4343-4350 — when the error came from the prefix
// assignments and the expanded name is an external command, they
// ran in the forked child (`addvars(…); if (errflag) _exit(1);`):
// the shell sees status 1 and its errflag is untouched.
if PREFIX_ASSIGN_FAILED.with(|c| c.replace(false)) {
if let Some(name) = args.first() {
let is_external = !with_executor(|exec| exec.function_exists(name))
&& !crate::ported::builtin::createbuiltintable().contains_key(name.as_str());
if is_external {
// Both bits: `${name?msg}` also sets ERRFLAG_HARD.
crate::ported::utils::errflag.fetch_and(
!(crate::ported::zsh_h::ERRFLAG_ERROR | crate::ported::zsh_h::ERRFLAG_HARD),
std::sync::atomic::Ordering::Relaxed,
);
with_executor(|exec| exec.set_last_status(1));
}
}
}
// c:Src/exec.c:3719 + 3755-3763 — the argument glob of an
// external runs in the forked child as well (`x=cat; $x
// *nomatch; print after` prints `after`).
if let Some(name) = args.first() {
let is_external = !with_executor(|exec| exec.function_exists(name))
&& (files_builtin_runs_from_path(name)
|| !crate::ported::builtin::createbuiltintable().contains_key(name.as_str()));
if is_external {
if let Some(status) = external_glob_failure_status() {
return Value::Status(status);
}
}
}
return Value::Status(1);
}
if args.is_empty() {
// c:Src/exec.c:3442 — a command whose words expand to ZERO
// words is a NULL command: `cmdoutval = use_cmdoutval ?
// lastval : 0`. `use_cmdoutval` is set (below, in
// BUILTIN_CMD_SUBST_TEXT) only when a command substitution
// ran during this command's word expansion, so:
// `false; $(exit 5)` → keep the subst status (5)
// `false; $nonexistent` → reset to 0 (null command).
// The previous port unconditionally kept `$?`, so
// `false; $unset` wrongly stayed 1 (A01grammar.ztst:5).
let keep =
crate::ported::exec::use_cmdoutval.load(std::sync::atomic::Ordering::Relaxed) != 0;
let status = if keep { vm.last_status } else { 0 };
crate::ported::exec::use_cmdoutval.store(0, std::sync::atomic::Ordering::Relaxed);
return Value::Status(status);
}
if args[0].is_empty() {
// Explicit empty command word — exec returns EACCES.
let script_name =
crate::ported::utils::scriptname_get().unwrap_or_else(|| "zshrs".to_string());
let lineno: u64 = with_executor(|exec| {
exec.scalar("LINENO")
.and_then(|s| s.parse::<u64>().ok())
.unwrap_or(1)
});
eprintln!("{}:{}: permission denied: ", script_name, lineno);
return Value::Status(126);
}
// AOP intercepts (zshrs extension, no C counterpart) — same
// gate as host_exec_external (the static-head path): dynamic
// command names (`cmd=/bin/echo; $cmd payload`) must consult
// registered intercepts before dispatch, else `intercept
// before /bin/echo ...` fires for the literal spelling but
// not the variable one. run_intercepts runs before-advice
// in-place and returns None to continue; Some(status) means
// an around/after advice fully handled the command.
let intercepted = with_executor(|exec| {
if exec.intercepts.is_empty() {
return None;
}
let full_cmd = if args.len() == 1 {
args[0].clone()
} else {
args.join(" ")
};
let rest: Vec<String> = args[1..].to_vec();
exec.run_intercepts(&args[0], &full_cmd, &rest)
});
if let Some(result) = intercepted {
return Value::Status(result.unwrap_or(127));
}
// zshrs-original builtins (async, doctor, peach, …, and the daemon
// z* family) reached via a run-time-resolved head (`$var`): they
// are absent from the static BUILTINS port table / builtintab, so
// execcmd_exec below would treat the head as external and report
// "command not found" — even though `whence` calls it a builtin and
// a literal head runs it via CallBuiltin. Dispatch by name here, but
// ONLY when the head is neither
// a user function nor a ported builtin, so the shell's
// function -> builtin -> external order is preserved.
if let Some(head) = args.first() {
let is_fn = with_executor(|e| e.function_exists(head));
let is_ported =
crate::ported::builtin::createbuiltintable().contains_key(head.as_str());
if !is_fn && !is_ported {
let status = run_daemon_builtin(head, &args[1..])
.or_else(|| try_run_registered_builtin(head, &args[1..]));
if let Some(status) = status {
crate::ported::builtin::LASTVAL
.store(status, std::sync::atomic::Ordering::Relaxed);
return Value::Status(status);
}
}
}
// c:Src/exec.c:2900 execcmd_exec — canonical simple-command
// dispatcher. Runs precmd-modifier walk (c:3013-3091), then
// dispatches to execbuiltin (c:4233) / runshfunc (c:3431+) /
// execute (c:4314) per the resolved head. zshrs's bytecode VM
// expanded the args before reaching here; we feed them in via
// eparams.args and let execcmd_exec do the rest exactly as C
// does for static heads. Without this, `c=builtin; $c source X`
// skipped the precmd walk and emitted "command not found:
// builtin".
let mut state = crate::ported::zsh_h::estate {
prog: Box::<crate::ported::zsh_h::eprog>::default(),
pc: 0,
strs: None,
strs_offset: 0,
};
let mut eparams = crate::ported::zsh_h::execcmd_params {
args: Some(args),
redir: None,
beg: 0,
varspc: None,
assignspc: None,
typ: crate::ported::zsh_h::WC_SIMPLE as i32,
postassigns: 0,
htok: 0,
};
// input/output=0 → no pipe redirection (use shell stdio
// directly); `output != 0` at c:2988 forks immediately. last1=2
// (c:Src/exec.c:2014 `last1 ? 1 : 2`): terminal pipe stage but
// the shell IS needed afterward — the VM keeps executing
// bytecode after this op. last1=1 would arm the fake-exec
// optimization (c:3646-3651, gate at c:3662 `last1 != 1`),
// making `execute()` execve THIS process for external heads:
// `p=/bin/echo; $p hi; echo after` replaced the shell and
// `after` never ran (D04parameter chunk 11 shell-killer).
// c:Src/exec.c:1690-1700 — execpline's job frame: save thisjob
// (`pj = thisjob`) and allocate the jobtab slot that
// execcmd_fork's addproc (c:2853) hangs the child pid off.
// Without a live thisjob, the fork at c:3662 (last1 != 1 →
// external must fork) registers no proc, nothing waits, and
// the child races the rest of the script.
let pj = {
use crate::ported::jobs;
*jobs::THISJOB
.get_or_init(|| std::sync::Mutex::new(-1))
.lock()
.unwrap_or_else(|e| e.into_inner())
};
// The pipeline's job frame (BUILTIN_EXECPLINE_CHILD_BLOCK) already
// holds this command's slot; only a chunk compiled without one
// allocates here.
let held = crate::exec_jobs::execpline_slot_current();
let newjob = held.unwrap_or_else(|| {
use crate::ported::jobs;
let table = jobs::JOBTAB.get_or_init(|| std::sync::Mutex::new(Vec::new()));
let mut tab = table.lock().unwrap_or_else(|e| e.into_inner());
jobs::initjob(&mut tab) // c:1700 `thisjob = newjob = initjob()`
});
{
use crate::ported::jobs;
*jobs::THISJOB
.get_or_init(|| std::sync::Mutex::new(-1))
.lock()
.unwrap_or_else(|e| e.into_inner()) = newjob as i32;
}
crate::ported::exec::REDIRS_PREAPPLIED.with(|c| c.set(had_redirs));
crate::ported::exec::execcmd_exec(
&mut state,
&mut eparams,
0, // input (c:2989)
0, // output (c:2988)
crate::ported::zsh_h::Z_SYNC as i32, // how
2, // last1=2 — shell continues (c:2014)
-1, // close_if_forked
);
crate::ported::exec::REDIRS_PREAPPLIED.with(|c| c.set(false));
// c:Src/exec.c:1828-1835 — execpline's Z_SYNC tail: waitjobs()
// reaps the forked external. c:Src/jobs.c:487-495 + 551-552 —
// the job's LAST proc sets lastval (0200|sig when signalled,
// else WEXITSTATUS). Builtin/shfunc heads never forked (job
// has no procs) — LASTVAL was already set by execbuiltin /
// doshfunc inside execcmd_exec; skip the wait.
{
use crate::ported::jobs;
let table = jobs::JOBTAB.get_or_init(|| std::sync::Mutex::new(Vec::new()));
let forked = jobs::hasprocs(&table.lock().unwrap_or_else(|e| e.into_inner()), newjob);
if forked {
// waitjobs() reads thisjob and holds no JOBTAB guard across the wait.
*jobs::THISJOB
.get_or_init(|| std::sync::Mutex::new(-1))
.lock()
.unwrap_or_else(|e| e.into_inner()) = newjob as i32;
jobs::waitjobs(); // c:1835
}
let mut tab = table.lock().unwrap_or_else(|e| e.into_inner());
if forked {
if let Some(p) = tab[newjob].procs.last() {
let val = if p.is_signaled() {
0o200 | p.term_sig() // c:Src/jobs.c:489-490
} else {
p.exit_status() // c:Src/jobs.c:494
};
crate::ported::builtin::LASTVAL
.store(val, std::sync::atomic::Ordering::Relaxed);
}
}
// c:1977-1979 — `deletejob(jn, 0)` once done; c:1981
// `thisjob = pj` restores the caller's job. A held slot is the
// job frame's to delete when the pipeline closes.
if held.is_none() && newjob < tab.len() {
jobs::deletejob(&mut tab, newjob, false);
}
*jobs::THISJOB
.get_or_init(|| std::sync::Mutex::new(-1))
.lock()
.unwrap_or_else(|e| e.into_inner()) = pj;
}
let status = crate::ported::builtin::LASTVAL.load(std::sync::atomic::Ordering::Relaxed);
crate::ported::jobs::waitonejob(-1);
Value::Status(status)
});
// c:Src/exec.c:3386-3419 — `< file` / `> file` with no command
// word. Resolves NULLCMD/READNULLCMD at runtime, then dispatches the
// resulting word the way execcmd's fall-through does (shell function →
// builtin → external). Redirects are already applied by the surrounding
// WithRedirectsBegin scope.
vm.register_builtin(BUILTIN_NULLCMD_CHECK, |vm, _argc| {
use std::sync::atomic::Ordering;
let nullcmd = crate::ported::params::getsparam("NULLCMD");
// c:3395 — `!nullcmd || !*nullcmd || opts[CSHNULLCMD]`
if nullcmd.as_deref().map_or(true, str::is_empty)
|| crate::ported::zsh_h::isset(crate::ported::zsh_h::CSHNULLCMD)
{
crate::ported::utils::zerr("redirection with no command"); // c:3397
crate::ported::builtin::LASTVAL.store(1, Ordering::Relaxed); // c:3398
vm.last_status = 1;
crate::ported::utils::errflag
.fetch_or(crate::ported::zsh_h::ERRFLAG_ERROR, Ordering::Relaxed); // c:3399
return Value::Bool(false);
}
Value::Bool(true)
});
vm.register_builtin(BUILTIN_NULLCMD_EXEC, |vm, argc| {
let args = pop_args(vm, argc);
let is_single_read = args
.first()
.map(|s| s != "0" && !s.is_empty())
.unwrap_or(false);
// c:Src/exec.c — when the surrounding redir-open failed
// (e.g. `< /nonexistent`), zerr already printed the diag
// and set redirect_failed. Don't invoke NULLCMD — return
// status 1 like the wordcode path does.
let redir_failed = with_executor(|exec| {
let f = exec.redirect_failed;
exec.redirect_failed = false;
f
});
if redir_failed {
crate::ported::builtin::LASTVAL.store(1, std::sync::atomic::Ordering::Relaxed);
return Value::Status(1);
}
// c:3395-3399 — the no-NULLCMD / CSH_NULLCMD refusal already ran in
// BUILTIN_NULLCMD_CHECK, before the redirections opened.
let nullcmd = crate::ported::params::getsparam("NULLCMD");
let nc_str = nullcmd.as_deref().unwrap_or("");
// c:3350 — SHNULLCMD → run `:`.
let cmd: String = if crate::ported::zsh_h::isset(crate::ported::zsh_h::SHNULLCMD) {
":".to_string()
} else if is_single_read {
// c:3354-3359 — single REDIR_READ + READNULLCMD set → readnullcmd.
let rnc = crate::ported::params::getsparam("READNULLCMD");
let rnc_str = rnc.as_deref().unwrap_or("");
if !rnc_str.is_empty() {
rnc_str.to_string()
} else {
nc_str.to_string() // c:3360-3363 fallback
}
} else {
nc_str.to_string() // c:3360-3363
};
// c:Src/exec.c:3408/3414/3418 — C does not "run NULLCMD" as a special
// case: it APPENDS the word to the command's arg list
// (`addlinknode(args, dupstring(nullcmd))`) and falls through to
// execcmd's ORDINARY dispatch, which resolves that word in this order:
// c:3484-3487 `shfunctab->getnode(shfunctab, cmdarg)` → shell function
// c:3489 `builtintab->getnode(builtintab, cmdarg)` → builtin
// otherwise → external command (PATH lookup).
// `host_exec_external` already implements the shell-function arm and
// the external arm (plus the AOP intercepts and the module-builtin
// name arms), so only the builtintab arm has to be decided here.
//
// The builtintab question must be asked of the TABLE.
// `builtin_in_builtintab` alone is NOT a membership test — it is the
// module *gate*, and `builtin_owning_module` returns None for any name
// it does not know, whose `None => true` arm
// (src/extensions/ext_builtins.rs:179-182) then reports EVERY string as
// an available builtin. With that as the only predicate, the default
// `READNULLCMD=more` (config.h DEFAULT_READNULLCMD), a user's
// `READNULLCMD=less`, `NULLCMD=/bin/cat` and every other external name
// were classified as core builtins and handed to
// `dispatch_builtin_raw("more", vec![])`, which cannot work: plain
// `< file` printed NOTHING and returned 1, and a missing NULLCMD
// returned a silent 1 instead of `command not found` / 127.
//
// Membership first, gate second. The zshrs-original coreutils-shaped
// builtins (`cat`, `basename`, … EXT_BUILTIN_NAMES) are not entries of
// `createbuiltintable()` at all, so the documented `NULLCMD=cat` /
// `READNULLCMD=cat` idioms keep reaching the real `/bin/cat` the way
// `zsh -f` does without needing an explicit exclusion.
//
// `dispatch_builtin` (not `dispatch_builtin_raw`) is the correct entry:
// C's `builtintab->getnode` filters DISABLED nodes, so `disable :;
// NULLCMD=:; > f` must fall through to PATH — the raw dispatcher
// deliberately bypasses that set (it is what `builtin NAME` uses).
let is_shfunc = with_executor(|exec| exec.function_exists(&cmd)); // c:3485
let is_builtin = crate::ported::builtin::createbuiltintable().contains_key(&cmd)
&& crate::extensions::ext_builtins::builtin_in_builtintab(&cmd); // c:3489
let status = if !is_shfunc && is_builtin {
dispatch_builtin(&cmd, Vec::new()) // c:3489-3504
} else {
with_executor(|exec| exec.host_exec_external(&[cmd]))
};
crate::ported::builtin::LASTVAL.store(status, std::sync::atomic::Ordering::Relaxed);
Value::Status(status)
});
// c:Src/exec.c:3342 — `zerr("redirection with no command")`.
// Bare prefix-keyword (`builtin`, `command`, `exec`, `noglob`,
// `nocorrect`) with a redirect but no command word. Emits the
// canonical diagnostic via zerr (which sets errflag) and
// returns Status(1). Bug #534.
// c:Src/exec.c:3104-3290 then c:3380-3402 — the precommand walk for a
// `builtin`/`command`/`exec` head that carries redirections, run on the
// expanded words BEFORE the redirect scope opens (c:3720), as C orders
// it. Operands: [prefix, words…]. Returns the words without the prefix
// as one array for the prefix opcode; BUILTIN_PRECMD_CHECK_OK then says
// whether the walk let the command run. A failed walk has already
// printed its diagnostic to the still-unredirected stderr.
vm.register_builtin(BUILTIN_PRECMD_CHECK, |vm, argc| {
let mut popped: Vec<Value> = Vec::with_capacity(argc as usize);
for _ in 0..argc {
popped.push(vm.pop());
}
popped.reverse();
let mut full: Vec<String> = Vec::with_capacity(popped.len());
for v in popped {
match v {
Value::Array(items) => full.extend(items.iter().map(|i| i.to_str())),
other => full.push(other.to_str()),
}
}
let words: Vec<Value> = full.iter().skip(1).map(|s| Value::str(s.as_str())).collect();
let ok = precmd_walk_ok(&full);
if !ok {
// c:3205 / c:3398 — `lastval = 1;` before `goto done` / return.
vm.last_status = 1;
crate::ported::builtin::LASTVAL.store(1, std::sync::atomic::Ordering::Relaxed);
}
PRECMD_CHECK_PASSED.with(|c| c.set(ok));
Value::array(words)
});
vm.register_builtin(BUILTIN_PRECMD_CHECK_OK, |_vm, _argc| {
Value::Bool(PRECMD_CHECK_PASSED.with(|c| c.replace(true)))
});
vm.register_builtin(BUILTIN_REDIR_NO_CMD, |_vm, _argc| {
crate::ported::utils::zerr("redirection with no command");
Value::Status(1)
});
vm.register_builtin(BUILTIN_DEBUG_TRAP, |vm, _argc| {
// c:Src/signals.c:1245 dotrap(SIGDEBUG) — fires the DEBUG
// trap body once per statement. The body sees the parent
// shell's $? (LASTVAL). Guard against re-entry: commands
// inside the DEBUG trap body would otherwise trigger
// DEBUG_TRAP recursively → stack overflow. zsh guards via
// its in_trap counter; we mirror with a thread-local Cell.
//
// c:Src/exec.c::trapcmd — before dotrap, the C source sets
// `ZSH_DEBUG_CMD` to the about-to-run command text via
// `dupstring(text)`. The trap body reads the parameter;
// C unsets it after the trap returns. compile_list emits
// the rendered statement text as the single arg here so the
// shell-visible parameter reflects the command. Bug #263 in
// docs/BUGS.md.
// Return value: `Int(1)` tells the emit-side JumpIfTrue to SKIP the
// statement this trap ran in front of — C's `donedebug == 2`
// (c:Src/exec.c:1499/1511/1519-1529) plus the forced-return case
// where C's list loop (`while (… && !retflag …)`, c:1443) never
// reaches the command. `Int(0)` = run it.
//
// Two call sites, distinguished by the `mode` operand:
// 0 — c:1476-1502, the DEBUG_BEFORE_CMD block that runs BEFORE the
// sublist (only when the option is set),
// 1 — c:1628-1644, the `sublist_done:` block that runs AFTER it
// (only when the option is NOT set).
// Firing the pre-sublist arm in both modes made the default
// (post-command) DEBUG trap observe the NEXT statement's `$LINENO`
// — A05execution:19 saw "Line 2 / Line 3" for a trap zsh reports as
// "Line 1 / Line 2".
let mode = vm.pop().to_int();
let cmd_text = vm.pop().to_str();
let before = mode == 0;
DEBUG_TRAP_REENTRY.with(|c| {
if c.get() {
return Value::Int(0);
}
// c:1476 `isset(DEBUGBEFORECMD)` / c:1628 `!isset(DEBUGBEFORECMD)`.
// !!! BASH-MODE !!! bash fires DEBUG BEFORE each command, never after,
// sets $BASH_COMMAND, skips function definitions, and does not
// descend into function bodies unless `set -T` (functrace).
let bash = crate::extensions::dash_mode::bash_mode();
if before != (isset(crate::ported::zsh_h::DEBUGBEFORECMD) || bash) {
return Value::Int(0);
}
if bash
&& before
&& (crate::extensions::dash_mode::is_funcdef_text(&cmd_text)
|| (crate::ported::params::locallevel.load(std::sync::atomic::Ordering::Relaxed) > 0
&& !crate::extensions::dash_mode::bash_set_o_get("functrace")))
{
return Value::Int(0);
}
// c:Src/exec.c:1423 — `if (sigtrapped[SIGDEBUG] &&
// isset(DEBUGBEFORECMD) && !intrap)`. Bug #573: without
// this gate, every sublist boundary called
// setsparam("ZSH_DEBUG_CMD", ...) even when no DEBUG trap
// was set, polluting the param table and (under
// WARN_CREATE_GLOBAL) emitting a spurious
// `scalar parameter ZSH_DEBUG_CMD created globally`
// warning at every function call.
//
// Two trap registries exist (per signals.rs:1481-1511 dotrap):
// - settrap path → sigtrapped[SIGDEBUG] bits set
// - bin_trap path → traps_table["DEBUG"] populated, sigtrapped untouched
// Mirror the dotrap dispatch decision: skip only when BOTH
// are absent.
let sig_debug = crate::ported::signals_h::SIGDEBUG as usize;
let debug_trapped = crate::ported::signals::sigtrapped
.lock()
.map(|v| v.get(sig_debug).copied().unwrap_or(0))
.unwrap_or(0);
let debug_in_table = crate::ported::builtin::traps_table()
.lock()
.map(|t| t.contains_key("DEBUG"))
.unwrap_or(false);
if debug_trapped == 0 && !debug_in_table {
return Value::Int(0);
}
c.set(true);
// c:1478-1481 — `int oerrexit_opt = opts[ERREXIT]; Param pm;
// opts[ERREXIT] = 0; noerrexit |= NOERREXIT_EXIT |
// NOERREXIT_RETURN;`. ERREXIT is forced OFF across the trap
// body so the option can be used as the "skip this command"
// signal (c:1499) without the body's own failing commands
// exiting the shell.
let oerrexit_opt = isset(crate::ported::zsh_h::ERREXIT); // c:1478
crate::ported::options::opt_state_set("errexit", false); // c:1480
let oldnoerrexit =
crate::ported::exec::noerrexit.load(std::sync::atomic::Ordering::Relaxed);
crate::ported::exec::noerrexit.store(
oldnoerrexit
| crate::ported::zsh_h::NOERREXIT_EXIT
| crate::ported::zsh_h::NOERREXIT_RETURN,
std::sync::atomic::Ordering::Relaxed,
); // c:1481
// c:Src/exec.c:1484 — set ZSH_DEBUG_CMD scalar (PM_READONLY
// is NOT set on ZSH_DEBUG_CMD, so the canonical
// setsparam path is fine here — no direct paramtab
// mutation needed).
// c:1636 — the post-sublist arm has no ZSH_DEBUG_CMD assignment;
// the parameter is a DEBUG_BEFORE_CMD feature only.
if before {
// c:1484-1485 — `getpermtext(state->prog, pc2, 0)`: the
// PERMANENT text, with newlines and tab indents (tnewlins=1,
// c:Src/text.c:279), so `while false; do :; done` reads
// "while false\ndo\n\t:\ndone". The compiled operand is the
// one-line job text; re-parse it and render it through the
// ported getpermtext, as printshfuncnode does for a function
// body (hashtable.rs). The text is already alias-expanded, so
// the re-lex must not expand again, and RCQUOTES must not
// fold a `''` pair the first lex kept as written.
let noalias_save = crate::ported::lex::noaliases();
let rcquotes_save = isset(crate::ported::zsh_h::RCQUOTES);
// A text the wordcode parser rejects falls back to the job
// text silently: C never parses it, so no diagnostic or
// errflag may escape.
let noerrs_save = *crate::ported::utils::noerrs_lock().lock().unwrap();
let errflag_save =
crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed);
crate::ported::utils::set_noerrs(1);
crate::ported::lex::set_noaliases(true);
crate::ported::options::opt_state_set("rcquotes", false);
let permtext = crate::ported::exec::parse_string(&cmd_text, 0)
.map(|p| crate::ported::text::getpermtext(Box::new(p), None, 0));
crate::ported::options::opt_state_set("rcquotes", rcquotes_save);
crate::ported::lex::set_noaliases(noalias_save);
crate::ported::utils::set_noerrs(noerrs_save);
crate::ported::utils::errflag
.store(errflag_save, std::sync::atomic::Ordering::Relaxed);
let text = permtext.filter(|t| !t.is_empty()).unwrap_or(cmd_text);
crate::ported::params::setsparam("ZSH_DEBUG_CMD", &text);
if bash {
crate::ported::params::setsparam("BASH_COMMAND", &text);
}
}
// c:1488/1636 — `exiting = donetrap;` … c:1493/1641 `donetrap = exiting;`
let exiting = crate::ported::exec::DONETRAP.load(std::sync::atomic::Ordering::Relaxed);
let ret = crate::ported::builtin::LASTVAL.load(std::sync::atomic::Ordering::Relaxed); // c:1489
let _ = crate::ported::signals::dotrap(crate::ported::signals_h::SIGDEBUG);
// c:1491-1492 — `if (!retflag) lastval = ret;`. A trap that
// ran `return N` keeps the forced status; anything else
// leaves the pre-trap `$?` alone.
let retflag =
crate::ported::builtin::RETFLAG.load(std::sync::atomic::Ordering::Relaxed) != 0;
if !retflag {
crate::ported::builtin::LASTVAL.store(ret, std::sync::atomic::Ordering::Relaxed);
// c:1492
}
crate::ported::exec::noerrexit
.store(oldnoerrexit, std::sync::atomic::Ordering::Relaxed); // c:1494
// c:1499 — `donedebug = isset(ERREXIT) ? 2 : 1;`. The trap
// setting ERREXIT is zsh's documented "skip this command"
// signal (zshmisc(1), DEBUG trap).
let donedebug2 = before && isset(crate::ported::zsh_h::ERREXIT); // c:1499
crate::ported::options::opt_state_set("errexit", oerrexit_opt); // c:1500/1643
crate::ported::exec::DONETRAP.store(exiting, std::sync::atomic::Ordering::Relaxed); // c:1493/1641
// c:Src/exec.c:1501-1502 — `if (pm) unsetparam_pm(pm, 0, 1);`
if before {
crate::ported::params::unsetparam("ZSH_DEBUG_CMD");
}
c.set(false);
if retflag {
// c:1443 — the enclosing list loop stops on retflag, so the
// command never runs. Mirror the forced status into the VM's
// own counter (the ported LASTVAL atomic is a separate store)
// and report "skip" so the emit-side jump lands past the
// statement, where the RETFLAG escape unwinds the function.
let forced =
crate::ported::builtin::LASTVAL.load(std::sync::atomic::Ordering::Relaxed);
vm.last_status = forced;
with_executor(|exec| exec.set_last_status(forced));
return Value::Int(1);
}
if donedebug2 {
// c:1511 — `if (donedebug != 2) execsimple(state);` and
// c:1519-1529 — the compound form skips the whole sublist and
// sets `donetrap = 1`.
crate::ported::exec::DONETRAP.store(1, std::sync::atomic::Ordering::Relaxed); // c:1527
return Value::Int(1);
}
Value::Int(0)
})
});
// Fatal-only abort check emitted between the pipes of an `&&` / `||`
// chain, where the full errexit check is suppressed. Mirrors ONLY the
// errflag arm of BUILTIN_ERREXIT_CHECK below: an errflag abandons the
// list in zsh, and no connector can consume it.
vm.register_builtin(BUILTIN_FATAL_ABORT_CHECK, |vm, _argc| {
use std::sync::atomic::Ordering;
// c:Src/exec.c:1390 — `while (wc_code(code) == WC_LIST && !breaks &&
// !retflag && !errflag)`: the enclosing list loops test the WHOLE
// errflag. A user interrupt sets ERRFLAG_INT and never ERRFLAG_ERROR
// (signals.c:457), so masking here let the rest of the list run after
// an interrupt:
// TRAPINT() { print T; return 1 }
// f() { print A; kill -INT $$; print C }; f; print B
// zsh: A T zshrs: A T B
//
// The gate is also NOT conditional on the shell being
// non-interactive. C's list loop is the same loop in both cases; an
// interactive shell survives the abort because `loop(toplevel=1)`
// resets the flag before it reads the next command line
// (c:Src/init.c:139/150 `errflag = 0;`, ported at
// ported/init.rs:2384/2394) — not because the list kept running. The
// `isset(INTERACTIVE)` exemption that used to sit here was the reason
// an interrupt was recorded and then ignored:
// kill -INT $$; print survived
// zsh: (nothing, exit 130) zshrs: survived, exit 0
// and it is why installing C's SIGINT handler (`intr()`,
// c:Src/init.c:1442) was unsafe before this — the handler sets
// ERRFLAG_INT and expects THIS gate to end the list.
let errflag_set = crate::ported::utils::errflag.load(Ordering::Relaxed) != 0;
if !errflag_set {
return Value::Int(0);
}
// CONTINUE_ON_ERROR does not reach here: C's list loop
// (c:Src/exec.c:1443) breaks on errflag whatever the option says,
// and only zsh_main's outer do-while re-enters loop() for the NEXT
// top-level line (c:Src/init.c:1960-1968, ported in
// vm_helper.rs execode's toplevel arm).
// Abort the chain with the failing command's own status intact —
// a cond syntax error left lastval=2 (c:Src/exec.c:5216-5221), and
// that 2 is what zsh exits with. Reading the executor's live
// lastval (not forcing 1) is the same rule the full check uses.
//
// An INTERRUPT is the one case where the executor's cell is not the
// live lastval. C has a single `lastval` global, and the SIGINT
// handler writes it directly (`lastval = 128 + SIGINT`,
// c:Src/signals.c:463) — as does a forced-return INT trap
// (`lastval = new_trap_return`, c:Src/signals.c:1202). zshrs splits
// that global in two (see BUILTIN_SUBLIST_FINISH): the handler and
// `dotrapargs` write `builtin::LASTVAL`, while the executor's cell
// holds whatever the interrupted command itself returned — 0 for the
// `kill` that raised the signal. Reading the executor here therefore
// threw the interrupt status away:
// <shell> -f -i -c 'kill -INT $$; print survived'
// zsh exit 130 zshrs exit 0
// and the same for an INT trap that returns non-zero (zsh exit 1).
// Take the handler's write for an interrupt, the executor's for
// everything else.
vm.last_status = if (crate::ported::utils::errflag.load(Ordering::Relaxed)
& crate::ported::zsh_h::ERRFLAG_INT)
!= 0
{
crate::ported::builtin::LASTVAL.load(Ordering::Relaxed)
} else {
with_executor(|exec| exec.last_status())
};
Value::Int(1)
});
vm.register_builtin(BUILTIN_PRINT_EXIT_VALUE, |vm, argc| {
// c:Src/exec.c:5498-5505 — the ANONYMOUS-FUNCTION report in
// execfuncdef:
// execshfunc(shf, args);
// ret = lastval;
// if (isset(PRINTEXITVALUE) && isset(SHINSTDIN) && lastval) {
// fprintf(stderr, "zsh: exit %lld\n", lastval);
// It has NO `!subsh` term, unlike execcmd_exec's site at
// c:4308-4309. `argc == 1` marks that call site (the compiler
// pushes a 1 before it); `argc == 0` is the per-command site.
let anon_site = argc >= 1 && vm.pop().to_int() != 0;
// c:Src/exec.c:4308-4316 — `if (isset(PRINTEXITVALUE) &&
// isset(SHINSTDIN) && lastval && !subsh) fprintf(stderr,
// "zsh: exit %lld\n", lastval);`
//
// SHINSTDIN keeps this to a shell reading its program from stdin
// (`zsh -f < script`, the interactive shell) — `-c` and script-file
// runs never report. `subsh` keeps it out of forked pipeline stages
// and `(...)` subshells, which is why zsh prints nothing for
// `false | true` or `(exit 3)`. A function BODY is silent for a
// different reason: c:Src/exec.c:6037 `opts[PRINTEXITVALUE] = 0`
// in doshfunc (ported at exec.rs), restored at c:6158.
let lastval = vm.last_status; // c:4309 lastval
if crate::ported::zsh_h::isset(crate::ported::zsh_h::PRINTEXITVALUE) // c:4308
&& crate::ported::zsh_h::isset(crate::ported::zsh_h::SHINSTDIN) // c:4308
&& lastval != 0 // c:4309
&& (anon_site
|| crate::ported::exec::subsh.load(std::sync::atomic::Ordering::Relaxed) == 0)
// c:4309 (`!subsh`; absent at the c:5498 anon-function site)
{
eprintln!("zsh: exit {lastval}"); // c:4311/4313
let _ = std::io::Write::flush(&mut std::io::stderr()); // c:4315 fflush(stderr)
}
Value::Status(0)
});
vm.register_builtin(BUILTIN_ERREXIT_CHECK, |vm, _argc| {
// Returns Value::Int(1) when the caller should jump to the
// current scope's return-patch landing (subshell-end / func-
// end / chunk-end). Returns Value::Int(0) otherwise. Emit
// side at `emit_errexit_check` pairs this with a JumpIfTrue
// → return_patches pattern so the caller can short-circuit.
//
// Four triggers:
// 1. RETFLAG set by a nested `return` / `exit` (eval,
// sourced file, called function). Unwind THIS scope so
// the flag propagates outward until something clears it.
// 2. EXIT_PENDING set (mostly subshell-context exits). Same
// propagation logic.
// 3. `set -e` + nonzero status — the classic errexit path.
// 4. errflag set in non-interactive mode — readonly
// reassign, bad redirect, parse error mid-expansion etc.
// Aborts the script (c:Src/init.c loop()).
use std::sync::atomic::Ordering;
let retflag = crate::ported::builtin::RETFLAG.load(Ordering::Relaxed);
// c:Src/exec.c:6198-6201 — "If we are in an exit trap, finish it
// first... we wouldn't set exit_pending if we were already in one."
// C's list loop (c:1443) never consults exit_pending at all;
// EXIT_PENDING is zshrs's own deferred-exit channel, and leaving it
// armed while the EXIT trap body runs made every command after the
// trap's FIRST one get skipped:
// h(){ echo a; echo b }; trap h EXIT; f(){ exit }; f
// zsh: a b zshrs: a
// `in_exit_trap` is the same counter C tests at c:6201.
let exit_pending = if crate::ported::signals::in_exit_trap.load(Ordering::Relaxed) != 0 {
0
} else {
crate::ported::builtin::EXIT_PENDING.load(Ordering::Relaxed)
};
// c:Src/exec.c:1571-1603 — `sublist_done:` runs the ZERR trap for
// the sublist that just failed. It is NOT gated on retflag: C only
// consults retflag at the TOP of the list loop (c:1370 `while
// (wc_code(code) == WC_LIST && !breaks && !retflag && !errflag)`),
// which stops the NEXT sublist — the current one still completes
// its sublist_done. So `return 5` fires the ERR trap on its way out.
//
// zshrs's escape short-circuit below returns before ever reaching
// the ZERR fire, so a `return N` inside a try-list skipped the trap:
// f() { { return 5 } always { print fin } }; f
// printed `fin / err=5` where zsh prints `err=5 / fin / err=5`.
// (Plain `f() { return 5 }` matched by luck — the inner fire was
// missing but the OUTER sublist fired instead, since doshfunc had
// cleared retflag by then and DONETRAP was still 0.)
//
// `exit` is deliberately excluded: C's `exit` goes zexit() →
// realexit(), leaving the process without ever reaching
// sublist_done. Verified: `zsh -fc 'trap "print err" ERR; f(){ exit
// 5 }; f'` prints nothing.
if retflag != 0 && exit_pending == 0 {
let last = vm.last_status;
// c:1651 — `!donetrap` as it stood when this sublist finished.
let donetrap_at_entry = crate::ported::exec::DONETRAP.load(Ordering::Relaxed) != 0;
// c:1598-1603 — same DONETRAP gate as the non-escape path below.
// ksh93 does not fire ERR for `return N` itself; the call site does
// (doshfunc re-arms donetrap for ksh93).
if last != 0
&& !donetrap_at_entry
&& !crate::extensions::dash_mode::ksh93_mode()
&& zerr_sigtrapped()
{
// c:Src/signals.c:1085-1087 — `int obreaks = breaks; int
// oretflag = retflag; int olastval = lastval;` and c:1220-1222
// — `breaks += obreaks; retflag = oretflag;`. dotrapargs
// brackets EVERY trap dispatch with this save/restore because
// the trap body runs as a normal list and would otherwise
// consume the caller's control-flow flags. That matters
// exactly here: we are firing ZERR while retflag is SET, and a
// FUNCTION-form trap (`TRAPZERR() { … }`) goes through
// doshfunc, whose epilogue eats retflag outright
// (c:Src/exec.c:6047-6052 `if (retflag) { retflag = 0; breaks
// = funcsave->breaks; }`). Without the bracket the pending
// `return 5` was swallowed by its own ERR trap and the
// function ran on:
// TRAPZERR() { print z }; f() { { return 2 } always { : }
// print after }; f
// printed `after`, where zsh returns from f.
//
// zshrs's `dotrap` inlines the dispatch and does not carry
// dotrapargs' save/restore, so the bracket lives at this call
// site. lastval is restored too (c:1087 / c:1213 `lastval =
// olastval`) — the trap body's own commands must not become
// the caller's `$?`.
let obreaks = crate::ported::builtin::BREAKS.load(Ordering::Relaxed); // c:1085
let oretflag = crate::ported::builtin::RETFLAG.load(Ordering::Relaxed); // c:1086
let olastval = crate::ported::builtin::LASTVAL.load(Ordering::Relaxed); // c:1087
let _ = crate::ported::signals::dotrap(crate::ported::signals_h::SIGZERR); // c:1601
crate::ported::exec::DONETRAP.store(1, Ordering::Relaxed); // c:1602
crate::ported::builtin::BREAKS.store(obreaks, Ordering::Relaxed); // c:1220
crate::ported::builtin::RETFLAG.store(oretflag, Ordering::Relaxed); // c:1222
crate::ported::builtin::LASTVAL.store(olastval, Ordering::Relaxed);
// c:1213
}
// c:1660-1680 — the same sublist_done then applies ERR_EXIT /
// ERR_RETURN to the `return N` that ended it: `setopt errexit;
// trap 'echo e' ZERR; return 1` inside a function exits there.
if last != 0 && !donetrap_at_entry {
let _ = errexit_tail(last);
}
}
if retflag != 0 || exit_pending != 0 {
if exit_pending != 0 {
// c:Src/builtin.c zexit — the deferred exit carries its
// status in EXIT_VAL; sync it into the VM counter so
// the top-level unwind reports it as the script's exit
// (run_chunk returns vm.last_status). Without this, a
// POSIX-fatal `.` failure exited 127 (bin_dot's return)
// instead of C's exit(1) at Src/exec.c:4383.
vm.last_status = crate::ported::builtin::EXIT_VAL.load(Ordering::Relaxed) & 0xFF;
}
return Value::Int(1);
}
let errflag_set = (crate::ported::utils::errflag.load(Ordering::Relaxed)
& crate::ported::zsh_h::ERRFLAG_ERROR)
!= 0;
// c:Src/init.c:1960-1968 — CONTINUE_ON_ERROR is decided by
// zsh_main's outer do-while, which re-enters loop() for the next
// top-level LINE; the current list (and every enclosing list,
// loop and function body) still breaks on errflag here. The
// re-entry is ported in vm_helper.rs execode's toplevel arm.
if errflag_set && !crate::ported::zsh_h::isset(crate::ported::zsh_h::INTERACTIVE) {
// c:Src/exec.c execlist — every enclosing list loop runs
// `while (... && !errflag)`, so a set errflag breaks the
// CURRENT scope and the check in the enclosing scope
// breaks THAT one, all the way out. Leave errflag SET —
// do NOT convert it to EXIT_PENDING: a process-exit
// signal tunnels through the containment boundaries C
// has, namely eval (Src/builtin.c:6221 `errflag &=
// ~ERRFLAG_ERROR`), source (Src/init.c:1663 same), fork
// boundaries (subshell/cmdsubst — child's errflag dies
// with the child), and the interactive toplevel
// (Src/init.c:139). Those boundaries clear errflag
// themselves and execution continues past them; with
// EXIT_PENDING armed here, `eval 'assoc=(odd)'; echo
// after` aborted the whole script where zsh 5.9 prints
// `after` (eval status 1). Bug #74's function case
// (`f() { local -r x=5; x=10; }; f; echo after`) still
// aborts: the function scope unwinds on THIS check, and
// the caller's next ERREXIT_CHECK sees the still-set
// errflag and unwinds too — exactly C's propagation.
//
// c:Src/init.c:234 — loop() BREAKS on errflag and
// zsh_main exits with the UNTOUCHED lastval, NOT a
// forced 1: `typeset -i x=3#8` (math error during the
// assignment, before typeset sets a status) exits 0 in
// zsh; a cond syntax error set lastval=2 (exec.c:5216-
// 5221) and zsh exits 2; the readonly-reassign case
// exits 1 because ITS lastval is 1. Sync the VM counter
// from the executor's live lastval instead of
// overwriting.
vm.last_status = with_executor(|exec| exec.last_status());
// c:Src/exec.c:1598-1603 — `sublist_done:` runs the ZERR trap
// for the failed sublist BEFORE the enclosing list loop breaks
// on errflag (`while (... && !errflag)` at c:1370). So an
// errflag-setting command (readonly reassign, bad redirect)
// must fire ZERR on its way out, exactly like the retflag
// escape above and the non-escape fall-through below. Without
// this the errflag early-return pre-empted the ZERR block
// further down, so `TRAPZERR() { … }; typeset -r ro=1; ro=2`
// aborted the script (correct) but never fired the trap. Same
// DONETRAP gate + dotrapargs save/restore bracket
// (c:signals.c:1085-1087 / 1213-1222) as the retflag branch:
// a function-form TRAPZERR runs through doshfunc and would
// otherwise consume the caller's breaks/retflag/lastval.
let last = with_executor(|exec| exec.last_status());
if last != 0 && crate::ported::exec::DONETRAP.load(Ordering::Relaxed) == 0 && zerr_sigtrapped() {
let obreaks = crate::ported::builtin::BREAKS.load(Ordering::Relaxed); // c:1085
let oretflag = crate::ported::builtin::RETFLAG.load(Ordering::Relaxed); // c:1086
let olastval = crate::ported::builtin::LASTVAL.load(Ordering::Relaxed); // c:1087
// c:Src/signals.c:1101 — dotrapargs returns early if errflag
// is set, and c:1174/1205-1218 brackets the dispatch with
// `traperr = errflag` … restore. The failing assignment left
// errflag SET, so the trap body (`print zerr`) would itself
// bail on the first op. Clear errflag across the dispatch so
// the body runs, then restore it so the script still aborts.
let oerrflag = crate::ported::utils::errflag.load(Ordering::Relaxed); // c:1174
crate::ported::utils::errflag.store(0, Ordering::Relaxed);
let _ = crate::ported::signals::dotrap(crate::ported::signals_h::SIGZERR); // c:1601
crate::ported::utils::errflag.store(oerrflag, Ordering::Relaxed); // c:1216
crate::ported::exec::DONETRAP.store(1, Ordering::Relaxed); // c:1602
crate::ported::builtin::BREAKS.store(obreaks, Ordering::Relaxed); // c:1220
crate::ported::builtin::RETFLAG.store(oretflag, Ordering::Relaxed); // c:1222
crate::ported::builtin::LASTVAL.store(olastval, Ordering::Relaxed);
// c:1213
}
return Value::Int(1);
}
let last = vm.last_status;
if last == 0 {
return Value::Int(0);
}
// c:Src/exec.c:1598 `if (!this_noerrexit && !donetrap &&
// !this_donetrap)` — gate the ZERR trap fire on DONETRAP so
// an inner sublist (e.g. `false` inside a function) that
// already fired ZERR doesn't fire it AGAIN at the outer
// sublist's post-command check (after the function
// returned non-zero). Bug #303 in docs/BUGS.md. DONETRAP
// is reset at top-level statement boundaries via
// BUILTIN_DONETRAP_RESET (compile_list emit at
// compile_zsh.rs).
let already_done = crate::ported::exec::DONETRAP.load(Ordering::Relaxed) != 0;
// bash `set -E`: the failing function call fires ERR again after the
// inner command already did (`f() { false; }; f` runs the trap twice).
let already_done = already_done
&& !(crate::extensions::dash_mode::bash_mode()
&& crate::extensions::dash_mode::bash_set_o_get("errtrace"));
// c:Src/exec.c:1652-1653 —
// if (sigtrapped[SIGZERR] && lastval &&
// !(noerrexit & NOERREXIT_EXIT)) {
// The ZERR half of the check is gated on the SAME runtime bit as
// the errexit half below. Without this an `&&`/`||` operand — or
// anything it calls — still fired ZERR, so
// TRAPZERR(){ print E }; f(){ print f; false; }; f && t
// printed E where zsh is silent (C03traps:14, E01options:18).
let zerr_suppressed = (crate::ported::exec::noerrexit.load(Ordering::Relaxed)
& crate::ported::zsh_h::NOERREXIT_EXIT)
!= 0; // c:1653
// c:1652 — `sigtrapped[SIGZERR] &&`: with no ZERR trap the block
// never runs, so `donetrap` stays 0 and cannot spare a caller's
// errexit / errreturn below.
if !already_done && !zerr_suppressed && zerr_sigtrapped() {
// c:Src/signals.c:1245 dotrap(SIGZERR) — canonical ZERR
// trap dispatch. Fires whenever a command exits
// non-zero.
let oretflag = crate::ported::builtin::RETFLAG.load(Ordering::Relaxed);
// c:Src/exec.c:1654-1657 — `int eflag = errflag; errflag = 0;
// dotrap(SIGZERR); errflag = eflag;`: an error raised INSIDE
// the trap body (a `set -u` failure) ends the trap, not the
// list — `set -u; trap 'print t; : $u; print x' ZERR; false;
// print after` prints `after`. Without the restore the
// trap's errflag aborted the enclosing list.
let eflag = crate::ported::utils::errflag.load(Ordering::Relaxed); // c:1654
crate::ported::utils::errflag.store(0, Ordering::Relaxed); // c:1655
let _ = crate::ported::signals::dotrap(crate::ported::signals_h::SIGZERR); // c:1656
// c:Src/subst.c:3355-3366 — the one error the restore must not
// drop: `${v?}` in a NON-interactive shell never gets here in C,
// it has already left through `zexit(1)`. The subst port defers
// that exit through ERRFLAG_HARD, so carry the bit across.
let hard = if isset(crate::ported::zsh_h::INTERACTIVE) {
0
} else {
crate::ported::utils::errflag.load(Ordering::Relaxed) & crate::ported::zsh_h::ERRFLAG_HARD
};
crate::ported::utils::errflag.store(eflag | hard, Ordering::Relaxed); // c:1657
// c:1602 — `donetrap = 1;` after firing.
crate::ported::exec::DONETRAP.store(1, Ordering::Relaxed);
// c:Src/signals.c:1201-1203 — a trap body that ran `return N`
// comes back with `lastval = new_trap_return` and `retflag =
// 1`; C's enclosing `while (wc_code(code) == WC_LIST &&
// !breaks && !retflag && !errflag)` (c:Src/exec.c:1443) then
// abandons the rest of the list and the containing function
// returns that status. zshrs's list loop is the VM, which
// reads `vm.last_status` / the executor's counter rather than
// the ported LASTVAL atomic — so mirror the forced status
// across and report "abort" to the caller. Without this
// fn(){ trap 'print t; return 42' ZERR; false; print B }
// ran `print B` and returned 0.
if oretflag == 0 && crate::ported::builtin::RETFLAG.load(Ordering::Relaxed) != 0 {
let forced = crate::ported::builtin::LASTVAL.load(Ordering::Relaxed); // c:1201
vm.last_status = forced;
with_executor(|exec| exec.set_last_status(forced));
return Value::Int(1); // c:1443 — list loop stops on retflag
}
}
// c:Src/exec.c:1651 — `if (!this_noerrexit && !donetrap &&
// !this_donetrap)` gates the errexit / errreturn half too, not only
// ZERR: a ZERR trap that already fired inside a function called by
// this sublist also spares the caller the top-level ERR_RETURN-as-
// ERR_EXIT (`setopt errreturn; trap 'echo z' ZERR; f() { false };
// f; echo s` prints `z` then `s`).
if already_done {
return Value::Int(0);
}
errexit_tail(last)
});
// BUILTIN_ASSIGN_ONLY_STATUS — status of an assignment-only
// simple command. c:Src/exec.c:3393-3396 (execcmd_exec, no
// command word + varspc): `if (errflag) lastval = 1; else
// lastval = cmdoutval;`; same shape at c:1322 (execsimple
// WC_ASSIGN: `lv = (errflag ? errflag : cmdoutval)`) and
// c:3977 (nullexec=2 redir variant). cmdoutval is the exit of
// a `$()` that ran in an RHS (already in vm.last_status via
// compile_assign's per-assign SetStatus), 0 otherwise. The
// store goes to the canonical LASTVAL too — that IS C's single
// `lastval` global; without it the errflag-abort path
// (BUILTIN_ERREXIT_CHECK trigger 4) syncs vm.last_status from
// a stale LASTVAL and `readonly r=1; r=2` exited 0, not 1.
vm.register_builtin(BUILTIN_ASSIGN_ONLY_STATUS, |vm, _argc| {
use std::sync::atomic::Ordering;
let had_cmd_subst = vm.pop().to_int() != 0;
let errflag_set = (crate::ported::utils::errflag.load(Ordering::Relaxed)
& crate::ported::zsh_h::ERRFLAG_ERROR)
!= 0;
// c:Src/exec.c addvars — `if (!pm) { lastval = 1; if
// (!cmdoutval) cmdoutval = 1; }` (assignment-failed cheat).
let assign_failed = ASSIGN_FAILED_FLAG.swap(false, std::sync::atomic::Ordering::Relaxed);
let _ = had_cmd_subst;
if assign_failed && crate::ported::exec::cmdoutval.load(Ordering::Relaxed) == 0 {
// c:Src/exec.c:2662-2663 — `if (!cmdoutval) cmdoutval = 1;`
crate::ported::exec::cmdoutval.store(1, Ordering::Relaxed);
}
let status = if errflag_set || assign_failed {
1 // c:Src/exec.c:3394 `lastval = 1` / addvars cmdoutval=1
} else {
// c:3396 `lastval = cmdoutval` — reset to 0 when the command
// started (c:2796 / c:1368, BUILTIN_CMDOUTVAL_RESET), then set by
// any `$(...)` that ran in it, RHS or subscript alike.
crate::ported::exec::cmdoutval.load(Ordering::Relaxed)
};
with_executor(|exec| exec.set_last_status(status));
// c:Src/jobs.c deletefilelist — a `=(cmd)` temp file is bound to the
// JOB of the command that created it and unlinked when that command
// completes (Src/exec.c:5588 for the shfunc case; the simple-command
// job's filelist likewise). An assignment-only command like
// `f==(cmd)` has no consuming builtin/exec, so the PsubFdGuard that
// cleans consuming commands never fires — the temp leaked and a later
// `$(<$f)` / `[[ -f $f ]]` still saw it, where zsh deletes it at the
// end of the assignment (verified: even `f==(x) && cat $f` fails).
// Clean here so the assignment command is the temp's job boundary.
close_pending_psub_fds();
Value::Status(status)
});
// `${var:-default}` / `${var:=default}` / `${var:?error}` / `${var:+alt}`
// Pops [name, op_byte, rhs] (rhs popped first). Returns the modified
// value as Value::Str. Handles unset/empty distinction (`:-` etc.
// treat empty same as unset, matching POSIX).
// BUILTIN_PARAM_DEFAULT_FAMILY — `${var-x}` / `${var:-x}` / `${var=x}` /
// `${var:=x}` / `${var?x}` / `${var:?x}` / `${var+x}` / `${var:+x}`.
// PURE PASSTHRU: pop name + op + rhs, reconstruct the canonical
// brace expression, hand to `subst::paramsubst` (C port of
// `Src/subst.c::paramsubst`). All "missing vs empty" gating,
// nounset suppression, default-evaluation, and elide-empty-words
// semantics live inside paramsubst.
vm.register_builtin(BUILTIN_PARAM_DEFAULT_FAMILY, |vm, argc| {
// c:Src/subst.c:1761 — the word's PREFORK_SINGLE bit, pushed last by
// compile_zsh::emit_param_modifier (see the note there).
let pf_flags = if argc as usize > 3 && vm.pop().to_int() != 0 {
crate::ported::zsh_h::PREFORK_SINGLE
} else {
0
};
let rhs = vm.pop().to_str();
let op = vm.pop().to_int() as u8;
let name = vm.pop().to_str();
// c:Src/params.c:428-430 — `IPDEF9("*", &pparams, …)` and
// `IPDEF9("argv", &pparams, …)` are ONE parameter, and the only shape
// discriminator in the read path is c:Src/params.c:2251
// `isvarat = (t[0] == '@' && !t[1])`, which the name `argv` misses just
// as `*` does. So `${argv:-…}` IS `${*:-…}`. The rebuilt body below
// reaches `paramsubst`, whose "is the parameter set" probe for this
// operator family tests only the literal `@` / `*` names — `argv` fell
// through to an ordinary lookup, came back UNSET, and
// `set -- x y; ${argv:-nope}` took the default where zsh takes the
// positionals. Normalising the spelling reuses every already-correct
// `$*` arm, the same way the compiler's `bare_target` does for `$argv`
// / `${argv}`. Every other modifier family (`#`, `%`, `/`, `:off:len`)
// already resolves `argv` and is left alone.
//
// NOT the assigning ops. c:Src/subst.c:3690-3697 routes `${name:=…}` /
// `${name=…}` through `setsparam`/`setaparam` on the NAME, and zsh
// rejects the `*` spelling there ("not an identifier: *"), while
// `${argv=…}` assigns the positional list. `${+name}` is the same
// story from the other side — zsh answers "bad substitution" for
// `${+*}` but 0/1 for `${+argv}`. Those three keep the literal name.
let name = if name == "argv" && !matches!(op, 1 | 5 | 8) {
"*".to_string()
} else {
name
};
// op=8 is the `${+name}` set-test prefix form (distinct from the
// `${name+rhs}` substitute-if-set suffix form which is op=7).
// Per compile_zsh.rs::parse_param_modifier: the `+` is emitted as
// a leading sigil and `rhs` is empty.
let body = if op == 8 {
format!("${{+{}}}", name)
} else {
let op_str = match op {
0 => ":-",
1 => ":=",
2 => ":?",
3 => ":+",
4 => "-",
5 => "=",
6 => "?",
7 => "+",
_ => "-",
};
format!("${{{}{}{}}}", name, op_str, rhs)
};
paramsubst_to_value_status(vm, &body, pf_flags)
});
// `${var:offset[:length]}` — substring. Pops [name, offset, length].
// length == -1 means "rest of string". Negative offset counts from end.
// BUILTIN_PARAM_SUBSTRING — `${var:offset:length}` literal-int form.
// PURE PASSTHRU: reconstruct `${name:offset:length}` and route
// through `subst::paramsubst`. Length sentinel `i64::MIN` =
// "no length given" (omit the `:length` portion).
//
// c:Src/subst.c:1571,3781 — `${name:-N}` is the colon-default
// operator, NOT a substring with negative offset. zsh's lexical
// rule disambiguates via a literal space: `${name: -N}` (space
// before `-`) is the substring form. The reconstructed body MUST
// preserve that space when offset < 0; otherwise paramsubst's
// `:-` dispatch fires on the synthesized `${name:-N}` body and
// returns N as the unset-default instead of slicing the last N
// chars. Length-form `${name:-N:M}` has the same trap.
vm.register_builtin(BUILTIN_PARAM_SUBSTRING, |vm, argc| {
// c:Src/subst.c:1761 — the word's PREFORK_SINGLE bit, pushed last by
// compile_zsh::emit_param_modifier (see the note there).
let pf_flags = if argc as usize > 3 && vm.pop().to_int() != 0 {
crate::ported::zsh_h::PREFORK_SINGLE
} else {
0
};
let length = vm.pop().to_int();
let offset = vm.pop().to_int();
let name = vm.pop().to_str();
// !!! DASH-STRICT GATE !!! dash/ash have no `${var:offset:length}`
// substring expansion (it is a "Bad substitution"); bash/ksh/sh do.
if crate::dash_mode::dash_strict() {
crate::ported::utils::zerr("bad substitution");
crate::ported::utils::errflag.fetch_or(
crate::ported::zsh_h::ERRFLAG_ERROR,
std::sync::atomic::Ordering::Relaxed,
);
with_executor(|exec| exec.set_last_status(1));
return Value::str("");
}
let off_sep = if offset < 0 { " " } else { "" };
let body = if length == i64::MIN {
format!("${{{}:{}{}}}", name, off_sep, offset)
} else {
format!("${{{}:{}{}:{}}}", name, off_sep, offset, length)
};
paramsubst_to_value_status(vm, &body, pf_flags)
});
// BUILTIN_PARAM_SUBSTRING_EXPR — `${var:offset_expr[:length_expr]}` form.
// PURE PASSTHRU: rebuild `${name:offset:length}` using the
// expression text verbatim (paramsubst's offset/length
// parser evaluates arith / param refs itself).
//
// c:Src/subst.c:1571,3781 — same `:-` disambiguation trap as
// BUILTIN_PARAM_SUBSTRING. The expression text may itself start
// with `-` (e.g. `${VAR:$((-1))}` arith resolves at the body-
// assembly layer in some upstream paths, leaving `-1` in
// off_expr). Insert a leading space when off_expr starts with
// `-` so paramsubst's check_colon_subscript (subst.c:1571)
// accepts the operand as a math expression instead of the
// `:-` operator catching it.
vm.register_builtin(BUILTIN_PARAM_SUBSTRING_EXPR, |vm, argc| {
// c:Src/subst.c:1761 — the word's PREFORK_SINGLE bit, pushed last by
// compile_zsh::emit_param_modifier (see the note there).
let pf_flags = if argc as usize > 4 && vm.pop().to_int() != 0 {
crate::ported::zsh_h::PREFORK_SINGLE
} else {
0
};
let has_len = vm.pop().to_int() != 0;
let len_expr = vm.pop().to_str();
let off_expr = vm.pop().to_str();
let name = vm.pop().to_str();
let off_sep = if off_expr.starts_with('-') { " " } else { "" };
let body = if has_len {
format!("${{{}:{}{}:{}}}", name, off_sep, off_expr, len_expr)
} else {
format!("${{{}:{}{}}}", name, off_sep, off_expr)
};
paramsubst_to_value_status(vm, &body, pf_flags)
});
// `${var#pat}` / `${var##pat}` / `${var%pat}` / `${var%%pat}`
// Pops [name, pattern, op_byte]. op: 0=`#` short-prefix, 1=`##` long,
// 2=`%` short-suffix, 3=`%%` long. Glob-pattern matching via the
// existing glob_match_static helper.
// BUILTIN_PARAM_STRIP — `${var#pat}` / `${var##pat}` / `${var%pat}` /
// `${var%%pat}`. PURE PASSTHRU: reconstruct the brace expression
// and route through `subst::paramsubst`. (M)/(S) flags arrive
// through SUB_FLAGS (already inside paramsubst's scope), so we
// just clear the bridge-side cached read.
vm.register_builtin(BUILTIN_PARAM_STRIP, |vm, argc| {
// c:Src/subst.c:1761 — the word's PREFORK_SINGLE bit, pushed last by
// compile_zsh::emit_param_modifier (see the note there).
let pf_flags = if argc as usize > 4 && vm.pop().to_int() != 0 {
crate::ported::zsh_h::PREFORK_SINGLE
} else {
0
};
let _dq_flag = vm.pop().to_int() != 0;
let op = vm.pop().to_int() as u8;
let pattern = vm.pop().to_str();
let name = vm.pop().to_str();
let op_str = match op {
0 => "#",
1 => "##",
2 => "%",
3 => "%%",
_ => "#",
};
let body = format!("${{{}{}{}}}", name, op_str, pattern);
paramsubst_to_value_status(vm, &body, pf_flags)
});
// `$((expr))` — pops [expr_string], evaluates via MathEval which
// honors integer-vs-float distinction (zsh-compatible). Returns
// the result as Value::Str so it can be Concat'd into surrounding
// word context.
vm.register_builtin(BUILTIN_ARITH_LASTBASE, |vm, _argc| {
// See [`BUILTIN_ARITH_LASTBASE`]: `lastbase = -1` at the head of an
// evaluation, and the literal's own base where the compiler lexed one.
let base = vm.pop();
let base = match base {
Value::Int(n) => n as i32,
other => other.to_str().parse::<i32>().unwrap_or(-1),
};
crate::ported::math::set_lastbase(base);
Value::Int(i64::from(base))
});
vm.register_builtin(BUILTIN_ARITH_EVAL, |vm, _argc| {
// Pure path: evaluate expr, return string. errflag may be
// set by arithsubst on math error; the caller decides
// whether to clear it. For `(( ... ))` (math command) the
// compile_arith path clears via BUILTIN_ARITH_CMD_FINISH;
// for `$((... ))` (substitution inside another command)
// errflag stays set so the surrounding command aborts —
// matches c:Src/math.c "math errors propagate as errflag
// through the containing word expansion".
let expr = vm.pop().to_str();
let result = crate::ported::subst::arithsubst(&expr, "", "");
let _ = vm; // silence unused warning when no math error path mutates
Value::str(result)
});
// After-call hook used by compile_arith's `(( ... ))` path: when
// arithsubst set errflag (math error), clear it and signal
// status=2 in vm.last_status — matches zsh's c:exec.c arith-
// failure: the math command exits 2 and the script continues.
vm.register_builtin(BUILTIN_ARITH_CMD_FINISH, |vm, _argc| {
use std::sync::atomic::Ordering;
let live = crate::ported::utils::errflag.load(Ordering::Relaxed);
let err = live & crate::ported::zsh_h::ERRFLAG_ERROR;
let hard = live & crate::ported::zsh_h::ERRFLAG_HARD;
if err != 0 {
// c:Src/subst.c:3344 — when `${var:?msg}` fires, errflag
// is OR'd with ERRFLAG_HARD to signal a script-abort
// error (vs a recoverable math error like `$((1/0))`).
// Clear only the ERRFLAG_ERROR bit; preserve
// ERRFLAG_HARD so the next ERREXIT_CHECK aborts the
// script. Bug #193 in docs/BUGS.md.
if hard != 0 {
// Keep ERRFLAG_HARD AND ERRFLAG_ERROR set so the
// script-abort gate downstream still fires.
vm.last_status = 2;
Value::Status(2)
} else {
crate::ported::utils::errflag
.fetch_and(!crate::ported::zsh_h::ERRFLAG_ERROR, Ordering::Relaxed);
vm.last_status = 2;
Value::Status(2)
}
} else {
Value::Status(vm.last_status)
}
});
// `$(cmd)` — pops [cmd_string], routes through
// run_command_substitution which performs an in-process pipe-capture.
// Avoids the Op::CmdSubst sub-chunk word-emit bug
// (`printf "a\nb"` produced "anb" via that path). Returns trimmed
// output (trailing newlines stripped per POSIX cmd-sub semantics).
vm.register_builtin(BUILTIN_CMD_SUBST_TEXT, |vm, _argc| {
let cmd = vm.pop().to_str();
// c:Src/exec.c:4727-4729 (getoutput) — `if (!isset(EXECOPT)) return
// newlinklist();`: under NO_EXEC the substitution yields nothing and
// runs nothing, `$(<file)` included (that test is ahead of c:4731).
if !isset(crate::ported::zsh_h::EXECOPT) {
return Value::str(String::new());
}
// The enclosing word's `BUILTIN_WORD_DEFER_EMPTIES` declaration
// covers that word's own segments, not the words of a command run
// inside it (`PRE$(f)${a}POST` — `f`'s own words are finished words
// and owe c:183-186 where they stand). Suspend it for the call.
let saved_defer = crate::ported::subst::PARAMSUBST_AFFIXES_DEFERRED.with(|c| c.get());
crate::ported::subst::PARAMSUBST_AFFIXES_DEFERRED.with(|c| c.set(0));
// Inherit live $? into the inner shell so cmd-subst sees the
// parent's most recent exit. Same rationale as the mode-3
// backtick path above.
let live_status = vm.last_status;
let result = with_executor(|exec| {
exec.set_last_status(live_status);
exec.run_command_substitution(&cmd)
});
// Mirror run_command_substitution's exec.last_status side
// effect into the VM's live counter so a containing
// assignment's BUILTIN_SET_VAR — which reads vm.last_status
// — sees the cmd-subst's exit. Without this, `a=$(false);
// echo $?` reads stale 0 (vm.last_status was zeroed by
// compile_assign's prelude SetStatus, and run_cmd_subst only
// updated exec.last_status). Pull the value back through
// exec since it owns the canonical post-subst record.
let cs_status = with_executor(|exec| exec.last_status());
vm.last_status = cs_status;
// c:Src/exec.c — a command substitution running during a
// command's word expansion makes its exit the status of an
// otherwise-empty command (`$(exit 5)` → 5). Flag it so
// BUILTIN_EXEC_DYNAMIC's null-command branch keeps `$?` instead
// of resetting to 0.
crate::ported::exec::use_cmdoutval.store(1, std::sync::atomic::Ordering::Relaxed);
// Hand the enclosing word's declaration back — its remaining
// segments are still part of that word.
crate::ported::subst::PARAMSUBST_AFFIXES_DEFERRED.with(|c| c.set(saved_defer));
Value::str(result)
});
// Text-based word expansion. Pops [preserved_text, mode_byte].
// mode_byte:
// 0 = Default — expand_string + xpandbraces + expand_glob
// 1 = DoubleQuoted — strip outer `"…"`, expand_string only
// (no brace, no glob — DQ semantics)
// 2 = SingleQuoted — strip outer `'…'`, no expansion
// (kept for symmetry; Snull early-return covers most SQ)
// 3 = AltBackquote — strip backticks, run as cmd-sub
// 7 = RedirTarget — same as Default but glob gated on MULTIOS
// (c:Src/glob.c:2161-2167 xpandredir)
// 8 = unquoted assignment VALUE — same as 6 plus PREFORK_SINGLE
// (c:Src/exec.c:2603 / :4239-4241)
// 9 = singsub word — mode 0 plus PREFORK_SINGLE and nothing else
// (c:Src/subst.c:514-520 `prefork(&foo, PREFORK_SINGLE, NULL)`:
// the `case` WORD c:Src/loop.c:611, every `[[ … ]]` operand
// c:Src/cond.c:53). No PREFORK_ASSIGN — filesub's colon-walk
// is assignment-only (c:Src/subst.c:689).
// Single result → Value::str; multi → Value::Array.
vm.register_builtin(BUILTIN_EXPAND_TEXT, |vm, _argc| {
let mode = vm.pop().to_int() as u8;
let text = vm.pop().to_str();
// Sync vm.last_status → exec.last_status so cmd-subst (mode 3)
// and any nested $? reads inside singsub see the live `$?`
// from the most recent VM op. Without this, cmd-subst inside
// arg-eval saw a stale exec.last_status that was zeroed at
// the start of the current statement. Direct port of zsh's
// pre-cmdsubst lastval propagation per Src/exec.c:4770.
let live_status = vm.last_status;
with_executor(|exec| exec.set_last_status(live_status));
let result_value = with_executor(|exec| match mode {
// Mode 1 = DoubleQuoted (argument context).
// Mode 5 = DoubleQuoted in scalar-assignment context.
// Both share the same DQ unescape pre-processing; mode 5
// additionally bumps `in_scalar_assign` so subst_port's
// paramsubst sees ssub=true and suppresses split flags
// `(f)` / `(s:STR:)` / `(0)` per Src/subst.c:1759 +
// Src/exec.c::addvars line 2546 (the PREFORK_SINGLE bit
// C zsh sets when prefork-ing the assignment RHS).
1 | 5 => {
// DoubleQuoted: strip outer `"…"` if present. In DQ
// context, `\` escapes the DQ-special chars `$`, `` ` ``,
// `"`, `\`. zsh's expand_string expects the lexer's
// `\0X` literal-marker for an already-escaped char, so
// we pre-process: `\$` → `\0$`, `\\` → `\0\`, etc. Then
// expand_string handles the rest.
let inner = if text.len() >= 2 && text.starts_with('"') && text.ends_with('"') {
&text[1..text.len() - 1]
} else {
text.as_str()
};
// The lexer's dquote_parse (Src/lex.c) already tokenized
// DQ contents: `$` → Qstring (\u{e18c}), `\$`/`\\`/`\"`/
// `` \` `` → Bnull (\u{e19f}) + literal. Stringsubst /
// multsub recognize these markers natively. We pass
// `inner` through verbatim — no re-tokenization needed.
let prepped: String = inner.to_string();
// Tell parameter-flag application that we're inside
// double quotes — array-only flags ((o), (O), (n),
// (i), (M), (u)) must be no-ops here per zsh.
exec.in_dq_context += 1;
if mode == 5 {
exec.in_scalar_assign += 1;
}
// Mode 1 = argv DQ word; mode 5 = scalar-assign RHS.
// In C zsh, the corresponding prefork-on-list paths
// are: argv → `prefork(argv_list, 0)` returns multi-
// word LinkList (Src/exec.c::execcmd), assignment →
// `prefork(rhs_list, PREFORK_SINGLE|PREFORK_ASSIGN)`
// returns single-word (Src/exec.c::addvars line
// 2546). zshrs's `multsub` (Src/subst.c:544) is the
// multi-result variant; `singsub` (Src/subst.c:514)
// asserts ≤1 node. Mode 5 keeps singsub; mode 1
// switches to multsub so `"${(@)arr}"`/`"$@"`/
// `"${arr[@]}"` in argv context emit multiple words
// as the C path would.
// c:Src/lex.c untokenize — the final argv pass C runs
// on every expanded word (glob.c:1862 / exec.c) drops
// the Nularg empty-word sentinel remnulargs left in
// place and folds any remaining token chars. Without
// it, quoted splits with empty pieces
// ("${(s:|:)x}" on "|a|b|") leak Nularg into argv.
let result_value = if mode == 5 {
let out = crate::ported::subst::singsub(&prepped);
if crate::ported::subst::PREFORK_STOPPED.with(|c| c.get()) {
// Stopped by an `(e)` NULL: the node keeps its quote
// tokens (no remnulargs), rendered by C's untokenize
// (c:Src/exec.c:2134): `v="pre${(e)a}post"` → `"pre`.
Value::str(crate::ported::lex::untokenize_ztokens(&out))
} else {
Value::str(crate::ported::lex::untokenize(&out))
}
} else {
// c:Src/subst.c:3892-3895 — `if (isarr) l->list.flags |=
// LF_ARRAY; else l->list.flags &= ~LF_ARRAY;`. Clear the
// carrier BEFORE the expansion so a word that runs no
// paramsubst at all reads `false` rather than some earlier
// expansion's stamp — the same reset the unquoted arm does
// before its own multsub.
crate::ported::subst::PARAMSUBST_LF_ARRAY.with(|c| c.set(false));
let (_first, nodes, _ms_ws, _ret) = crate::ported::subst::multsub(&prepped, 0);
// Read immediately: anything below can re-enter paramsubst
// and overwrite the cell. This is C's `isarr` for the
// OUTERMOST expansion of this word — c:4245 `if (isarr)`.
let seg_is_array = crate::ported::subst::PARAMSUBST_LF_ARRAY.with(|c| c.get());
// c:Src/subst.c:655 — multsub returns Vec::new()
// for zero-word results (quoted array splat that
// resolved to empty array). Surface as
// Value::Array(vec![]) so the downstream array
// assignment / argv flattening sees ZERO args.
// Previous Rust port returned Value::str("") which
// surfaced as ONE empty arg. Bug #120 in
// docs/BUGS.md.
if crate::ported::subst::PREFORK_STOPPED.with(|c| c.get()) {
// An `(e)` NULL stopped prefork: every node already in
// the list stays (c:Src/subst.c:4383-4394 inserted the
// elements before the failing one, the first joined to
// the text before the `$`), unexpanded, with its quote
// tokens rendered by untokenize (c:Src/exec.c:2134).
stopped_nodes_value(nodes)
} else if nodes.is_empty() {
// c:Src/subst.c:4245 `if (isarr)` gates the array emit
// block, and c:4362-4365 `if (plan9) { uremnode(l, n);
// return n; }` deletes the WHOLE word from inside it —
// so whether a zero-word expansion removes its word is
// decided by THIS expansion's own `isarr`, never by the
// previous one's. `Value::Array(vec![])` cannot carry
// the bit, so record it here exactly as the unquoted
// arm does (`note_empty_is_scalar(!(seg_zero_words &&
// seg_is_array))`). Without the write the cell still
// held an unrelated earlier expansion's value, and a
// preceding empty-SCALAR read (`local x=$a[2]`, which
// leaves it `true`) resurrected a quoted empty-array
// word as one empty word under RC_EXPAND_PARAM:
// `e=(); r=( q "${e[@]:/A/B}" )` counted 2 where zsh
// counts 1. See EMPTY_EXPANSION_IS_SCALAR.
note_empty_is_scalar(!seg_is_array);
Value::array(Vec::new())
} else if nodes.len() == 1 {
Value::str(crate::ported::lex::untokenize(
&nodes.into_iter().next().unwrap(),
))
} else {
Value::array(
nodes
.into_iter()
.map(|n| Value::str(crate::ported::lex::untokenize(&n)))
.collect(),
)
}
};
if mode == 5 {
exec.in_scalar_assign -= 1;
}
exec.in_dq_context -= 1;
// c:Src/subst.c:326-327 → prefork c:142-147 — subst.rs's prefork
// stopped on an `(e)` NULL: the word is what preceded the `$`
// (c:1878). The lexer's opening Dnull stays in that node and
// untokenizes to a literal `"` when the word itself opened a
// double quote; this handler stripped those outer quotes above,
// so put it back. Mode 5 also carries UNQUOTED scalar-assignment
// words (`v=${(e)a}`), which have no quote to restore.
// PREFORK_CUT tells the words that follow to stay unexpanded.
if crate::ported::subst::PREFORK_STOPPED.with(|c| c.replace(false)) {
PREFORK_CUT.with(|c| c.set(true));
// The stopped nodes are rendered WITH their quote tokens
// (stopped_nodes_value, or ztokens for mode 5), so a lexer
// Dnull already shows as `"`. Only an ASCII `"` that this
// handler stripped above still has to be put back.
let opened_dq = text.starts_with('"');
let quote = if opened_dq { "\"" } else { "" };
// The quote belongs to the FIRST node, the one holding the
// text before the `$`; later nodes are whole elements.
return match result_value {
Value::Array(items) if !items.is_empty() => {
let mut words: Vec<Value> = items.iter().cloned().collect();
words[0] = Value::str(format!("{}{}", quote, words[0].to_str()));
Value::array(words)
}
other => Value::str(format!("{}{}", quote, other.to_str())),
};
}
result_value
}
2 => {
// SingleQuoted: pure literal, strip outer `'…'`.
let inner = if text.len() >= 2 && text.starts_with('\'') && text.ends_with('\'') {
&text[1..text.len() - 1]
} else {
text.as_str()
};
Value::str(inner.to_string())
}
3 => {
// Backquote command sub: strip outer backticks.
// Word-split the result on IFS when the surrounding
// word is unquoted — zsh: `print -l \`echo a b c\``
// emits one arg per word. The $(…) path applies the
// same split via BUILTIN_WORD_SPLIT after capture; do
// the equivalent here for the `…` form.
let inner = if text.len() >= 2 && text.starts_with('`') && text.ends_with('`') {
&text[1..text.len() - 1]
} else {
text.as_str()
};
// Apply the live VM status before running the inner
// shell so the inherited $? matches zsh's lastval
// propagation.
exec.set_last_status(live_status);
// c:Src/exec.c:4727-4729 — getoutput returns an empty list
// under NO_EXEC.
let captured = if isset(crate::ported::zsh_h::EXECOPT) {
exec.run_command_substitution(inner)
} else {
String::new()
};
let trimmed = captured.trim_end_matches('\n');
if exec.in_dq_context > 0 {
Value::str(trimmed.to_string())
} else {
let ifs = exec.scalar("IFS").unwrap_or_else(|| " \t\n".to_string());
let parts: Vec<Value> = trimmed
.split(|c: char| ifs.contains(c))
.filter(|s| !s.is_empty())
.map(|s| Value::str(s.to_string()))
.collect();
if parts.is_empty() {
Value::str(String::new())
} else if parts.len() == 1 {
parts.into_iter().next().unwrap()
} else {
Value::array(parts)
}
}
}
4 => {
// HeredocBody: expand variables / command-subst / arith
// but NOT glob or brace. Heredoc lines like `[42]` must
// pass through verbatim — running them through the
// default pipeline triggers NOMATCH on the literal.
Value::str(crate::ported::subst::singsub(&text))
}
_ => {
// Default (unquoted): the lexer's gettokstr already
// tokenized backslash-escapes (`\$` → Bnull+$, etc).
// Pass `text` through verbatim — multsub/stringsubst
// recognize the markers natively. No bridge-side
// re-tokenization needed.
//
// Mode 6 = unquoted RHS in scalar-assign context.
// Pass PREFORK_ASSIGN so prefork's filesub colon-walk
// fires per c:Src/exec.c:2546.
let prepped: String = text.clone();
if std::env::var("ZSHRS_TRACE_DEFP").is_ok() {
eprintln!(
"[TRACE_DEFP] text={:?} prepped={:?} mode={}",
text, prepped, mode
);
}
// Mode 8 = the unquoted VALUE of a `NAME=VALUE` assignment
// (bare statement or typeset-family argument). C preforks
// exactly that with `PREFORK_SINGLE|PREFORK_ASSIGN`
// (c:Src/exec.c:2603 and c:Src/exec.c:4239-4241); the
// PREFORK_SINGLE half is paramsubst's `ssub`
// (c:Src/subst.c:1761), which gates off the forced split at
// c:Src/subst.c:3913.
// Mode 9 = a word C expands with `singsub` (c:Src/subst.c:520
// `prefork(&foo, PREFORK_SINGLE, NULL)`) — the `case` WORD
// (c:Src/loop.c:611) and every `[[ … ]]` operand
// (c:Src/cond.c:53). PREFORK_SINGLE alone: it is paramsubst's
// `ssub` (c:Src/subst.c:1761), which takes the c:4226
// `if (isarr && ssub)` IFS[0] join BEFORE the c:4256 array-emit
// block, so the c:4264 unique fold and the c:4301-4326 sort do
// not run; it also turns off `xpandbraces` (c:Src/subst.c:170)
// and c:3913's `force_split`. NO PREFORK_ASSIGN — a `case`
// word / cond operand gets no `filesub` colon-walk.
// Mode 12 = the same `singsub`, for a `[[ … == pat ]]` RHS or a
// `case` arm. It differs from mode 9 only in what it hands
// BACK: the word keeps its tokens (see the untokenize below),
// because a pattern operand's guard still has to tell a
// metacharacter `shtokenize` armed from a raw byte of a value.
let pf_flags = if mode == 8 {
crate::ported::zsh_h::PREFORK_SINGLE | crate::ported::zsh_h::PREFORK_ASSIGN
} else if mode == 9 || mode == 12 {
crate::ported::zsh_h::PREFORK_SINGLE
} else if mode == 6 {
crate::ported::zsh_h::PREFORK_ASSIGN
} else if mode == 13 {
// Mode 13 = a command argument under MAGIC_EQUAL_SUBST +
// KSH_TYPESET: c:Src/exec.c:3353-3355 preforks it with
// `esprefork = PREFORK_TYPESET`, whose c:Src/subst.c:103
// `asssub` stops word splitting after the first `=`.
crate::ported::zsh_h::PREFORK_TYPESET
} else {
0
};
// c:Src/subst.c:544+ — `multsub(&prepped, 0)` is the
// unquoted-argv equivalent of zsh's `prefork(list,
// 0, NULL)` for a single-element list. Returns the
// post-expansion node list (Vec<String>) so array-
// shape results (e.g. `${a:e}`, `${a[@]}`,
// `${(s::)str}`) splat into multiple argv words.
// singsub() collapses to one string and discards the
// splat — parity bug #28 (whole-array modifier).
// c:Src/subst.c:3929-3932 — `if (isarr) l->list.flags |=
// LF_ARRAY; else l->list.flags &= ~LF_ARRAY;`. C's paramsubst
// holds the LinkList and stamps its `isarr` on it directly;
// the Rust port hands the same bit back through the
// `PARAMSUBST_LF_ARRAY` thread-local (subst.rs:20511) — set at
// subst.rs:17796 (`isarr != 0 && !forced_split_to_one`) and
// reset to false at the top of EVERY paramsubst
// (subst.rs:3891 / subst.rs:17445).
//
// Clear it BEFORE multsub so a segment that runs no paramsubst
// at all reads false instead of some earlier expansion's
// value. `multsub`'s own `isarr` return cannot be used for
// this: an unquoted `$(cmd)` / `` `cmd` `` sets LF_ARRAY
// unconditionally (subst.rs:897 / :1159, c:Src/subst.c:285-286
// `if (!qt) list->list.flags |= LF_ARRAY;` and c:331), so
// `x$(true)y` would look array-shaped when zsh keeps that
// word (verified: it is the single word `xy`).
//
// Every paramsubst re-initialises the cell on entry, so
// clearing it here cannot disturb subst.rs's own readers
// (stringsubst reads it immediately after each paramsubst
// call, subst.rs:1094).
crate::ported::subst::PARAMSUBST_LF_ARRAY.with(|c| c.set(false));
// Mode 10 (a deferred command argument): c:Src/subst.c:165-191
// runs filesub in prefork's second pass, after stringsubst has
// run over EVERY word, so `print =nosuchcmd $(cmd)` runs `cmd`
// before `=nosuchcmd` fails. This handler expands one word, so
// the word's filesub is left to BUILTIN_GLOBLIST's all-words
// pass (the word comes back with its Equals/Tilde token).
let saved_skip_filesub = crate::ported::subst::SKIP_FILESUB.with(|c| c.get());
if mode == 10 {
crate::ported::subst::SKIP_FILESUB.with(|c| c.set(true));
}
let (_first, nodes, _ms_ws, _ret) =
crate::ported::subst::multsub(&prepped, pf_flags);
crate::ported::subst::SKIP_FILESUB.with(|c| c.set(saved_skip_filesub));
// c:Src/subst.c:326-327 → prefork c:142-147 — an `(e)` NULL ended
// prefork: the word is the text before the `$` (c:1878), and the
// brace / filesub / remnulargs passes after the substitution loop
// never ran. PREFORK_CUT keeps the later words unexpanded.
if crate::ported::subst::PREFORK_STOPPED.with(|c| c.replace(false)) {
PREFORK_CUT.with(|c| c.set(true));
// remnulargs (c:170) never ran either, so C's nodes still
// hold their quote tokens and untokenize (c:Src/exec.c:2134)
// renders them through ztokens. Every node before the cut
// stays: `(@e)` inserted the earlier elements
// (c:Src/subst.c:4383-4394), so `A${(@e)arr}B` with
// arr=(p x '$(') is `Ap` and `x`.
return stopped_nodes_value(nodes);
}
// Read immediately: brace expansion / filesub / glob below can
// re-enter paramsubst and overwrite the cell. `seg_is_array` is
// the array-ness of the OUTERMOST paramsubst in this segment —
// C's c:4245 `if (isarr)` for the same expansion. Paired with
// `seg_zero_words` it separates the two empty shapes for the
// empty-result arm further down (c:4362 vs c:4464).
let seg_is_array = crate::ported::subst::PARAMSUBST_LF_ARRAY.with(|c| c.get());
let seg_zero_words = nodes.is_empty();
if std::env::var("ZSHRS_TRACE_MULTSUB").is_ok() {
eprintln!("[TRACE_MULTSUB] prepped={:?} nodes={:?}", prepped, nodes);
}
// c:Src/subst.c:166 — xpandbraces runs AFTER prefork's
// substitution pass and BEFORE untokenize/glob. Per
// word, scan for Inbrace TOKEN and expand. Words that
// don't contain Inbrace TOKEN pass through unchanged.
// Brace expansion is done here (inside the bridge
// default arm) instead of via a post-EXPAND_TEXT
// BRACE_EXPAND emit because untokenize (line below)
// strips TOKEN bytes, after which the strict-TOKEN
// xpandbraces gate would no longer match.
let brace_ccl = opt_state_get("braceccl").unwrap_or(false);
// c:Src/options.c — `no_brace_expand` (negated
// `braceexpand`) gates brace expansion entirely.
// When off, `{a,b}` stays literal.
// c:Src/subst.c:170 — `if (unset(IGNOREBRACES) && !(flags &
// PREFORK_SINGLE))` guards the `xpandbraces` loop, so a word
// preforked as a scalar (assignment VALUE, mode 8) is NEVER
// brace-expanded: `local x={a,b}` stores the five literal
// characters. This pass stands in for prefork's loop, so it
// owes the same guard.
let brace_expand = opt_state_get("braceexpand").unwrap_or(true)
&& (pf_flags & crate::ported::zsh_h::PREFORK_SINGLE) == 0; // c:170
let pre_brace: Vec<String> = if nodes.is_empty() {
vec![String::new()]
} else {
nodes
};
let brace_expanded: Vec<String> = pre_brace
.into_iter()
.flat_map(|w| {
if brace_expand && w.contains('\u{e18f}') {
crate::ported::glob::xpandbraces(&w, brace_ccl)
.into_iter()
.filter(|x| !(x.is_empty() && crate::dash_mode::bash_mode()))
.collect()
} else {
vec![w]
}
})
.collect();
// zsh stores the option as `glob` (default ON);
// `setopt noglob` writes `glob=false`. Honor either
// form so the dispatcher behaves the same as zsh.
// Mode 7 = redirect-target word: glob only under
// MULTIOS (c:Src/glob.c:2161-2167 xpandredir,
// "Globbing is only done for multios.").
let noglob = opt_state_get("noglob").unwrap_or(false)
|| opt_state_get("GLOB").map(|v| !v).unwrap_or(false)
|| !opt_state_get("glob").unwrap_or(true)
|| (mode == 7 && !opt_state_get("multios").unwrap_or(true))
// Mode 9 = singsub. c:Src/subst.c:514-525 runs `prefork`
// and NOTHING else — `globlist` is never called, so a
// `case` word (c:Src/loop.c:610-612) and a `[[ … ]]`
// operand (c:Src/cond.c:53) are never filename-generated.
|| mode == 9
// Mode 12 = the pattern-operand spelling of mode 9, so it
// owes the same "singsub never reaches globlist" rule.
|| mode == 12
// Mode 11 = a segment of a larger word (see compile_zsh's
// text-expansion arm): c:Src/exec.c:3755-3757 globs the
// assembled word, so the segment itself is not globbed.
|| mode == 11
// c:Src/exec.c:2603-2613 — a scalar `NAME=VALUE` is
// preforked PREFORK_SINGLE|PREFORK_ASSIGN (mode 8) and
// reaches globlist only under GLOB_ASSIGN; without it the
// value is never globbed. Missing this term, a value the
// compiler did not DQ-wrap globbed here: `x=q(` said "bad
// pattern: q(", `x=q(a)` "number expected", `x=q(|b)` "no
// matches found".
|| (mode == 8 && !crate::ported::zsh_h::isset(crate::ported::zsh_h::GLOBASSIGN));
// c:Src/subst.c:168 — prefork's `if (*(char *)getdata(node))`
// runs on the node AS IT STANDS, i.e. still carrying the quote
// markers the lexer left and the `Nularg` that c:169's
// `remnulargs` re-inserts for a node made of nothing else
// (c:Src/glob.c:3683-3686). `untokenize` drops that sentinel
// (c:Src/exec.c:2143), but only much later, once the node is
// already a word. Testing emptiness AFTER the untokenize below
// inverted that order and deleted the word C keeps:
// `unset u; r=( q ${u:-""} )` counted 1 where zsh counts 2
// (same for `${u:-''}`, `${u-""}`, `${1:-""}`, `${a[@]:+""}`).
// Record C's answer here and let the empty-result arm consult
// it.
let nonempty_before_untokenize = brace_expanded.iter().any(|w| !w.is_empty());
let parts: Vec<String> = brace_expanded
.into_iter()
.flat_map(|s| {
// The lexer leaves glob metacharacters in their
// META-encoded form: `*` → `\u{e187}`, `?` →
// `\u{e186}`, `[` → `\u{e191}`, etc. expand_string
// doesn't untokenize them, so the literal-char
// checks below (`s.contains('*')`) would miss
// every real glob and skip expand_glob — that
// bug let `echo *.toml` print the literal
// `*.toml` because the META `\u{e187}` never
// matched the literal `*`. Untokenize once so
// the metacharacter checks see the canonical
// form. zsh's pattern.c expects `*` etc. as
// bare chars at the glob layer.
// c:Src/pattern.c:4306 haswilds on the still-
// TOKENIZED word (pre-untokenize), matching C's
// zglob entry gate (Src/glob.c:1230) which runs
// on the lexer-tokenized string. haswilds
// matches ONLY token codes: source-level
// `*.toml` carries Star and fires; bare literal
// `[`/`*`/`?` from `$'...'` decode, `:-`
// default values, or nested-substitution
// results were never shtokenize'd (C
// subst.c:3231 sets globsubst=0 in the `:-`
// arm) and stay literal — bug #625. Plain
// multibyte text (`↔`) never matches a token
// codepoint — bug #627.
let is_glob_pre = !noglob && crate::ported::pattern::haswilds(&s);
// c:Src/glob.c:1230 — zglob receives the word in
// LEXER-TOKENIZED form and only untokenizes it when
// it declines to glob (c:1232) or falls back to the
// literal (c:1884). The token form is what makes a
// QUOTED metachar distinguishable from an active one:
// in `*(.e['[[ $REPLY == a* ]]'])` the body's `]`
// bytes are raw ASCII while the qualifier's real
// closer is `Outbrack`, which is exactly how
// checkglobqual (c:1163/1170, testing Outpar/Inpar)
// and get_strarg's tokenized delimiter half
// (Src/subst.c:1379-1390) find the true end. zshrs
// untokenized here, one line before the glob layer,
// so every quoted metachar became indistinguishable
// from an active one and the qualifier parser closed
// on the first quoted `]`. Keep the tokenized word
// for the glob call; the untokenized form still
// drives the non-glob arms below.
let s_tok = s.clone();
// c:36 `nulstring` — a segment (mode 11) of a word
// whose end-of-word drop is still to run keeps the
// Nularg that marks a split's empty field, as
// `paramsubst_to_value_pf` does; untokenize would fold
// it to "", which that drop cannot tell from a truly
// empty node. The drop removes the marker (c:170).
let nul = crate::ported::zsh_h::Nularg;
let s = if mode == 11
&& s.contains(nul)
&& crate::ported::subst::PARAMSUBST_AFFIXES_DEFERRED.with(|c| c.get()) > 0
{
s.split(nul)
.map(crate::lex::untokenize)
.collect::<Vec<_>>()
.join(&nul.to_string())
} else if mode == 12 {
// c:Src/glob.c:3640-3645 — `shtokenize` says "this
// metacharacter is ACTIVE" by rewriting it to a
// TOKEN and says "this one is data" by leaving the
// raw byte, and C carries both spellings into
// `patcompile` unchanged. Mode 12 is a `[[ … ]]` /
// `case` PATTERN operand, the one word where that
// distinction still has a consumer: untokenizing
// here collapses the two, and the guard that runs
// next can then only escape ALL of the word's metas
// or none of them. c:Src/subst.c:1551-1552 puts
// both halves in one string — the `(~j)` separator
// is tokenized, the elements it joins are not — so
// neither answer is right. Hand the word on
// tokenized; BUILTIN_GLOB_SUBST_GUARD /
// BUILTIN_PAT_DATA_BACKSLASH run the untokenize
// once they have escaped the raw half.
s
} else {
crate::lex::untokenize(&s)
};
// c:Src/exec.c:2603-2613 — only an assignment VALUE
// skips globlist without GLOB_ASSIGN, and that value
// arrives here in mode 8, which `noglob` above already
// covers. The word's text says nothing about its role:
// a text-shape test (`[A-Za-z_][A-Za-z0-9_]*=`) that
// used to skip the glob here also kept `print a=zzq*`,
// `set -- a=zzq*`, `for w in a=zzq*`, `> a=zzq*` and
// the array element `x=(a=zzq*)` from globbing, where
// zsh reports "no matches found".
// Glob-trigger decision: pre-untokenize
// haswilds_tokens_only result (computed above
// before the untokenize that collapses META
// tokens to their ASCII forms). The TOKEN-only
// gate matches C `Src/pattern.c:4306-4376`
// exactly — only Inbrack/Star/Quest/Inpar/Bar/
// Inang/Pound/Hat token codes count as wild,
// not their literal ASCII counterparts. Source-
// level `*.toml` carries Star token so globs;
// `$'…'`-decoded `[abc]` carries bare `[` so
// stays literal. Bug #625.
// c:Src/subst.c:677-678 — `filesub`'s own precondition
// for the PREFORK_TYPESET arm is `(*namptr)[1] &&
// strchr(*namptr + 1, Equals)`: an `=` anywhere but
// position 0. There is NO identifier test. Gating the
// arm below on an assignment-shape test — which demanded a
// leading `[A-Za-z_][A-Za-z0-9_]*` — therefore lost every
// word whose `=` is not preceded by a bare identifier:
// setopt magicequalsubst; print -r -- x:y=~/z
// zsh: x:y=/home/u/z zshrs: x:y=~/z
// Same for `ME:a=~/x`, `1abc=~/x` and `-o=~/x`, the last
// of which is the common `--prefix=~/dir` shape.
// c:Src/subst.c:678 — filesub's own gate is
// `strchr(*namptr + 1, Equals)`: the Equals TOKEN,
// which the lexer emits ONLY for an unquoted `=`.
// Test the still-TOKENIZED word so a quoted `=` does
// not arm the arm below.
let has_nonleading_equals = s_tok
.chars()
.skip(1)
.any(|c| c == crate::ported::zsh_h::Equals);
// c:Src/subst.c:180 `filesub(&cptr, flags & …)` acts on a
// leading Tilde / Equals token; mode 10 deferred it above.
let filesub_deferred = mode == 10
&& (s_tok.starts_with(crate::ported::zsh_h::Tilde)
|| s_tok.starts_with(crate::ported::zsh_h::Equals));
if (is_glob_pre || filesub_deferred) && mode == 10 {
// Mode 10: the command's BUILTIN_GLOBLIST runs this
// word's filesub and glob after every argument has
// been expanded (c:Src/subst.c:165-191, then
// c:Src/exec.c:3755-3757).
vec![s_tok]
} else if is_glob_pre {
// c:Src/exec.c:3755-3762 — an error raised here is a
// globlist error (`lastval = 1`); see GLOB_WORD_ERRFLAG.
let ef = || {
crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed)
& crate::ported::zsh_h::ERRFLAG_ERROR
};
let before = ef();
// c:Src/glob.c:2164-2166 — a redirect target
// (mode 7) is globbed with `in_expandredir` set,
// so a NULL_GLOB no-match is `redirection failed
// (no match)` (c:1888-1894), not a dropped word.
let redir = (mode == 7) as i32;
crate::ported::glob::IN_EXPANDREDIR.store(redir, std::sync::atomic::Ordering::SeqCst);
let globbed = exec.expand_glob(&s_tok);
crate::ported::glob::IN_EXPANDREDIR.store(0, std::sync::atomic::Ordering::SeqCst);
if before == 0 && ef() != 0 {
GLOB_WORD_ERRFLAG.with(|c| c.set(true));
}
globbed
} else if has_nonleading_equals
&& crate::ported::zsh_h::isset(crate::ported::zsh_h::MAGICEQUALSUBST)
{
// c:Src/exec.c:3353 — when MAGIC_EQUAL_SUBST is set
// on a non-typeset command, esprefork = PREFORK_TYPESET,
// so every arg runs through
// filesub(PREFORK_TYPESET): the `~`/`=` after the
// first `=` (and after each `:`) undergo filename
// expansion. `print foo=~/bar` → `foo=$HOME/bar`.
// filesub (subst.c:667) keys on the Tilde/Equals
// TOKENS, not the literal chars, because that is
// exactly what tells a quoted `~`/`=` from a live
// one. This arm used to `untokenize` the word and
// then `shtokenize` it back, which re-marks EVERY
// literal `~`/`=` as a token — including the ones
// that came out of quotes. With MAGIC_EQUAL_SUBST
// set, `print -r -- --a='b:=c'` then did `=`
// filename expansion on the quoted `=c` and failed
// with `c not found` (zsh prints `--a=b:=c`), and
// `A=( --height='${X:=75%}' )` — fzf-tab.plugin.zsh
// sh:117-128 — errored `75%} not found` at plugin
// load, aborting the rest of the zinit turbo
// `atload` chain. Hand filesub the word C hands it:
// the one the lexer produced.
let exp = crate::ported::subst::filesub(
&s_tok,
crate::ported::zsh_h::PREFORK_TYPESET,
);
vec![crate::lex::untokenize(&exp).to_string()]
} else {
vec![s]
}
})
.collect();
if parts.len() == 1 {
let only = parts.into_iter().next().unwrap_or_default();
// Empty unquoted expansion → drop the arg entirely
// (zsh "remove empty unquoted words" rule). Returning
// an empty Value::Array makes pop_args contribute zero
// items. Direct port of subst.c's empty-elide pass at
// the end of multsub which removes empty linknodes
// from unquoted contexts. Quoted DQ/SQ paths (modes
// 1/2/5) take separate arms above and always emit
// Value::Str so the empty arg survives.
//
// c:Src/subst.c:4437 + 1650-1656 — a word CONTAINING a
// quoted span never drops: `x"${v[-1]}"y` (v empty)
// is the scalar "xy", and a standalone `"${v[-1]}"`
// is ONE empty arg. The lexer marks DQ/SQ spans with
// Dnull(\u{e19e})/Snull(\u{e19d})/Qstring(\u{e18c})/
// Bnull(\u{e19f}); their presence in the SOURCE word
// means qt semantics apply. Without this gate, zpwr's
// global `setopt rc_expand_param` turned autopair's
// `local lchar="${LBUFFER[-1]}"` (empty prompt +
// backspace) into an ARGLESS `local` — the full
// parameter-table dump the user saw per keystroke.
if only.is_empty() && !nonempty_before_untokenize {
// A quote span that WRAPS the expansion keeps the
// empty arg (`"${v[-1]}"` → one empty arg). But a
// quote INSIDE the `${…}` braces — e.g. the alternate
// of `${x:+'q'}` or `${x:-'d'}` — does NOT: when that
// branch isn't taken the result is a plain unquoted
// empty and must ELIDE, matching zsh (`a=(A ${x:+'q'}
// C)` → 2 elements, not 3). So only count quote
// markers at brace-depth 0 (outside `${…}`). Inbrace
// = \u{e18f}, Outbrace = \u{e190}.
let mut depth = 0i32;
let mut word_has_quoted_span = false;
for c in text.chars() {
match c {
'\u{e18f}' => depth += 1,
'\u{e190}' => depth -= 1,
'\u{e19e}' | '\u{e19d}' | '\u{e18c}' | '\u{e19f}' | '"' | '\''
if depth <= 0 =>
{
word_has_quoted_span = true;
break;
}
_ => {}
}
}
if word_has_quoted_span {
// Returns a SCALAR Value, so the empty-Array
// shape bit does not describe it — leave the
// cell alone. Overwriting it here would let a
// trailing quoted-empty segment resurrect a word
// an EARLIER empty array already deleted:
// `setopt rcexpandparam; a=(); x${a}"${P}"y` is
// ZERO words in zsh, and concat_plan9's
// `(Array(empty), scalar)` arm returns the scalar
// when the bit says "scalar".
Value::str(String::new())
} else {
// The empty `Value::Array` below stands for TWO
// different C shapes, and under RC_EXPAND_PARAM
// they behave OPPOSITELY:
//
// c:Src/subst.c:4362-4365 (plan9, empty ARRAY)
// if (plan9) { uremnode(l, n); return n; }
// → the whole word is deleted:
// `a=(); x${a}y` and `x${${a}}y` are 0 words.
//
// c:Src/subst.c:4438-4467 (scalar arm, empty
// SCALAR) — c:4464
// *str = strcatsub(&y, ostr, aptr, x, xlen,
// fstr, globsubst, copied);
// then c:4467 `setdata(n, (void *) y);`
// → the surrounding text survives:
// `unset P; x${P}y` and `x${${P}}y` are the
// single word `xy`.
//
// Nesting is NOT the discriminator — shape is.
// The word is deleted only when the expansion was
// ARRAY-shaped (c:4245 `if (isarr)`) AND produced
// zero words, i.e. C's `while ((x = *aval++))`
// loop at c:4327 never ran and left `plan9`
// non-zero at c:4362. Anything else empty — an
// unset/empty scalar, a nested subexp that
// resolved to a scalar, a command substitution
// with no output — takes c:4438's scalar arm and
// keeps the word.
note_empty_is_scalar(!(seg_zero_words && seg_is_array));
Value::array(Vec::new())
}
} else {
Value::str(only)
}
} else {
Value::array(parts.into_iter().map(Value::str).collect())
}
}
});
// Pull any inner cmd-subst (`` `cmd` `` via mode 3 or via
// mode 0/6 multsub → getoutput, `$(cmd)` via the default
// arm's multsub path, nested `$()`s reached through
// stringsubst) back into vm.last_status so a containing
// assignment's BUILTIN_SET_VAR — which reads vm.last_status —
// sees the cmd-subst's exit. Without this, backtick
// assignments (`a=\`false\`; echo $?`) reported 0 because the
// ported LASTVAL update never reached the VM-side counter.
let cs_status = with_executor(|exec| exec.last_status());
vm.last_status = cs_status;
result_value
});
// `${#name}` — pops [name]. Returns the value's element count for
// arrays (indexed and assoc) or character length for scalars.
// BUILTIN_PARAM_LENGTH — `${#name}`. PURE PASSTHRU.
vm.register_builtin(BUILTIN_PARAM_LENGTH, |vm, _argc| {
let name = vm.pop().to_str();
// PARAM_LENGTH's empty-result semantics differ from
// paramsubst_to_value: 0 nodes → "0" (numeric length), not
// empty array. paramsubst on `${#X}` always returns at least
// one node in practice (the length string); the empty case
// is defensive.
let mut ret_flags: i32 = 0;
let (_full, _pos, nodes) = crate::ported::subst::paramsubst(
&format!("${{#{}}}", name),
0,
false,
0i32,
&mut ret_flags,
);
if crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed) != 0 {
with_executor(|exec| exec.set_last_status(1));
}
if nodes.is_empty() {
Value::str("0")
} else {
nodes_to_value(nodes)
}
});
// `${var/pat/repl}` / `${var//pat/repl}` / `${var/#pat/repl}` /
// `${var/%pat/repl}` — Pops [name, pattern, replacement, op_byte].
// op: 0=first, 1=all, 2=anchor-prefix (`/#`), 3=anchor-suffix (`/%`).
// BUILTIN_PARAM_REPLACE — `${var/pat/repl}` / `${var//pat/repl}` /
// `${var/#pat/repl}` / `${var/%pat/repl}`. PURE PASSTHRU.
vm.register_builtin(BUILTIN_PARAM_REPLACE, |vm, argc| {
// c:Src/subst.c:1761 — the word's PREFORK_SINGLE bit, pushed last by
// compile_zsh::emit_param_modifier (see the note there).
let pf_flags = if argc as usize > 5 && vm.pop().to_int() != 0 {
crate::ported::zsh_h::PREFORK_SINGLE
} else {
0
};
let dq_flag = vm.pop().to_int() != 0;
let op = vm.pop().to_int() as u8;
let repl = vm.pop().to_str();
let pattern = vm.pop().to_str();
let name = vm.pop().to_str();
// !!! DASH-STRICT GATE !!! dash / ash have no `${var/pat/repl}`
// pattern-replacement expansion — it is a "Bad substitution" error
// (bash/ksh/POSIX-sh support it, so those modes fall through). Raise
// the canonical zsh diagnostic + exit 1 to match /bin/dash's failure.
if crate::dash_mode::dash_strict() {
crate::ported::utils::zerr("bad substitution");
crate::ported::utils::errflag.fetch_or(
crate::ported::zsh_h::ERRFLAG_ERROR,
std::sync::atomic::Ordering::Relaxed,
);
with_executor(|exec| exec.set_last_status(1));
return Value::str("");
}
// DQ context: C's lexer marks every `$` inside double quotes
// as the Qstring token (Src/lex.c dquote_parse) and keeps `'`
// a plain char — so a DQ replacement's `$'…'` is LITERAL in
// C (Src/subst.c:301 decodes only the tokenized Snull form;
// `"${a/X/$'\0'}"` keeps the five chars `$'\0'`). The body
// rebuilt below re-enters stringsubst as raw text, which
// would mis-decode `$'…'` as ANSI-C; stamp the Qstring
// marker on the repl's `$` so stringsubst sees the same DQ
// signal C's tokens carry. The PATTERN side keeps decoding
// (matches observed zsh: the pattern's `$'\0'` matches a
// real NUL while the repl's stays literal).
let repl = if dq_flag {
repl.replace('$', "\u{e18c}")
} else {
repl
};
// op encoding: 0 = first `/`, 1 = all `//`, 2 = anchor-prefix
// `/#`, 3 = anchor-suffix `/%`. The brace form distinguishes
// first-vs-all by single vs doubled slash, and anchored by
// a `#` or `%` immediately after the slash(es).
let body = match op {
0 => format!("${{{}/{}/{}}}", name, pattern, repl),
1 => format!("${{{}//{}/{}}}", name, pattern, repl),
2 => format!("${{{}/#{}/{}}}", name, pattern, repl),
3 => format!("${{{}/%{}/{}}}", name, pattern, repl),
_ => format!("${{{}/{}/{}}}", name, pattern, repl),
};
// c:Src/subst.c:1625 — paramsubst's qt flag. The compiler
// threads the word's DQ context onto the stack; dropping it
// (the old `let _dq_flag`) ran the rebuilt body with qt=false
// whenever the opcode fired outside an EXPAND_TEXT scope, so
// DQ-only semantics inside the replacement (e.g. `$'` staying
// literal per Src/subst.c:301 — `"${a/x/$'\t'q}"`) were lost.
// Bump in_dq_context exactly like EXPAND_TEXT mode 1 so
// paramsubst_to_value's qt probe sees the right context.
if dq_flag {
with_executor(|exec| exec.in_dq_context += 1);
}
let ret = paramsubst_to_value_status(vm, &body, pf_flags);
if dq_flag {
with_executor(|exec| exec.in_dq_context -= 1);
}
ret
});
vm.register_builtin(BUILTIN_REGISTER_COMPILED_FN, |vm, argc| {
let args = pop_args(vm, argc);
// c:Src/exec.c:5389-5394 — `if (htok && names) { execsubst(names);
// if (errflag) { state->pc = end; return 1; } }`: the name words are
// prefork-expanded and globbed (c:2741-2746), so a NOMATCH defines
// nothing and fails the definition.
if crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed)
& crate::ported::utils::ERRFLAG_ERROR
!= 0
{
return Value::Status(1); // c:5393
}
// c:5399 — `while ((s = (char *) ugetnode(names)))`: one function per
// name the expansion produced (`function a* { … }` defines one per
// matching file). The names lead the argument list; the five
// definition fields follow.
let nnames = args.len().saturating_sub(5);
let (names, fields) = args.split_at(nnames);
let mut status = Value::Status(0);
for name in names {
let mut one = Vec::with_capacity(fields.len() + 1);
one.push(name.clone());
one.extend_from_slice(fields);
status = register_compiled_fn(vm, one);
}
status
});
fn register_compiled_fn(vm: &mut fusevm::VM, args: Vec<String>) -> Value {
let mut iter = args.into_iter();
let name = iter.next().unwrap_or_default();
let body_b64 = iter.next().unwrap_or_default();
let body_source = iter.next().unwrap_or_default();
let line_base_str = iter.next().unwrap_or_default();
let line_base: i64 = line_base_str.parse().unwrap_or(0);
// c:Src/exec.c:5384-5388 — `shf->lineno = (funcstack && (tp == FS_FUNC ||
// tp == FS_EVAL)) ? funcstack->flineno + lineno : lineno;`. Inside an
// `eval` the compiled line is relative to the eval text, so add the
// eval frame's file offset. (A function body is compiled with file
// lines already, so the FS_FUNC arm needs no adjustment here.)
let line_base: i64 = match crate::ported::modules::parameter::FUNCSTACK
.lock()
.ok()
.and_then(|stk| stk.last().map(|top| (top.tp, top.flineno)))
{
Some((tp, flineno)) if tp == crate::ported::zsh_h::FS_EVAL && line_base >= 0 => {
flineno + line_base // c:5387
}
_ => line_base,
};
// c:Src/exec.c:5382 `do_tracing = *state->pc++;` — the `-T` of
// `function -T name { … }`, carried across from compile_funcdef.
let tracing_text = iter.next().unwrap_or_default();
let do_tracing = tracing_text.starts_with('1'); // c:5382
// RUST-ONLY: a trailing `k` = defined with the `function name {` keyword.
crate::extensions::dash_mode::note_function_spelling(&name, tracing_text.ends_with('k'));
// c:Src/exec.c:5451-5456 — `shf->redir = <redir_prog>`: the rendered
// text of the definition's trailing redirections (empty when there
// were none). See `shfunc::redir_text`.
let redir_text = iter.next().unwrap_or_default(); // c:5453
// c:5387 — `tracing_flags = do_tracing ? PM_TAGGED_LOCAL : 0;`
let tracing_flags: u32 = if do_tracing {
crate::ported::zsh_h::PM_TAGGED_LOCAL
} else {
0
}; // c:5387
// `#<idx>` — the body lives in the ENCLOSING chunk's `sub_chunks` and
// only its index travelled through the constant pool (see
// compile_zsh.rs `compile_funcdef`). `vm.chunk` is the chunk currently
// executing this CallBuiltin, i.e. the one that owns the sub-chunk:
// at top level the script chunk, and inside a function body the body
// chunk that `vm_pool::acquire` (vm_helper.rs:4098) is running.
//
// Anything else is the historical `base64(bincode(chunk))` payload —
// still accepted so a chunk restored from a bytecode cache written by
// an older binary keeps working. `#` is outside the base64 alphabet so
// the two forms cannot be confused.
let sub_chunk = body_b64
.strip_prefix('#')
.and_then(|n| n.parse::<usize>().ok())
.map(|idx| vm.chunk.sub_chunks.get(idx).cloned().ok_or(()));
let decoded = match sub_chunk {
Some(Ok(chunk)) => Ok(chunk),
Some(Err(())) => Err(()),
None => {
let bytes = base64_decode(&body_b64);
bincode::deserialize::<fusevm::Chunk>(&bytes).map_err(|_| ())
}
};
let status = match decoded {
Ok(chunk) => with_executor(|exec| {
// c:Src/exec.c:5383 — `shf->filename =
// ztrdup(scriptfilename);` — the function's
// definition-file is read from the canonical
// file-scope `scriptfilename` global at compile
// time, NOT from a per-executor struct field.
// exec.scriptfilename is seeded once at
// bins/zshrs.rs:1717 to the bin basename ("zsh")
// and never updates on source/dot, so reading from
// it left every user function's def_file as "zsh".
// Route through scriptfilename_get() so source /
// dot's set_scriptfilename calls propagate.
let def_file = crate::ported::utils::scriptfilename_get()
.or_else(|| exec.scriptfilename.clone());
let def_file_for_prov = def_file.clone();
if !body_source.is_empty() {
exec.function_source
.insert(name.clone(), body_source.clone());
}
exec.function_line_base.insert(name.clone(), line_base);
exec.function_def_file.insert(name.clone(), def_file);
// PFA-SMR aspect: every `name() {}` / `function name { }`
// funnels through here at compile time. Emit one record
// with the function name + raw body source.
#[cfg(feature = "recorder")]
if crate::recorder::is_enabled() {
let ctx = exec.recorder_ctx();
let body = if body_source.is_empty() {
None
} else {
Some(body_source.as_str())
};
crate::recorder::emit_function(&name, body, ctx);
}
// c:Src/exec.c:5516-5531 — `TRAP<SIG>() { ... }` is the
// function-named trap install. zsh detects the `TRAP`
// prefix at func-def time and calls
// `settrap(signum, NULL, ZSIG_FUNC)` so the next
// dispatch of that signal routes to the named shfunc.
// Bug #157 in docs/BUGS.md — fusevm_bridge's funcdef
// opcode skipped this dispatch entirely, so TRAPEXIT /
// TRAPUSR1 / TRAPZERR / TRAPDEBUG never fired.
//
// ORDER MATTERS. C runs settrap at c:5518 and
// `shfunctab->addnode` only at c:5539, and dosavetrap
// says why (c:634-637): "Get the old function: this
// assumes we haven't added the new one yet." Running
// the install first made settrap→unsettrap→removetrap→
// dosavetrap snapshot the NEW body, so endtrapscope
// "restored" the inner definition and a nested
// `TRAPEXIT() { … }` permanently clobbered the outer one.
// BUGS.md #1114 — the TRAPxxx() FUNCTION-trap form is zsh-only.
// bash, ksh and dash have no such concept: there `TRAPINT` is an
// ordinary function whose name merely begins with TRAP, and SIGINT
// keeps its default disposition. Recognising it in a drop-in mode
// also SILENTLY DESTROYS an already-installed list trap for that
// signal, since the two forms are alternatives in zsh.
// posix_faithful() is raised only for a bare drop-in flag, so
// --zsh, native zshrs and `emulate sh` are untouched.
if !crate::extensions::dash_mode::posix_faithful() && name.len() > 4 && name.starts_with("TRAP") {
if let Some(sn) = crate::ported::jobs::getsigidx(&name[4..]) {
let _ = crate::ported::signals::settrap(
sn,
None,
crate::ported::zsh_h::ZSIG_FUNC as i32,
);
// c:5530 — `removetrapnode(signum);` "Remove the
// old node explicitly in case it has an
// alternative name". NOT mirrored here: zshrs's
// `jobs::removetrapnode` routes through
// `hashtable::removeshfuncnode`, which calls back
// into `unsettrap` (C explicitly avoids that path
// — see the comment at Src/signals.c:836-838) and
// would tear down the trap `settrap` just armed.
// The `tab.add` below overwrites the canonical
// `TRAP<SIG>` node anyway; only the alt-name case
// (TRAPCLD vs TRAPCHLD) is left unhandled.
}
}
// Mirror into canonical shfunctab so scanfunctions /
// ${(k)functions} / functions builtin see user defs.
// C: exec.c:funcdef → shfunctab->addnode(ztrdup(name),shf).
if let Ok(mut tab) = crate::ported::hashtable::shfunctab_lock().write() {
let mut shf = crate::ported::hashtable::shfunc_with_body(&name, &body_source);
// c:Src/exec.c:5453/5455 — `shf->redir = …`. Stored as
// rendered text (see `shfunc::redir_text`); `None` is C's
// `shf->redir == NULL`.
shf.redir_text = if redir_text.is_empty() {
None
} else {
Some(redir_text.clone())
};
// c:Src/exec.c:5437 — `shf->node.flags = tracing_flags;`
shf.node.flags |= tracing_flags as i32; // c:5437
// c:5532-5538 — /* Is this function traced and redefining
// itself? */
// if (funcstack && funcstack->tp == FS_FUNC &&
// !strcmp(s, funcstack->name)) {
// Shfunc old = ((Shfunc)shfunctab->getnode(shfunctab, s));
// if (old)
// shf->node.flags |= old->node.flags &
// (PM_TAGGED|PM_TAGGED_LOCAL);
// }
// The ported walker does this at exec.rs:7387, but fusevm —
// not that walker — is what registers a `name() { … }`, so a
// `functions -T f`-tagged function that redefined itself
// came back untraced (E02xtrace:6).
if let Ok(stk) = crate::ported::modules::parameter::FUNCSTACK.lock() {
if let Some(top) = stk.last() {
// c:5533
if top.tp == crate::ported::zsh_h::FS_FUNC && top.name == name {
// c:5535 — `Shfunc old = shfunctab->getnode(shfunctab, s);`
// Read through the write guard already held
// above: `shfunctab_lock()` is a std RwLock and
// is NOT reentrant, so re-acquiring it here
// self-deadlocked on exactly the
// self-redefinition case (C04funcdef:30 hung).
if let Some(old) = tab.get(&name) {
// c:5537
shf.node.flags |= old.node.flags
& (crate::ported::zsh_h::PM_TAGGED as i32
| crate::ported::zsh_h::PM_TAGGED_LOCAL as i32);
}
}
}
}
// `shfunc_with_body` stamps the AMBIENT `scriptfilename`
// (c:Src/exec.c:5383). That is right for an ordinary
// definition but wrong twice over for an autoloaded one:
//
// * c:Src/exec.c:5622-5630 — while an autoload file's text
// runs, C sets `scriptfilename = getshfuncfile(shf)`, so a
// `name() { … }` INSIDE it records the fpath file. zshrs
// runs that body on the normal VM path with the CALLER's
// scriptfilename still in place, so a ksh-style autoload
// file — one that defines the function and then calls it —
// got attributed to whoever triggered the load.
// * the function is then re-registered UNCHANGED when its
// chunk is compiled at call time, and that second stamp
// would overwrite the first even if the first were right.
//
// Result before this: `whence -v f` said "from ./caller.zsh"
// where zsh says "from dir/f", and `funcsourcetrace[1]`
// pointed at the caller — which compsys reads directly
// (`_git` locates git-completion.bash through
// `"$(dirname ${funcsourcetrace[1]%:*})"`).
if let Some(f) = crate::vm_helper::autoload_def_file(&name) {
shf.filename = Some(f); // c:5625 getshfuncfile(shf)
} else if let Some(prev) = tab.get(&name) {
// Re-registration of an unchanged body relabels nothing.
if prev.body.as_deref() == Some(body_source.as_str()) {
shf.filename = prev.filename.clone();
shf.node.flags |=
prev.node.flags & crate::ported::zsh_h::PM_LOADDIR as i32;
}
}
// c:Src/exec.c:5409 — `shf->lineno = lineno;`. Use
// the same max(1, line_base) clamp as the synth_shf
// in vm_helper::dispatch_function_call. Bug #396.
shf.lineno = std::cmp::max(1, line_base);
// c:Src/exec.c:5402 — `shfunc_set_sticky(shf);`
// stamps the definition-time `sticky` emulation
// snapshot onto the function so a later call can
// re-enter that emulation (doshfunc c:5978). The
// ported execfuncdef does this at exec.rs:7141, but
// fusevm — not that walker — is what actually
// registers a `name() { … }`, so `emulate sh -c
// 'f() { … }'` produced a function with no sticky
// emulation at all (B07emulate.ztst:6,7,8,12,13,14).
crate::ported::exec::shfunc_set_sticky(&mut shf);
// zshrs re-runs this registration when a function's
// chunk is (re)compiled at call time — see the
// filename note above. That second pass happens with
// the AMBIENT sticky (normally none), which would
// erase the definition-time stamp. An unchanged body
// is not a redefinition, so keep what it had.
if shf.sticky.is_none() {
if let Some(prev) = tab.get(&name) {
if prev.body.as_deref() == Some(body_source.as_str()) {
shf.sticky = prev
.sticky
.as_deref()
.map(|b| crate::ported::exec::sticky_emulation_dup(b, 0));
}
}
}
// docs/BUGS.md #1105 — C settles every lexer-time
// decision when the definition runs (c:Src/exec.c:5389
// `shf->funcdef = dupeprog(…)`) and prints that wordcode
// back unchanged (c:Src/hashtable.c:954). zshrs stores
// the raw source and re-lexes it to print, so the one
// lexer-time option that survives into a deparse —
// RCQUOTES, c:Src/lex.c:1328 — has to be recorded here
// or a later `setopt rcquotes` rewrites the listing of a
// function defined long before it. Skipped for the
// re-registration of an unchanged body (the same test
// the filename and sticky stamps above use): that second
// pass runs at CALL time, whose option state is not the
// definition's.
if tab
.get(&name)
.is_none_or(|prev| prev.body.as_deref() != Some(body_source.as_str()))
{
crate::vm_helper::funcdef_note_rcquotes(
&name,
&body_source,
crate::ported::zsh_h::isset(crate::ported::zsh_h::RCQUOTES),
);
}
tab.add(shf);
}
// Lineage tap: this is where a `name() { … }` actually
// lands in the VM path — `execfuncdef`'s shfunctab
// install only runs for the interpreter path. The first
// definition is the function's origin; a later one is a
// `redefine` op on the same chain.
if crate::provenance::active() {
crate::provenance::on_func_define(
&name,
Some(body_source.as_str()),
def_file_for_prov.as_deref(),
std::cmp::max(1, line_base),
);
}
exec.functions_compiled.insert(name, chunk);
0
}),
Err(_) => 1,
};
Value::Status(status)
}
// Wire the ShellHost so direct shell ops (Op::Glob, Op::TildeExpand,
// Op::ExpandParam, Op::CmdSubst, Op::CallFunction, etc.) route through
// ZshrsHost back into the executor.
vm.set_shell_host(Box::new(ZshrsHost));
}
impl ZshrsHost {
/// True iff `c` can be a `(j:…:)` / `(s:…:)` delimiter — non-alphanumeric,
/// non-underscore. Restricting to punctuation avoids `(jL)` consuming `L`
/// as a delim instead of as the next flag.
fn is_zsh_flag_delim(c: char) -> bool {
!c.is_ascii_alphanumeric() && c != '_'
}
}
/// Shared `${name[idx]}` subscript dispatch for BUILTIN_ARRAY_INDEX
/// and the KSHARRAYS-unset arm of BUILTIN_ARRAY_INDEX_UNBRACED.
///
/// c:Src/subst.c subscript parsing — when paramsubst re-parses the
/// synthesized `${name[idx]}` body, characters like `'` `"` `\` `$`
/// etc. are LEXER-active inside the `[…]` and get reinterpreted
/// (quote-strip, paramsubst recursion, …). For PRE-EVALUATED key
/// strings (the dynamic-key fast path at compile_zsh.rs:3234 already
/// expanded `$k` via EXPAND_TEXT), the idx is a literal string that
/// must match the stored key byte-for-byte — no further
/// reinterpretation. Direct assoc lookup bypasses the lexer for this
/// case, avoiding the quote-strip bug where `h[a'b]` failed to
/// resolve because paramsubst's subscript lexer treated the `'` as a
/// quote. Bug #338. Only fires for simple assoc-name + non-flag idx
/// (no outer-flag sentinels, no `(…)` flag prefix on idx, no splat
/// operator). Other paths (slice, splat, flag-based search,
/// magic-assoc) still flow through paramsubst.
///
/// `ssub` is c:Src/subst.c:1761 `(pf_flags & PREFORK_SINGLE)` — see the
/// `BUILTIN_ARRAY_INDEX` argc contract. It only reaches the textual
/// `paramsubst` rebuild at the bottom: every direct-lookup shortcut above it
/// resolves a single assoc value, which c:4226's join leaves alone.
/// Spell an ALREADY-EXPANDED subscript so a flat `${name[…]}` rebuild reads it
/// back as the key/index it is.
///
/// c:Src/params.c:2047-2054 — `getindex` decides the whole-parameter splat on
/// the RAW bracket text, before `getarg` runs `parsestr`/`singsub` on it:
///
/// ```c
/// s = *pptr + 1;
/// if ((s[0] == '*' || s[0] == '@') && s + 1 == tbrack) {
/// ... v->start = 0; v->end = -1; s += 2;
/// } else {
/// start = getarg(&s, &inv, v, 0, &we, ...);
/// }
/// ```
///
/// So in C a subscript that merely EXPANDS to `@` or `*` can never be the
/// splat — the text at `s[0]` is still `$k`. zshrs expands the subscript in the
/// VM and then rebuilds the flat `${name[VALUE]}` string for `paramsubst`,
/// which puts that `@` exactly where c:2048 reads it as the splat: `k='@';
/// ${h[$k]}` enumerated the whole hash instead of reading the key `@`.
///
/// Every compiler route that reaches a rebuild rejects a SOURCE-literal
/// `[@]`/`[*]` first (`braced_subscript_ref`, `braced_subscript_dynamic_ref`
/// and `parse_zsh_flag_subscript` all bail on `key == "@" || key == "*"`), so
/// an `@`/`*` seen here is always an expansion result. Re-spell it with C's
/// exact-match subscript group (c:Src/params.c:1449-1450 `(e)`), which sidesteps
/// c:2048 — `s[0]` is `(` — and then keys on the literal text. `${h[(e)@]}` is
/// byte-identical to `k='@'; ${h[$k]}` on zsh 5.9 for every shape measured:
/// hash key (`AT`), array/scalar (`bad math expression`), `(k)` (`@`),
/// `${#…}` (`2`) and `${+…}` (`1`).
fn expanded_subscript_text(idx: &str) -> std::borrow::Cow<'_, str> {
if idx == "@" || idx == "*" {
std::borrow::Cow::Owned(format!("(e){}", idx)) // c:1449-1450
} else {
std::borrow::Cow::Borrowed(idx)
}
}
/// The value of one assoc element read by `array_index_lookup`. A MISSING
/// key reads as the empty string (c:Src/params.c:1606-1610 creates a
/// PM_UNSET node), and an unquoted empty word is then deleted by prefork
/// (c:Src/subst.c:183-186) — `print -l -- $h[missing] x` is ONE word. Returning
/// `Value::str("")` directly skipped that drop, so a missing key became an
/// empty argument; `nodes_to_value` is where the bridge applies it.
fn assoc_key_value(v: Option<String>) -> Value {
match v {
Some(s) if !s.is_empty() => Value::str(s),
_ => nodes_to_value(vec![String::new()]),
}
}
/// `assoc_key_value` for a key read that answered from the plain hash
/// store. c:Src/params.c:1597-1606 hands back no node for a missing key, so
/// c:Src/subst.c:2804-2807 sets `vunset`, and with NO_UNSET the reference
/// is an error (c:3608-3613): `zerr("%s: parameter not set", idbeg)`. The
/// fast paths below answer before paramsubst runs, so they owe that check.
/// The alias views (getpmalias, c:Src/Modules/parameter.c) return an
/// unset-flagged node that zsh does not report, so `direct_assoc_key_get`'s
/// alias arms keep plain `assoc_key_value`.
fn hash_key_value(name: &str, idx: &str, v: Option<String>) -> Value {
if v.is_none() && !crate::ported::zsh_h::isset(crate::ported::zsh_h::UNSET) {
crate::ported::utils::zerr(&format!("{}[{}]: parameter not set", name, idx)); // c:3612
crate::ported::utils::errflag
.fetch_or(crate::ported::zsh_h::ERRFLAG_ERROR, std::sync::atomic::Ordering::Relaxed);
with_executor(|exec| exec.set_last_status(1));
return Value::str(String::new());
}
assoc_key_value(v)
}
/// One element of a plain indexed array by integer subscript, without the
/// textual `${name[idx]}` rebuild — which clones the WHOLE array on every
/// read, making a loop over an N-element array quadratic (8000 elements:
/// 2.7s against zsh's 0.017s; zpwr's zshRegenSearchableEnv.zsh indexes
/// `$lines[i]` over every autoload file and never finished).
///
/// `Some(elem)` only for the unambiguous case — a non-special `PM_ARRAY` in
/// the live paramtab, a nonzero integer subscript (a literal, or a bare
/// parameter holding one), KSH_ARRAYS off, and a non-empty element. Anything
/// else (flags, ranges, magic arrays, namerefs, empty elements whose word
/// elision depends on quoting) returns `None` and keeps the general path.
/// zshrs-original — no C counterpart (c:Src/params.c:getarg is O(1)).
fn array_elem_fast(name: &str, idx: &str) -> Option<String> {
use crate::ported::zsh_h::{PM_ARRAY, PM_SPECIAL};
if crate::ported::zsh_h::isset(crate::ported::zsh_h::KSHARRAYS) {
return None;
}
let n: i64 = match idx.parse() {
Ok(n) => n,
Err(_) => {
// A bare identifier holding an integer (`$a[i]`).
let bare = idx
.chars()
.next()
.is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
&& idx.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
if !bare {
return None;
}
crate::ported::params::getsparam(idx)?.trim().parse().ok()?
}
};
if n == 0 || name.is_empty() || matches!(name, "argv" | "@" | "*") {
return None;
}
if crate::ported::params::is_nameref(name) {
return None;
}
let tab = crate::ported::params::paramtab().read().ok()?;
let pm = tab.get(name)?;
let visible = crate::ported::modules::param_private::getprivatenode(&**pm as *const _);
if visible.is_null() || !std::ptr::eq(visible, &**pm as *const _) {
return None;
}
let flags = pm.node.flags as u32;
if crate::ported::zsh_h::PM_TYPE(flags) != PM_ARRAY || flags & PM_SPECIAL != 0 {
return None;
}
let arr = pm.u_arr.as_ref()?;
let at = if n > 0 {
usize::try_from(n - 1).ok()?
} else {
arr.len().checked_sub(usize::try_from(-n).ok()?)?
};
let elem = arr.get(at)?;
(!elem.is_empty()).then(|| elem.clone())
}
fn array_index_lookup(name: &str, idx: &str, ssub: bool) -> Value {
let idx_is_simple = !idx.starts_with('(') && idx != "@" && idx != "*" && !idx.contains(',');
if idx_is_simple {
if let Some(elem) = array_elem_fast(name, idx) {
return Value::str(elem);
}
// assoc_key_hit: single-lock O(1) probe — exec.assoc() clones
// the WHOLE map per lookup (O(n), quadratic in shell loops).
// When `name` IS an assoc, exact-key semantics apply to EVERY
// plain key: hit → value, miss → empty (C `${assoc[missing]}`).
// Never fall through to the textual `${name[key]}` rebuild —
// keys carrying `{`/`}`/`[`/`]` (zsh-autopair probes
// `${AUTOPAIR_LBOUNDS[$pair]}` with pair='{') re-parse as
// broken syntax there ("failed to compile regex: repetition
// quantifier…" + a `}` appended per keystroke).
if let Some((_, v)) = crate::vm_helper::assoc_key_hit(name, idx) {
return hash_key_value(name, idx, v);
}
}
// c:Src/params.c:1449-1450 getindex — a leading `(e)`/`(E)` flag
// group makes the subscript LITERAL (group consumed, exact key).
// The textual rebuild below re-parses a FLAT `${name[(e)KEY]}`
// string, so a `]` / `}` that arrived via `$key` expansion
// terminates the subscript / brace early — "bad substitution" or
// spilled-junk values (zpwr expandstats iterates alias keys
// containing brackets). C never re-parses: getarg scans the
// TOKENIZED source where expanded data brackets are inert. Do the
// exact-match lookup directly against the assoc (plain or magic
// alias tables); search groups ((r)/(i)/(k)/…) and other targets
// keep the textual path.
if let Some(rest) = idx.strip_prefix('(') {
if let Some(close) = rest.find(')') {
let grp = &rest[..close];
if !grp.is_empty() && grp.chars().all(|ch| ch == 'e' || ch == 'E') {
let key = &rest[close + 1..];
if let Some(hit) = direct_assoc_key_get(name, key) {
return if is_alias_view(name) { assoc_key_value(hit) } else { hash_key_value(name, idx, hit) };
}
}
}
}
// Plain assoc key that the flat rebuild would mangle (`]` closes
// the subscript, `}` closes the brace): direct lookup. On a miss
// return empty — the textual fallback cannot represent the key.
if (idx.contains(']') || idx.contains('}')) && !idx.starts_with('(') {
if let Some(hit) = direct_assoc_key_get(name, idx) {
return if is_alias_view(name) { assoc_key_value(hit) } else { hash_key_value(name, idx, hit) };
}
}
let body = format!("${{{}[{}]}}", name, expanded_subscript_text(idx));
// The key here is already expanded; C validated only the raw text
// (c:Src/params.c:2029-2045). See subst::SUBSCRIPT_PREEXPANDED.
crate::ported::subst::SUBSCRIPT_PREEXPANDED.with(|c| c.set(true));
// c:Src/subst.c:4226 — `if (isarr && ssub) { val = sepjoin(aval, NULL, 1);
// isarr = 0; }`. `PREFORK_SINGLE` is the whole of `ssub` (c:1761), and the
// ported `paramsubst` already carries that gate (`ssub_c4226` /
// `ssub_join_c3903` in `src/ported/subst.rs`); this fast path just had no
// way to say it.
let v = paramsubst_to_value_pf(
&body,
if ssub {
crate::ported::zsh_h::PREFORK_SINGLE
} else {
0
},
);
// A body that never reached the subscript check must not leave the
// carrier armed for the next, unrelated subscript.
crate::ported::subst::SUBSCRIPT_PREEXPANDED.with(|c| c.set(false));
v
}
/// The `zsh/parameter` alias views `direct_assoc_key_get` serves itself.
fn is_alias_view(name: &str) -> bool {
matches!(
name,
"aliases" | "galiases" | "saliases" | "dis_aliases" | "dis_galiases" | "dis_saliases"
)
}
/// Exact-key read against an assoc-like target WITHOUT the textual
/// `${name[key]}` reparse (see array_index_lookup — expanded `]`/`}`
/// in keys break the flat form). `Some(hit)` when `name` is a target
/// this helper understands (plain assoc, or the alias magic assocs of
/// zsh/parameter — Src/Modules/parameter.c getpmalias family);
/// `None` = not direct-capable, caller keeps the textual path.
fn direct_assoc_key_get(name: &str, key: &str) -> Option<Option<String>> {
use crate::ported::zsh_h::{ALIAS_GLOBAL, DISABLED};
// c:Src/Modules/parameter.c:1247+ getpmalias / getpmgalias /
// getpmsalias — each view filters its table by flags.
let alias_view = |global: bool, suffix: bool, disabled: bool| -> Option<String> {
let tab = if suffix {
crate::ported::hashtable::sufaliastab_lock()
} else {
crate::ported::hashtable::aliastab_lock()
};
tab.read().ok().and_then(|t| {
t.iter().find_map(|(k, a)| {
let f = a.node.flags as u32;
if k == key
&& ((f & ALIAS_GLOBAL as u32 != 0) == global || suffix)
&& ((f & DISABLED as u32 != 0) == disabled)
{
Some(a.text.clone())
} else {
None
}
})
})
};
match name {
"aliases" => Some(alias_view(false, false, false)),
"galiases" => Some(alias_view(true, false, false)),
"saliases" => Some(alias_view(false, true, false)),
"dis_aliases" => Some(alias_view(false, false, true)),
"dis_galiases" => Some(alias_view(true, false, true)),
"dis_saliases" => Some(alias_view(false, true, true)),
_ => {
// Single-lock O(1) probe (see assoc_key_hit) — the previous
// double exec.assoc() cloned the whole map twice per lookup.
crate::vm_helper::assoc_key_hit(name, key).map(|(_, v)| v)
}
}
}
/// KSHARRAYS bare-`$name` expansion words for the unbraced
/// no-subscript form (BUILTIN_ARRAY_INDEX_UNBRACED's KSHARRAYS arm).
///
/// - `@` / `*` stay the full positional list (the c:Src/params.c:
/// 2293-2296 first-element collapse is gated on
/// `itype_end(t, IIDENT, 1) != t` — an identifier-shaped name —
/// which `@`/`*` are not). The literal `[idx]` then joins the LAST
/// word, matching zsh 5.9: `setopt ksharrays; set -- p q;
/// print -- $@[0]` → `zsh:1: no matches found: q[0]`.
/// - Identifier-named arrays collapse to the FIRST element
/// (c:Src/params.c:2293-2296 `v->end = 1, v->isarr = 0`).
/// - Assocs collapse to the first value in scan order; the `options`
/// magic assoc's scan order is `OPTIONTAB` bucket order (first key
/// `posixargzero`), matching zsh 5.9: `emulate sh -L;
/// print $options[posixargzero]` → `off[posixargzero]`.
/// - Scalars / unset names expand to their value / empty (zsh 5.9:
/// `setopt ksharrays; print -- $unsetvar[0]` →
/// `zsh:1: no matches found: [0]`).
fn ksharrays_bare_words(name: &str) -> Vec<String> {
if name == "@" || name == "*" {
return with_executor(|exec| exec.pparams());
}
// Magic special-parameter lookups first — mirrors the
// BUILTIN_GET_VAR precedence (partab before executor tables).
if let Some(vals) = crate::vm_helper::partab_array_get(name) {
return vec![vals.into_iter().next().unwrap_or_default()];
}
if let Some(keys) = crate::vm_helper::partab_scan_keys(name) {
// c:Src/params.c:2342-2350 — under KSH emulation a bare special
// hash is `${hash[0]}`, same arm as the plain assoc below.
if crate::ported::zsh_h::EMULATION(crate::ported::zsh_h::EMULATE_KSH) {
return vec![crate::vm_helper::partab_get(name, "0").unwrap_or_default()];
}
let v = keys
.first()
.and_then(|k| crate::vm_helper::partab_get(name, k))
.unwrap_or_default();
return vec![v];
}
let arr_or_assoc = with_executor(|exec| {
if let Some(arr) = exec.array(name) {
// c:Src/params.c:2293-2296 — first element only.
return Some(arr.first().cloned().unwrap_or_default());
}
if let Some(map) = exec.assoc(name) {
// c:Src/params.c:2351-2358 — under KSH EMULATION a bare
// `$assoc` is `${assoc[0]}` (KEY-"0" lookup), EMPTY unless the
// hash has a key "0": `emulate -L ksh; typeset -A h=(a 1 b 2);
// print $h` is empty. Every other mode (`setopt ksharrays`,
// `emulate sh`) falls through to the first bucket value below.
if crate::ported::zsh_h::EMULATION(crate::ported::zsh_h::EMULATE_KSH) {
return Some(map.get("0").cloned().unwrap_or_default());
}
// Mirrors BUILTIN_GET_VAR's bare-assoc ordering
// (sorted keys, first value).
let mut keys: Vec<&String> = map.keys().collect();
keys.sort();
return Some(
keys.first()
.and_then(|k| map.get(*k).cloned())
.unwrap_or_default(),
);
}
None
});
if let Some(v) = arr_or_assoc {
return vec![v];
}
vec![with_executor(|exec| exec.get_variable(name))]
}
/// Run `body` through `crate::ported::subst::paramsubst` and convert
/// the resulting node list into a fusevm `Value`. Centralises the
/// pattern duplicated across ~10 BUILTIN_* handlers:
/// - build a `${...}` body string from opcode operands
/// - paramsubst the body
/// - propagate errflag to `exec.last_status`
/// - delegate the LinkList → Value conversion to `nodes_to_value`
///
/// **Extension** — Rust-only helper. No direct C analog because C
/// zsh uses LinkList everywhere; the conversion happens at the
/// boundary back into the VM's stack.
fn paramsubst_to_value(body: &str) -> Value {
paramsubst_to_value_pf(body, 0)
}
/// `paramsubst_to_value` with an explicit `pf_flags` (`PREFORK_*`) set.
///
/// c:Src/subst.c:1627 — `paramsubst(l, n, str, qt, pf_flags, ret_flags)`.
/// The only caller that needs a non-zero set today is the `${(flags)NAME}`
/// fast path when the word is a scalar-assignment VALUE: C preforks that with
/// `PREFORK_SINGLE|PREFORK_ASSIGN` (c:Src/exec.c:2603 for `x=…`,
/// c:Src/exec.c:4239-4241 for the typeset-family `NAME=…` argument), and
/// `PREFORK_SINGLE` is the `ssub` that turns off c:3913's forced split.
fn paramsubst_to_value_pf(body: &str, pf_flags: i32) -> Value {
// c:Src/subst.c:1625 paramsubst's `qt` flag is the C signal that
// the current expansion is inside `"…"`. The fast-path bridges
// (BUILTIN_PARAM_*, BUILTIN_BRIDGE_BRACE_ARRAY) used to hardcode
// qt=false, which silently broke DQ-only semantics inside
// `${arr:^other}` / `${arr:^^other}` (Src/subst.c:3456-3520).
// The executor's `in_dq_context` counter is bumped by EXPAND_TEXT
// mode 1 / mode 5 before the bridge fires, so reading it here
// propagates the DQ flag without changing every bridge call site.
let qt = with_executor(|exec| exec.in_dq_context > 0);
// c:Src/subst.c:318-324 — this is the bridge's stand-in for stringsubst's
// paramsubst call, and that call site is where SH_WORD_SPLIT enters:
// if ((isset(SHWORDSPLIT) && !(pf_flags & PREFORK_NOSHWORDSPLIT)) ||
// (pf_flags & PREFORK_SPLIT))
// pf_flags |= PREFORK_SHWORDSPLIT;
// node = paramsubst(list, node, &str, qt,
// pf_flags & (PREFORK_SINGLE|PREFORK_SHWORDSPLIT|PREFORK_SUBEXP), …);
// paramsubst's `spbreak` (c:1707) reads only that flag, never the option.
// Passing the callers' bare flags left every compiled `${…}` fast path
// unsplit: `setopt shwordsplit; s='a o b'; print -l ${s/o/x}` printed one
// word where zsh prints `a` `x` `b` (same for `${s:-x}`, `${s#a}`,
// `${s:1}`, `${(U)s}`, `${${s}/o/ }`). A scalar-assignment value still
// passes PREFORK_SINGLE, which keeps `spbreak` off there.
let pf_flags = {
use crate::ported::zsh_h::{
PREFORK_NOSHWORDSPLIT, PREFORK_SHWORDSPLIT, PREFORK_SINGLE, PREFORK_SPLIT,
PREFORK_SUBEXP, SHWORDSPLIT,
};
let mut f = pf_flags;
if (crate::ported::zsh_h::isset(SHWORDSPLIT) && f & PREFORK_NOSHWORDSPLIT == 0)
|| f & PREFORK_SPLIT != 0
{
f |= PREFORK_SHWORDSPLIT; // c:321
}
f & (PREFORK_SINGLE | PREFORK_SHWORDSPLIT | PREFORK_SUBEXP) // c:324-325
};
let mut ret_flags: i32 = 0;
// c:Src/subst.c:183-186 — `body` is the `${…}` BODY, not the word: the
// caller's literals are attached by its own concat opcodes afterwards.
// `PARAMSUBST_AFFIXES_DEFERRED` (set by `BUILTIN_WORD_DEFER_EMPTIES`)
// says the caller will also run the end-of-word empty-node removal, so
// `paramsubst` must not run it early — see that declaration in
// `src/ported/subst.rs`.
//
// The declaration belongs to the OUTERMOST expansion of the word only.
// A bridge expansion re-entered from inside this one is its own
// finished word with nobody left to attach anything to it, so it keeps
// the removal — `IN_BRIDGE_PARAMSUBST` is that re-entry guard (the
// ported `IN_PARAMSUBST_NEST` covers only the `stringsubst` route).
// Both cells are restored afterwards so the word's remaining segments
// still defer (`A${a%z}B${b%z}C`).
let reentered = IN_BRIDGE_PARAMSUBST.with(|c| c.replace(true));
let saved_defer = crate::ported::subst::PARAMSUBST_AFFIXES_DEFERRED.with(|c| c.get());
if reentered {
crate::ported::subst::PARAMSUBST_AFFIXES_DEFERRED.with(|c| c.set(0));
}
let (_full, _pos, nodes) =
crate::ported::subst::paramsubst(body, 0, qt, pf_flags, &mut ret_flags);
let null_return = take_paramsubst_null();
crate::ported::subst::PARAMSUBST_AFFIXES_DEFERRED.with(|c| c.set(saved_defer));
IN_BRIDGE_PARAMSUBST.with(|c| c.set(reentered));
if null_return {
// c:Src/subst.c:1878/326-327 — the word ends at this `$`. For a scalar
// nothing of this expansion is kept. For an array, c:4383-4394 had
// already inserted the elements evaluated before the failing one, so
// those survive as words (`arr=(one '$(' two); ${(e)arr}` is `one`).
// See BUILTIN_PREFORK_CUT_CHECK.
let kept: Vec<String> = nodes
.into_iter()
.filter(|n| !n.is_empty())
.map(|n| crate::ported::lex::untokenize(&n).to_string())
.collect();
return if kept.is_empty() {
Value::str(String::new())
} else {
nodes_to_value(kept)
};
}
// c:Src/exec.c:3523-3525 — an expansion error aborts the command with
// `if (errflag) { if (!lastval) lastval = 1; …`: a non-zero status from
// the previous command survives (`nosuchcmd; print ${.bad}` exits 127).
if crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed) != 0 {
with_executor(|exec| {
if exec.last_status() == 0 {
exec.set_last_status(1);
}
});
}
// c:Src/lex.c untokenize — the final argv pass C runs on every
// expanded word (glob.c:1862 / exec.c) DROPS the Nularg
// empty-word sentinel (c:2089 `if (c != Nularg)`) that
// remnulargs faithfully leaves in place (glob.c:3673 re-adds it
// for all-empty results). These fast-path bridges are terminal —
// their output lands directly in argv slots — so apply it here.
// Without it, quoted splits with empty pieces ("${(s:|:)x}" on
// "|a|b|") leak Nularg into argv.
// c:Src/subst.c:178-181 — `prefork` runs `filesub` on the word AFTER
// `stringsubst` and BEFORE anything untokenizes it, which is what makes a
// `~` inside an expansion body expand: `filesubstr` (c:741) matches the
// lexer's `Tilde` TOKEN, never an ASCII `~`. These bridges are terminal
// and the untokenize below folds that token back to `~`, so the filesub
// the word path runs afterwards had nothing left to act on and
// `${XDG_CACHE_HOME:-~/.cache}` came back literal (powerlevel10k's dump
// path, powerlevel10k.zsh-theme:62). Run C's order here: filesub first,
// untokenize second.
//
// Gated exactly like the prefork site (subst.rs:396): not under
// `SHFILEEXPANSION` (whose file expansion runs BEFORE substitution, so an
// expansion result is never tilde-expanded), not inside `"…"` (`qt`), and
// not while `SKIP_FILESUB` marks a `${var/pat/repl}` pattern context where
// a literal `~` must survive.
// The word this expansion belongs to runs its own end-of-word drop.
// A lone node that is NOTHING BUT the c:36 `nulstring` marker is an
// empty FIELD a split produced, not an empty word. C drops the marker
// in its final untokenize pass (c:Src/lex.c:2089), but prefork's
// node-removal decision at c:183 was made before that, with the marker
// still in place, so the word survives as "". Folding it here instead
// hands `nodes_to_value` a node it cannot tell from a genuine empty,
// and its single-node drop deletes it — see the trace there. `IFS=:;
// v=":"; set -- $v` under `--dash` reported `$#` as 0 where dash, bash
// and ksh all report 1.
// Only outside `"…"`. A quoted expansion keeps its empty string on its
// own (`nodes_to_value`'s `in_dq_context` arm), so there is no drop to
// protect it from — and the paths a quoted word takes do not all run
// remnulargs afterwards, so keeping the marker there put a literal
// Nularg in the output: `b=(1 2 3 4 5); c=(2 4 6);
// print -r -- "[${(j: :)b:*c}]"` printed `[¡]` instead of `[]`.
let lone_marker = !qt
&& nodes.len() == 1
&& nodes[0].chars().eq(std::iter::once(crate::ported::zsh_h::Nularg));
let keep_nulargs = (saved_defer > 0 && !reentered) || lone_marker;
let do_filesub = !qt
&& !crate::ported::zsh_h::isset(crate::ported::zsh_h::SHFILEEXPANSION)
&& !crate::ported::subst::SKIP_FILESUB.with(|c| c.get());
let nodes: Vec<String> = nodes
.into_iter()
.map(|n| {
let n = if do_filesub {
crate::ported::subst::filesub(
&n,
pf_flags
& (crate::ported::zsh_h::PREFORK_TYPESET
| crate::ported::zsh_h::PREFORK_ASSIGN),
)
} else {
n
};
// c:36 `nulstring` survives for the word's end-of-word drop (see
// BUILTIN_WORD_ELIDE_EMPTY / BUILTIN_ARRAY_DROP_EMPTY): untokenize
// would fold it to "", which that drop cannot tell from a real
// empty node.
if keep_nulargs && n.contains(crate::ported::zsh_h::Nularg) {
n.split(crate::ported::zsh_h::Nularg)
.map(crate::ported::lex::untokenize)
.collect::<Vec<_>>()
.join(&crate::ported::zsh_h::Nularg.to_string())
} else {
crate::ported::lex::untokenize(&n)
}
})
.collect();
let value = nodes_to_value(nodes);
// Provenance: this is the funnel every `${...}` bytecode fast path
// reaches, so it is where a tracked parameter's chain is handed to
// the value the expansion produced.
if crate::provenance::active() {
if let Some(name) = prov_subst_name(body) {
crate::provenance::on_param_read(&name, &value);
}
}
value
}
/// !!! RUST-ONLY ADAPTER — the dual `$?` store !!!
///
/// `paramsubst_to_value_pf` for the compiled `${…}` fast-path builtins, whose
/// body can run a command substitution (`${y:-$(exit 4)}`, `${y#$(…)}`).
/// C has ONE `lastval`: getoutput's `lastval = cmdoutval` (c:Src/exec.c:4775)
/// is what a later `$?` in the same command reads, so
/// `print ${y:-$(exit 4)} $?` prints `4`. zshrs also keeps `vm.last_status`,
/// which `BUILTIN_GET_VAR` treats as authoritative, so the inner status has
/// to be handed back to it — the same two-way mirror `BUILTIN_CMD_SUBST_TEXT`
/// and `BUILTIN_EXPAND_TEXT` do around their own cmd-subst runs.
fn paramsubst_to_value_status(vm: &mut fusevm::VM, body: &str, pf_flags: i32) -> Value {
// The substitution sees the live `$?` (`false; print ${y:-$(print $?)}`).
let live_status = vm.last_status;
with_executor(|exec| exec.set_last_status(live_status));
let v = paramsubst_to_value_pf(body, pf_flags);
vm.last_status = with_executor(|exec| exec.last_status()); // c:4775
v
}
/// Parameter name inside a `${...}` expansion body, for the provenance
/// tap in `paramsubst_to_value_pf`. Skips a leading `(flags)` group and
/// the `#`/`+`/`^`/`=`/`~` prefix sigils, then takes the identifier —
/// `${(k)assoc[key]}` yields `assoc`, `${#F}` yields `F`. Returns `None`
/// for the forms with no single named source (`$(...)`, `${(%)...}`).
fn prov_subst_name(body: &str) -> Option<String> {
let mut rest = body.strip_prefix("${").or_else(|| body.strip_prefix('$'))?;
rest = rest.trim_end_matches('}');
// Skip one leading `(flags)` group.
if let Some(after) = rest.strip_prefix('(') {
rest = after.split_once(')').map(|(_, r)| r)?;
}
rest = rest.trim_start_matches(['#', '+', '^', '=', '~']);
let name: String = rest
.chars()
.take_while(|c| c.is_alphanumeric() || *c == '_')
.collect();
if name.is_empty() {
None
} else {
Some(name)
}
}
/// Wrap a `Vec<String>` (e.g. paramsubst nodes, multsub parts,
/// xpandbraces output) into a fusevm `Value`: 0 → empty Array, 1 →
/// Str, >1 → Array. Same unwrap idiom every handler that calls a
/// canonical Vec-returning fn does.
/// c:Src/subst.c:1663 — `int plan9 = isset(RCEXPANDPARAM);`
///
/// zsh calls the RC_EXPAND_PARAM word shape "plan9" after the rc(1)
/// shell it comes from. The option is read fresh on every expansion
/// (`setopt` mid-script changes the very next word), so the concat
/// builtins must consult it at RUNTIME, not bake it in at compile time.
fn plan9_active() -> bool {
with_executor(|_exec| opt_state_get("rcexpandparam").unwrap_or(false))
}
thread_local! {
/// The `isarr` bit that `Value` cannot carry.
///
/// c:Src/subst.c:4245 `if (isarr)` gates the whole array emit block,
/// so plan9's word-removal rule (c:4362 `uremnode`) only ever applies
/// to an ARRAY-valued expansion. An empty SCALAR has `isarr == 0`,
/// takes the c:4437 scalar branch, and leaves the surrounding text
/// intact — `setopt rcexpandparam; v=; print -rl -- x$v y` prints `x`
/// and `y`, while the same line with an empty ARRAY prints only `y`.
///
/// zshrs collapses BOTH shapes to `Value::Array(vec![])`: a real empty
/// array, and an unquoted empty scalar (collapsed so a standalone `$v`
/// contributes zero argv words, mirroring prefork's `uremnode` at
/// c:Src/subst.c:184-187). The two are indistinguishable by the time
/// they reach a concat builtin, so the expansion builtins record here
/// whether the empty Array they just produced came from a scalar.
///
/// Sticky until the next expansion overwrites it — a word folds its
/// segments left-associatively (`concat(concat(x, $e), y)`), so the
/// propagating second concat must still see the first one's bit.
/// Consequence: only a builtin that RETURNS an empty `Value::Array` may
/// write the cell. A builtin returning an empty SCALAR `Value` must leave
/// it alone, or it resurrects a word an earlier empty array deleted
/// (`a=(); x${a}"${P}"y` is zero words in zsh) — see the
/// `word_has_quoted_span` arm of `BUILTIN_EXPAND_TEXT`.
static EMPTY_EXPANSION_IS_SCALAR: std::cell::Cell<bool> =
const { std::cell::Cell::new(false) };
}
/// Record whether the empty expansion just produced was a scalar (`true`)
/// or a genuine array (`false`). See `EMPTY_EXPANSION_IS_SCALAR`.
fn note_empty_is_scalar(is_scalar: bool) {
EMPTY_EXPANSION_IS_SCALAR.with(|c| c.set(is_scalar));
}
/// True when the empty `Value::Array` about to be concatenated stands for
/// an empty SCALAR (c:4438-4467), not an empty array (c:4362).
fn empty_is_scalar() -> bool {
EMPTY_EXPANSION_IS_SCALAR.with(|c| c.get())
}
thread_local! {
/// The other `isarr` bit `Value` cannot carry: whether an empty element
/// of the array now on the stack is ELIDABLE.
///
/// c:Src/subst.c:36 `char nulstring[] = {Nularg, '\0'};` — zsh does not
/// represent a split-produced empty field as the empty string. Every
/// place that manufactures one (the SH_WORD_SPLIT scalar split at
/// c:3919 `sepsplit`, command substitution's split, the quoted-array
/// retention at c:4354 `if (qt && !*y && isarr != 2) y =
/// dupstring(nulstring)`) stores `nulstring`, whose node text is
/// NON-empty — so prefork's node-removal test at c:183
/// `if (*(char *)getdata(node))` KEEPS it, and `remnulargs` (c:170)
/// turns it back into "" afterwards. Only an empty element that came
/// from a genuine ARRAY read is stored as a true empty string, and only
/// that one reaches c:186 `uremnode`.
///
/// zshrs renders both shapes as `String::new()`, so the marker C tests
/// on is gone by the time a word is assembled. This cell carries it
/// instead: `get_var_impl` sets it on the unquoted array/assoc read
/// paths (C's `isarr` != 2 array reference), and `BUILTIN_WORD_ELIDE_EMPTY`
/// consumes it. Without the distinction the elide either dropped
/// split fields zsh keeps (`setopt shwordsplit; IFS=:; s='a::b';
/// print -rl -- ${s}` is `a` `` `b`; `IFS=:; print -rl -- $(printf
/// 'a::b')` likewise) or kept array empties zsh drops.
///
/// Sticky across a word's segment folds, cleared when an end-of-word
/// drop builtin consumes it.
static ARRAY_EMPTIES_ELIDABLE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
thread_local! {
/// The opposite bit: this word's array came out of a QUOTED splat whose
/// empty elements C stores as `nulstring`, so the end-of-word drop must
/// KEEP them.
///
/// c:Src/subst.c:4387, :4404, :4426 — every node the array emit block
/// produces runs `if (qt && !*y && isarr != 2) y = dupstring(nulstring)`.
/// `nulstring` (c:36 `{Nularg, '\0'}`) is NON-empty, so c:183's
/// `if (*(char *)getdata(node))` keeps the node and c:186's `uremnode`
/// never sees it; `remnulargs` (c:170) turns it back into `""`.
///
/// The rule has a RUN-time cut-off that no compile-time gate can express:
/// c:4261 `if ((!aval[0] || !aval[1]) && !plan9)` claims the empty and
/// single-element cases FIRST and strips the surrounding `Dnull` markers
/// (c:4272-4274 `*--aptr = '\0', fstr++`), so those nodes really are empty
/// and c:186 deletes them. That is why `a=(); b=(); "${a[@]}""${b[@]}"` is
/// ZERO words while `a=(x '' y); PRE"${a[@]}"POST` is three. Hence the bit
/// is set by the READ (which knows the element count) and only when the
/// compile site marked the splat quoted (`BUILTIN_ARRAY_ALL` argc 4, or
/// `BUILTIN_GET_VAR_DQ` on the `@` positional).
///
/// Word-scoped: cleared when a word opens (`BUILTIN_WORD_DEFER_EMPTIES`
/// argc 0), cleared by any UNQUOTED array read
/// (`note_array_empties_elidable`, its exact complement), and consumed by
/// the end-of-word drop.
///
/// Known residue: the bit is per-WORD, while C's `nulstring` is per-NODE,
/// so a word mixing a quoted and an unquoted splat
/// (`PRE"${a[@]}"${b[@]}POST`) keeps both sets of empties where C keeps
/// only the quoted one.
static QUOTED_SPLICE_KEEPS_EMPTIES: std::cell::Cell<bool> =
const { std::cell::Cell::new(false) };
}
/// Record that the value just read is a genuine ARRAY reference, so an empty
/// element of it is a true empty word. See `ARRAY_EMPTIES_ELIDABLE`.
fn note_array_empties_elidable() {
ARRAY_EMPTIES_ELIDABLE.with(|c| c.set(true));
// c:4387's `qt` half is false for this read, so nothing it produced is
// `nulstring`. The two bits are complements; do not let a previous word's
// quoted splat keep this one's empties.
QUOTED_SPLICE_KEEPS_EMPTIES.with(|c| c.set(false));
}
/// Read and clear the elidable-empties bit. See `ARRAY_EMPTIES_ELIDABLE`.
fn take_array_empties_elidable() -> bool {
ARRAY_EMPTIES_ELIDABLE.with(|c| c.replace(false))
}
/// c:Src/subst.c:4387 — record that a QUOTED splat of `n` elements was read.
/// c:4261's cut-off means the `nulstring` rewrite is only reachable for
/// `n >= 2`; below that the emit block strips the quotes and the node is a
/// true empty. See `QUOTED_SPLICE_KEEPS_EMPTIES`.
fn note_quoted_splice_elems(n: usize) {
QUOTED_SPLICE_KEEPS_EMPTIES.with(|c| c.set(n >= 2));
}
/// Read and clear the quoted-splat bit. See `QUOTED_SPLICE_KEEPS_EMPTIES`.
fn take_quoted_splice_keeps_empties() -> bool {
QUOTED_SPLICE_KEEPS_EMPTIES.with(|c| c.replace(false))
}
/// Declare that the word now being assembled attaches its own literals, so
/// `paramsubst` must leave c:183-186's empty-node removal to this word's
/// end-of-word drop. See `BUILTIN_WORD_DEFER_EMPTIES` and, in
/// `src/ported/subst.rs`, `PARAMSUBST_AFFIXES_DEFERRED`.
fn open_deferred_affix_word() {
crate::ported::subst::PARAMSUBST_AFFIXES_DEFERRED.with(|c| c.set(c.get() + 1));
// c:4387's `qt`/`nulstring` bit belongs to the word being assembled, so a
// word that opens starts from a clean one — a preceding whole-word
// `"${a[@]}"` emits no end-of-word drop and would otherwise leave it set.
QUOTED_SPLICE_KEEPS_EMPTIES.with(|c| c.set(false));
}
/// End the declaration `open_deferred_affix_word` made — the marker's
/// closing half (argc 1), emitted by `compile_zsh` immediately after this
/// word's drop. Pairing it with the OPEN rather than with the drop itself
/// matters: `BUILTIN_ARRAY_DROP_EMPTY` is also emitted for a bare splice
/// segment that opened nothing (`P${b[@]}${a%z}Q` emits one for `${b[@]}`),
/// and letting that close the enclosing word ended the declaration before
/// `${a%z}` was reached.
///
/// The `PARAMSUBST_EMPTIES_DEFERRED` report is cleared only when the
/// OUTERMOST word closes: the drop that consumes it is that word's.
fn close_deferred_affix_word() {
let depth = crate::ported::subst::PARAMSUBST_AFFIXES_DEFERRED.with(|c| {
c.set((c.get() - 1).max(0));
c.get()
});
if depth == 0 {
crate::ported::subst::PARAMSUBST_EMPTIES_DEFERRED.with(|c| c.set(false));
}
}
thread_local! {
/// True while `paramsubst_to_value_pf` is inside `paramsubst`.
///
/// The deferral `BUILTIN_WORD_DEFER_EMPTIES` declares is a property of
/// the WORD the compiler is assembling, so it applies to that word's own
/// segment expansions and to nothing they in turn expand. A bridge
/// expansion re-entered from inside one (a nested body the compiler
/// routed through its own opcodes, or anything the ported code drives
/// back through this funnel) is a finished word already, so c:183-186's
/// removal stays where it is for that one.
static IN_BRIDGE_PARAMSUBST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// Re-assert `was_scalar` when `v` is an empty result.
///
/// For a pass-through stage — one that rewrites word TEXT but cannot turn a
/// scalar into an array or vice versa — the shape bit belongs to whichever
/// expansion produced the value, not to the stage. Such stages usually end in
/// `nodes_to_value`, which records "array" for an empty result, so without
/// this the producer's bit is lost before `concat_plan9` reads it.
/// Non-empty results carry their shape in the `Value` itself and are
/// returned untouched.
fn restore_empty_shape(v: Value, was_scalar: bool) -> Value {
if matches!(&v, Value::Array(a) if a.is_empty()) {
note_empty_is_scalar(was_scalar);
}
v
}
/// `concat_splice` with the provenance tap applied to the result. Every
/// concat bytecode op routes through this (or `concat_plan9_prov`), so a
/// word built out of a tracked parameter keeps that parameter's lineage
/// even though the concatenated bytes are a fresh allocation.
fn concat_splice_prov(lhs: Value, rhs: Value) -> Value {
if !crate::provenance::active() {
return concat_splice(lhs, rhs);
}
let (l, r) = (lhs.clone(), rhs.clone());
let out = concat_splice(lhs, rhs);
crate::provenance::on_concat(&l, &r, &out);
out
}
/// `concat_plan9` with the provenance tap. See `concat_splice_prov`.
fn concat_plan9_prov(lhs: Value, rhs: Value) -> Value {
if !crate::provenance::active() {
return concat_plan9(lhs, rhs);
}
let (l, r) = (lhs.clone(), rhs.clone());
let out = concat_plan9(lhs, rhs);
crate::provenance::on_concat(&l, &r, &out);
out
}
/// c:Src/subst.c:4366-4437 — the NON-plan9 arm of paramsubst's array
/// emit block: "simply join the first and last values."
///
/// The word prefix (`ostr..aptr`) is concatenated onto element 0
/// (c:4386 `strcatsub(&y, ostr, aptr, x, xlen, NULL, …)`), the interior
/// elements are emitted bare (c:4393-4412), and the word suffix (`fstr`)
/// is concatenated onto the final element (c:4414-4429). Applied left-
/// associatively across a word's segments this reproduces zsh's
/// `pre${arr}post` → `prep` / `q` / `rpost`.
///
/// An EMPTY array never reaches this arm in C: c:4261
/// `if ((!aval[0] || !aval[1]) && !plan9)` collapses it to the scalar ""
/// first, so the surrounding text survives as one word (`x$e y` → `x`).
/// That is what the empty-Array arms below reproduce.
fn concat_splice(lhs: Value, rhs: Value) -> Value {
match (lhs, rhs) {
(Value::Array(la), Value::Array(ra)) => {
if la.is_empty() {
return Value::Array(ra);
}
if ra.is_empty() {
return Value::Array(la);
}
// Last of la merges with first of ra; rest unchanged.
let mut la = la.to_vec();
let last_l = la.pop().unwrap();
let mut ra_iter = ra.iter().cloned();
let first_r = ra_iter.next().unwrap();
let l_s = last_l.as_str_cow();
let r_s = first_r.as_str_cow();
let mut merged = String::with_capacity(l_s.len() + r_s.len());
merged.push_str(&l_s);
merged.push_str(&r_s);
la.push(Value::str(merged));
la.extend(ra_iter);
Value::array(la)
}
(Value::Array(la), rhs_scalar) => {
// c:4261 — empty array + empty surrounding text is zero
// words, not one empty word. Bug #120 in docs/BUGS.md:
// `b=("${a[@]:0:-1}")` gave len=1 instead of zsh's len=0.
let rhs_s = rhs_scalar.as_str_cow();
if la.is_empty() {
if rhs_s.is_empty() {
return Value::array(Vec::new());
}
return Value::str(rhs_s.to_string());
}
let mut la = la.to_vec();
let last = la.pop().unwrap();
let l_s = last.as_str_cow();
let mut s = String::with_capacity(l_s.len() + rhs_s.len());
s.push_str(&l_s);
s.push_str(&rhs_s);
la.push(Value::str(s));
Value::array(la)
}
(lhs_scalar, Value::Array(ra)) => {
let lhs_s = lhs_scalar.as_str_cow();
if ra.is_empty() {
// Symmetric c:4261 empty-array rule; see the arm above.
if lhs_s.is_empty() {
return Value::array(Vec::new());
}
return Value::str(lhs_s.to_string());
}
let mut ra = ra.to_vec();
let first = ra.remove(0);
let r_s = first.as_str_cow();
let mut s = String::with_capacity(lhs_s.len() + r_s.len());
s.push_str(&lhs_s);
s.push_str(&r_s);
let mut out = Vec::with_capacity(ra.len() + 1);
out.push(Value::str(s));
out.extend(ra);
Value::array(out)
}
(lhs_s, rhs_s) => {
let l = lhs_s.as_str_cow();
let r = rhs_s.as_str_cow();
let mut s = String::with_capacity(l.len() + r.len());
s.push_str(&l);
s.push_str(&r);
Value::str(s)
}
}
}
/// c:Src/subst.c:4316-4365 — the plan9 (RC_EXPAND_PARAM) arm of
/// paramsubst's array emit block.
///
/// Every element gets the FULL word prefix and suffix
/// (c:4341 `strcatsub(&y, ostr, aptr, x, xlen, y + 1, …)` inside the
/// per-element loop), giving the cross product with the surrounding
/// text: `pre${arr}post` → `preppost` / `preqpost` / `prerpost`.
///
/// An EMPTY array removes the WHOLE word: the c:4327
/// `while ((x = *aval++))` loop body never runs, so `plan9` is still
/// non-zero at c:4362 and the node is deleted —
/// `if (plan9) { uremnode(l, n); return n; }` (c:4362-4365). `e=();
/// setopt RC_EXPAND_PARAM; print -rl -- x$e y` prints only `y`. This is
/// the opposite of the non-plan9 rule at c:4261, which keeps `x`.
fn concat_plan9(lhs: Value, rhs: Value) -> Value {
// c:4245 `if (isarr)` — an empty SCALAR never enters the array emit
// block, so it contributes "" and the word survives (c:4437). Only a
// real empty ARRAY reaches c:4362's `uremnode`. `Value` cannot tell
// the two apart; EMPTY_EXPANSION_IS_SCALAR carries the missing bit.
let scalar_empty = empty_is_scalar();
match (lhs, rhs) {
// c:4362-4365 — an empty array on either side deletes the word.
// Propagated as an empty Array so a later concat in the same word
// (`x${e[@]}y` folds twice) keeps the word deleted; pop_args
// splats an empty Array into zero argv words.
(Value::Array(la), rhs_v) if la.is_empty() => {
if scalar_empty {
// Empty scalar prefix: "" + rhs (c:4437 strcatsub).
return match rhs_v {
Value::Array(ra) if ra.is_empty() => Value::array(Vec::new()),
other => other,
};
}
Value::array(Vec::new())
}
(lhs_v, Value::Array(ra)) if ra.is_empty() => {
if scalar_empty {
// Empty scalar suffix: lhs + "" (c:4437 strcatsub).
return lhs_v;
}
Value::array(Vec::new())
}
(Value::Array(la), Value::Array(ra)) => {
let mut out = Vec::with_capacity(la.len() * ra.len());
for a in la.iter() {
let a_s = a.as_str_cow();
for b in ra.iter() {
let b_s = b.as_str_cow();
let mut s = String::with_capacity(a_s.len() + b_s.len());
s.push_str(&a_s);
s.push_str(&b_s);
out.push(Value::str(s));
}
}
Value::array(out)
}
(Value::Array(la), rhs_scalar) => {
let r = rhs_scalar.as_str_cow();
let out: Vec<Value> = la
.iter()
.map(|a| {
let a_s = a.as_str_cow();
let mut s = String::with_capacity(a_s.len() + r.len());
s.push_str(&a_s);
s.push_str(&r);
Value::str(s)
})
.collect();
Value::array(out)
}
(lhs_scalar, Value::Array(ra)) => {
let l = lhs_scalar.as_str_cow();
let out: Vec<Value> = ra
.iter()
.map(|b| {
let b_s = b.as_str_cow();
let mut s = String::with_capacity(l.len() + b_s.len());
s.push_str(&l);
s.push_str(&b_s);
Value::str(s)
})
.collect();
Value::array(out)
}
(lhs_s, rhs_s) => {
// Both scalar: nothing to distribute (c:4444 scalar branch).
let l = lhs_s.as_str_cow();
let r = rhs_s.as_str_cow();
let mut s = String::with_capacity(l.len() + r.len());
s.push_str(&l);
s.push_str(&r);
Value::str(s)
}
}
}
/// Flatten one word-segment `Value` into its element strings: an Array splats
/// to its items, a scalar is a single element.
fn word_seg_elems(v: &Value) -> Vec<String> {
match v {
Value::Array(items) => items.iter().map(|i| i.as_str_cow().into_owned()).collect(),
other => vec![other.as_str_cow().into_owned()],
}
}
/// Assemble a DQ word from its segments, mixing plan9 (`^`, cross-product) and
/// non-plan9 (splice) segments in one pass — see BUILTIN_WORD_ASSEMBLE_PLAN9.
///
/// c:Src/subst.c:4316-4437 — zsh threads a "growing edge" (`aptr`/`fstr`)
/// through the whole word: an element stays active until a splice freezes all
/// but the last. `active_lo` is the index where that active tail begins.
/// * plan9 segment → every active element crosses with EVERY new element;
/// all results stay active (c:4316-4350 cartesian). An empty plan9 array
/// deletes the word (c:4362 `uremnode`).
/// * splice segment → every active element takes the FIRST new element, the
/// remaining new elements append as fresh words; the last becomes the new
/// growing edge (c:4366-4437 first/last join). A single-element splice keeps
/// the whole active tail active (nothing frozen). An empty splice array
/// contributes nothing and leaves the word intact.
fn word_assemble_plan9(segments: &[Value], plan9_flags: &[bool]) -> Value {
let mut words: Vec<String> = Vec::new();
let mut active_lo: usize = 0;
let mut started = false;
for (i, seg) in segments.iter().enumerate() {
let plan9 = plan9_flags.get(i).copied().unwrap_or(false);
let elems = word_seg_elems(seg);
if plan9 && elems.is_empty() {
// c:4362-4365 — plan9 empty array deletes the whole word.
return Value::array(Vec::new());
}
if !started {
started = true;
// c:Src/subst.c:4261 — `if ((!aval[0] || !aval[1]) && !plan9)`.
// A NON-plan9 EMPTY expansion (empty array, or an empty scalar
// that zshrs collapsed to the same empty `Value::Array`) is
// folded into the word text as the empty string and the node
// SURVIVES (c:4268-4274 `strcatsub` of prefix + "" + suffix).
// Only the plan9 arm deletes the word, and that is the
// `uremnode` case already returned above (c:4362-4365).
//
// Seeding `words` with that single empty element is what keeps a
// growing edge alive for the segments that follow. Leaving
// `words` empty instead made `words[active_lo..]` an empty slice
// forever, so every later segment cross-multiplied against
// nothing and the whole word vanished: `n=""; a=(x y z);
// print -rl -- $n${^a}` printed nothing where zsh prints
// `x`/`y`/`z`, and `$n$a${^a}` dropped the leading `x`. Only a
// word whose FIRST segment was the empty one was affected —
// `pre$n${^a}` already started from the literal and hit the
// "contributes nothing" `continue` below.
words = if elems.is_empty() {
vec![String::new()]
} else {
elems
};
// plan9 → the whole first array is the growing edge; splice/scalar
// → only its last element grows, earlier ones are finalized words.
active_lo = if plan9 {
0
} else {
words.len().saturating_sub(1)
};
continue;
}
if plan9 {
let mut new_active = Vec::with_capacity(words[active_lo..].len() * elems.len());
for a in &words[active_lo..] {
for r in &elems {
new_active.push(format!("{a}{r}"));
}
}
let frozen_len = active_lo;
words.truncate(frozen_len);
words.extend(new_active);
active_lo = frozen_len; // all cross-products stay active
} else {
if elems.is_empty() {
// Non-plan9 empty array contributes nothing; word survives.
continue;
}
let frozen_len = active_lo;
let r0 = &elems[0];
let head: Vec<String> = words[active_lo..]
.iter()
.map(|a| format!("{a}{r0}"))
.collect();
words.truncate(frozen_len);
words.extend(head);
words.extend(elems[1..].iter().cloned());
active_lo = if elems.len() == 1 {
frozen_len // single-element splice: head stays the growing edge
} else {
words.len() - 1 // multi: only the last appended word grows
};
}
}
match words.len() {
0 => Value::array(Vec::new()),
1 => Value::str(words.pop().unwrap()),
_ => Value::array(words.into_iter().map(Value::str).collect()),
}
}
fn nodes_to_value(nodes: Vec<String>) -> Value {
// c:Src/glob.c:3649 remnulargs — strip the Nularg (`\u{e1a1}`)
// sentinel and other INULL bytes that paramsubst's splat block
// emits for empty array elements (so prefork's empty-node-delete
// pass doesn't drop them). Downstream consumers (cond `-z`/`-n`,
// command args, etc.) must see the post-remnulargs strings. Bug
// #185 in docs/BUGS.md: `[[ -z "${b[@]}" ]]` for b=("") returned
// false because the leftover `\u{e1a1}` had StringLen=1.
//
// ORDER MATTERS, and the single-node drop below is the second half of
// it. C tests a node's emptiness at c:183 BEFORE remnulargs runs at
// c:170, and `nulstring` is one byte long, so a node holding only the
// marker is NON-empty at that test. The drop has ALREADY happened by
// the time the marker becomes "", and nothing removes the node twice.
//
// Traced for `IFS=:; v=":"; set -- $v` under `--dash`:
// spacesplit(":") -> ["<nul>", ""] leading marker, trailing empty
// paramsubst c:183 -> ["<nul>"] the real empty goes, marker stays
// caller's fold -> [""] untokenize folds the marker
// here, unguarded -> [] dropped a second time
// `$#` was 0 where dash, bash and ksh all report 1. Two or more nodes
// never reach the single-node drop, which is why `::` was already
// right and only the lone separator was wrong.
let node_was_marked: bool = nodes.len() == 1 && !nodes[0].is_empty();
let stripped: Vec<String> = nodes
.into_iter()
.map(|mut s| {
crate::ported::glob::remnulargs(&mut s);
s
})
.collect();
if stripped.is_empty() {
// Zero nodes = an ARRAY-shaped expansion that produced no words
// (empty array splat, empty slice). c:4245 `if (isarr)` holds, so
// plan9 deletes the surrounding word (c:4362).
note_empty_is_scalar(false);
Value::array(Vec::new())
} else if stripped.len() == 1 {
let only = stripped.into_iter().next().unwrap();
// c:Src/subst.c:183-186 — `else if (!(flags & PREFORK_SINGLE)
// && !(*ret_flags & PREFORK_KEY_VALUE) && !keep)
// uremnode(list, node);`
// C zsh's prefork removes empty linknodes from the result
// list when in non-SINGLE (argv-context) mode. The ported
// prefork at subst.rs:388-396 honors the same delete-empty
// pass, but some paramsubst paths land here with a single-
// empty-string Vec instead of an empty Vec (paramsubst's
// slice / substring / parameter-flag branches allocate a
// result before checking emptiness). Mirror the prefork
// drop at this layer: single-empty under !in_dq_context
// collapses to Value::Array(empty), and pop_args (line 6243)
// splats the empty Array → zero argv words. DQ context
// (in_dq_context > 0) keeps the empty string so
// `echo "${UNSET}"` still produces an empty arg per zsh's
// quoting rules (c:Src/subst.c:1650-1656 isarr comment).
if only.is_empty() && !node_was_marked {
let in_dq = with_executor(|exec| exec.in_dq_context > 0);
if !in_dq {
// One empty node = a SCALAR-shaped empty result (c:4437),
// not an empty array — see EMPTY_EXPANSION_IS_SCALAR.
note_empty_is_scalar(true);
return Value::array(Vec::new());
}
}
Value::str(only)
} else {
Value::array(stripped.into_iter().map(Value::str).collect())
}
}
fn pop_args(vm: &mut fusevm::VM, argc: u8) -> Vec<String> {
let mut popped: Vec<Value> = Vec::with_capacity(argc as usize);
for _ in 0..argc {
popped.push(vm.pop());
}
popped.reverse();
let mut args: Vec<String> = Vec::with_capacity(popped.len());
for v in popped {
match v {
Value::Array(items) => {
for item in items.iter() {
args.push(item.to_str());
}
}
other => args.push(other.to_str()),
}
}
// `expand_glob` set the glob-failed cell when a no-match glob
// triggered nomatch (c:Src/glob.c:1877). Signal the failure via
// last_status + the per-command glob_failed cell; the dispatcher
// (`host_exec_external`) consumes + clears it and returns status 1
// without running the command body.
if with_executor(|exec| exec.current_command_glob_failed.get()) {
with_executor(|exec| exec.set_last_status(1));
}
// c:Src/exec.c:2709 setunderscore / c:Src/params.c:252 underscore_gsu
// — `$_` has exactly ONE store in zsh, the `zunderscore` global
// (`Src/init.c:49`), read back through `underscoregetfn`. It is
// never written into the parameter table: the `_` Param created by
// `IPDEF2("_", underscore_gsu, PM_DONTIMPORT)` (c:Src/params.c:326)
// carries `nullstrsetfn` as its setfn, so even `_=x` stores nothing.
//
// The deferred `pending_underscore` → `set_scalar("_")` promotion
// that used to live here was a second, contradictory store: it wrote
// the paramtab node, which (a) CLEARED the PM_UNSET that `unset _`
// had just set — resurrecting the parameter, so `${+_}` flipped back
// to 1 and `$_` kept reading a value where zsh reports empty — and
// (b) shadowed the canonical zunderscore value. Every dispatch path
// now calls `set_zunderscore` (the `setunderscore` equivalent) just
// before running its command, which is where C sets it
// (execcmd_exec, c:3545-3547), so the deferral is unnecessary as
// well: argument expansion has already happened by then, exactly as
// in C.
args
}
/// zsh dispatch order is alias → function → builtin → external. The
/// compiler emits direct CallBuiltin ops for known builtin names for
/// perf, which silently skips a user function that shadows the same
/// name (e.g. `echo() { ... }; echo hi` would run the C builtin
/// without this check). Returns Some(status) when the call is routed
/// to the user function; the builtin handler should fall through to
/// its native impl when None.
/// Fork+exec a system binary by name. Used by `reg_overridable!` as
/// the fall-through path when `[builtins].coreutils_shadows = off`
/// (the default) — runs the canonical `/bin/X` instead of zshrs's
/// in-process shadow so old scripts hit zero behavioral divergence.
///
/// Inherits stdin/stdout/stderr from the parent so pipelines work
/// transparently. Resolves the binary via PATH; mirrors what zsh's
/// own external-command dispatch would do. Returns the child's exit
/// status (or 127 if PATH lookup fails — the standard "command not
/// found" code).
/// RAII guard that queues signals for the lifetime of a synchronous
/// foreground `waitpid` (via `std::process::Command::status`/`wait`).
///
/// zshrs installs a process-wide SIGCHLD handler (`zhandler` →
/// `wait_for_processes` → `waitpid(-1, WNOHANG)`) that reaps EVERY
/// exited child to drive the job table. `std::process::Command` does
/// its own targeted `waitpid(pid)`; when the reaper fires on any
/// thread between the fork and that wait, it reaps the child first and
/// `Command::status()` fails with ECHILD ("No child processes (os
/// error 10)"). This surfaced as `zshrs: hostname: No child processes
/// (os error 10)` when a coreutils shadow (`coreutils_shadows = off`
/// default) fork-execs `/usr/bin/hostname` while a background prewarm
/// child exits at the same instant.
///
/// Holding this guard bumps `queueing_enabled` (a global SeqCst atomic
/// that `zhandler` honors on every thread), so a SIGCHLD arriving
/// during the wait is pushed onto the deferred queue instead of being
/// reaped — `Command::status()` reaps its own child and reads the real
/// status. On drop, `unqueue_signals()` drains the queue, so any
/// genuine background children that exited meanwhile still get reaped
/// and routed to the job table. This is the same queue_signals /
/// unqueue_signals fencing zsh uses around its own foreground waits
/// (Src/exec.c). Panic-safe via `Drop`.
/// Apply `entersubsh`'s trap reset to the CURRENT process state.
///
/// !!! WARNING: RUST-ONLY HELPER !!!
/// C does this inline inside `entersubsh` (c:Src/exec.c:1088-1092), which
/// every subshell — `( … )`, `$( … )` AND each forked pipeline stage —
/// funnels through. zshrs enters a subshell context in three separate
/// places (the in-process `subshell_begin`, the in-process
/// `run_command_substitution`, and the pipeline stage fork), so the reset
/// lives here to keep them from drifting apart.
///
/// ```c
/// if (!(flags & ESUB_KEEPTRAP))
/// for (sig = 0; sig <= SIGCOUNT; sig++)
/// if (!(sigtrapped[sig] & ZSIG_FUNC) &&
/// !(isset(POSIXTRAPS) && (sigtrapped[sig] & ZSIG_IGNORED)))
/// unsettrap(sig);
/// ```
///
/// `unsettrap` clears BOTH the body and the sigtrapped flags, so both
/// stores are reset here. Function-form traps (ZSIG_FUNC, kept in
/// shfunctab as TRAPxxx) survive by construction; under POSIX_TRAPS an
/// IGNORED trap survives too. The loop bound stops below the pseudo
/// signals (c:Src/signals.h:34-35), so ERR/ZERR and DEBUG survive while
/// SIGEXIT (sig 0) is cleared.
pub(crate) fn entersubsh_reset_traps() {
let posixtraps = crate::ported::zsh_h::isset(crate::ported::zsh_h::POSIXTRAPS);
// ksh93 and mksh reset EVERY trap in a subshell, ERR and DEBUG included (zsh keeps
// the pseudo-signals): `trap "print e" ERR; (false)` prints one ERR, from
// the parent, and `(false; true)` / `$(false)` print none.
let korn = crate::extensions::dash_mode::korn_mode();
if let Ok(mut tbl) = crate::ported::builtin::traps_table().lock() {
tbl.retain(|name, body| {
// Above SIGCOUNT — outside c:1088's loop entirely.
if !korn && (name == "ERR" || name == "ZERR" || name == "DEBUG") {
return true;
}
// c:1090-1092 — otherwise keep ONLY (POSIXTRAPS && ignored).
posixtraps && body.is_empty()
});
}
if let Ok(mut st) = crate::ported::signals::sigtrapped.lock() {
let count = crate::ported::signals_h::SIGCOUNT as usize;
for sig in 0..if korn { st.len() } else { st.len().min(count + 1) } {
let state = st[sig];
if state == 0 {
continue;
}
if (state & crate::ported::zsh_h::ZSIG_FUNC) != 0 {
continue; // c:1090
}
if posixtraps && (state & crate::ported::zsh_h::ZSIG_IGNORED) != 0 {
continue; // c:1091
}
st[sig] = 0; // c:1092 unsettrap(sig)
}
}
}
// ---------------------------------------------------------------------------
// In-process subshell: signal delivery belongs to the PARENT.
// ---------------------------------------------------------------------------
/// Depth of nested in-process `( … )` subshells, for the signal
/// bookkeeping below.
///
/// !!! WARNING: RUST-ONLY HELPER !!!
/// C has no counter because it forks: `entersubsh` (`Src/exec.c:1123`)
/// runs in a fresh process whose signal state is a private copy. This
/// counter exists only so `subshell_signal_enter` / `_leave` can tell
/// the OUTERMOST boundary — the one where `$$` stops naming the shell
/// that is running the body — from a nested one.
static SUBSH_SIGNAL_DEPTH: std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0);
/// The top-level shell's `sigtrapped[]` while an in-process subshell
/// runs; `None` when no subshell is active.
///
/// !!! WARNING: RUST-ONLY HELPER !!!
/// This is C's `sigtrapped[]` (`Src/signals.c:39`) as the PARENT still
/// sees it — in C that array simply stays put in the parent process
/// while the forked child mutates its own copy. zshrs has one process
/// and one array, so the parent's view has to be kept beside it.
static SUBSH_PARENT_SIGTRAPPED: std::sync::Mutex<Option<Vec<i32>>> = std::sync::Mutex::new(None);
/// Signals delivered to the process while an in-process subshell was
/// running, which the PARENT traps. Replayed at the outermost
/// `subshell_end`.
///
/// !!! WARNING: RUST-ONLY HELPER !!!
/// The C analogue is `trap_queue[]` (`Src/signals.c:92`): the parent
/// sets `trap_queueing_enabled` in `zwaitjob` (`Src/jobs.c:1688`
/// `queue_traps(wait_cmd)`) for as long as the child runs, so a trap
/// that arrives meanwhile is deferred and dispatched by
/// `unqueue_traps()` (`Src/jobs.c:1751` → `Src/signals.c:1041-1047`)
/// once the child is reaped. A separate queue is needed here because
/// zshrs's `trap_queue` gate (`handletrap`, c:974) tests the LIVE
/// `sigtrapped[]`, which the in-process subshell has already cleared.
static SUBSH_DEFERRED_SIGS: std::sync::Mutex<Vec<i32>> = std::sync::Mutex::new(Vec::new());
/// Called from `zhandler` (`src/ported/signals.rs`, at C's c:410
/// queueing check) before any trap dispatch. Returns 1 when the
/// delivery has been recorded for the parent and the handler must
/// return without acting.
///
/// !!! WARNING: RUST-ONLY HELPER !!!
/// C needs nothing here. `( … )` forks (`Src/exec.c:2922`
/// `entersubsh(flags, &esret)`), so `kill -USR1 $$` inside the
/// subshell names the PARENT process: the child's handlers are never
/// entered, and the parent — which `entersubsh` never touched —
/// runs its own trap once `zwaitjob` drains the trap queue. zshrs runs
/// the body in the same process, so the one set of handlers has to
/// answer for both roles. Recording the delivery and replaying it
/// against the parent's restored table at `subshell_end` reproduces
/// both the disposition zsh picks and the point at which it runs.
///
/// SIGCHLD and SIGWINCH are never deferred, matching the two signals C
/// itself excludes from the `settrap` / `removetrap` disposition
/// switches (`Src/signals.c:714-718`, `Src/signals.c:810-814`): job
/// reaping and resize redisplay have to stay live inside the body.
///
/// When the parent has NO trap for the signal this returns 0 and the
/// handler proceeds normally. That is the one leg an in-process
/// subshell cannot reproduce: C's parent would take the DEFAULT action
/// (`( trap 'echo IN' USR1; kill -USR1 $$ )` kills zsh outright), which
/// here would have to kill the shell out from under a body that C
/// leaves running.
pub fn subshell_defer_signal(sig: libc::c_int) -> i32 {
if sig == libc::SIGCHLD || sig == libc::SIGWINCH {
return 0;
}
let idx = crate::ported::signals_h::SIGIDX(sig) as usize;
// `try_lock`, not `lock`: this runs inside a signal handler, so a
// delivery that lands while the SAME thread is mid-`subshell_signal_enter`
// would self-deadlock on a blocking acquire. A miss degrades to normal
// handling, which is what happened before this hook existed.
let parent = match SUBSH_PARENT_SIGTRAPPED.try_lock() {
Ok(g) => match g.as_ref() {
Some(v) => v.get(idx).copied().unwrap_or(0),
None => return 0,
},
Err(_) => return 0,
};
if parent == 0 {
return 0;
}
if (parent & crate::ported::zsh_h::ZSIG_IGNORED) != 0 {
// The parent ignores it; C's parent process would drop it on
// the floor (`Src/signals.c:713-719` installed SIG_IGN).
return 1;
}
match SUBSH_DEFERRED_SIGS.try_lock() {
Ok(mut q) => q.push(sig),
// Could not record it; fall through to normal handling rather
// than swallow the delivery outright.
Err(_) => return 0,
}
1
}
/// Arm parent-side signal delivery for the duration of an in-process
/// `( … )` or `$( … )`. Must run BEFORE `entersubsh_reset_traps` clears
/// the table.
///
/// !!! WARNING: RUST-ONLY HELPER !!!
/// See `subshell_defer_signal`. Only the OUTERMOST subshell records the
/// snapshot: `$$` names the top-level shell at every nesting level, so
/// a nested `( ( … ) )` still routes deliveries to the same table.
pub(crate) fn subshell_signal_enter() {
if SUBSH_SIGNAL_DEPTH.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0 {
let snap = crate::ported::signals::sigtrapped
.lock()
.map(|g| g.clone())
.unwrap_or_default();
if let Ok(mut p) = SUBSH_PARENT_SIGTRAPPED.lock() {
*p = Some(snap);
}
if let Ok(mut q) = SUBSH_DEFERRED_SIGS.lock() {
q.clear();
}
}
}
/// Disarm parent-side delivery and dispatch whatever arrived. Must run
/// AFTER `subshell_end` has put the parent's `sigtrapped[]` and
/// `traps_table` back.
///
/// !!! WARNING: RUST-ONLY HELPER !!!
/// The dispatch itself is C's `unqueue_traps()` tail
/// (`Src/signals.c:1043-1047`): `while (trap_queue_front !=
/// trap_queue_rear) handletrap(trap_queue[…])`, run at the point
/// `zwaitjob` reaches after the child is reaped (`Src/jobs.c:1751`).
pub(crate) fn subshell_signal_leave() {
if SUBSH_SIGNAL_DEPTH.fetch_sub(1, std::sync::atomic::Ordering::SeqCst) != 1 {
return;
}
if let Ok(mut p) = SUBSH_PARENT_SIGTRAPPED.lock() {
*p = None;
}
let pending: Vec<i32> = match SUBSH_DEFERRED_SIGS.lock() {
Ok(mut q) => std::mem::take(&mut *q),
Err(_) => return,
};
for sig in pending {
// c:Src/signals.c:1046 — `(void) handletrap(trap_queue[…]);`
let _ = crate::ported::signals::handletrap(sig);
}
}
/// Put the process's signal DISPOSITIONS back the way the parent had
/// them, for every signal whose trap state the subshell changed.
///
/// !!! WARNING: RUST-ONLY HELPER !!!
/// C gets this from the fork: `trap 'echo IN' USR1` inside `( … )`
/// calls `settrap` → `install_handler` (`Src/signals.c:724-732`) in the
/// CHILD, so the parent's `SIG_DFL` survives untouched and a later
/// `kill -USR1 $$` still kills the shell. zshrs shares the process, so
/// the child's `sigaction` leaked out and swallowed the signal. The
/// branch order below is `removetrap`'s tail verbatim
/// (`Src/signals.c:801-815`) for the "parent had no trap" case, and
/// `settrap`'s two installs (`Src/signals.c:713-719` ignored,
/// `Src/signals.c:724-732` trapped) for the others.
pub(crate) fn subshell_restore_signal_dispositions(parent: &[i32], child: &[i32]) {
let count = crate::ported::signals_h::SIGCOUNT;
for sig in 1..=count {
let i = sig as usize;
let p = parent.get(i).copied().unwrap_or(0);
let c = child.get(i).copied().unwrap_or(0);
if p == c {
continue;
}
// c:714-718 / c:810-814 — C leaves these two alone in both
// the install and the reset switch.
if sig == libc::SIGWINCH || sig == libc::SIGCHLD {
continue;
}
if (p & crate::ported::zsh_h::ZSIG_IGNORED) != 0 {
crate::ported::signals_h::signal_ignore(sig); // c:719
} else if p != 0 {
crate::ported::signals::install_handler(sig); // c:732
} else if sig == libc::SIGINT && crate::ported::signals::is_interact() {
crate::ported::signals::intr(); // c:804
crate::ported::signals::noholdintr(); // c:805
} else if sig == libc::SIGHUP {
crate::ported::signals::install_handler(sig); // c:807
} else if sig == libc::SIGPIPE
&& crate::ported::signals::is_interact()
&& crate::ported::exec::FORKLEVEL.load(std::sync::atomic::Ordering::Relaxed) == 0
{
crate::ported::signals::install_handler(sig); // c:809
} else {
crate::ported::signals_h::signal_default(sig); // c:815
}
}
}
/// `waitpid(pid, &status, 0)` that retries on `EINTR`.
///
/// !!! WARNING: RUST-ONLY HELPER !!!
/// No C counterpart — C zsh reaches the same place by blocking signals
/// around its foreground waits (`queue_signals` / `unqueue_signals`
/// fencing in `Src/exec.c`), so its `waitpid` is never interrupted in
/// the first place.
///
/// zshrs installs a process-wide SIGCHLD handler (`zhandler` →
/// `wait_for_processes`). When it fires while the shell is blocked in
/// this wait, `waitpid` returns -1/`EINTR` WITHOUT touching `status`.
/// The pipeline reap loop ignored the return value and read the
/// still-zero `status`, so `WIFEXITED(0)` was true and every FORKED
/// stage reported exit 0: `false | true` published `$pipestatus` as
/// `0 0` instead of zsh's `1 0`, and `setopt pipefail` had no non-zero
/// entry left to promote (c:Src/jobs.c:434-435 `if (jpipestats[i])
/// pipefail = jpipestats[i];`, applied at c:451-454).
///
/// The handler can also win outright: if the child exits while the last
/// pipeline stage is still running IN THIS PROCESS, SIGCHLD is delivered
/// and `wait_for_processes` reaps it long before this loop is reached,
/// so `waitpid` here fails with `ECHILD` and the stage's status is gone.
/// That window is as wide as the last stage's whole run — `(exit 5) |
/// (sleep 0.5; exit 3)` published `$pipestatus` as `0 3` where zsh says
/// `5 3`. The reaper publishes every status it takes
/// (`extensions/reaped_status.rs`), which is what C gets for free by
/// having only one collector, so claim it back here.
///
/// Returns the raw wait status, or `None` if the child could not be
/// reaped and the reaper has no record of it either.
fn waitpid_eintr(pid: libc::pid_t) -> Option<i32> {
loop {
let mut status: i32 = 0;
let rc = unsafe { libc::waitpid(pid, &mut status, 0) };
if rc >= 0 {
return Some(status);
}
let err = std::io::Error::last_os_error().raw_os_error().unwrap_or(0);
if err != libc::EINTR {
// The SIGCHLD reaper collected this child first; take the
// status it recorded instead of reporting a clean exit.
return crate::reaped_status::take(pid);
}
}
}
/// [`waitpid_eintr`] that also returns the child's resource usage.
///
/// c:Src/signals.c:279 — the SIGCHLD reaper collects with `wait3(&status,
/// WAITFLAGS, &ru)` and stores it on the process, `pn->ti = ru` (c:352),
/// which is where `dumptime`'s per-process user/system times come from. A
/// child the reaper got to first is claimed back from `reaped_status` with
/// the times it recorded.
fn wait4_eintr(pid: libc::pid_t) -> Option<(i32, libc::rusage)> {
loop {
let mut status: i32 = 0;
let mut ru: libc::rusage = unsafe { std::mem::zeroed() };
let rc = unsafe { libc::wait4(pid, &mut status, 0, &mut ru) };
if rc >= 0 {
return Some((status, ru));
}
let err = std::io::Error::last_os_error().raw_os_error().unwrap_or(0);
if err != libc::EINTR {
return crate::reaped_status::take_rusage(pid).map(|(st, utime, stime)| {
let mut ru: libc::rusage = unsafe { std::mem::zeroed() };
ru.ru_utime = usec_timeval(utime);
ru.ru_stime = usec_timeval(stime);
(st, ru)
});
}
}
}
/// The processes of a `time`d multi-stage pipeline, collected for
/// `dumptime` (c:Src/jobs.c:1029-1037).
///
/// !!! WARNING: RUST-ONLY SHAPE — C KEEPS THESE ON THE JOB'S PROCS !!!
/// In C every forked stage is `addproc`ed onto `jobtab[thisjob]` with its
/// text (c:Src/exec.c:2907) and the timed job is dumped when it finishes.
/// zshrs's foreground pipeline has no job-table entry, so BUILTIN_TIME_SUBLIST
/// hands the per-stage texts to BUILTIN_RUN_PIPELINE through
/// [`TIMED_PIPELINE`] and reads the filled-in procs back.
pub(crate) struct TimedPipeline {
/// One job text per stage, in pipeline order.
texts: Vec<String>,
/// The in-shell last stage is a process of the job (c:Src/exec.c:3690
/// `!is_cursh` — an external command or a subshell).
last_forks: bool,
/// Filled by the pipeline driver.
procs: Vec<crate::ported::zsh_h::process>,
}
thread_local! {
/// Set by BUILTIN_TIME_SUBLIST around a timed pipeline's body; TAKEN by
/// the first BUILTIN_RUN_PIPELINE that runs, so a pipeline nested inside
/// one of its stages is not mistaken for it.
static TIMED_PIPELINE: std::cell::RefCell<Option<TimedPipeline>> =
const { std::cell::RefCell::new(None) };
}
/// c:Src/exec.c:3690 — `is_cursh = (is_builtin || is_shfunc || nullexec ||
/// type >= WC_CURSH)` for the compiler's hint (compile_zsh.rs
/// `command_cursh_hint`): 1 = current shell, 0 = forks, 2 = the command word
/// decides at run time.
fn time_body_is_cursh(hint: i64, name: &str) -> bool {
match hint {
1 => true,
2 => {
// c:3488-3491 — shfunctab is consulted BEFORE builtintab.
let is_shfunc = crate::ported::hashtable::shfunctab_lock()
.read()
.map(|t| t.get(name).is_some())
.unwrap_or(false);
is_shfunc || crate::ported::builtin::createbuiltintable().contains_key(name)
}
_ => false,
}
}
/// `a - b` for rusage times — c:Src/jobs.c `dtime_tv`.
fn timeval_sub(a: libc::timeval, b: libc::timeval) -> libc::timeval {
let mut sec = a.tv_sec - b.tv_sec;
let mut usec = a.tv_usec as i64 - b.tv_usec as i64;
if usec < 0 {
sec -= 1;
usec += 1_000_000;
}
libc::timeval {
tv_sec: sec,
tv_usec: usec as libc::suseconds_t,
}
}
/// Microseconds as a `timeval`.
fn usec_timeval(us: u64) -> libc::timeval {
libc::timeval {
tv_sec: (us / 1_000_000) as libc::time_t,
tv_usec: (us % 1_000_000) as libc::suseconds_t,
}
}
/// A `process` entry for [`TimedPipeline`]: C's addproc fields (c:Src/jobs.c
/// 1473-1486) plus the wait's status and rusage (update_process).
fn timed_proc(
pid: libc::pid_t,
text: &str,
status: i32,
ru: &libc::rusage,
bgtime: std::time::Instant,
) -> crate::ported::zsh_h::process {
crate::ported::zsh_h::process {
pid,
text: text.to_string(),
status,
ti: crate::ported::zsh_h::timeinfo::from_rusage(ru),
bgtime: Some(bgtime),
endtime: Some(std::time::Instant::now()),
}
}
/// The level bookkeeping `entersubsh` does in a freshly forked child.
///
/// c:Src/exec.c:1221 — `forklevel = locallevel;`. `bin_break`'s `exit` arm
/// (c:Src/builtin.c:5870-5894) only defers the exit while `locallevel >
/// forklevel`; in a forked child the function it was called from is the
/// child's outermost level, so `exit N` ends the child with status N.
///
/// !!! WARNING: RUST-ONLY LINE — SUBSHELL_DEPTH HAS NO C COUNTERPART !!!
/// `SUBSHELL_DEPTH` counts the in-process `( … )` bodies this process is
/// inside, and `zexit` defers to EXIT_PENDING while it is non-zero because
/// exiting would take the parent shell with it. After a fork that reason is
/// gone: the child is its own process, as C's always is. Left at its
/// inherited value, `exit 2` in a pipeline stage or background job forked
/// from inside a function or `( … )` only unwound the child's VM, which then
/// exited 0 — `(setopt pipefail; false | exit 2 | true; print $?)` printed
/// 1 where zsh prints 2.
thread_local! {
/// c:Src/exec.c:3063 — `last1 = forked = 1;`: execcmd_exec has already
/// forked for the command it is about to run (a non-last pipeline stage,
/// an `&` job, a coproc, the sh-emulation last stage).
///
/// !!! WARNING: RUST-ONLY FLAG — C KEEPS `forked` AS AN execcmd_exec LOCAL !!!
/// zshrs forks in the pipeline/bg/coproc drivers, one level above the
/// stage chunk, so the fact crosses into the chunk through this flag. The
/// chunk's leading BUILTIN_EXECCMD_FORKED_LEVEL consumes it.
static EXECCMD_FORKED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// The VM (by address) whose chunk head consumed EXECCMD_FORKED for a
/// non-subshell command. BUILTIN_EXEC_FORKED_SIMPLE honours it only from
/// that same VM, so a `$( … )` or function body run while the forked
/// command's words expand — each on its own VM — never execs in its place.
///
/// !!! WARNING: RUST-ONLY FLAG — C KEEPS `forked` AS AN execcmd_exec LOCAL !!!
static FORKED_SIMPLE_VM: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// The VM whose chunk head consumed EXECCMD_FORKED (subshell or not).
/// BUILTIN_FORKED_REDIRS honours it only from that same VM.
///
/// !!! WARNING: RUST-ONLY FLAG — C KEEPS `forked` AS AN execcmd_exec LOCAL !!!
static FORKED_REDIR_VM: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// Depth of the redirect scope holding the forked command's OWN
/// redirections (0: none). c:Src/exec.c:2478 — addfd saves the original
/// fd only `if (!forked && save[fd1] == -2)`, so those redirections park
/// nothing: the child exits after the command and never restores.
///
/// !!! WARNING: RUST-ONLY FLAG — C PASSES `forked` TO EVERY addfd CALL !!!
static FORKED_REDIR_SCOPE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// c:Src/exec.c:2478 — `if (!forked && save[fd1] == -2)`: true when the
/// redirect scope at `depth` (the innermost open one) belongs to the command
/// this child was forked for, whose redirections save no original fd. A
/// saved dup there outlived the command in the child: `{ sleep 2 } >/dev/null
/// &` kept the caller's stdout open for two seconds, so `$( … & )` and a
/// pipe reader waited for it.
fn redir_scope_forked(depth: usize) -> bool {
depth != 0 && FORKED_REDIR_SCOPE.with(|c| c.get()) == depth
}
/// c:Src/exec.c:2440 — `fdtable[fdN] |= FDT_SAVED_MASK;` on the copy
/// movefd made FDT_INTERNAL (c:Src/utils.c:2006). The mark is how a forked
/// child's entersubsh finds the copies it will never restore and closes them
/// (c:1214-1217). Unmarked, a job forked inside `{ … } 2>/dev/null` kept the
/// caller's stderr open until it finished. The restore's zclose clears it.
pub(crate) fn mark_saved_fd(saved: i32) {
if saved >= 0 {
crate::ported::utils::fdtable_set(
saved,
crate::ported::zsh_h::FDT_INTERNAL | crate::ported::zsh_h::FDT_SAVED_MASK,
);
}
}
/// Head of a stage / `&` / coproc chunk: account for execcmd_fork's
/// `entersubsh` (c:Src/exec.c:1200 `zsh_subshell++;`) when the driver forked.
///
/// C forks once per such command. For `( … )` that one fork IS the subshell:
/// with `forked` already set, the `if (!forked)` block (c:3715-3752) is
/// skipped and the body runs in this child without a second fork, so
/// `(print $ZSH_SUBSHELL) | cat` prints 1. zshrs's `( … )` always bumps in
/// subshell_begin, so for a subshell the fork's bump is left to it; any other
/// command takes it here. Without a fork (the in-shell last stage) nothing
/// happens. The bump is never undone: the child exits.
fn execcmd_forked_level(is_subsh: bool, vm_addr: usize) {
if !EXECCMD_FORKED.with(|f| f.replace(false)) {
return;
}
// The chunk's top command is the one forked for; see BUILTIN_FORKED_REDIRS.
FORKED_REDIR_VM.with(|f| f.set(vm_addr));
// c:Src/exec.c:1245-1246 — `if (!job_control_ok) opts[MONITOR] = 0;` in
// entersubsh. job_control_ok (c:1133) needs ESUB_JOB_CONTROL, which
// execcmd_fork passes only for a non-async `( … )` (c:2919-2920), and
// POSIX_JOBS. Without this a pipeline stage kept MONITOR and ran
// update_job's foreground tail for its own children:
// `{ sh -c 'kill -INT $$'; echo in } | cat` lost `in`.
let job_control_ok = is_subsh && crate::ported::zsh_h::isset(crate::ported::zsh_h::POSIXJOBS);
if !job_control_ok && crate::ported::zsh_h::isset(crate::ported::zsh_h::MONITOR) {
crate::ported::options::dosetopt(crate::ported::zsh_h::MONITOR, 0, 0);
}
// The chunk's own top command is the one this child was forked for; see
// BUILTIN_EXEC_FORKED_SIMPLE. A `( … )` is too: its body runs as
// `execlist(state, 0, 1)` (c:Src/exec.c:4379), so the body's last command
// takes the fake exec in this child (compile_zsh exiting_tail_list).
FORKED_SIMPLE_VM.with(|f| f.set(vm_addr));
if !is_subsh {
if let Ok(mut tab) = crate::ported::params::paramtab().write() {
if let Some(pm) = tab.get_mut("ZSH_SUBSHELL") {
pm.u_val += 1; // c:1200
pm.u_str = Some(pm.u_val.to_string());
pm.node.flags &= !(crate::ported::zsh_h::PM_UNSET as i32);
}
}
}
}
fn forked_child_subsh_levels() {
use std::sync::atomic::Ordering;
crate::ported::exec::FORKLEVEL.store(
crate::ported::params::locallevel.load(Ordering::Relaxed),
Ordering::Relaxed,
); // c:1221
crate::ported::builtin::SUBSHELL_DEPTH.store(0, Ordering::Relaxed);
// !!! RUST-ONLY: a forked child is no longer inside the in-process
// `$( … )` it was forked from; its signal traps print to its own fd 1,
// as in C, and the parent's saved fds are gone (mark_saved_fd).
CMDSUBST_OUTER_FDS.with(|s| s.borrow_mut().clear());
}
/// Holds SIGCHLD blocked across the span in which the VM forks children.
///
/// C: `execpline` opens that span with `child_block()` (c:Src/exec.c:1748),
/// before any stage is forked, and closes it with `child_unblock()` only
/// after the job is registered (c:1815, the async arm) or after the wait
/// (c:2017). Its comment says why: "We need to block SIGCHLD in case the
/// process we are spawning terminates before the job table is set up to
/// handle it" (c:2339-2343). `getoutputfile` does the same around its own
/// fork (c:4999/c:5030).
///
/// zshrs has a second, harder reason. The reaper allocates
/// (`wait_for_processes` builds a `Vec`), and libmalloc holds its fork
/// lock inside `fork()`. A SIGCHLD from an earlier stage delivered there
/// re-enters malloc on that lock and the process dies with SIGKILL
/// ("BUG IN CLIENT OF LIBPLATFORM: Trying to recursively lock an
/// os_unfair_lock", faulting stack `fork → _sigtramp → zhandler →
/// wait_for_processes → Vec::push → _xzm_fork_lock_wait`). With the
/// reaper armed and no block, `repeat 300 { true | false | true }; print
/// ok` was killed before printing on every run.
///
/// !!! WARNING: RUST-ONLY SHAPE — C CALLS child_block/child_unblock !!!
/// This guard restores the PRIOR state on drop instead of unconditionally
/// unblocking. C's execpline recursion never forks a pipeline from inside
/// another pipeline's still-blocked span in the same process, but the VM
/// does: the last stage of a pipeline runs in the parent, and a nested
/// pipeline or process substitution there would otherwise lift the outer
/// block before the outer wait. So SIGCHLD is unblocked on drop only if it
/// was unblocked on entry. A forked child never drops the guard (it leaves
/// through `exit`/`_exit`), so it inherits the blocked mask, as C's child
/// of `zfork` does until `execute` unblocks before `execve` (c:793).
#[cfg(unix)]
pub(crate) struct ChildBlockSpan {
was_blocked: bool,
}
#[cfg(unix)]
impl ChildBlockSpan {
pub(crate) fn enter() -> Self {
let mask = crate::ported::signals::signal_mask(libc::SIGCHLD);
let old = crate::ported::signals::signal_block(&mask); // c:Src/signals.h:52
let was_blocked = unsafe { libc::sigismember(&old, libc::SIGCHLD) } == 1;
ChildBlockSpan { was_blocked }
}
}
#[cfg(unix)]
impl Drop for ChildBlockSpan {
fn drop(&mut self) {
if !self.was_blocked {
crate::ported::signals_h::child_unblock(); // c:Src/signals.h:53
}
}
}
pub(crate) struct ForegroundWaitGuard {
/// c:Src/jobs.c:1638 — `int first = 1, q = queue_signal_level();`
q: i32,
}
impl ForegroundWaitGuard {
#[inline]
pub(crate) fn enter() -> Self {
// c:Src/jobs.c:1638-1642 — `waitforpid`'s prologue verbatim:
// int first = 1, q = queue_signal_level();
// dont_queue_signals();
// child_block(); /* unblocked in signal_suspend() */
// `zwaitjob` opens the same window at c:1684-1689. Both then block
// in `signal_suspend(SIGCHLD, wait_cmd)` (c:1658 / c:1710), and that
// call's sigsuspend mask is EMPTY — c:Src/signals.c:216-232 does
// `sigemptyset(&set)` and adds at most a conditional SIGINT. So a
// foreground wait is a delivery point for every other signal,
// SIGWINCH included: the shell's standing `winch_block()`
// (c:Src/init.c:1458, re-armed by preprompt at c:Src/utils.c:1541)
// is lifted for exactly as long as the shell waits. It is the one
// window C reliably opens in the middle of a command, which is why
// a resize during a completion reaches `$COLUMNS` while the
// completion is still running.
//
// This guard used to be `queue_signals()` alone. That kept the
// SIGCHLD reaper off the child by QUEUEING the delivery in
// userspace rather than blocking it, and left SIGWINCH blocked for
// the whole of a completion no matter how many children it forked
// — a queued SIGWINCH is not dispatched until the queue level
// reaches zero, which for a completion is after the widget has
// returned. Measured with a completer that read `$COLUMNS`, ran
// `sleep 1` and read it again, across a 24x80 -> 24x60 resize: zsh
// reported 80 then 60, zshrs 80 then 80.
//
// The visible cost was the prompt row. `asklist`'s `trashzle`
// (c:Src/Zle/compresult.c:1922 → c:Src/Zle/zle_main.c:2071-2095)
// redraws the command line only when the handler has already raised
// `resetneeded`/`winchanged` (c:Src/utils.c:1956-1958), so a
// row-shrink during `git <TAB>` had zsh repainting `READY% git`
// above the query and zshrs repainting nothing at all.
//
// `child_block` gives the same protection the queueing did and
// gives it the way C does: the reaper cannot take the child out
// from under `Child::wait` while SIGCHLD is blocked at the OS
// level, and SIGWINCH is free to arrive.
let q = crate::ported::signals_h::queue_signal_level(); // c:1638
crate::ported::signals_h::dont_queue_signals(); // c:1641
crate::ported::signals_h::child_block(); // c:1642
// c:1643 — `queue_traps(wait_cmd);`. Signals are dispatched during
// the wait but user TRAPS are held until the child is reaped; the
// old `queue_signals` deferred both together, so this keeps the
// trap half of that behaviour where C keeps it. `wait_cmd` is 0:
// this is not the `wait` builtin.
crate::ported::signals::queue_traps(0); // c:1643
crate::ported::signals_h::winch_unblock(); // c:Src/signals.c:232
ForegroundWaitGuard { q }
}
}
impl Drop for ForegroundWaitGuard {
#[inline]
fn drop(&mut self) {
// c:Src/jobs.c:1667-1669 — `unqueue_traps(); child_unblock();
// restore_queue_signals(q);`. The `winch_block` ahead of them puts
// back the standing mask that c:Src/utils.c:1541 leaves in place
// between prompts.
crate::ported::signals_h::winch_block(); // c:Src/utils.c:1541
crate::ported::signals::unqueue_traps(); // c:1667
crate::ported::signals_h::child_unblock(); // c:1668
crate::ported::signals_h::restore_queue_signals(self.q); // c:1669
}
}
/// `Command::status()` plus the reaper-stole-it recovery that the forked
/// pipeline stages already get from [`waitpid_eintr`].
///
/// [`ForegroundWaitGuard`] alone is not enough. Its `child_block` masks
/// SIGCHLD for the CALLING thread, and zshrs is multi-threaded: the signal
/// is delivered to any thread that has not blocked it, whose `zhandler`
/// runs `wait_for_processes` → `waitpid(-1, WNOHANG)` and takes the child.
/// `Command::status()` then fails with ECHILD, and because it owns the
/// child and never hands back the pid, the status the reaper published
/// (`extensions/reaped_status.rs`) cannot be claimed — the caller can only
/// report a failure for a command that ran fine.
///
/// That is what `echo a b c | wc -w` hit: the last stage runs in THIS
/// process, so it goes through here rather than through `waitpid_eintr`.
/// Measured in a Debian container before this helper existed, it printed
/// the correct `3` and then exited 127 with
/// `zshrs: wc: No child processes (os error 10)` on 136 of 200 runs.
///
/// Spawning explicitly keeps the pid, so the losing collector can claim
/// the status exactly as the pipeline's targeted wait does. The status is
/// rebuilt with `ExitStatus::from_raw`, so every caller keeps its own
/// mapping of exit codes and signals.
#[cfg(unix)]
pub(crate) fn foreground_status(
command: &mut std::process::Command,
) -> std::io::Result<std::process::ExitStatus> {
let _wait_guard = ForegroundWaitGuard::enter();
let child = command.spawn()?;
wait_pid_status(child.id() as libc::pid_t)
}
/// Wait for the foreground child `pid`, claiming its status back from the
/// SIGCHLD reaper when the reaper collected it first (ECHILD). The caller
/// holds a `ForegroundWaitGuard` from before the spawn. Shared by
/// `foreground_status` and the `posix_spawn` path in
/// `vm_helper::execute_external_bg`, which has a pid but no `Child`.
pub(crate) fn wait_pid_status(pid: libc::pid_t) -> std::io::Result<std::process::ExitStatus> {
use std::os::unix::process::ExitStatusExt as _;
loop {
let mut raw: libc::c_int = 0;
let mut ru: libc::rusage = unsafe { std::mem::zeroed() };
if unsafe { libc::wait4(pid, &mut raw, 0, &mut ru) } == pid {
let usec = |tv: libc::timeval| tv.tv_sec as u64 * 1_000_000 + tv.tv_usec as u64;
fg_child_times_add(usec(ru.ru_utime), usec(ru.ru_stime));
return Ok(std::process::ExitStatus::from_raw(raw));
}
let e = std::io::Error::last_os_error();
match e.raw_os_error() {
Some(libc::EINTR) => continue,
Some(libc::ECHILD) => {
return match take_reaped_status(pid) {
Some((raw, utime, stime)) => {
fg_child_times_add(utime, stime);
Ok(std::process::ExitStatus::from_raw(raw))
}
None => Err(e),
}
}
_ => return Err(e),
}
}
}
thread_local! {
/// User / system CPU (microseconds) of the foreground externals this
/// thread has waited for since the collector was opened, or `None` when
/// nothing collects. A timed pipeline's in-shell last stage opens it: C
/// forks that stage and times it as one process (`pn->ti = ru`,
/// c:Src/signals.c:352), zshrs runs it here and the externals it spawns
/// are what that process would have been.
///
/// !!! WARNING: RUST-ONLY COLLECTOR — C READS THE STAGE'S OWN wait3 RUSAGE !!!
static FG_CHILD_TIMES: std::cell::Cell<Option<(u64, u64)>> = const { std::cell::Cell::new(None) };
}
fn fg_child_times_add(utime: u64, stime: u64) {
FG_CHILD_TIMES.with(|c| {
if let Some((u, s)) = c.get() {
c.set(Some((u + utime, s + stime)));
}
});
}
/// Claim the reaper's record for `pid`, allowing for the fact that ECHILD
/// arrives BEFORE the record is published.
///
/// `wait_for_processes` takes the child with `waitpid` and only then stores
/// the status (`signals.rs`, `reaped_status::record`). Everything between
/// those two is a window in which the losing collector already sees ECHILD
/// and the ring is still empty: reading it once left 8 of 400 runs of
/// `echo a b c | wc -w` reporting `No child processes` even with the
/// recovery in place. The child is known dead by then, so waiting out the
/// window costs nothing that is not already lost, and this runs only on the
/// lost-race path.
///
/// The budget is bounded because the record may never come: a collector
/// that does not publish (the `waitpid(-1)` in `bin_wait`, say) leaves
/// nothing to claim, and the caller must be allowed to report the error
/// rather than spin.
#[cfg(unix)]
pub(crate) fn take_reaped_status(pid: i32) -> Option<(i32, u64, u64)> {
const TRIES: u32 = 200; // 200 x 100us = 20ms
for _ in 0..TRIES {
if let Some(rec) = crate::reaped_status::take_rusage(pid) {
return Some(rec);
}
let ts = libc::timespec { tv_sec: 0, tv_nsec: 100_000 };
unsafe { libc::nanosleep(&ts, std::ptr::null_mut()) };
}
None
}
/// !!! WARNING: RUST-ONLY HELPER !!!
///
/// C has no counterpart: `fork()` gives a forked `(...)` subshell its own
/// copy of the fd table, so the flock fds a subshell opens (`Src/utils.c:2111`
/// `addlockfd` marks them `FDT_FLOCK` / `FDT_FLOCK_EXEC`) vanish with the
/// child and its `fcntl(F_SETLK)` locks are released. zshrs runs `(...)`
/// in-process, so it has to enumerate those slots at subshell entry and
/// close the new ones at subshell exit. Walks the same `fdtable` /
/// `max_zsh_fd` pair as `zcloselockfd` (`Src/utils.c:2155-2164`).
fn current_flock_fds() -> Vec<i32> {
use crate::ported::zsh_h::{FDT_FLOCK, FDT_FLOCK_EXEC};
let max_fd = crate::ported::utils::MAX_ZSH_FD.load(std::sync::atomic::Ordering::Relaxed);
if max_fd < 0 {
return Vec::new();
}
(0..=max_fd)
.filter(|fd| {
let slot = crate::ported::utils::fdtable_get(*fd);
slot == FDT_FLOCK || slot == FDT_FLOCK_EXEC
})
.collect()
}
/// `exec`'s external command: C's `execute(args, cflags, use_defpath)`
/// (c:Src/exec.c:4369, body c:729-881) through the same search and zexecve
/// as every other external (`vm_helper::execute_spawn`). `in_place` execs
/// over this process and only returns on failure; otherwise (an in-process
/// subshell, whose C counterpart was a forked child) the command is spawned
/// and waited for. Returns the command's status, or C's exit status for a
/// failed exec. `args` is the command and its arguments; `exec_argv0` the
/// `exec -a` name; `login` the `-`/`exec -l` flag.
fn exec_execute(
args: &[String],
exec_argv0: Option<String>,
login: bool,
use_defpath: bool,
in_place: bool,
) -> i32 {
let cmd = &args[0];
crate::lowfd::cloexec_internal_fds(); // c:4352
// c:3318-3328 — `exec -a NAME` travels as ARGV0 in the environment;
// execute() takes argv[0] from it and unsets it (c:758-768), else
// prefixes `-` for `exec -l` / `-` (c:772-776).
let argv0_env = exec_argv0.or_else(|| std::env::var("ARGV0").ok());
let mut argv: Vec<String> = Vec::with_capacity(args.len());
argv.push(match &argv0_env {
Some(z) => z.clone(),
None if login => format!("-{}", cmd),
None => cmd.clone(),
});
argv.extend(args[1..].iter().cloned());
// c:810-819 — `command -p`: the default-path hit alone.
let defpath = if use_defpath && !cmd.contains('/') {
crate::ported::exec::search_defpath(cmd, libc::PATH_MAX as usize)
} else {
None
};
let _wait_guard = (!in_place).then(ForegroundWaitGuard::enter);
let eno = if use_defpath && !cmd.contains('/') && defpath.is_none() {
0 // c:815-819 — not on the default path
} else {
match crate::vm_helper::execute_spawn(
cmd,
&argv,
defpath.as_deref(),
None,
argv0_env.is_some(),
in_place,
) {
Ok(pid) => {
return match wait_pid_status(pid) {
Ok(status) => crate::exec_jobs::wait_status_val(status),
Err(_) => 127,
}
}
Err(eno) => eno,
}
};
drop(_wait_guard);
// c:871-881
if eno != 0 {
crate::ported::utils::zerr(&format!(
"{}: {}",
crate::ported::utils::zsh_errno_msg(eno),
cmd
));
return if eno == libc::EACCES || eno == libc::ENOEXEC { 126 } else { 127 };
}
// c:873-874 — `if (commandnotfound(arg0, args) == 0) _realexit();`
if let Some(rc) =
with_executor(|exec| exec.dispatch_function_call("command_not_found_handler", args))
{
return rc;
}
crate::ported::utils::zerr(&format!(
"command not found: {}",
crate::ported::utils::nicedupstring(cmd)
));
127
}
/// Whether `exec` is running inside a subshell that zshrs keeps in this
/// process — `( … )` (the snapshot stack) or a command substitution
/// (`SubshStateGuard`, the in-process `entersubsh`). C forked both, so its
/// exec replaced only that child; replacing THIS process would end the
/// parent shell too (`x=$(exec echo hi)` ended the script).
fn exec_in_process_subshell() -> bool {
with_executor(|exec| !exec.subshell_snapshots.is_empty())
|| crate::ported::exec::SUBSH_STATE_DEPTH.load(std::sync::atomic::Ordering::SeqCst) > 0
}
/// Advice for an in-process command, run with the executor borrowed. `None`
/// means no intercept took over the call, so it proceeds normally (a `before`
/// advice has already run); `Some(status)` is the status an `around` / `after`
/// advice produced for the call.
fn run_command_intercepts(name: &str, args: &[String]) -> Option<i32> {
with_executor(|exec| {
if exec.intercepts.is_empty() {
return None;
}
let full_cmd = std::iter::once(name)
.chain(args.iter().map(String::as_str))
.collect::<Vec<_>>()
.join(" ");
exec.run_intercepts(name, &full_cmd, args)
})
.map(|result| result.unwrap_or(127))
}
/// Advice for the ALIAS a command was written as. The alias is gone from the text
/// by dispatch, so the compiler leaves it in [`ALIAS_ORIGIN`] together with the
/// command it expanded to; a marker for any other command is stale and dropped.
/// Advice sees only the arguments the user typed (those after the alias body),
/// while `intercept_proceed` and `after` advice run the expanded command.
fn intercept_alias_origin(name: &str, args: &[String]) -> Option<i32> {
let (alias, body_words, command) = ALIAS_ORIGIN.with(|a| a.borrow_mut().take())?;
// `alias ls="ls -G"`: the expanded command is advised under its own name.
if command != name || alias == name || with_executor(|exec| exec.intercepts.is_empty()) {
return None;
}
let typed = args.get(body_words.saturating_sub(1)..).unwrap_or(&[]);
let full_cmd = std::iter::once(alias.as_str())
.chain(typed.iter().map(String::as_str))
.collect::<Vec<_>>()
.join(" ");
let original = (name.to_string(), args.to_vec());
with_executor(|exec| exec.run_intercepts_with(&alias, &full_cmd, typed, Some(original)))
.map(|result| result.unwrap_or(127))
}
/// [`run_command_intercepts`] for a command word that is not an external: a
/// shell function, a ported or opcode builtin, a native command. Anonymous
/// functions are internal plumbing and never intercepted.
fn intercept_in_process_command(name: &str, args: &[String]) -> Option<i32> {
if name.starts_with("_zshrs_anon_") || with_executor(|exec| exec.intercepts.is_empty()) {
return None;
}
if !(with_executor(|exec| exec.function_exists(name)) || builtin_prefix_finds(name)) {
return None;
}
run_command_intercepts(name, args)
}
/// The opcode builtins (`echo`, `cd`, …) enter here before they run, so this is
/// where their advice runs; [`dispatch_builtin`] reaches the unadvised variant,
/// or the advice would fire twice for one command.
/// [`run_command_intercepts`] for builtins whose bare form reads $? afterwards
/// (`exit`, `return`, `exec`): the advice runs, then the status the command will
/// read is put back. `Some` is the value an `around` / `after` advice produced.
fn advise_keeping_status(vm: &mut fusevm::VM, name: &str, args: &[String]) -> Option<Value> {
let live = vm.last_status;
if let Some(status) = run_command_intercepts(name, args) {
return Some(Value::Status(status));
}
vm.last_status = live;
with_executor(|exec| exec.set_last_status(live));
crate::ported::builtin::LASTVAL.store(live, std::sync::atomic::Ordering::Relaxed);
None
}
fn try_user_fn_override(name: &str, args: &[String]) -> Option<i32> {
if let Some(status) = intercept_alias_origin(name, args) {
return Some(status);
}
if let Some(status) = run_command_intercepts(name, args) {
return Some(status);
}
user_fn_override_unadvised(name, args)
}
fn user_fn_override_unadvised(name: &str, args: &[String]) -> Option<i32> {
let has_fn = with_executor(|exec| {
exec.functions_compiled.contains_key(name) || exec.function_exists(name)
});
if !has_fn {
return None;
}
Some(with_executor(|exec| {
exec.dispatch_function_call(name, args).unwrap_or(127)
}))
}
/// Builtin ID for `${name}` reads — routes through canonical
/// `getsparam` (Src/params.c:3076) via paramtab + env walk so nested
/// VMs (function calls) see the same storage.
pub const BUILTIN_GET_VAR: u16 = 283;
/// Like `BUILTIN_GET_VAR` but forces double-quoted (DQ) semantics on
/// the read regardless of the runtime `in_dq_context`. The compiler
/// emits this for a QUOTED simple-var read (`"$name"`) — those compile
/// to a direct GET_VAR with no EXPAND_TEXT wrapper, so `in_dq_context`
/// is 0 and the plain GET_VAR would wrongly word-elide an array's empty
/// elements (`a=(1 "" 3); "$a"` must keep the empty → `1 3`, not
/// `1 3`). With force_dq the array joins via sepjoin keeping empties and
/// a scalar is returned verbatim (no empty-drop, no SH_WORD_SPLIT).
pub const BUILTIN_GET_VAR_DQ: u16 = 639;
/// Builtin ID for `name=value` assignments — pops [name, value] and
/// routes through canonical `setsparam` (Src/params.c:3350).
pub const BUILTIN_SET_VAR: u16 = 284;
/// Builtin ID that sets the thread-local [`SET_VAR_GLOB_ELIGIBLE`] flag true.
/// Emitted by the compiler immediately before a `BUILTIN_SET_VAR` whose scalar
/// RHS carried an UNQUOTED glob token, so the runtime knows the RHS is a literal
/// glob pattern eligible for GLOB_ASSIGN. Takes no stack args, pushes nothing.
pub const BUILTIN_MARK_GLOB_ELIGIBLE: u16 = 640;
/// Builtin ID for pipeline execution. Pops N sub-chunk indices from the stack;
/// each index points into `vm.chunk.sub_chunks` (compiled stage bodies). Forks
/// N children, wires stdin/stdout between them via pipes, runs each stage's
/// bytecode on a fresh VM in its child, parent waits for all and pushes the
/// last stage's exit status. This is bytecode-native pipeline execution —
/// no tree-walker delegation.
pub const BUILTIN_RUN_PIPELINE: u16 = 285;
/// Builtin ID for `Array → String` joining. Pops one value: if it's an Array,
/// joins its string-coerced elements with a single space; otherwise passes
/// through. Used after `Op::Glob` to convert the pattern's matched paths into
/// the single argv-token form the bytecode word model expects (no per-word
/// splitting yet — that's a future phase).
pub const BUILTIN_ARRAY_JOIN: u16 = 286;
/// Builtin ID for `cmd &` background execution. IDs 287/288/289 are reserved
/// for the planned array work in Phase G1 (SET_ARRAY/SET_ASSOC/ARRAY_INDEX),
/// so this lands at 290. Pops the sub-chunk index then the job text; forks;
/// child detaches (`setsid`), runs the sub-chunk on a fresh VM, exits with
/// last_status; parent registers the job in the canonical JOBTAB
/// (initjob/addproc/spawnjob per c:Src/exec.c:1700-1758) so `jobs` / `wait
/// %N` / `kill %N` / `disown` and the zsh/parameter assocs all see it, then
/// returns Status(0) immediately.
pub const BUILTIN_RUN_BG: u16 = 290;
/// Indexed-array assignment: `arr=(a b c)`. Compile_simple emits N element
/// pushes followed by name push, then `CallBuiltin(BUILTIN_SET_ARRAY, N+1)`.
/// The handler pops args (last popped = name in our pushing order) and stores
/// `Vec<String>` into `executor.arrays`. Tree-walker callers see the same
/// storage. Any prior scalar binding in `executor.variables` for `name` is
/// removed so `${name}` (scalar context) consistently reflects the array's
/// first element via `get_variable`.
pub const BUILTIN_SET_ARRAY: u16 = 287;
/// Single-key set on an associative array: `foo[key]=val`. Stack (top-down):
/// [name, key, value]. Stores `value` into `executor.assoc_arrays[name][key]`,
/// creating the outer entry if missing. compile_simple detects `var[...]=...`
/// in assignments and emits this builtin.
pub const BUILTIN_SET_ASSOC: u16 = 288;
/// `${arr[idx]}` — single-element array index. Pops two args:
/// stack: [name, idx_str]
/// Returns the indexed element as Value::str. Indexing semantics: zsh is
/// 1-based by default; bash is 0-based. We follow zsh.
/// Special idx values: `@` and `*` return the whole array as Value::Array
/// (which fuses correctly via the Op::Exec splice for argv splice).
pub const BUILTIN_ARRAY_INDEX: u16 = 289;
/// `${#arr[@]}` and `${#arr}` (when arr is an array name) — array length.
/// Pops one arg: name. Returns Value::str of len.
/// `${arr[@]}` — splice all elements as a Value::Array. Pops one arg: name.
/// The Array gets flattened by Op::Exec/ExecBg/CallFunction into argv.
pub const BUILTIN_ARRAY_ALL: u16 = 292;
/// Flatten one level of Value::Array nesting. Pops N values; for each, if it's
/// a Value::Array, its elements are appended directly; otherwise the value is
/// appended as-is. Pushes a single Value::Array of the flattened result. Used
/// by the for-loop word-list compile path: when a word like `${arr[@]}`
/// produces a nested Array, this lets `for i in ${arr[@]}` iterate over the
/// inner elements rather than the outer single-element array.
pub const BUILTIN_ARRAY_FLATTEN: u16 = 293;
/// `coproc [name] { body }` — bidirectional pipe to async child. Pops a name
/// (optional, "" for default) and a sub-chunk index. Creates two pipes, forks,
/// child redirects its fd 0/1 to the inner ends and runs the body, parent
/// stores [write_fd, read_fd] into the named array (default `COPROC`). Caller
/// closes the fds and `wait`s when done. Job-table integration deferred to
/// Phase G6 alongside the bg `&` work.
pub const BUILTIN_RUN_COPROC: u16 = 294;
/// `arr+=(d e f)` — append N elements to an existing indexed array. Compile
/// emits N element pushes + name push, then `CallBuiltin(295, N+1)`. Handler
/// drains args (last popped = name), extends `executor.arrays[name]` (creates
/// the entry if missing). Mirrors zsh's `+=` semantics for indexed arrays.
pub const BUILTIN_APPEND_ARRAY: u16 = 295;
/// `name[@]=(...)` / `name[*]=(...)` whole-array SET. Identical to
/// BUILTIN_SET_ARRAY for an indexed array / scalar (whole replace), but
/// rejects an associative target with "attempt to set slice of
/// associative array" (c:Src/params.c:3324-3327).
pub const BUILTIN_SET_ARRAY_AT: u16 = 633;
/// `name[@]+=(...)` / `name[*]+=(...)` whole-array APPEND. Indexed
/// append (push), assoc target → same slice-of-assoc error as 633.
pub const BUILTIN_APPEND_ARRAY_AT: u16 = 634;
/// `select var in words; do body; done` — interactive numbered-menu loop.
/// Compile emits N word pushes + var-name push + sub-chunk index push, then
/// `CallBuiltin(296, N+2)`. Handler prints `1) word1\n2) word2\n...` to
/// stderr, prints `$PROMPT3` (default `?# `) to stderr, reads a line from
/// stdin. On EOF returns 0. On a valid 1-based number, sets `var` to the
/// chosen word, runs the sub-chunk, then redisplays the menu and loops. On
/// invalid input redraws the menu without running the body. `break` from
/// inside the body exits the loop (handled by the body's own bytecode).
pub const BUILTIN_RUN_SELECT: u16 = 296;
/// `m[k]+=value` — append onto an existing assoc-array value (string concat).
/// If the key doesn't exist, behaves like SET_ASSOC. Stack: [name, key, value].
/// `break` from inside a body that runs on a sub-VM (select, future
/// loop-via-builtin constructs). Writes the canonical
/// `crate::ported::builtin::BREAKS` atomic (port of `Src/loop.c:46
/// breaks`). Outer-loop builtins drain BREAKS/CONTFLAG after each
/// body run, matching the loop.c:529-534 drain pattern.
pub const BUILTIN_SET_BREAK: u16 = 299;
/// `continue` from inside a sub-VM body. Sets CONTFLAG=1 + bumps
/// BREAKS, matching `bin_break`'s WC_CONTINUE arm at Src/builtin.c
/// c:5836 `contflag = 1; FALLTHROUGH; breaks++;`.
pub const BUILTIN_SET_CONTINUE: u16 = 300;
/// Brace expansion: `{a,b,c}` → 3 values, `{1..5}` → 5 values, `{01..05}` →
/// zero-padded numerics, `{a..e}` → letter range. Pops one string, returns
/// Value::Array of expansions (empty array → original string preserved).
pub const BUILTIN_BRACE_EXPAND: u16 = 301;
/// Glob qualifier filter: `*(qualifier)` filters glob results by predicate.
/// Pops [pattern, qualifier_string]. Returns Value::Array of matching paths.
/// Re-export the regex_match host method as a builtin so `[[ s =~ pat ]]`
/// works even when fusevm's Op::RegexMatch isn't routed (compat fallback).
/// Word-split a string on IFS (default: whitespace). Pops one string,
/// returns Value::Array of fields. Used in array-literal context where
/// `arr=($(cmd))` should expand cmd's stdout into multiple elements.
pub const BUILTIN_WORD_SPLIT: u16 = 304;
/// `${=name}` / SH_WORD_SPLIT forced IFS split — c:Src/subst.c:3920-3928
/// `aval = sepsplit(val, spsep, 0, 1);`.
///
/// Unlike BUILTIN_WORD_SPLIT (which routes through `multsub`'s
/// PREFORK_SPLIT walker — the c:553-620 loop that COLLAPSES runs of
/// separators and never emits an empty field), this is the *other* zsh
/// splitter: `sepsplit` → `Src/utils.c:3711 spacesplit(s, allownull=0)`,
/// which distinguishes the two IFS classes and preserves empty fields.
///
/// Stack: \[value\]. argc selects the empty-field rule:
/// * argc == 0 — the expansion is a bare unquoted word (`${=v}`): the
/// leading/trailing `""` fields spacesplit emits for skipped
/// IFS-WHITESPACE are empty argv words and prefork deletes them
/// (c:Src/subst.c:184-187 `uremnode`).
/// * argc == 1 — the expansion is quoted (`"${=v}"`) or has adjacent
/// word segments (`x${=v}y`): those fields survive, because in C the
/// word's `Dnull` quote markers / literal prefix+suffix attach to the
/// first and last elements (c:4386 / c:4429 strcatsub) and the node is
/// no longer empty. `v=$' a:b '` → `""`, `a:b`, `""` quoted; `x`,
/// `a:b`, `y` with surrounding text.
///
/// Empty fields that come from an IFS-NON-whitespace separator are the
/// `nulstring` (`Nularg`, c:Src/subst.c:36) and survive in BOTH cases —
/// `IFS=x; v=xaxbx` splits to `""`, `a`, `b`, `""` quoted or not.
pub const BUILTIN_FORCE_SPLIT: u16 = 643;
/// Register a pre-compiled fusevm chunk as a function. Stack: [name,
/// base64-bincode-of-Chunk]. Used by compile_zsh's compile_funcdef to
/// register functions parsed via parse_init+parse without going through the
/// ShellCommand JSON serialization path.
pub const BUILTIN_REGISTER_COMPILED_FN: u16 = 305;
/// `BUILTIN_VAR_EXISTS` constant.
pub const BUILTIN_VAR_EXISTS: u16 = 306;
/// Native param-modifier builtins. Each takes a fixed argv shape and
/// returns the modified value as Value::Str.
///
/// `${var:-default}` / `${var:=default}` / `${var:?error}` / `${var:+alt}`
/// — pop [name, op_byte, rhs]. op_byte: 0=`:-`, 1=`:=`, 2=`:?`, 3=`:+`.
pub const BUILTIN_PARAM_DEFAULT_FAMILY: u16 = 307;
/// `${var:offset[:length]}` — pop [name, offset, length] (length=-1 means
/// "rest of value"; negative offset counts from end).
pub const BUILTIN_PARAM_SUBSTRING: u16 = 308;
/// `${var#pat}` / `${var##pat}` / `${var%pat}` / `${var%%pat}` — pop
/// [name, pattern, op_byte]. op_byte: 0=`#`, 1=`##`, 2=`%`, 3=`%%`.
pub const BUILTIN_PARAM_STRIP: u16 = 309;
/// `${var/pat/repl}` / `${var//pat/repl}` / `${var/#pat/repl}` /
/// `${var/%pat/repl}` — pop [name, pattern, replacement, op_byte].
/// op_byte: 0=first, 1=all, 2=anchor-prefix, 3=anchor-suffix.
pub const BUILTIN_PARAM_REPLACE: u16 = 310;
/// `${#name}` — character length of a scalar value, or element count
/// of an indexed/assoc array. Pops \[name\], returns count as Value::Str.
pub const BUILTIN_PARAM_LENGTH: u16 = 311;
/// `$((expr))` arithmetic substitution. Pops \[expr_string\], evaluates
/// via the executor's MathEval (integer-aware), returns result as
/// Value::Str. Bypasses ArithCompiler's float-only Op::Div path so
/// `$((10/3))` returns "3" not "3.333...".
pub const BUILTIN_ARITH_EVAL: u16 = 312;
/// `(( ... ))` math command post-eval status hook. Pops nothing,
/// pushes Value::Status. If errflag is set (math error in the
/// preceding BUILTIN_ARITH_EVAL call), clears it and emits status=2
/// matching c:Src/math.c arith-failure semantics. Otherwise emits
/// the current vm.last_status. Used by compile_arith's `(( ... ))`
/// path so the math command swallows errors without halting the
/// script — `$((... ))` substitutions skip this hook so their
/// errflag propagates up to the containing command.
pub const BUILTIN_ARITH_CMD_FINISH: u16 = 527;
/// `$(cmd)` command substitution. Pops \[cmd_string\], runs through
/// `run_command_substitution` which compiles via parse_init+parse + ZshCompiler
/// and captures stdout via an in-process pipe. Returns trimmed output
/// as Value::Str. Avoids the sub-chunk word-emit quoting bug in the
/// raw Op::CmdSubst path.
pub const BUILTIN_CMD_SUBST_TEXT: u16 = 313;
/// Text-based word expansion. Pops \[preserved_text\]: the word with
/// quotes preserved (Dnull→`"`, Snull→`'`, Bnull→`\`), runs
/// `expand_string` (variable + cmd-sub + arith) then `xpandbraces`
/// then `expand_glob`. Returns Value::str (single match) or
/// Value::Array (multi-match brace/glob).
pub const BUILTIN_EXPAND_TEXT: u16 = 314;
/// `[[ a -ef b ]]` — same-inode test. Stack: [a, b]. Pushes Bool true iff
/// both paths resolve to the same `(dev, inode)` pair (zsh + bash semantics).
pub const BUILTIN_SAME_FILE: u16 = 315;
/// `[[ a -nt b ]]` — file `a` newer than file `b` (mtime strict).
/// Stack: [path_a, path_b]. Pushes Bool. zsh-compatible "missing"
/// rules: if both exist, compare mtime; if only `a` exists → true;
/// otherwise false.
pub const BUILTIN_FILE_NEWER: u16 = 324;
/// `[[ a -ot b ]]` — mirror of `-nt`. If both exist, compare mtime;
/// if only `b` exists → true; otherwise false.
pub const BUILTIN_FILE_OLDER: u16 = 325;
/// `[[ -k path ]]` — sticky bit (S_ISVTX) set on path.
pub const BUILTIN_HAS_STICKY: u16 = 326;
/// `[[ -u path ]]` — setuid bit (S_ISUID).
pub const BUILTIN_HAS_SETUID: u16 = 327;
/// `[[ -g path ]]` — setgid bit (S_ISGID).
pub const BUILTIN_HAS_SETGID: u16 = 328;
/// `[[ -O path ]]` — owned by effective UID.
pub const BUILTIN_OWNED_BY_USER: u16 = 329;
/// `[[ -G path ]]` — owned by effective GID.
pub const BUILTIN_OWNED_BY_GROUP: u16 = 330;
/// `[[ -N path ]]` — file modified since last accessed (atime <= mtime).
pub const BUILTIN_FILE_MODIFIED_SINCE_ACCESS: u16 = 341;
/// `name+=val` (no parens) — runtime-dispatched append.
/// If name is an indexed array → push val as element.
/// If name is an assoc array → error (zsh requires `(k v)` form).
/// Else → scalar concat (existing SET_VAR behavior).
pub const BUILTIN_APPEND_SCALAR_OR_PUSH: u16 = 331;
/// `[[ -c path ]]` — character device.
pub const BUILTIN_IS_CHARDEV: u16 = 332;
/// `[[ -b path ]]` — block device.
pub const BUILTIN_IS_BLOCKDEV: u16 = 333;
/// `[[ -p path ]]` — FIFO / named pipe.
pub const BUILTIN_IS_FIFO: u16 = 334;
/// `[[ -S path ]]` — socket.
pub const BUILTIN_IS_SOCKET: u16 = 335;
/// `BUILTIN_ERREXIT_CHECK` constant.
pub const BUILTIN_ERREXIT_CHECK: u16 = 336;
/// Fatal-error-only abort check, for use INSIDE an `&&` / `||` chain.
///
/// A chain suppresses the errexit check (a non-zero status is "consumed"
/// by the connector — `false && x` must not fire ERREXIT or the ZERR
/// trap). But an errflag — a *fatal* error such as a `[[ ]]` bad pattern
/// — is not a status the connector can consume: zsh abandons the whole
/// list. Without this, zshrs ran the `||` right-hand side after the
/// error (`[[ x = [a- ]] || touch f` created `f`; zsh does not) and the
/// aborted builtin then overwrote the cond's status 2 with 1.
///
/// Same errflag arm as `BUILTIN_ERREXIT_CHECK`, with the errexit/ZERR
/// half omitted.
pub const BUILTIN_FATAL_ABORT_CHECK: u16 = 641;
/// Post-`always`-arm checks for the canonical RETFLAG / BREAKS /
/// CONTFLAG atomics that mark try-block escapes. Each returns
/// Value::Int(1) when the corresponding atomic is set (and consumes
/// it so the next escape doesn't re-fire) and Value::Int(0) otherwise.
/// Paired with JumpIfFalse + Jump to outer return_patches /
/// break_patches / continue_patches by compile_zsh's `Try` arm.
pub const BUILTIN_RETFLAG_CHECK: u16 = 600;
/// `BUILTIN_BREAKS_CHECK` constant.
pub const BUILTIN_BREAKS_CHECK: u16 = 601;
/// `BUILTIN_CONTFLAG_CHECK` constant.
pub const BUILTIN_CONTFLAG_CHECK: u16 = 602;
/// `loops++` on entry to a compiled for/while/until/repeat
/// (c:Src/loop.c:114/427/523).
pub const BUILTIN_LOOP_ENTER: u16 = 656;
/// `loops--` on exit from a compiled for/while/until/repeat
/// (c:Src/loop.c:188/491/546).
pub const BUILTIN_LOOP_EXIT: u16 = 657;
/// Post-body `if (breaks) { breaks--; … }` drain (c:Src/loop.c:529-534).
/// Int(1) = terminate this loop, Int(0) = next iteration.
pub const BUILTIN_LOOP_BREAK_DRAIN: u16 = 658;
/// Non-consuming `breaks != 0` probe for execlist's per-statement gate
/// (c:Src/exec.c:1370).
pub const BUILTIN_BREAKS_PENDING: u16 = 659;
/// `shtokenize` the top-of-stack string in place — c:Src/subst.c:4419-4420
/// `if (globsubst) shtokenize(y)`, the step that makes a `${~spec}` /
/// `$~spec` value's metachars PATTERN-ACTIVE.
///
/// zshrs expands a `[[ ]]` operand at the VM level and hands `cond_str`
/// (c:Src/cond.c:525) a finished string, so the token state C carries in
/// the word itself has to be re-applied at the point of use. Without it a
/// module condition compiles the value as a literal: `[[ -prefix $~pat ]]`
/// (Completion/Base/Utility/_numbers sh:65) is the one shipped completer
/// that depends on it.
pub const BUILTIN_COND_SHTOKENIZE: u16 = 660;
/// Fire the DEBUG trap (SIGDEBUG) before each statement.
/// c:Src/exec.c:1357-1500 DEBUGBEFORECMD — when a "DEBUG" entry is
/// installed via `trap '...' DEBUG`, run the body just before the
/// next command. Cheap when no DEBUG trap is set (one hashmap lookup
/// returns None and we early-out).
pub const BUILTIN_DEBUG_TRAP: u16 = 603;
/// `set -n` / `set -o noexec` — parse but don't execute. Returns
/// Value::Int(1) when the noexec option is set so the caller's
/// JumpIfTrue skips the statement body. c:Src/exec.c:1390 main loop
/// check.
pub const BUILTIN_NOEXEC_CHECK: u16 = 604;
/// c:Src/exec.c:4051 — `else if (isset(EXECOPT) && !errflag)`: a simple
/// command's words are expanded (prefork c:3304, globlist c:3757) whether
/// or not NO_EXEC is set; only the execution is skipped. No args. Returns
/// Int(1) under NO_EXEC, after setting the status to 1 when the expansion
/// raised errflag (c:3760-3763); the caller's JumpIfTrue then drops the
/// expanded words without running the command. Int(0) otherwise.
pub const BUILTIN_NOEXEC_CMD_GATE: u16 = 748;
/// Block-level redirect-failure gate. Reads exec.redirect_failed
/// (set by host.redirect when a redirect open fails); returns
/// Value::Int(1) AND clears the flag if set, else 0. Emit-side at
/// compile_zsh.rs::compile_command's Redirected arm pairs with a
/// JumpIfTrue → WithRedirectsEnd to abandon the body. Without this,
/// a multi-statement block after a failed redir kept running every
/// statement after the first (the first builtin consumed the flag,
/// subsequent statements ran unimpeded).
pub const BUILTIN_REDIRECT_FAILED_CHECK: u16 = 605;
/// Drop-in replacement for fusevm's Op::Exec for the dynamic-first-
/// word path (`$cmd`, `$(cmd)`, `~/bin/foo`). Returns
/// Value::Status(vm.last_status) when post-expansion argv is empty
/// (preserves the inner cmd-subst's exit), Value::Status(126) with
/// "permission denied" when `argv[0]` is empty, otherwise routes
/// through executor.host_exec_external like Op::Exec did.
pub const BUILTIN_EXEC_DYNAMIC: u16 = 606;
/// Reset `use_cmdoutval` to 0 at the START of a dynamic command (before
/// its words expand), so a command substitution from a PREVIOUS command
/// can't leak into this command's null-command status decision
/// (c:Src/exec.c:3009 `use_cmdoutval = !args`). See BUILTIN_EXEC_DYNAMIC.
pub const BUILTIN_USE_CMDOUTVAL_RESET: u16 = 637;
/// Reset `cmdoutval` to 0 at the START of a simple command that carries
/// assignments, before any of its words or assignment values expand
/// (c:Src/exec.c:2796 execcmd_analyse, c:1368 execsimple WC_ASSIGN).
pub const BUILTIN_CMDOUTVAL_RESET: u16 = 731;
/// Tilde-expand a match pattern's leading `~`, the way `singsub` does
/// before the pattern reaches `patcompile`.
///
/// c:Src/cond.c:299-307 — `right = dupstring(ecrawstr(…)); singsub(&right);
/// … patcompile(right, …)`. `singsub` is `prefork(PREFORK_SINGLE)`
/// (c:Src/subst.c:520), and prefork runs `filesub` on every word, so an
/// unquoted `~` in a `[[ … == ~/* ]]` pattern — or one that arrives via
/// `${~var}` — is a home directory, not a literal character. `case`
/// patterns take the same route (c:Src/loop.c:610 `singsub(&pat)`).
/// zshrs untokenizes the pattern at compile time and re-tokenizes it in
/// the matcher, so the expansion has to happen here.
///
/// Only a LEADING `~` is considered, which is all `filesubstr`
/// (c:Src/subst.c:741) ever expands: a `~` elsewhere is EXTENDED_GLOB's
/// "except" operator and must survive untouched, and a quoted one has
/// already been backslash-escaped by `escape_quoted_glob_metas` so it
/// fails the leading-char test.
///
/// powerlevel10k's directory segment is the visible consumer: its
/// `_POWERLEVEL9K_DIR_CLASSES` walk matches `$PWD` against `~` and `~/*`
/// via `[[ $_p9k__cwd == ${~a} ]]` (internal/p10k.zsh:2029). Without the
/// expansion both classes missed, every path under `$HOME` fell through
/// to the `*` DEFAULT class, and the prompt showed the generic folder
/// icon in place of the home / home-subfolder one.
fn pattern_filesub(pattern: &str) -> String {
let first = pattern.chars().next();
if first != Some('~') && first != Some(crate::ported::zsh_h::Tilde) {
return pattern.to_string();
}
// filesubstr keys on the Tilde TOKEN, so shtokenize first (a raw `~`
// becomes Tilde; an already-tokenized one passes through), then
// untokenize the surviving glob metas back for the matcher.
let mut tok = pattern.to_string();
crate::ported::glob::shtokenize(&mut tok);
crate::ported::lex::untokenize(&crate::ported::subst::filesub(&tok, 0))
}
/// `[[ lhs == pat ]]` / `!=` glob compare — cond-specific so the
/// bad-pattern diagnostic follows Src/cond.c:308-316: zwarnnam
/// "bad pattern: %s" WITHOUT errflag (the script continues) and the
/// cond statement exits 2. Stack: [lhs, pat] → Bool. On compile
/// failure pushes Bool(false) and arms COND_BAD_PATTERN so
/// BUILTIN_COND_STATUS_FROM_BOOL reports 2.
pub const BUILTIN_COND_STRMATCH: u16 = 624;
/// Pops the cond result Bool → Int status per Src/cond.c: true→0,
/// false→1, but 2 when COND_BAD_PATTERN was armed during this cond
/// (covers `!=` where LogNot flips the Bool before status time).
pub const BUILTIN_COND_STATUS_FROM_BOOL: u16 = 625;
/// `[[ ]]` unknown condition. Pops \[op_name\], emits `zerr("unknown
/// condition: %s")` and sets ERRFLAG_ERROR so the next BUILTIN_ERREXIT_CHECK
/// (trigger 4) aborts the input — matching zsh's COND_MODI "unknown condition"
/// path (Src/cond.c:150-188) for a `-X` op with no matching loadable module.
/// Returns Bool(false). Replaces a compile-time `eprintln!` hack that printed
/// the message but never set errflag (so the line didn't abort).
pub const BUILTIN_COND_UNKNOWN: u16 = 632;
/// Bare-`exec` redirect epilogue. Consumes `exec.redirect_failed` and
/// applies the C `done:` tail of execcmd_exec:
/// - c:Src/exec.c:252-259 execerr — `redir_err = lastval = 1` (the
/// failed redirect makes the exec statement exit 1, NOT fatal by
/// itself);
/// - c:Src/exec.c:4367-4386 — `if (isset(POSIXBUILTINS) && (cflags
/// & (BINF_PSPECIAL|BINF_EXEC)) ...) { if (redir_err || errflag)
/// { if (!isset(INTERACTIVE)) exit(1); } }` — POSIX_BUILTINS makes
/// a failed exec redirect fatal in a non-interactive shell.
/// Returns Value::Status(0|1) for the trailing SetStatus.
pub const BUILTIN_EXEC_REDIR_DONE: u16 = 626;
/// Assignment-prefix epilogue for bare `exec` redirects
/// (`x=$(cmd) exec >file`). c:Src/exec.c:3969-3976 — nullexec==1
/// runs addvars THEN, without POSIX_BUILTINS, restores the params
/// (`save_params` / `restore_params`): the RHS side effects fire but
/// the values don't persist. With POSIX_BUILTINS the assignments
/// stick. Pops the BEGIN_INLINE_ENV frame either way.
pub const BUILTIN_EXEC_INLINE_ENV_DONE: u16 = 627;
/// `< file` / `> file` with no command word (NULLCMD path).
/// Resolves NULLCMD (default "cat") / READNULLCMD (default "more")
/// at runtime per Src/exec.c:3386-3419, then dispatches that word
/// exactly as execcmd's fall-through does: shell function (c:3485)
/// → builtin (c:3489) → external. Argc is 1: the int (0 or 1) on the
/// stack indicates whether this is a single REDIR_READ redirect
/// (selects READNULLCMD when set + non-empty).
pub const BUILTIN_NULLCMD_EXEC: u16 = 607;
/// c:Src/exec.c:3395-3399 — the redirection-only command's refusal,
/// taken before its redirections open: no NULLCMD, or CSH_NULLCMD set,
/// is `zerr("redirection with no command")` with `lastval = 1` and
/// ERRFLAG_ERROR. argc=0; Bool(true) = go on to NULLCMD_EXEC.
pub const BUILTIN_NULLCMD_CHECK: u16 = 760;
/// Emitted right before BUILTIN_EXEC_DYNAMIC when the simple command has
/// redirections. No args. The VM has already opened them, so the dispatch
/// passes `execcmd_exec` an empty `redir` list; this tells its AUTOCD test
/// (c:Src/exec.c:3596 `(!redir || empty(redir))`) that there were some.
pub const BUILTIN_EXEC_DYNAMIC_REDIRS: u16 = 761;
/// Emitted right before a command word compiled to a builtin opcode: the
/// command runs in the current shell, so execcmd_exec's is_cursh arm
/// (c:Src/exec.c:3674-3682) marks the pipeline's job STAT_CURSH, plus
/// STAT_NOPRINT while it has no processes. No args; pushes Int(0).
pub const BUILTIN_MARK_CURSH: u16 = 762;
/// Opens the window in which the prefix assignments of `X=… cmd` expand.
/// argc=1: the command word ("" when it is an expansion). Closed by
/// BUILTIN_SEAL_INLINE_ENV. See PREFIX_ASSIGN_CMD.
pub const BUILTIN_PREFIX_ASSIGNS_START: u16 = 763;
/// Emitted right after the command-name word of a dynamic simple command is
/// expanded. argc=1: Int, nonzero when more words follow. Pushes Int(0). Records whether globbing that word
/// failed (c:Src/exec.c:3350-3354 zglobs the name in the shell, before the
/// fork, so its errflag is not cleared like an argument glob failure is).
/// Read by [`take_cmd_name_glob_failed`].
pub const BUILTIN_CMD_NAME_GLOB_MARK: u16 = 764;
/// `[[ s -pcre-match re ]]` (Src/Modules/pcre.c:506 `cond_pcre_match`). Stack:
/// [lhs, rhs] -> Bool. Always the PCRE engine, whatever REMATCHPCRE says (that
/// option only picks the engine for `=~`, c:Src/cond.c:113-119).
pub const BUILTIN_COND_PCRE_MATCH: u16 = 765;
/// `cmd &!` where `cmd` is a `%job` word (c:Src/exec.c:3020-3023 + the matching
/// restore after the command): argc=1, Int. Nonzero saves AUTOCONTINUE and
/// turns it on; zero restores the saved value. Pushes Int(0).
pub const BUILTIN_AUTOCONTINUE_FORCE: u16 = 766;
/// `.` (dot) — alias of source/bin_dot but dispatches with the
/// literal name "." so the diagnostic prefix matches zsh's
/// (`zsh:.:1: …` vs source's `zsh:source:1: …`).
/// c:Src/builtin.c:9308 — `BUILTIN(".", BINF_PSPECIAL, bin_dot, …)`.
pub const BUILTIN_DOT: u16 = 608;
/// `logout` — fusevm maps this to BUILTIN_EXIT alongside `exit`/`bye`,
/// which drops the name and dispatches with BIN_EXIT funcid. zsh's
/// `logout` outside a login shell must emit "not login shell" + exit 1,
/// which only fires when bin_break sees BIN_LOGOUT funcid. Dedicated
/// opcode dispatches via BUILTINS table by literal name "logout".
pub const BUILTIN_LOGOUT: u16 = 610;
/// `BUILTIN_PARAM_SUBSTRING_EXPR` constant.
pub const BUILTIN_PARAM_SUBSTRING_EXPR: u16 = 337;
/// `BUILTIN_XTRACE_LINE` constant.
pub const BUILTIN_XTRACE_LINE: u16 = 338;
/// `BUILTIN_XTRACE_ARRAY_LINE` — xtrace an `arr=(...)` assignment from the
/// whole assembled `Value::Array` (see compile_zsh array-literal codegen).
pub const BUILTIN_XTRACE_ARRAY_LINE: u16 = 649;
/// `BUILTIN_MAKE_ARRAY_COUNTED` — like `Op::MakeArray(u16)` but the element
/// count is a runtime `Int` on the stack, so it is not capped at 65535. Used
/// by the array-literal codegen only when the literal has > u16::MAX elements
/// (e.g. a .zcompdump's ~103k-element `_comps=(...)`).
pub const BUILTIN_MAKE_ARRAY_COUNTED: u16 = 650;
/// `BUILTIN_ARGV_RFLATTEN` — pop one `Op::MakeArray`-packed argv bundle and
/// push it back as ONE recursively-flattened `Value::Array` of scalars. Emitted
/// by the simple-command codegen ONLY on the >255-arg overflow path: the
/// `Call`/`CallFunction`/`CallBuiltin` opcodes carry argc as a u8, so a command
/// with more than 255 args is packed into a single Array (dispatched with
/// argc=1) instead. But those call ops flatten their argv only ONE level, which
/// would stringify a nested Array (a brace/glob/`$arr` word contributes a
/// `Value::Array`). Pre-flattening here — same descent as
/// [`flatten_array_value`], the array-assignment path — makes the bundle flat
/// so the call op's single-level splat restores every positional arg. Bit
/// compsys: a completer's `_arguments <specs…>` with a large brace-form option
/// set (curl ships 59 `{-x,--long}` specs) dropped the long forms.
pub const BUILTIN_ARGV_RFLATTEN: u16 = 653;
/// `BUILTIN_ARRAY_JOIN_STAR` constant.
pub const BUILTIN_ARRAY_JOIN_STAR: u16 = 339;
/// `BUILTIN_SET_RAW_OPT` constant.
pub const BUILTIN_SET_RAW_OPT: u16 = 340;
/// `time { compound; ... }` — wall-clock-time the sub-chunk and print
/// elapsed seconds. Stack: [sub_chunk_idx as Int]. Runs the sub-chunk
/// on the current VM (so positional/local state is shared) and prints
/// the timing summary to stderr in zsh's format. Pushes Status.
pub const BUILTIN_TIME_SUBLIST: u16 = 316;
/// `{name}>file` / `{name}<file` / `{name}>>file` — named-fd allocation.
/// Stack: [path, varid, op_byte]. Opens `path` per `op_byte`, gets the
/// new fd (≥10 in zsh; we use libc::open with O_CLOEXEC bit cleared so
/// the inherited fd survives Command::new spawns), stores the fd number
/// as a string in `$varid`. Pushes Status (0 success, 1 error).
pub const BUILTIN_OPEN_NAMED_FD: u16 = 317;
/// Word-segment concat that does cartesian-product distribution over
/// arrays. Stack: [lhs, rhs]. Used for RC_EXPAND_PARAM `${arr}` and
/// explicit-distribute forms (`${^arr}`, `${(@)…}`).
///
/// - both scalar: `Value::str(a + b)` (fast path, identical to Op::Concat)
/// - lhs Array, rhs scalar: `Value::Array([a + rhs for a in lhs])`
/// - lhs scalar, rhs Array: `Value::Array([lhs + b for b in rhs])`
/// - both Array: cartesian product `[a + b for a in lhs for b in rhs]`
pub const BUILTIN_CONCAT_DISTRIBUTE: u16 = 318;
/// Forced-distribute concat — like `BUILTIN_CONCAT_DISTRIBUTE` but
/// always distributes cartesian regardless of the `rcexpandparam`
/// option. Emitted by the segments fast-path when an
/// `is_distribute_expansion` segment is present (`${^arr}`,
/// `${(@)arr}`, `${(s.…)arr}` etc.) per zsh: the source-level
/// distribution flag overrides the option default.
/// Direct port of Src/subst.c:1875 `case Hat: nojoin = 1` and the
/// `rcexpandparam` test bypass for the explicit-distribute flags.
pub const BUILTIN_CONCAT_DISTRIBUTE_FORCED: u16 = 522;
/// Capture current `last_status` into the `TRY_BLOCK_ERROR` variable.
/// Emitted between the try block and the always block of `{ … } always
/// { … }` so the finally arm can read $TRY_BLOCK_ERROR.
pub const BUILTIN_SET_TRY_BLOCK_ERROR: u16 = 320;
/// `BUILTIN_RESTORE_TRY_BLOCK_STATUS` constant.
pub const BUILTIN_RESTORE_TRY_BLOCK_STATUS: u16 = 432;
/// `BUILTIN_BEGIN_INLINE_ENV` constant.
pub const BUILTIN_BEGIN_INLINE_ENV: u16 = 433;
/// `BUILTIN_END_INLINE_ENV` constant.
pub const BUILTIN_END_INLINE_ENV: u16 = 434;
/// Closes the current inline-env frame's save list. Emitted right
/// after the prefix assignments of `X=foo cmd` have committed and
/// before `cmd` dispatches, so assignments performed BY the command
/// are not recorded into (and therefore not reverted with) the frame.
/// c:Src/exec.c:4410 `save_params` snapshots only the parsed
/// WC_ASSIGN chain; the list is closed before the builtin/shell
/// function runs. Without the seal, `X=y . file` reverted every
/// global the sourced file assigned — which emptied git's
/// `git-completion.bash` option tables (`__git_log_common_options`
/// et al.) that `_git` sources via `GIT_SOURCING_ZSH_COMPLETION=y . …`.
pub const BUILTIN_SEAL_INLINE_ENV: u16 = 654;
/// End-of-sublist `waitonejob` for a sublist that ran wholly in the
/// current shell. Emitted by `compile_zsh::compile_sublist` after each
/// element of the `&&`/`||` chain whose parse-time `cmplx` flag is set
/// (see `compile_zsh::sublist_elem_is_cmplx`) and whose top level is
/// NOT a multi-stage pipeline.
///
/// c:Src/exec.c:1489-1492 — `execlist` routes each sublist element on
/// the parse-time flag: `if (WC_SUBLIST_FLAGS(code) & WC_SUBLIST_SIMPLE)
/// execsimple(state); else execpline(state, code, ltype, ...);`. Only
/// the `execpline` arm builds a job, and `execpline` ends by calling
/// `waitonejob` on it.
///
/// c:Src/jobs.c:1748-1757 — `waitonejob(Job jn)`:
/// ```c
/// if (jn->procs || jn->auxprocs) zwaitjob(jn - jobtab, 0);
/// else { deletejob(jn, 0); pipestats[0] = lastval; numpipestats = 1; }
/// ```
/// A sublist that forked (a real multi-stage pipeline) takes the
/// `zwaitjob` arm, whose `storepipestats` (c:Src/jobs.c:420) publishes
/// the per-stage array — in zshrs that is `BUILTIN_RUN_PIPELINE`'s own
/// `set_array("pipestatus", ...)`. Every other cmplx sublist runs with
/// an empty proc list and takes the `else` arm, which is what this
/// builtin performs. Resolving which arm applies is a compile-time
/// decision in C (the parse-time flag) and is a compile-time decision
/// here too, so no marker is emitted for the pipeline case at all.
///
/// This is what makes a compound command publish `$pipestatus`:
/// `if ...; fi`, `for ...; done`, `case ... esac`, `while ...; done`,
/// `{ ... }`, `( ... )` and a bare command all reach `execpline` when
/// their body is cmplx, so zsh leaves `numpipestats == 1`. It also
/// makes the OUTER sublist win over an inner pipeline's array —
/// `if true; then true|false; fi` is `n=1 p=(1)`, not `(0 1)` — because
/// the outer procs-less job overwrites what the inner job stored.
///
/// Fires BEFORE the `!` negation (`emit_negate_status`): C applies
/// `WC_SUBLIST_NOT` inside `execpline` after the wait, so
/// `! [[ -z x ]]` records the PRE-negation status — `p=(1)` with `$?`
/// of 0.
pub const BUILTIN_SUBLIST_FINISH: u16 = 655;
/// `[[ -o option ]]` — shell-option-set test. Stack: \[option_name\].
/// Normalizes the name (strip underscores, lowercase) and reads
/// `exec.options`. Pushes Bool.
pub const BUILTIN_OPTION_SET: u16 = 321;
/// Tri-state `[[ -o NAME ]]` — same lookup as BUILTIN_OPTION_SET
/// but returns a Value::Int (0=set, 1=unset, 3=invalid-name). The
/// 3-state code matches zsh's `[[ -o invalid ]]` exit (Src/cond.c
/// :502 `optison()`). Used by compile_cond's `-o` arm to skip the
/// generic bool→status conversion and preserve the invalid-name
/// signal in `$?`.
pub const BUILTIN_OPTION_CHECK_TRISTATE: u16 = 609;
/// `${var:#pattern}` — array filter: remove elements matching `pattern`.
/// Stack: [name, pattern]. For scalar `var`, returns empty if it matches
/// the pattern, else the value. For array `var`, returns Array of
/// non-matching elements.
pub const BUILTIN_PARAM_FILTER: u16 = 322;
/// `a[i]=(elements)` / `a[i,j]=(elements)` / `a[i]=()` —
/// subscripted-array assign with array-literal RHS. Stack:
/// [...elements, name, key]. Empty elements + single-int key `a[i]=()`
/// removes that element. Comma-key `a[i,j]=(...)` splices.
pub const BUILTIN_SET_SUBSCRIPT_RANGE: u16 = 323;
/// `[[ -X file ]]` for unknown unary test op `-X`. Stack: \[op_name\].
/// Emits zsh's `unknown condition: -X` diagnostic to stderr and
/// pushes Bool(false). Without this, unknown conditions silently
/// returned false matching neither zsh's error format nor the
/// expected status code (zsh returns 2 for parse error).
/// `[[ -t fd ]]` — fd-is-a-tty check. Stack: \[fd_string\].
/// Routes through libc::isatty. Pushes Bool.
///
/// ID 644 (unique, next free above the previous max of 643). This was
/// 325, which COLLIDED with BUILTIN_FILE_OLDER (also 325). The VM's
/// builtin table is last-registration-wins, and FILE_OLDER registered
/// after IS_TTY, so every `[[ -t fd ]]` silently dispatched to the
/// file-`-ot` handler: it compared the mtime of a file NAMED by the fd
/// string ("0", "1", …) — which never exists — so `[[ -t 0 ]]` was
/// always false. That broke interactive detection (`[[ -t 0 && -t 1 ]]`)
/// and any config gated on it. c:Src/cond.c:390 `return !isatty(...)`.
pub const BUILTIN_IS_TTY: u16 = 644;
/// Runtime rejection of a process substitution used inside a `[[ … ]]`
/// cond operand. c:Src/exec.c:4918/5040/5069 — `getoutputfile`/`getproc`
/// error `"process substitution %s cannot be used here"` when `thisjob ==
/// -1`, which is the case during cond evaluation. zshrs's THISJOB never
/// distinguishes that context at runtime, so the compiler emits this
/// builtin (gated on `in_cond_operand`) instead of the ProcessSubIn/Out
/// opcode. Pops the substitution text, zerrs, sets errflag (aborting the
/// statement → empty stdout, exit 1, matching zsh), returns empty.
pub const BUILTIN_PROCSUB_COND_ERROR: u16 = 645;
/// `${^arr}` cross-product concat — RC_EXPAND_PARAM forced ON by the `^` flag.
///
/// Distinct from BUILTIN_CONCAT_DISTRIBUTE_FORCED, which the other distribute
/// shapes (`${(@)a}`, `${(f)v}`, `${a[@]}`) share: those keep the word when the
/// array is EMPTY (`x${(@)a}y` → `xy`), but plan9 DELETES it
/// (c:Src/subst.c:4362-4365 `if (plan9) { uremnode(l, n); return n; }`), so
/// `x${^a}y` with `a=()` produces no word at all. One builtin cannot serve both
/// — the plan9-ness is known only at compile time, from the `^` flag itself.
/// Routes to `concat_plan9`, which already ports both c:4362's removal and the
/// c:4316-4350 cartesian emit, and is what the OPTION path
/// (`setopt rcexpandparam`) has always used.
pub const BUILTIN_CONCAT_PLAN9: u16 = 646;
/// `${^^arr}` concat — RC_EXPAND_PARAM forced OFF by the doubled flag
/// (c:Src/subst.c:2553-2555 `plan9 = 0`).
///
/// The mirror of BUILTIN_CONCAT_PLAN9. Needed because every other concat
/// builtin consults `plan9_active()` (the runtime OPTION) and so cross-products
/// anyway under `setopt rcexpandparam`, while `^^` must override the option:
/// setopt rcexpandparam; a=(a b c); print -rl -- ${^^a}.x
/// # zsh: `a`, `b`, `c.x` — spliced, NOT `a.x b.x c.x`
/// The override is computed in paramsubst but the distribution call is made
/// here, so — like the `^` flag — the only place that knows is the compiler.
/// Routes straight to `concat_splice`, C's non-plan9 join-first-and-last path
/// (c:4366-4437).
pub const BUILTIN_CONCAT_SPLICE_NOPLAN9: u16 = 647;
/// Atomic word assembler for a DQ word that MIXES a plan9 (`^`) segment with a
/// non-plan9 (splice/scalar) segment — e.g. `"${(@)^a}${(@)b}"`.
///
/// The per-pair concat fold (CONCAT_PLAN9 / CONCAT_SPLICE picked ONCE for the
/// whole word) cannot express a word where segment A distributes but segment B
/// splices: a single operator does full-cross OR first/last-splice, never both,
/// and it loses track of which trailing elements are still the "growing edge".
/// zsh (Src/subst.c:4316-4437) instead threads a growing edge through the whole
/// word — an element is "active" until a splice freezes all but the last.
///
/// This builtin ports that edge-tracking directly. Stack (bottom→top):
/// descriptor, seg0, seg1, …, seg(n-1) with argc = n + 1
/// where `descriptor` is an n-char string, one char per segment: `'1'` = plan9
/// (`^`), `'0'` = splice/scalar/literal. Each segment value is an Array (splat)
/// or scalar (1 element). Result is the assembled Array (or scalar / deleted).
pub const BUILTIN_WORD_ASSEMBLE_PLAN9: u16 = 652;
/// `break N`/`continue N` runtime-count validator (see registration).
pub const BUILTIN_BREAK_COUNT_VALIDATE: u16 = 648;
/// `[[ -r/-w/-x file ]]` via access(2) (doaccess) — see handler.
pub const BUILTIN_COND_ACCESS: u16 = 638;
/// Evaluate a `[[ ]]` module/completion condition (`-prefix`/`-suffix`/
/// `-after`/`-between`). Stack (top-first): argc operand words, then the
/// operator word. Dispatches to `complete::eval_mod_cond`. Result pushed as
/// Bool (true = condition matched). Used by the `ZshCond::ModCond` compile arm.
pub const BUILTIN_COND_MOD: u16 = 651;
/// c:Src/cond.c:122-193 COND_MODI — an infix module condition `[[ a -op b ]]`
/// (Src/parse.c:2697-2701). Stack: left word, right word, operator word
/// (top). Looks the operator up as an infix condition, autoloading its
/// module (`getconddef(1, name + 1, 1)`, c:150); failing that, as a prefix
/// condition named by the left word (c:173-177). Bool result; an unknown
/// condition arms the status-2 carrier like BUILTIN_COND_MOD.
pub const BUILTIN_COND_MODI: u16 = 749;
/// c:Src/exec.c:3548-3579 — the `rm *` confirmation. Stack: the expanded
/// argv words of an `rm` (left in place), then a mask (top) of the words
/// whose source ends in an unquoted `*`. Sets ERRFLAG_ERROR when the user
/// declines (checkrmall returns 0), which aborts the command.
pub const BUILTIN_RM_STAR_CHECK: u16 = 750;
/// `provenance` — report the lineage of a tracked parameter: where its
/// bytes entered the shell (command substitution, glob, heredoc, an
/// earlier assignment) and every bytecode-level op that touched them
/// since. Handler: `ShellExecutor::builtin_provenance`; engine:
/// `src/extensions/provenance.rs`. ID 661 is the first free slot above
/// the 653-660 block.
pub const BUILTIN_PROVENANCE: u16 = 661;
/// PRINT_EXIT_VALUE report for one finished simple command. Direct port
/// of c:Src/exec.c:4308-4316 (`execcmd_exec`'s tail):
/// ```c
/// if (isset(PRINTEXITVALUE) && isset(SHINSTDIN) && lastval && !subsh)
/// fprintf(stderr, "zsh: exit %lld\n", lastval);
/// ```
/// The ported `execcmd_exec` carries the same code (exec.rs), but fusevm —
/// not that walker — is what actually runs a command, so the report never
/// fired. `compile_simple` emits this call right after the dispatch's
/// `Op::SetStatus` (both the builtin and the function/external arm), which
/// is exactly where the C line sits. Pushes Status(0), which the emit side
/// pops; `vm.last_status` is left untouched.
pub const BUILTIN_PRINT_EXIT_VALUE: u16 = 662;
/// Update `$LINENO` to track the source line of the next statement.
/// Stack: \[n\] (the line number from `ZshPipe.lineno`). Direct port
/// of zsh's `lineno` global tracking (Src/input.c:330) — the
/// compiler emits one of these per top-level pipe so `$LINENO`
/// reflects the source position at runtime. ID 342 picked because
/// the previous `326` collided with `BUILTIN_HAS_STICKY` (the 325
/// collision between IS_TTY and FILE_OLDER has since been fixed by
/// moving IS_TTY to 644).
pub const BUILTIN_SET_LINENO: u16 = 342;
/// Pop a scalar from the VM stack, run expand_glob on it, push the
/// result as Value::Array. Used by the segment-concat compile path
/// when var refs concatenate with glob meta literals (`$D/*`,
/// `${prefix}*`, etc.) — those skip the bridge's pathname-expansion
/// pass and would otherwise leak the glob meta to argv as a literal.
pub const BUILTIN_GLOB_EXPAND: u16 = 343;
/// MULTIOS-gated glob expansion for redirect-target words
/// (c:Src/glob.c:2161-2167 xpandredir: "Globbing is only done for
/// multios."). Same stack shape as BUILTIN_GLOB_EXPAND; additionally
/// passes the word through literally when `unsetopt multios`.
// 624 is BUILTIN_COND_STRMATCH — the VM's builtin table is
// last-registration-wins, so a duplicate id silently shadows the
// earlier handler.
pub const BUILTIN_REDIR_GLOB_EXPAND: u16 = 628;
/// Reset the default-word glob-pending carrier at the START of a word
/// whose source contains a glob metachar (so the flag never leaks from a
/// prior word/statement). Paired with BUILTIN_DEFAULT_WORD_GLOB.
pub const BUILTIN_DEFAULT_WORD_GLOB_RESET: u16 = 635;
/// Filename-generate the ASSEMBLED word ONLY when the default/alternate
/// paramsubst arm took a SOURCE word carrying glob metachars
/// (subst::DEFAULT_WORD_GLOB_PENDING). A parameter VALUE never sets the
/// flag, so `x='*file'; ${x:-d}` stays literal while `${x:-*file}` /
/// `${x:-a*}bar` glob. Reads+clears the flag. c:Src/subst.c → globlist.
pub const BUILTIN_DEFAULT_WORD_GLOB: u16 = 636;
/// `BUILTIN_SET_LOOP_VAR` constant — for-loop variable binding via
/// `setloopvar` (Src/params.c:6362): a PM_NAMEREF loop var REBINDS
/// to each word (SETREFNAME + setscope) instead of assigning
/// through the chain. Returns Bool(false) when zerr fired
/// (read-only reference / invalid self reference) so the loop
/// driver aborts, mirroring C execfor's errflag check.
pub const BUILTIN_SET_LOOP_VAR: u16 = 629;
/// Emitted once per typeset-family command, just before its first
/// `NAME=…` argument: from there on every word is one of C's postassigns
/// (c:Src/parse.c:1986-1989, c:2008-2050), globbed inside execcmd_exec's
/// builtin branch (c:Src/exec.c:4167-4285) where a NOMATCH leaves `lastval`
/// alone. Sets aside a NOMATCH the earlier command words raised
/// (c:3755-3763, `lastval = 1`).
///
/// Arg: the number of postassign words (dispatch leaves them out of `$_`).
pub const BUILTIN_TYPESET_POSTASSIGNS_BEGIN: u16 = 684;
/// Emitted after the last word of a command that emitted
/// BUILTIN_TYPESET_POSTASSIGNS_BEGIN: moves a postassign NOMATCH off the
/// per-command cell (so argument collection does not store status 1) and
/// puts back the command-word NOMATCH BEGIN set aside.
pub const BUILTIN_TYPESET_POSTASSIGNS_END: u16 = 685;
/// Emitted right before the dispatch of a command whose command word was the
/// enabled, unquoted TYPESET reserved word (C's WC_TYPESET, c:Src/parse.c:1931-1932).
/// c:Src/exec.c:3088-3096 — `if (type == WC_TYPESET && (hn =
/// builtintab->getnode2(builtintab, cmdarg)))`: "If reserved word for typeset
/// command found (and so enabled), use regardless of whether builtin is
/// enabled as we share the implementation." `getnode2` ignores DISABLED, so
/// `disable typeset` does not stop the reserved-word form. No args; sets the
/// carrier dispatch_builtin consumes before its disabled-builtin test.
pub const BUILTIN_TYPESET_RESWD: u16 = 686;
/// The `[` spelling of the test builtin (c:Src/builtin.c:7231 `bin_test`,
/// funcid BIN_BRACKET). fusevm's name table maps `[` and `test` to one
/// BUILTIN_TEST slot, which cannot tell them apart when the closing `]` is
/// missing; compile_zsh emits this id when the command word is `[`, so
/// bin_test sees BIN_BRACKET and reports "']' expected".
pub const BUILTIN_TEST_BRACKET: u16 = 690;
/// Emitted right before the dispatch of a command that carried the `-`
/// precommand modifier (c:Src/builtin.c:42 `BIN_PREFIX("-", BINF_DASH)`,
/// accumulated into `cflags` at c:Src/exec.c:3246). No args; sets the
/// EXEC_DASH carrier. c:Src/exec.c:772-776 — an external command then gets
/// argv[0] `-name`; a function or builtin runs unchanged.
pub const BUILTIN_EXEC_DASH: u16 = 687;
/// Emitted right before the external dispatch of the SIMPLE command at the
/// top of a chunk that a driver may run in a child forked for it (`cmd &`, a
/// pipeline stage, a coproc — compile_zsh.rs `forked_simple_exec`). No args.
/// When that chunk's BUILTIN_EXECCMD_FORKED_LEVEL did find the fork, it sets
/// the EXEC_CARRIER_FORKED bit: c:Src/exec.c:3063 `last1 = forked = 1` and
/// c:4369 `execute(args, cflags, use_defpath)` — the child becomes the command.
pub const BUILTIN_EXEC_FORKED_SIMPLE: u16 = 741;
/// Emitted right before the external/function dispatch of a simple command,
/// with the command's job text (c:Src/exec.c:3536-3538 `getjobtext`). Sets
/// the JOB_TEXT carrier the foreground wait reads when it reports a job that
/// died of a signal (exec_jobs::foreground_job_report).
pub const BUILTIN_JOB_TEXT: u16 = 744;
/// zshrs-only. Emitted right before the dispatch of a simple command whose
/// first word was an alias: stack `[alias_name, body_word_count, command_name]`, argc 3. Sets
/// the ALIAS_ORIGIN carrier that `call_function` takes for `intercept ALIAS`.
pub const BUILTIN_ALIAS_ORIGIN: u16 = 790;
/// c:Src/exec.c:3755-3757 `globlist(args, 0)` over the WHOLE argument list,
/// after prefork has expanded every word (c:3357-3359). Stack: the N
/// expanded word values in source order, then two Int bitmasks: bit i of the
/// first marks word i as an assembled value to glob like BUILTIN_GLOB_EXPAND,
/// bit i of the second marks it as a BUILTIN_EXPAND_TEXT mode-10 result that
/// still carries its glob tokens; argc = N + 2 (N <= 63). Globs the
/// eligible words in order and stops at the first error (c:Src/subst.c:494
/// `for (…; !errflag && node; …)`), leaving later words as they are. Pushes
/// one value per word (an Array where a glob expanded).
pub const BUILTIN_GLOBLIST: u16 = 688;
/// c:Src/subst.c:142-147 — `if (!(node = stringsubst(…))) return;`: prefork
/// stops at a NULL paramsubst (a failed `(e)` re-lex), and c:118-121 stops it
/// before the next word once errflag is set. No args; pushes
/// Bool(PREFORK_CUT || errflag & ERRFLAG_ERROR) without clearing either. The compiler checks it after each
/// expansion segment of a word (true: keep the prefix assembled so far, plus
/// a literal `"` for an opening DQ, and skip the word's remaining segments,
/// c:1878) and after each word (true: push the later words as their
/// unexpanded source text).
pub const BUILTIN_PREFORK_CUT_CHECK: u16 = 689;
/// EXTEND step of typeset paren-init packing. Pops `argc` values:
/// [base, e1, …, eN] — base is either the opener (`name=(` /
/// `name+=(`) or a previous EXTEND result. Pushes base with
/// `\u{1f}` + element appended per element. Array values SPLICE
/// their items as separate elements (`typeset b=( x $arr )` splat);
/// an empty Array contributes nothing (unquoted-empty elision).
/// CallBuiltin's argc is u8, so the compiler emits one EXTEND per
/// ≤200-element chunk — p10k's 408-element `__p9k_colors=( … )`
/// overflowed a single-shot pack (argc wrapped mod 256 and the
/// stack spilled into the arg list: "not an identifier: 173…").
/// BUILTIN_TYPESET_PAREN_CLOSE appends the final `\u{1f})`,
/// yielding the exact REJOIN_SEP-delimited one-arg form
/// bin_typeset's single-arg splitter consumes (builtin.rs ~4891,
/// empties preserved, leading/trailing sentinel-empties trimmed
/// once). One arg in → one arg out: bin_typeset's multi-arg rejoin
/// (paren-depth scan, unsafe on EXPANDED paren-literal elements
/// like p10k's `')' ''`) never runs.
pub const BUILTIN_TYPESET_PAREN_PACK: u16 = 630;
/// CLOSE step — pops the EXTEND chain's result, pushes it with
/// `\u{1f})` appended. See BUILTIN_TYPESET_PAREN_PACK.
pub const BUILTIN_TYPESET_PAREN_CLOSE: u16 = 631;
/// Shared body of BUILTIN_GLOB_EXPAND / BUILTIN_REDIR_GLOB_EXPAND.
/// c:Src/glob.c:1872 — `zglob` runs per-word in the argv pipeline.
/// When the upstream EXPAND_TEXT returned an array (e.g. `${a:e}`
/// splat → ["txt","md"]), glob each element separately, not a
/// sepjoin'd scalar. `skip_glob` short-circuits to a literal
/// pass-through (noglob, or a redirect target under
/// `unsetopt multios`).
fn glob_expand_word_value(raw: Value, skip_glob: bool) -> Value {
let patterns: Vec<String> = match raw {
Value::Array(items) => items.iter().map(|v| v.to_str()).collect(),
other => vec![other.to_str()],
};
// c:Src/glob.c:1230 — zglob returns before globbing when
// `unset(EXECOPT)`, so NO_EXEC never reports a NOMATCH.
if skip_glob || !crate::ported::zsh_h::isset(crate::ported::zsh_h::EXECOPT) {
return if patterns.is_empty() {
Value::array(Vec::new())
} else if patterns.len() == 1 {
Value::str(patterns.into_iter().next().unwrap())
} else {
Value::array(patterns.into_iter().map(Value::str).collect())
};
}
let mut out: Vec<String> = Vec::with_capacity(patterns.len());
for pattern in &patterns {
// c:Src/subst.c — filename generation runs `filesub` (tilde/`=`
// expansion) BEFORE globbing. A `~`/`=` reaching this word-glob op
// comes from `${~spec}` / GLOB_SUBST marking a substituted VALUE:
// literal and quoted `~` words are filesub'd (or skip glob) upstream
// and never arrive here. filesubstr matches the Tilde TOKEN, so
// shtokenize first (raw `~`->Tilde; already-Tilde `${~a[@]}` results
// pass through), run filesub, then untokenize surviving glob metas
// for expand_glob. Gated on `~`/`=` (raw or token) so ordinary
// substituted words skip the roundtrip. Fixes `${~x}` x="~/foo".
// c:178 — prefork's second-pass filesub only runs when
// `unset(SHFILEEXPANSION)` (see the GLOB_SUBST arm above).
let filesubbed = if (pattern.contains('~')
|| pattern.contains('=')
|| pattern.contains(crate::ported::zsh_h::Tilde)
|| pattern.contains(crate::ported::zsh_h::Equals))
&& !crate::ported::zsh_h::isset(crate::ported::zsh_h::SHFILEEXPANSION)
{
let mut tok = pattern.clone();
crate::ported::glob::shtokenize(&mut tok);
crate::ported::lex::untokenize(&crate::ported::subst::filesub(&tok, 0))
} else {
pattern.clone()
};
let matches = with_executor(|exec| exec.expand_glob(&filesubbed));
if matches.is_empty() {
// c:1872 nullglob — drop this word, don't emit a hole
continue;
}
for m in matches {
out.push(m);
}
}
if out.is_empty() {
return Value::array(Vec::new());
}
if patterns.len() == 1 && out.len() == 1 && out[0] == patterns[0] {
// No real matches; expand_glob returned the literal. Pass
// back as scalar so downstream ops don't re-flatten.
return Value::str(out.into_iter().next().unwrap());
}
Value::array(out.into_iter().map(Value::str).collect())
}
/// Push a `CmdState` token onto the command-context stack. Direct
/// port of zsh's `cmdpush(int cmdtok)` (Src/prompt.c:1623). The
/// stack is consulted by `%_` in PS4/prompt expansion to produce
/// the cumulative control-flow-context labels (`if`, `then`,
/// `cmdand`, `cmdor`, `cmdsubst`, …) that `zsh -x` xtrace shows
/// in the trace prefix. Compile_zsh emits push/pop pairs around
/// each compound command (if/while/[[…]]/((…))/$(…) etc.).
/// Token is a `CmdState as u8`.
pub const BUILTIN_CMD_PUSH: u16 = 344;
/// Pop the top of the command-context stack. Direct port of zsh's
/// `cmdpop(void)` (Src/prompt.c:1631).
pub const BUILTIN_CMD_POP: u16 = 345;
/// Emit an xtrace line built from the top `argc` values on the VM
/// stack, peeked WITHOUT consuming. Used to trace simple commands
/// AFTER expansion, so `echo for $i` shows as `echo for a` / `echo
/// for b`. Direct port of Src/exec.c:2055-2066.
pub const BUILTIN_XTRACE_ARGS: u16 = 346;
/// Trace one assignment: emits `name=<quoted-value> ` (no newline)
/// to xtrerr if XTRACE is on. Coalesces with subsequent
/// XTRACE_ASSIGN / XTRACE_ARGS calls onto the SAME line via the
/// `XTRACE_DONE_PS4` flag so `a=1 b=2 echo $a $b` produces:
/// `<PS4>a=1 b=2 echo 1 2\n`
/// matching C zsh's `execcmd_exec` body (Src/exec.c:2517-2582):
/// xtr = isset(XTRACE);
/// if (xtr) { printprompt4(); doneps4 = 1; }
/// while (assign) {
/// if (xtr) fprintf(xtrerr, "%s=", name);
/// ... eval value ...
/// if (xtr) { quotedzputs(val, xtrerr); fputc(' ', xtrerr); }
/// }
///
/// Stack contract on entry: [..., name, value]. Both peeked, NOT
/// consumed (the matching SET_VAR call pops them after). argc = 2.
pub const BUILTIN_XTRACE_ASSIGN: u16 = 525;
/// Emit a trailing `\n` + flush iff XTRACE is on AND PS4 was
/// emitted by an earlier XTRACE_ASSIGN this line. Used at the end
/// of compile_simple's assignment-only path so the trace line gets
/// terminated. Mirrors C's exec.c:3397-3399 (the assign-only return
/// path through execcmd_exec which does `fputc('\n', xtrerr);
/// fflush(xtrerr)`).
///
/// Stack: untouched. argc = 0.
pub const BUILTIN_XTRACE_NEWLINE: u16 = 526;
/// Push the live `xtrace` opt-state as `Value::Int(1)` (on) or
/// `Value::Int(0)` (off). Used by `compile_cond` to gate the
/// trace-string-building block on xtrace state at runtime — without
/// this the trace path's `compile_word_str` on each operand re-
/// evaluates side-effectful expressions (`$((i++))`) once for the
/// trace string and once for the actual condition, doubling the
/// effective increment. Bug #159 in docs/BUGS.md.
///
/// Stack: pushes Int(0|1). argc = 0.
pub const BUILTIN_XTRACE_IS_ON: u16 = 611;
/// Reset the `DONETRAP` flag at the start of each top-level statement
/// (sublist boundary). Mirrors C `Src/exec.c:1455` — `donetrap = 0`.
/// Stack: untouched. argc = 0. Bug #303 in docs/BUGS.md.
pub const BUILTIN_DONETRAP_RESET: u16 = 612;
/// c:Src/exec.c:1700-1706 — the `exiting` epilogue of execlist, run at the end
/// of a forked compound command (see compile_zsh `emit_exiting_exit_trap`):
/// `if (exiting && sigtrapped[SIGEXIT]) { errflag = 0; dotrap(SIGEXIT);
/// sigtrapped[SIGEXIT] = 0; errflag = eflag; }`. Stack: pushes Int(0). argc = 0.
pub const BUILTIN_EXITING_EXIT_TRAP: u16 = 729;
/// Head of a pipeline-stage / `&` / coproc chunk: `execcmd_forked_level`.
/// Stack: pops Int(is_subsh), pushes Int(0). argc = 1.
pub const BUILTIN_EXECCMD_FORKED_LEVEL: u16 = 740;
/// Emitted right before the WithRedirectsBegin of the command at the top of
/// a chunk a driver may run in a child forked for it, when that command has
/// redirections. No args. When the chunk's BUILTIN_EXECCMD_FORKED_LEVEL found
/// the fork, the scope it opens saves no fds (c:Src/exec.c:2478
/// `if (!forked && …)`); see redir_scope_forked.
pub const BUILTIN_FORKED_REDIRS: u16 = 745;
/// c:Src/exec.c:1748 — execpline's `child_block();` ahead of a synchronous
/// pipeline, and its job frame (c:1656-1666 `pj = thisjob; thisjob = newjob =
/// initjob()`). Stack: \[depth\], the pipeline's nesting depth in its chunk.
/// Paired with BUILTIN_EXECPLINE_CHILD_UNBLOCK.
pub const BUILTIN_EXECPLINE_CHILD_BLOCK: u16 = 746;
/// c:Src/exec.c:2017 — execpline's `child_unblock();` once the pipeline
/// has run (and been waited for), after the job frame closes (the procs-less
/// job is deleted, `thisjob = pj`). Stack: \[depth\]. Unconditional, as in C: a
/// pipeline nested inside another one's command (a function body, `eval`)
/// leaves SIGCHLD unblocked for the rest of the outer command.
pub const BUILTIN_EXECPLINE_CHILD_UNBLOCK: u16 = 747;
/// Take a copy of stderr for this simple command's xtrace output before
/// its redirections apply (c:Src/exec.c:3765-3773). Released when the
/// redirect scope it precedes ends (c:4445-4452).
///
/// Stack: untouched. argc = 0.
pub const BUILTIN_XTRERR_COPY: u16 = 730;
/// c:Src/exec.c:1417 (`int oldnoerrexit = noerrexit;`) + c:1536-1538
/// (`if (isandor || isnot) noerrexit |= NOERREXIT_EXIT|NOERREXIT_RETURN;`).
/// Saves the current `noerrexit` on a per-thread stack and ORs in the two
/// suppression bits for the duration of one `&&`/`||` chain operand (or a
/// `!`-negated command). Stack: untouched. argc = 0.
pub const BUILTIN_NOERREXIT_SUPPRESS: u16 = 665;
/// c:Src/exec.c:1621 / c:1626 — `noerrexit = oldnoerrexit;`. Pops the
/// matching save pushed by [`BUILTIN_NOERREXIT_SUPPRESS`].
/// Stack: untouched. argc = 0.
pub const BUILTIN_NOERREXIT_RESTORE: u16 = 666;
/// c:Src/loop.c:144 + :201 (execfor), :480 (execwhile), :536 (execrepeat) —
/// `lastval = 1;` on the `errflag` exit from a loop body. Emitted only on the
/// fatal-abort path of a compiled for/while/until/repeat; `execselect` has no
/// such assignment in C and never emits it.
/// Stack: pushes Int(0). argc = 0.
pub const BUILTIN_LOOP_ERRFLAG_STATUS: u16 = 667;
/// `BUILTIN_LOOP_ERRFLAG_BREAK` — the loop's own post-body errflag guard,
/// `c:Src/loop.c:479-482` (execwhile) / `:198-203` (execfor) / `:535-538`
/// (execrepeat) / `:329-330` (execselect). Returns 1 when the loop must
/// BREAK. argc = 0.
///
/// This is NOT the same test as the per-statement prologue. C's list loop
/// (`c:Src/exec.c:1443`, `while (… && !breaks && !retflag && !errflag)`)
/// ENDS the list on errflag; the prologue gate only SKIPS one statement.
/// Outside a loop those are indistinguishable, which is why the gap survived:
/// inside one, every statement is skipped, the loop's own exit test still
/// runs, and a residual `$? == 0` means it NEVER terminates.
pub const BUILTIN_LOOP_ERRFLAG_BREAK: u16 = 671;
// ───────────────────────────────────────────────────────────────────────
// Compiled-arithmetic runtime ops.
//
// `ArithCompiler` lowers `(( … ))` and `$(( … ))` straight to fusevm ops.
// Six operators have no faithful fusevm op, so they lower to these
// instead — one indirect call per OCCURRENCE of the operator, against
// the whole-expression re-lex `BUILTIN_ARITH_EVAL` pays on EVERY
// evaluation.
// ───────────────────────────────────────────────────────────────────────
/// `a / b` — c:Src/math.c:1237-1257. Integer division when both operands
/// are integers (`Op::Div` is unconditionally float), `notzero`'s
/// "division by zero" on an integer zero divisor, and the c:1252
/// `b == -1` special case that avoids the `INT_MIN / -1` trap. argc = 2.
pub const BUILTIN_ARITH_DIV: u16 = 672;
/// `a % b` — c:Src/math.c:1258-1272. Same zero-divisor diagnostic as
/// DIV (`Op::Mod` silently yields 0), `fmod` on floats, and c:1269's
/// `b == -1 → 0`. argc = 2.
pub const BUILTIN_ARITH_MOD: u16 = 673;
/// `a ** b` — c:Src/math.c:1335-1358. Integer power by repeated
/// multiplication when both operands are integers (`Op::Pow` is
/// `powf`, which returns a float and loses precision above 2^53),
/// float promotion on a negative exponent (c:1337-1342), and the
/// c:1352 "imaginary power" error. argc = 2.
pub const BUILTIN_ARITH_POW: u16 = 674;
/// `a && b` in its NON-short-circuiting form — the `&&=` compound
/// assignment (c:Src/math.c:40 DANDEQ), where both sides are already on
/// the stack. Result is integer 1/0, c:1200's `BOOL` type. argc = 2.
pub const BUILTIN_ARITH_LOGAND: u16 = 675;
/// `a || b` for `||=` — c:Src/math.c:41 DOREQ. argc = 2.
pub const BUILTIN_ARITH_LOGOR: u16 = 676;
/// `a ^^ b` — c:Src/math.c:26 DXOR, logical xor. No C equivalent and no
/// fusevm op; both operands always evaluate. argc = 2.
pub const BUILTIN_ARITH_LOGXOR: u16 = 677;
/// Write one arithmetic result back to a parameter — c:Src/math.c:972
/// `setmathvar`, reached from c:1364-1372 when the operator was
/// `OP_E2`/`OP_E2IO`. Pops \[name, value\].
///
/// Distinct from `BUILTIN_SET_VAR`, which stores a shell scalar: only
/// `setmathvar` applies the PM_INTEGER / FORCEFLOAT coercions and the
/// `lastbase` display base that make `typeset -i x; (( x = 3.7 ))`
/// store 3 rather than "3.7". argc = 2.
pub const BUILTIN_SET_MATH_VAR: u16 = 678;
/// Finish a compiled `(( … ))` math command. Pops the numeric result,
/// records it as `lastmathval` (c:Src/math.c:1500, which
/// `callmathfunc`'s MFF_USERFUNC branch returns at c:1115), and sets
/// the command status from it: c:Src/exec.c:5267 `val == 0`, i.e. 0
/// when the expression is non-zero and 1 when it is zero — or 2, with
/// `errflag` cleared, when the expression raised a math error.
///
/// Replaces the `LoadConst("0") / StrEq / …six status ops… /
/// BUILTIN_ARITH_CMD_FINISH` tail the string-evaluator path emits, and
/// keeps the numeric result numeric instead of round-tripping it
/// through its printed form. argc = 1.
pub const BUILTIN_ARITH_CMD_FINISH_VAL: u16 = 679;
/// `lastbase = <n>` for the COMPILED arithmetic path. Pops \[base\], sets the
/// math layer's input base, returns it.
///
/// c:Src/math.c:367 `mathevall` opens every evaluation with `lastbase = -1;`
/// and `lexconstant` (c:462) sets the base of each literal it reads. The
/// interpreted evaluator is that code; the compiled path never enters it, so
/// nothing reset the base between evaluations and `assignsparam`'s
/// `pm.base == 0 ? lastbase` inheritance (c:Src/params.c:2801) handed the next
/// freshly created integer whatever base the LAST evaluation had left behind:
///
/// ```text
/// typeset -i iv="2#101" # sets lastbase = 2, for `iv`
/// (( c += 3 )) # compiled: no literal, no reset
/// print -r -- "$c" # zsh: 3 zshrs: 2#11
/// ```
///
/// Emitted once at the head of every compiled expression with `-1`, and again
/// by [`crate::arith_compiler`] with the base of a `0x`/`0b`/`0o` literal it
/// lexes — which is what `lexconstant` does, at the point the literal is read.
/// argc = 1.
pub const BUILTIN_ARITH_LASTBASE: u16 = 683;
/// The whole quiet-case statement prologue in one call.
///
/// c:Src/exec.c:1451-1502 runs four things before every sublist: the
/// `lineno` write (c:1451), `donetrap = 0` (c:1455), the
/// DEBUG_BEFORE_CMD block (c:1476-1502) and the `noexec` gate (c:1390).
/// In C those are inline field writes and flag tests inside `execlist`;
/// zshrs emitted them as four separate `CallBuiltin`s plus the constant
/// load for `$ZSH_DEBUG_CMD`'s text, on EVERY statement, whether or not
/// a DEBUG trap existed to read any of it.
///
/// This op does the two unconditional writes and then reports whether
/// the other two blocks can be skipped entirely: `Bool(true)` when no
/// DEBUG trap is installed in EITHER registry (`sigtrapped[SIGDEBUG]`
/// or `traps_table["DEBUG"]` — the same pair `BUILTIN_DEBUG_TRAP`
/// consults), `noexec` is unset, and `errflag` is clear. Those are
/// exactly the conditions under which `BUILTIN_DEBUG_TRAP` returns
/// `Int(0)` and `BUILTIN_NOEXEC_CHECK` returns `Int(0)`, so a `true`
/// answer means the skipped ops were provably no-ops. On `false` the
/// compiler's slow path runs both blocks unchanged.
///
/// argc = 1: the line number, or -1 for a construct that records none
/// (c:Src/parse.c:2112's braceless short-function body), which C
/// signals with `code == 0`.
pub const BUILTIN_STMT_PROLOGUE_FAST: u16 = 680;
/// `BUILTIN_WORD_DEFER_EMPTIES` constant — opens a word whose surrounding
/// literals are attached by the compiler's own concat opcodes, not by
/// `paramsubst`.
///
/// c:Src/subst.c:183-186 removes an assembled list node whose text is
/// empty, and `stringsubst` has already glued the word's prefix and
/// suffix onto the array elements by then (c:4386 / c:4414, or every
/// element under plan9 at c:4341). `src/ported/subst.rs`'s port of that
/// removal is correctly ordered when the caller hands it the whole word,
/// but the compiled fast paths hand it only the `${…}` body. This marker
/// tells it so (`PARAMSUBST_AFFIXES_DEFERRED`); the matching end-of-word
/// `BUILTIN_WORD_ELIDE_EMPTY` / `BUILTIN_ARRAY_DROP_EMPTY` then performs
/// the removal on the finished word, which is C's order.
///
/// argc 0 opens the word, argc 1 closes it; the pushed status is popped by
/// the emitter in both halves. Emitted only where a drop will run.
pub const BUILTIN_WORD_DEFER_EMPTIES: u16 = 681;
/// c:`Src/subst.c:3030-3033` + c:3912-3930 for the BARE-name `${=NAME}` /
/// `${==NAME}` / `$=NAME` spelling — everything up to, but not including,
/// c:3932's `sepsplit`, which the compile site emits as `BUILTIN_FORCE_SPLIT`.
///
/// argc is two bits:
/// bit 0 the `spbreak`/`nojoin` pair the spelling sets — set for `${=NAME}`
/// (c:2566-2570 `spbreak = 2; if (nojoin < 2) nojoin = !(ifs && *ifs);`)
/// and clear for `${==NAME}` (c:2561-2565 `spbreak = 0; if (nojoin < 2)
/// nojoin = 0;`).
/// bit 1 `qt` — the word is double-quoted, which c:3033 needs. The runtime
/// `in_dq_context` counter cannot answer it: a whole-word `"${=a}"`
/// compiles to this call with no `BUILTIN_EXPAND_TEXT` wrapper around
/// it, so the counter is 0 there. Same dual check the bare `$NAME`
/// fast path makes (`compile_zsh.rs`, `word_is_single_dq_span`).
///
/// The `ssub` callers do NOT come here: c:4226 joins and stops for them, and
/// the compile site keeps them on `BUILTIN_GET_VAR_DQ`.
pub const BUILTIN_BARE_SPBREAK: u16 = 682;
thread_local! {
/// c:Src/exec.c:1417 — C keeps `oldnoerrexit` as an execlist-local
/// automatic, so the save/restore pairs nest with the C call stack.
/// zshrs's compiler emits the two halves as separate ops, so the saved
/// values need an explicit stack. Thread-local because `noerrexit`
/// itself is per-shell state and worker threads run their own lists.
static NOERREXIT_SAVES: std::cell::RefCell<Vec<i32>> =
const { std::cell::RefCell::new(Vec::new()) };
}
/// `[[ -z X ]]` / `[[ -n X ]]` operand-empty test that honours zsh's
/// array-splice semantics. C zsh evaluates `[[ -z X ]]` per
/// `Src/cond.c:347` (case 'z'): `s` is the SCALAR operand passed
/// through `cond_str`'s singsub. For `"${arr[@]}"` zsh expands per
/// `Src/subst.c:multsub` which yields each element as its own word
/// list node; cond.c then sees the joined-or-single-element form.
///
/// The compile-side `-z` shortcut at `compile_zsh.rs:5371` used
/// `Op::StringLen` which calls `Value::len` — for `Value::Array`
/// that returns ARRAY LENGTH, not string length. `b=("")` produced
/// `Value::Array([""])` → `len = 1` → `-z` returned false.
///
/// This builtin pops one `Value` and pushes `1` (empty) or `0`
/// (non-empty) per the cond context:
/// - `Value::Str(s)` → s.is_empty()
/// - `Value::Array([])` → true (zero words → vacuous-empty)
/// - `Value::Array([s])` → s.is_empty() (single-word case)
/// - `Value::Array([_; n>=2])` → false (multiple non-empty
/// words; zsh would raise "unknown condition" but the
/// observable test result is non-empty/false)
///
/// Companion to BUILTIN_COND_STR_NONEMPTY (#185 in docs/BUGS.md).
pub const BUILTIN_COND_STR_EMPTY: u16 = 613;
/// `[[ -n X ]]` operand-non-empty test (logical complement of
/// BUILTIN_COND_STR_EMPTY).
pub const BUILTIN_COND_STR_NONEMPTY: u16 = 614;
/// `N<<<"str"` / `N<<HERE` — here-string or here-document redirect to
/// an explicit fd. Pops `[content, fd, from_heredoc]` from the stack;
/// creates a temp file, writes the body, reopens read-only, dup2's to
/// `fd`, unlinks the temp path so it disappears on close. Mirrors C
/// `Src/exec.c:4655 getherestr` + `addfd(forked, save, mfds, fn->fd1,
/// fil, 0, NULL)` at c:3766-3780. Bug #205 in docs/BUGS.md.
///
/// `from_heredoc` is C's `REDIRF_FROM_HEREDOC` (set at
/// c:Src/parse.c:2970-2971): 0 appends the trailing newline of
/// c:4671-4672, 1 passes the body through byte-for-byte.
///
/// The fd itself is parked in the enclosing redirect scope via
/// `save_fd_for_scope` unless a bare `exec` is being applied
/// (c:3978-3986 nullexec==1), so `cmd N<<E` is undone at the end of
/// the command while `exec N<<E` persists.
///
/// Stack: pushes `Value::Status(0)` on success, `Status(1)` on
/// failure. argc = 3.
pub const BUILTIN_EXEC_HERESTR_FD: u16 = 615;
/// MULTIOS write/append fan-out for `cmd > a > b` / `cmd > a >> b`
/// style redirects (Bug #36 in docs/BUGS.md). zsh's MULTIOS option
/// (Src/exec.c:2418 `mfds[fd1]` check + addfd splice) creates a
/// pipe at fd1, spawns an internal "tee" process that copies
/// stdin → every collected target file. Without this, only the
/// LAST redirect target survives because each dup2 overwrites the
/// previous binding.
///
/// Stack layout (pushed by compile_zsh's compile_redirs coalescing
/// pass): `[target_1, op_byte_1, target_2, op_byte_2, …, target_N,
/// op_byte_N, fd]`. Pops 2N+1 elements; `argc = 2*N + 1`. A target
/// may be a Value::Array of glob matches (spliced into one member
/// per match, c:Src/glob.c:2195-2203); an op may be DUP_WRITE for a
/// numeric `>&N` member (c:Src/exec.c:3895-3917).
///
/// Runtime (MULTIOS set):
/// 1. Seed the member list with `dup(1)` when this command's
/// stdout is the pipeline output (c:Src/exec.c:3722-3724).
/// 2. Open/dup all targets per their op_byte in redirect order
/// (WRITE truncate + noclobber gate / APPEND / DUP_WRITE live
/// dup); the first member replaces the fd (c:2448-2450).
/// 3. Save `dup(fd)` onto the active redirect_scope_stack so
/// `host_redirect_scope_end` restores the original fd.
/// 4. Create a pipe; spawn a thread that reads from the pipe
/// read-end and writes every chunk to every opened target.
/// 5. dup2 the pipe write-end onto `fd` so the command's writes
/// go through the splitter.
/// 6. Track `(pipe_write_fd, JoinHandle)` so scope-end can close
/// the pipe (draining the thread) and join before restoring.
///
/// MULTIOS unset (c:2418 `unset(MULTIOS)` replace arm): each entry
/// is applied as a plain sequential replace via host_apply_redirect
/// — every file still opened/truncated, last one wins.
pub const BUILTIN_MULTIOS_REDIRECT: u16 = 617;
/// MULTIOS input-side concatenation for `cmd < a < b` shapes
/// (Bug #36 input arm). C zsh's `Src/exec.c:2418` mfds dispatch
/// also covers the read direction — when multiple `<` redirects
/// target the same fd, mfds[fd] grows and addfd splices a
/// concatenating cat into the pipe.
///
/// Stack layout (mirrors the write side): `[source_1, op_1,
/// source_2, op_2, …, source_N, op_N, fd]`. Pops 2N + 1 elements
/// (argc = 2N + 1). op is READ for file sources, DUP_READ for
/// numeric `<&N` members; a source may be a Value::Array of glob
/// matches (spliced, c:Src/glob.c:2195-2203).
///
/// Runtime (MULTIOS set):
/// 1. Open/dup every source in redirect order; first member
/// replaces the fd (c:Src/exec.c:2448-2450).
/// 2. Save `dup(fd)` onto the redirect_scope_stack.
/// 3. Create a pipe; spawn a thread that reads each source in
/// order and writes every chunk to the pipe write-end. Close
/// write-end when done so the consumer sees EOF.
/// 4. dup2 the pipe read-end onto `fd`.
/// 5. Track the JoinHandle so scope-end joins (no fd-close needed
/// here — the producer thread closes its own pipe write-end
/// on exit).
///
/// MULTIOS unset: sequential replace via host_apply_redirect — last
/// source wins (c:2418).
pub const BUILTIN_MULTIOS_READ: u16 = 618;
/// BUILTIN_MULTIOS_READ member op for a here-string body: the runtime writes
/// the body plus a trailing newline to a temp file (c:Src/exec.c:4671-4672,
/// `if (!(fn->flags & REDIRF_FROM_HEREDOC)) t[len++] = '\n';`). fusevm's
/// `redirect_op` values stop at 8.
pub const MULTIOS_OP_HERESTR_BODY: u8 = 9;
/// BUILTIN_MULTIOS_READ member op for a here-document body: written verbatim
/// (REDIRF_FROM_HEREDOC, c:Src/parse.c:2970-2971).
pub const MULTIOS_OP_HEREDOC_BODY: u8 = 10;
/// c:Src/exec.c:4673-4679 getherestr — `gettempfile`, `write_loop`, `close`,
/// reopen read-only, `unlink`: a read descriptor on the body, as
/// BUILTIN_EXEC_HERESTR_FD builds for a single here-string.
fn multios_body_fd(body: &str, append_newline: bool) -> std::io::Result<i32> {
let text = if append_newline { format!("{}\n", body) } else { body.to_string() };
let mut tmpl: Vec<u8> = b"/tmp/zshrs_hs_XXXXXX\0".to_vec();
let write_fd = unsafe { libc::mkstemp(tmpl.as_mut_ptr() as *mut libc::c_char) };
if write_fd < 0 {
return Err(std::io::Error::last_os_error());
}
let bytes = text.as_bytes();
let mut off = 0;
while off < bytes.len() {
let n = unsafe {
libc::write(write_fd, bytes[off..].as_ptr() as *const libc::c_void, bytes.len() - off)
};
if n <= 0 {
let err = std::io::Error::last_os_error();
unsafe {
libc::close(write_fd);
libc::unlink(tmpl.as_ptr() as *const libc::c_char);
}
return Err(err);
}
off += n as usize;
}
unsafe { libc::close(write_fd) }; // c:4676
let read_fd = unsafe { libc::open(tmpl.as_ptr() as *const libc::c_char, libc::O_RDONLY) };
let err = std::io::Error::last_os_error();
unsafe { libc::unlink(tmpl.as_ptr() as *const libc::c_char) }; // c:4678
if read_fd < 0 {
Err(err)
} else {
Ok(read_fd)
}
}
/// c:Src/exec.c:3775-3777 + c:2447-2480 addfd — when `fd` is 0 and the
/// top redirect scope is the pipeline stage command's own list, take the
/// pipeline input as the input multio's first member: returns a private
/// dup of the pipe (above the script's fd range). One-shot per scope. With
/// MULTIOS unset C's addfd replaces the pipe instead (c:2418), so the seed is
/// dropped.
fn take_pipe_input_seed(exec: &ShellExecutor, fd: i32) -> Option<i32> {
if fd != 0
|| PIPE_INPUT_SCOPE.with(|c| c.get()) != Some(exec.redirect_scope_stack.len())
{
return None;
}
PIPE_INPUT_SCOPE.with(|c| c.set(None));
if !opt_state_get("multios").unwrap_or(true) {
return None;
}
let dup = unsafe { libc::dup(0) };
(dup >= 0).then(|| crate::ported::utils::movefd(dup)) // c:2458 `fdN = movefd(fd1)`
}
/// The concatenating half of an input multio (c:Src/exec.c:2447-2480): a
/// pipe onto `fd` fed by a thread that reads every member in order. The
/// members are closed by the thread; the join is tracked on the top multios
/// scope. Returns false when the pipe cannot be created (members closed).
fn multios_read_concat(exec: &mut ShellExecutor, fd: i32, source_fds: Vec<i32>) -> bool {
let (read_end, write_end) = match os_pipe::pipe() {
Ok(p) => p,
Err(_) => {
for f in &source_fds {
unsafe {
libc::close(*f);
}
}
return false;
}
};
// dup the pipe read-end onto fd before spawning the
// producer; close the original read_end so the consumer
// (reading via fd) is the sole reference until scope-end.
let read_dup = unsafe { libc::dup(AsRawFd::as_raw_fd(&read_end)) };
drop(read_end);
if read_dup < 0 {
for f in &source_fds {
unsafe {
libc::close(*f);
}
}
return false;
}
unsafe {
libc::dup2(read_dup, fd);
libc::close(read_dup);
}
// macOS raises a write's SIGPIPE on the process, not the writing
// thread, so the thread mask below does not cover it there; mark the
// write end itself instead.
#[cfg(target_os = "macos")]
unsafe {
// <sys/fcntl.h>: `#define F_SETNOSIGPIPE 73` (absent from the libc crate).
const F_SETNOSIGPIPE: libc::c_int = 73;
libc::fcntl(AsRawFd::as_raw_fd(&write_end), F_SETNOSIGPIPE, 1);
}
// Spawn the producer.
let handle = crate::signal_thread::spawn(move || {
// !!! WARNING: RUST-ONLY !!! C's multio concatenator is a forked
// child (c:Src/exec.c:2472 `zfork`), so a reader that stops early
// (`read x`) SIGPIPEs only that child. This producer is a thread of
// the shell: block SIGPIPE here so the write fails with EPIPE
// instead of killing the shell. A write-raised SIGPIPE is directed at
// the writing thread, so the mask covers it.
unsafe {
let mut set: libc::sigset_t = std::mem::zeroed();
libc::sigemptyset(&mut set);
libc::sigaddset(&mut set, libc::SIGPIPE);
libc::pthread_sigmask(libc::SIG_BLOCK, &set, std::ptr::null_mut());
}
let mut w = write_end;
let mut buf = [0u8; 8192];
for sfd in source_fds {
loop {
let n = unsafe { libc::read(sfd, buf.as_mut_ptr() as *mut libc::c_void, buf.len()) };
if n <= 0 {
break;
}
let n = n as usize;
if std::io::Write::write_all(&mut w, &buf[..n]).is_err() {
break;
}
}
// zclose, not close: movefd marked the member FDT_INTERNAL
// (c:Src/utils.c:2007-2010), and zclose clears that entry.
let _ = crate::ported::utils::zclose(sfd);
}
// Closing w (the write_end) at scope drop signals EOF
// to the consumer.
});
// Track using a closed-write sentinel — the producer
// owns write_end so we just need to join. Use -1 fd
// marker meaning "no fd to close".
if let Some(top) = exec.multios_scope_stack.last_mut() {
top.push((-1, handle));
} else {
let _ = handle.join();
}
true
}
/// One member of an input multio applied as a plain replacement (the
/// NO_MULTIOS and single-member paths): a here-document / here-string body
/// goes through `multios_body_fd` and addfd's save + dup2 (c:2421-2443);
/// every other op keeps `host_apply_redirect`.
fn multios_apply_member(exec: &mut ShellExecutor, fd: i32, op_byte: u8, source: &str) {
if op_byte != MULTIOS_OP_HERESTR_BODY && op_byte != MULTIOS_OP_HEREDOC_BODY {
exec.host_apply_redirect(fd as u8, op_byte, source);
return;
}
exec.save_fd_for_scope(fd);
match multios_body_fd(source, op_byte == MULTIOS_OP_HERESTR_BODY) {
Ok(read_fd) => {
if read_fd != fd {
unsafe {
libc::dup2(read_fd, fd);
libc::close(read_fd);
}
}
}
Err(e) => {
// c:Src/exec.c:3828 — `zwarn("can't create temp file for here document: %e", errno);`
crate::ported::utils::zwarn(&format!(
"can't create temp file for here document: {}",
crate::ported::utils::zsh_errno_msg(e.raw_os_error().unwrap_or(0))
));
exec.redirect_failed = true;
}
}
}
/// Toggle `ShellExecutor::exec_redirs_permanent`. Emitted by
/// compile_zsh's bare-`exec`-with-redirects arm tightly around each
/// `Op::Redirect`: `LoadInt(1); CallBuiltin; …Redirect…; LoadInt(0);
/// CallBuiltin`. While set, `host_apply_redirect` skips pushing the
/// saved fd into the enclosing redirect scope, making the fd change
/// permanent.
///
/// c:Src/exec.c:3978-3986 — nullexec==1 (`exec` carrying only
/// redirections): "If nullexec is 1 we specifically *don't* restore
/// the original fd's before returning" — the per-execcmd `save[]`
/// dups are closed unrestored. An ENCLOSING group's own saves are a
/// different execcmd's `save[]` and still restore (verified:
/// `{ exec 2>/dev/null; } 2>&1; ls /nope` prints the ls error in zsh).
pub const BUILTIN_EXEC_PERM_REDIRS: u16 = 619;
/// Set `ShellExecutor::pipe_output_pending`. Emitted by compile_pipe
/// at the head of a NON-LAST pipeline-stage sub-chunk when that
/// stage's top-level command carries redirects (`Simple` with redirs
/// or `Redirected` compound). The forked stage child runs the chunk
/// with stdout already dup2'd onto the pipe; the first
/// `host_redirect_scope_begin` (the stage command's own redirect
/// list) consumes the flag into `pipe_output_scope`, enabling the
/// MULTIOS stream-split for fd-1 write redirects in that list.
///
/// c:Src/exec.c:3722-3724 — `addfd(forked, save, mfds, 1, output, 1,
/// NULL)` registers the pipe in mfds[1] in the SAME execcmd that
/// walks the stage command's redirect list; mfds is per-execcmd, so
/// nested body commands (`{ echo a > f; } | cat`) never see it.
pub const BUILTIN_PIPE_OUTPUT_MARK: u16 = 620;
/// Install the pipeline stage's parked fds onto 0/1.
///
/// c:Src/exec.c:3720-3724 — `addfd(forked, save, mfds, 0, input, 0,
/// NULL)` / `addfd(..., 1, output, 1, NULL)`. Runs after prefork
/// (c:3304) and globlist (c:3702) have expanded the stage's argument
/// words, which is why a `$(...)` in those words reads the shell's
/// original stdin rather than the pipe. Emitted by
/// `compile_zsh.rs::emit_stage_fds_install`; the fds themselves are
/// parked by `BUILTIN_RUN_PIPELINE`.
pub const BUILTIN_PIPE_FDS_INSTALL: u16 = 642;
/// Magic-equals prefork for a single arg word of a
/// `BINF_MAGICEQUALS` builtin head (`alias`). Direct port of
/// c:Src/exec.c:3298-3304 — `esprefork = PREFORK_TYPESET;
/// prefork(args, esprefork, NULL)` runs on the argv BEFORE the addfd
/// redirect loop at c:3720, so an expansion zerr (`alias bad===` →
/// equalsubstr "= not found" at Src/subst.c:726) prints to the
/// command's UN-redirected stderr. argc=1: pops the just-pushed
/// word value, runs shtokenize → prefork(PREFORK_TYPESET) →
/// untokenize on it (each element for Array splices), pushes the
/// result back. Emitted by compile_simple per arg word when the
/// dispatch head is `alias`; BUILTIN_ALIAS itself no longer
/// preforks (it would double-fire the diagnostic).
pub const BUILTIN_MAGIC_EQUALS_PREFORK: u16 = 621;
/// Bare (unbraced) `$name[idx]` subscript — same dispatch as
/// `BUILTIN_ARRAY_INDEX` while KSHARRAYS is unset, but under
/// KSHARRAYS the unbraced form does NOT subscript (c:Src/subst.c:
/// 2800-2802 + 2867): `$name` expands bare and `[idx]` stays literal
/// trailing text that undergoes filename generation. Operands:
/// [name, idx, suffix, quoted].
pub const BUILTIN_ARRAY_INDEX_UNBRACED: u16 = 622;
/// Assignment-only simple-command exit status. Direct port of
/// `lv = (errflag ? errflag : cmdoutval)` (c:Src/exec.c:1322,
/// execsimple's WC_ASSIGN arm) / `if (errflag) lastval = 1; else
/// lastval = cmdoutval;` (c:Src/exec.c:3393-3396, execcmd_exec's
/// no-command-word varspc path; redir variant at c:3977). Pops
/// [had_cmd_subst]; cmdoutval is the live vm.last_status when a
/// `$()` ran in any RHS of the chain, 0 otherwise. Writes the
/// canonical LASTVAL (C's single `lastval` global) so the
/// non-interactive errflag abort exits with this value per
/// Src/init.c:234. Caller pairs with SetStatus.
pub const BUILTIN_ASSIGN_ONLY_STATUS: u16 = 623;
/// c:Src/exec.c addvars — `if (!pm) { lastval = 1; if (!cmdoutval)
/// cmdoutval = 1; }`. Set by BUILTIN_SET_VAR on assignsparam
/// failure, consumed by BUILTIN_ASSIGN_ONLY_STATUS so the
/// assignment-only command reports status 1. Process-global like
/// C's `cmdoutval` (function bodies may run on a different thread
/// than the opcode that reads the status back).
pub static ASSIGN_FAILED_FLAG: std::sync::atomic::AtomicBool =
std::sync::atomic::AtomicBool::new(false);
/// Precommand walk ahead of the redirections, for a `builtin`/`command`/
/// `exec` head with redirections (c:Src/exec.c:3104-3402 run before c:3720).
/// Operands: [prefix, words…]; returns the words minus the prefix as one
/// array. Pairs with BUILTIN_PRECMD_CHECK_OK.
pub const BUILTIN_PRECMD_CHECK: u16 = 742;
/// Whether the last BUILTIN_PRECMD_CHECK let the command run. argc=0;
/// pushes Bool. Resets the flag to true.
pub const BUILTIN_PRECMD_CHECK_OK: u16 = 743;
thread_local! {
/// BUILTIN_PRECMD_CHECK's verdict, read once by BUILTIN_PRECMD_CHECK_OK
/// (the two ops run back to back on the same VM thread).
static PRECMD_CHECK_PASSED: std::cell::Cell<bool> = const { std::cell::Cell::new(true) };
}
/// The error exits of C's precommand walk (c:Src/exec.c:3104-3402) for
/// `full` = [prefix, words…]; `false` when the walk ended the command.
///
/// * A shell function named like the prefix shadows it (c:3483-3487): the
/// redirections belong to the function call.
/// * c:3250-3290 — `exec`'s option errors: the walk `zerr`s and sets
/// errflag itself.
/// * c:3395-3402 — the walk consumed every word and redirections remain:
/// `zerr("redirection with no command")`.
///
/// `builtin NAME` naming no builtin (c:3490) stays with BUILTIN_BUILTIN: its
/// notion of "a builtin" also covers the zshrs extension and native-command
/// registries, which only that handler consults.
fn precmd_walk_ok(full: &[String]) -> bool {
use std::sync::atomic::Ordering::Relaxed;
let Some(prefix) = full.first() else {
return true;
};
let has_fn = with_executor(|exec| {
exec.functions_compiled.contains_key(prefix.as_str()) || exec.function_exists(prefix)
});
if has_fn {
return true;
}
let before = crate::ported::utils::errflag.load(Relaxed) & crate::ported::zsh_h::ERRFLAG_ERROR;
let walk = crate::ported::exec::execcmd_compile_head(full, crate::ported::zsh_h::WC_SIMPLE);
if before == 0
&& (crate::ported::utils::errflag.load(Relaxed) & crate::ported::zsh_h::ERRFLAG_ERROR) != 0
{
return false; // c:3258/c:3276/c:3285 `zerr(...); … goto done`
}
if walk.is_empty_command && !walk.has_command_vv {
crate::ported::utils::zerr("redirection with no command"); // c:3397
return false;
}
// c:3488-3499 — a word reached through `builtin` is looked up in
// builtintab here, before c:3786 applies the redirections, so
// `builtin nosuch 2>/dev/null` still reports on the original stderr and
// opens nothing.
if walk.precmd_skip > 0
&& crate::lex::untokenize(&walk.preargs[walk.precmd_skip - 1]) == "builtin"
{
let cmdarg = crate::lex::untokenize(&walk.preargs[walk.precmd_skip]);
if !builtin_prefix_finds(&cmdarg) {
// c:3491 — `zwarn("no such builtin: %s", cmdarg);`
crate::ported::utils::zwarn(&format!("no such builtin: {}", cmdarg));
return false; // c:3492 `lastval = 1;` … `return;`
}
}
true
}
/// `redirection with no command` parse-time error for bare
/// `builtin 2>&1` / `command < file` / `exec >&-` precmd-keyword
/// shapes with a redirect but no following command. Direct port
/// of `Src/exec.c:3342 zerr("redirection with no command")`.
/// argc=0; pushes Value::Status(1).
pub const BUILTIN_REDIR_NO_CMD: u16 = 616;
/// GLOB_SUBST guard for `[[ x == $pat ]]` pattern RHS coming from
/// parameter / command substitution. C-zsh's `[[ == ]]` semantics
/// (Src/options.c GLOB_SUBST default OFF + Src/cond.c:552
/// `cond_match` + Src/pattern.c patcompile tokenization-based
/// meta detection) treat chars from substitution as LITERAL
/// unless GLOB_SUBST is on. The Rust patcompile accepts both
/// tokenized and raw-ASCII meta chars, losing the distinction,
/// so `pat="h*"; [[ hello == $pat ]]` matched in zshrs but not
/// in zsh. Bug #116 in docs/BUGS.md.
///
/// Compile-time signal: emitted by `compile_cond_expr` ONLY when
/// the RHS contains `$` or backtick. Runtime checks the live
/// option state. If GLOB_SUBST is OFF, the popped string has
/// its glob metachars escaped with `\` so the downstream StrMatch
/// → patcompile treats them as literals. If GLOB_SUBST is ON,
/// the value passes through unchanged so `setopt glob_subst`
/// restores zsh's pattern-on-expansion behavior.
///
/// Stack: pops one string, pushes the (possibly escaped) result.
/// argc = 1.
pub const BUILTIN_GLOB_SUBST_GUARD: u16 = 528;
/// `${~spec}` / `$~spec` pattern-data guard — the `strcatsub`
/// `if (glbsub) shtokenize(dest)` step (c:Src/subst.c:822/830) applied
/// to a value that is about to become a `[[ … == pat ]]` RHS or a
/// `case` arm pattern.
///
/// `BUILTIN_GLOB_SUBST_GUARD` covers the option-driven leg (GLOB_SUBST
/// off → escape the value's metas). It cannot cover the FLAG leg,
/// because `${~spec}` forces the substitution's metachars ACTIVE and
/// the compiler therefore emits no guard at all — the value reached
/// `patcompile` as raw bytes, which made a DATA backslash
/// indistinguishable from a SOURCE-level quote. c:Src/glob.c:3651
/// leaves a backslash before a non-`ztokens` char in the string as
/// ordinary data (`p='a\ b'; [[ 'a b' == ${~p} ]]` must NOT match,
/// `[[ 'a\ b' == ${~p} ]]` must), so the value has to be respelled in
/// the normalizer's literal-backslash form before it is compiled.
/// docs/BUGS.md #1090, globsubst leg.
///
/// Stack: pops one string, pushes the respelled result. argc = 1.
pub const BUILTIN_PAT_DATA_BACKSLASH: u16 = 668;
/// Stage an ALREADY-EXPANDED here-document body as pending stdin,
/// verbatim — no trailing newline appended.
///
/// c:Src/exec.c:4671-4672 — `getherestr` appends the newline only when
/// the here-string did NOT come from a here-document:
/// if (!(fn->flags & REDIRF_FROM_HEREDOC))
/// t[len++] = '\n';
/// The quoted form already had a non-appending sink (`Op::HereDoc`),
/// but the UNQUOTED form has to run `BUILTIN_EXPAND_TEXT` first, and
/// the only stack-consuming sink available afterwards was
/// `Op::HereString` — which appends unconditionally, because `<<<`
/// genuinely must. The lowering compensated with
/// `trim_end_matches('\n')`, and strip-all-then-append-one is lossy in
/// both directions: it ADDED a newline to a body that ended without one
/// (`cat <<EOF` + `hello` with no final newline printed `hello\n` where
/// zsh prints `hello`), and COLLAPSED N trailing newlines to one
/// (`hello\n\n\n` printed as `hello\n`). argc = 1.
pub const BUILTIN_HEREDOC_BODY_SINK: u16 = 669;
/// `BUILTIN_WORD_ELIDE_EMPTY` — prefork's empty-word removal
/// (c:Src/subst.c:180-187) for a word that is EXACTLY one unquoted
/// `$NAME`. Emitted only by that compile fast path, because C's test is
/// post-assembly and only the word SHAPE makes it decidable early.
/// argc = 1.
pub const BUILTIN_WORD_ELIDE_EMPTY: u16 = 670;
/// Coerce a string parameter value to a math number (Int or Float)
/// for arithmetic-context reads, mirroring C-zsh's `getmathparam`
/// (Src/math.c:337). When the variable holds a string like "hello"
/// that isn't numeric, C falls back to recursively evaluating the
/// raw string as an arith expression; if that fails too, returns 0.
///
/// Used by the ArithCompiler pre-load path so `(( y = x ))` with
/// `x="hello"` reads `x` as integer 0, then assigns y as integer 0
/// — matching zsh's behaviour. The previous Rust port used
/// BUILTIN_GET_VAR which returned the raw string "hello"; the
/// ArithCompiler stored it verbatim in y's slot, and the post-sync
/// BUILTIN_SET_VAR wrote y="hello" as scalar instead of y=0 as
/// integer. Bug #118 in docs/BUGS.md.
///
/// Stack: pops `name` (string), pushes coerced numeric Value.
/// argc = 1.
pub const BUILTIN_GET_MATH_VAR: u16 = 529;
/// GLOB_SUBST runtime gate for words containing parameter / command
/// substitution. C-zsh's `prefork` (Src/subst.c) runs `shtokenize`
/// on the substituted value when `GLOB_SUBST` is set, making the
/// substituted chars eligible for filename generation. With the
/// option off, substituted chars stay literal.
///
/// The Rust port's compile_zsh emits `compile_word_str` for words
/// like `/tmp/X/$pat`, which returns the post-expansion string but
/// never runs glob expansion (no path here triggers
/// BUILTIN_GLOB_EXPAND). Bug #119 in docs/BUGS.md: with `setopt
/// glob_subst`, `for f in /tmp/X/$pat` (pat="*.txt") never matched
/// `*.txt` files.
///
/// This opcode wraps the substitution result and dispatches at
/// runtime: when GLOB_SUBST is OFF, return unchanged; when ON,
/// pass the value through `expand_glob` so glob metas become
/// active. Emitted by `compile_for_words` (and similar sites)
/// after WORD_SPLIT for words with unquoted expansion.
///
/// Stack: pops a Value (Str or Array of Str), pushes the glob-
/// expanded result (still Str or Array depending on input shape).
/// argc = 1.
pub const BUILTIN_GLOB_SUBST_EXPAND: u16 = 530;
/// `BUILTIN_ASSOC_HAS_KEY` constant — `${(k)assoc[name]}` key-existence
/// query. Returns the key text on hit, empty string on miss. Bug #145.
pub const BUILTIN_ASSOC_HAS_KEY: u16 = 531;
/// `BUILTIN_ARRAY_DROP_EMPTY` constant — filter empty elements from
/// an Array on the stack. Used by `for x in $@` / `for x in $*`
/// unquoted forms. Bug #166.
pub const BUILTIN_ARRAY_DROP_EMPTY: u16 = 532;
/// `BUILTIN_QUOTED_STAR_ONE_WORD` — normalize the result of a QUOTED
/// `"$*"` / `"${*}"` expansion to EXACTLY ONE word.
///
/// c:Src/subst.c:3032 — the quoted (`qt`) branch of paramsubst ends in
/// `val = sepjoin(aval, sep, 1)`, a plain string join. Joining the
/// EMPTY positional list yields `""`, so `"$*"` with no positionals is
/// one empty word, exactly like `"$empty"` — which is why
/// `set --; printf '%d|%s|%d\n' $# "$*" 7` prints `0||7` in zsh, bash,
/// dash and ksh alike.
///
/// zshrs routes `"$*"` through `BUILTIN_EXPAND_TEXT` mode 1, whose
/// `multsub` returns a ZERO-node list for the empty case (correct for
/// `"$@"`, which really does vanish) and the bridge turns that into
/// `Value::Array(vec![])` — so the word was elided and printf saw one
/// argument fewer. This op restores the join's single-word shape at the
/// one call site that knows the splat was `*` and not `@`.
///
/// Stack: pops the expansion result, pushes `Value::str("")` when it
/// was an empty Array, and the value unchanged otherwise. argc = 1.
pub const BUILTIN_QUOTED_STAR_ONE_WORD: u16 = 663;
/// `BUILTIN_KSH_FUNSUB` — zsh NOFORK command substitution
/// (`Src/subst.c:1904-2100`), which also covers the ksh93 funsub
/// `${ list; }` and mksh valsub `${| list; }`: a command substitution that
/// runs in the CURRENT shell environment rather than a subshell.
///
/// Three forms, selected by the character right after `${`
/// (c:Src/subst.c:1924/1930):
/// * blank → `${ cmd }`, value is the body's STDOUT. c:2026-2029 scopes
/// it under `.zsh.cmdsubst`; c:2035-2044 captures via a temp-file
/// redirect so the body still runs in the current shell.
/// * `|` → `${| cmd }`, value is `$REPLY`, which is LOCAL to the body
/// (c:2018-2024 `createparam("REPLY", PM_LOCAL|PM_UNSET|PM_HIDE)`).
/// * `{VAR}` → `${{VAR} cmd }`, value is `$VAR`, NOT localised, and an
/// array stays an array (c:2082-2083 re-enters the parameter path).
///
/// ksh(1), Command Substitution: "${ command;} … the command is executed
/// in the current shell environment", and the value is the standard output
/// with trailing newlines removed (zsh strips ONE newline unquoted and
/// none quoted — c:1908 `trim = (!EMULATION(EMULATE_ZSH)) ? 2 : !qt`).
/// mksh(1)'s valsub matches zsh's `${| … }` exactly.
///
/// Stack (bottom→top): body, rplyvar, kind, qt — kind 0 = stdout capture,
/// 1 = REPLY form, 2 = named-variable form; qt = 1 when the word was
/// double-quoted. argc = 4. Pushes the resulting string, or an Array when
/// the named variable holds one / when the unquoted result is word-split.
pub const BUILTIN_KSH_FUNSUB: u16 = 664;
/// `BUILTIN_QUOTEDZPUTS` constant — run top-of-stack value through
/// `crate::ported::utils::quotedzputs` and push the quoted result.
/// Used by the cond xtrace path so non-printable bytes (e.g.
/// `$'\C-[OP'` expanded ESC+OP) get re-wrapped in `$'…'` form for
/// the trace prefix line, matching zsh's `Src/exec.c` cond trace
/// which calls `quotedzputs(operand, xtrerr)` on each side. Bug
/// surfaced when `[[ -n $'\C-[OP' ]]` traced as `[[ -n OP ]]`
/// (raw bytes leaked through the terminal) vs zsh's
/// `[[ -n $'\C-[OP' ]]` source-form preservation.
pub const BUILTIN_QUOTEDZPUTS: u16 = 533;
/// `BUILTIN_QUOTE_TOKENIZED_OUTPUT` — port of
/// `crate::ported::exec::quote_tokenized_output` (Src/exec.c:2114)
/// applied to top-of-stack scalar. Used by cond xtrace for the RHS
/// of pattern-context comparisons (`=` / `==` / `!=`) where C zsh
/// emits the SOURCE form: untokenize lexer tokens (Star → `*`,
/// Inpar → `(`, …) and backslash-escape special chars, but
/// preserve literal ASCII unchanged. Distinct from quotedzputs
/// which wraps the whole string in `'…'` / `$'…'` based on
/// non-printability — that's wrong for `[[ x = a* ]]` which must
/// render as `[[ x = a* ]]`, not `'a*'`.
pub const BUILTIN_QUOTE_TOKENIZED_OUTPUT: u16 = 534;
/// Bridge into subst_port::substitute_brace_array for nested forms
/// that need to PRESERVE array shape across the expand_string
/// boundary. Stack: `[content_string]`. Returns Value::Array of the
/// per-element words. Used by the compile path for
/// `${(@)<nested>...##pat}` shapes — the standard substitute_brace
/// returns String which collapses array→scalar; this builtin
/// preserves the multi-word output via paramsubst's third return
/// (`nodes` vec, the C source's `aval` thread).
pub const BUILTIN_BRIDGE_BRACE_ARRAY: u16 = 347;
/// Word-segment concat with FIRST/LAST sticking. Stack: [lhs, rhs].
/// Used for default unquoted splice forms (`${arr[@]}`, `$@`, `$*`)
/// where prefix sticks to first element only and suffix to last only.
///
/// Distribution table:
/// - both scalar: `Value::str(a + b)` (fast path)
/// - lhs scalar, rhs Array(b₀..bₙ): `Value::Array([lhs+b₀, b₁, …, bₙ])`
/// - lhs Array(a₀..aₙ), rhs scalar: `Value::Array([a₀, …, aₙ₋₁, aₙ+rhs])`
/// - both Array: `Value::Array([a₀, …, aₙ₋₁, aₙ+b₀, b₁, …, bₙ])`
/// (last of lhs merges with first of rhs; the rest stay separate)
///
/// This is the default zsh semantics for `print -l X${arr[@]}Y` →
/// "Xa", "b", "cY" — three distinct args, surrounding text only on ends.
pub const BUILTIN_CONCAT_SPLICE: u16 = 319;
/// `${(flags)name}` — zsh parameter expansion flags. Stack: [name, flags].
/// Flags applied left-to-right. Supported subset (high-value, used by zpwr):
///
/// `L` — lowercase the value (scalar; or each element if array)
/// `U` — uppercase
/// `j:sep:` — join array with `sep` (delim is the char after `j`)
/// `s:sep:` — split scalar on `sep` (returns Value::Array)
/// `f` — split on newlines (shorthand for `s.\n.`)
/// `o` — sort array ascending
/// `O` — sort array descending
/// `P` — indirect: read name's value as another var name, return that's value
/// `@` — keep as array (returns Value::Array — useful before `j` etc.)
/// `k` — keys of assoc array
/// `v` — values of assoc array
/// `#` — word count (array length as scalar)
///
/// Flags can stack: `(jL)` joins then lowercases; `(s.,.U)` splits on `,`
/// then uppercases each element. The long-tail flags (`q`, `qq`, `qqq` for
/// quoting, `A` for assoc, `%` for prompt expansion, `e`/`g` for re-eval,
/// `n`/`p` for numeric, `t` for type, etc.) are deferred — they hit the
/// runtime fallback via the catch-all expansion path.
pub const BUILTIN_PARAM_FLAG: u16 = 297;
/// `ShellHost` implementation that delegates to the current `ShellExecutor`
/// via the `with_executor` thread-local.
///
/// Construct fresh on each VM run (it carries no state itself). The VM
/// dispatches host method calls during `vm.run()`, and `with_executor`
/// resolves to the executor pointer set by `ExecutorContext::enter`.
/// fusevm-host implementation tying bytecode ops to the
/// shell executor.
/// zshrs-original — no C counterpart. C zsh has no bytecode VM
/// to host; everything runs through `execlist()`/`execpline()`
/// directly (Src/exec.c lines 1349/1668).
pub struct ZshrsHost;
/// Short label for a sub-chunk, used as a provenance origin. A `Chunk`
/// keeps no original source text (only ops, constants and a source
/// *file* name), so the readable handle is reconstructed from the
/// leading string constants — for `$(date +%s)` that is `date +%s`.
fn prov_chunk_label(sub: &fusevm::Chunk) -> String {
sub.constants
.iter()
.filter_map(|c| match c {
Value::Str(s) if !s.is_empty() => Some(s.as_str()),
_ => None,
})
.take(3)
.collect::<Vec<_>>()
.join(" ")
}
impl fusevm::ShellHost for ZshrsHost {
fn glob(&mut self, pattern: &str, _recursive: bool) -> Vec<String> {
let matches = with_executor(|exec| exec.expand_glob(pattern));
if crate::provenance::active() {
crate::provenance::on_glob(pattern, &matches);
}
matches
}
fn tilde_expand(&mut self, s: &str) -> String {
with_executor(|exec| s.to_string())
}
fn brace_expand(&mut self, s: &str) -> Vec<String> {
// Direct call to the canonical brace expander
// (Src/glob.c::xpandbraces port at glob.rs:1678). Was
// routing through singsub which uses PREFORK_SINGLE — that
// flag explicitly suppresses brace expansion in subst.c:166,
// so `print X{1,2,3}Y` returned the literal string.
//
// brace_ccl: respect the BRACE_CCL option which the bracket-
// class form `{a-z}` requires. Pull from executor options.
let brace_ccl = with_executor(|exec| opt_state_get("braceccl").unwrap_or(false));
crate::ported::glob::xpandbraces(s, brace_ccl)
}
fn str_match(&mut self, s: &str, pattern: &str) -> bool {
let pattern: &str = &pattern_filesub(pattern);
if let Some(m) = crate::pattern_data_escape::ksh93_flagged_match(s, pattern) {
return m;
}
// bash `shopt -s nocasematch` — bash(1): "bash matches patterns in a
// case-insensitive fashion when performing matching while executing
// CASE or [[ conditional commands". This host method is the `case`
// arm dispatch, the half BUILTIN_COND_STRMATCH (which already does
// this, ~4.4k lines up) does not cover, so `shopt -s nocasematch;
// case ABC in abc)` wrongly took the `*)` arm. Same treatment: fold
// BOTH sides for the match decision — glob metacharacters are not
// letters, so `*` / `?` / `[…]` structure survives `to_lowercase`.
// No-op unless the bash shopt is active; --zsh unaffected.
let (folded_s, folded_pat);
let (s, pattern): (&str, &str) = if crate::dash_mode::nocasematch() {
folded_s = s.to_lowercase();
folded_pat = pattern.to_lowercase();
(&folded_s, &folded_pat)
} else {
(s, pattern)
};
// Shell glob match — `*`, `?`, `[...]`, alternation. After the
// cond path moved to BUILTIN_COND_STRMATCH, the consumer here
// is the `case` arm dispatch, whose bad-pattern semantics are
// Src/loop.c:663-667: `if (!(pprog = patcompile(pat, ...)))
// zerr("bad pattern: %s", pat);` — errflag set, the arm
// doesn't match, and the script aborts at the next command
// boundary (matching `zsh -fc 'case x in [a-) ...'` printing
// the diagnostic with exit 0 = untouched lastval).
// Same drop-in split as the cond path: a bare POSIX-family drop-in
// reads a source-level `(` by its own rules, not by zsh's parse-time
// tokenization — see `dropin_source_pattern_parens_literal`.
let pat_eff = if crate::pattern_data_escape::dropin_source_pattern_parens_literal() {
crate::pattern_data_escape::escape_shglob_parens(
pattern,
crate::pattern_data_escape::dropin_keeps_ksh_groups(),
)
} else {
pattern.to_string()
};
let mut pat_tok = pat_eff.clone();
crate::ported::glob::tokenize(&mut pat_tok);
if crate::ported::pattern::patcompile(
&pat_tok,
crate::ported::zsh_h::PAT_STATIC as i32,
None,
)
.is_none()
{
crate::ported::utils::zerr(&format!("bad pattern: {}", pattern)); // c:667
return false;
}
glob_match_static(s, &pat_eff)
}
fn expand_param(&mut self, name: &str, _modifier: u8, _args: &[Value]) -> Value {
// Sole funnel: route through `getsparam` matching C zsh's
// `getsparam(name)` → `getvalue` → `getstrvalue` →
// `Param.gsu->getfn` dispatch (Src/params.c:3076 / 2335).
//
// The lookup chain (GSU dispatch + variables + env + array-
// join) lives in `params::getsparam`; subst.rs and this
// bridge both call into it so the logic is in exactly one
// place — mirroring C's "every read goes through getsparam"
// architecture. fuseVM bytecode triggers this bridge when
// the VM hits a PARAM opcode, equivalent to C's wordcode VM
// resolving a parameter read during `exec.c` execution.
//
// Modifier handling: the `_modifier` / `_args` parameters
// are populated by the bytecode compiler but applied by
// separate VM opcodes (LENGTH/STRIP/SUBST/etc.) downstream
// of this fetch — matching C's split between getsparam
// (value fetch) and paramsubst's modifier-walk loop. This
// bridge is the value-fetch step only.
let val_str = crate::ported::params::getsparam(name).unwrap_or_default();
let value = Value::str(val_str);
// Provenance: a read of a tracked parameter hands the
// parameter's chain to the produced value, by `Arc` identity
// for the rest of this chunk and by content for the host
// boundaries downstream that only see `String`.
if crate::provenance::active() {
crate::provenance::on_param_read(name, &value);
}
value
}
fn process_sub_in(&mut self, sub: &fusevm::Chunk) -> String {
// c:Src/exec.c:4999 (`getoutputfile`: `child_block();`) and, for
// `<(cmd)`, the enclosing execpline's c:1748 block that C's
// `getproc` forks inside. The VM opens no execpline span around a
// simple command, so take it here. See ChildBlockSpan.
#[cfg(unix)]
let _child_block = ChildBlockSpan::enter();
// c:Src/exec.c:4906 getoutputfile — `=(cmd)` (marked "equalsubst" by the
// compiler) is the TEMP-FILE flavor: create a real regular file, fork a
// writer whose stdout is the file, WAIT for it (so the file is complete
// and seekable before the consumer runs), and return the file path. It
// is unlinked at job end. This differs from `<(cmd)` below, which is a
// /dev/fd pipe that is never waited on.
if sub.source == "equalsubst" {
let nam = crate::ported::utils::gettempname(None, true)
.unwrap_or_else(|| format!("/tmp/zshrs_eqsub_{}", std::process::id()));
let cpath = match std::ffi::CString::new(nam.as_str()) {
Ok(c) => c,
Err(_) => return String::from("/dev/null"),
};
// c:4945 — O_WRONLY|O_CREAT|O_EXCL|O_NOCTTY, 0600.
let fd = unsafe {
libc::open(
cpath.as_ptr(),
libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL | libc::O_NOCTTY,
0o600,
)
};
if fd < 0 {
return String::from("/dev/null");
}
let sub_for_child = sub.clone();
match unsafe { libc::fork() } {
-1 => {
unsafe { libc::close(fd) };
let _ = fs::remove_file(&nam);
return String::from("/dev/null");
}
0 => {
forked_child_subsh_levels(); // c:Src/exec.c:1221
// c:Src/exec.c:5037 entersubsh → c:1200 `zsh_subshell++`.
// The child _exits, so the guard is never dropped.
std::mem::forget(CmdSubstSubshellBump::enter());
// c:4985 — child: stdout → the temp file, run the body, exit.
// Clear the inherited pending-file list so this child never
// unlinks the PARENT's =() temp files when its own commands
// dispatch (fork copies the list; unlink hits the shared fs).
// c:Src/exec.c:5044 — `execode(prog, 0, 1, "equalsubst")`.
std::mem::forget(crate::ported::exec::EvalContextFrame::push("equalsubst"));
PSUB_PENDING_FILES.with(|v| v.borrow_mut().clear());
unsafe {
libc::dup2(fd, libc::STDOUT_FILENO);
libc::close(fd);
}
let mut vm = fusevm::VM::new(sub_for_child);
register_builtins(&mut vm);
vm.set_shell_host(Box::new(ZshrsHost));
let _ = vm.run();
let _ = std::io::stdout().flush();
unsafe { libc::_exit(0) };
}
child_pid => {
// c:4976-4980 — parent: close the write fd and WAIT so the
// file is fully written before the consumer opens it.
unsafe {
libc::close(fd);
let mut status: libc::c_int = 0;
libc::waitpid(child_pid, &mut status, 0);
}
psub_pending_file_add(&nam); // c:4960
return nam;
}
}
}
// c:Src/exec.c::getproc — `<(cmd)` uses pipe + fork + the
// `/dev/fd/N` filesystem entry (where N is the read end of
// the pipe held open in the parent). Consumer opens
// `/dev/fd/N`, reads the cmd's stdout through the pipe.
// Both macOS and Linux expose `/dev/fd` for held-open file
// descriptors. Previous Rust port captured stdout into
// `/tmp/zshrs_psub_*` tempfiles synchronously — works for
// `diff <(a) <(b)` style readers that scan once but diverges
// from zsh's observable path string and breaks any consumer
// that introspects the path or expects a non-seekable pipe.
let mut fds: [libc::c_int; 2] = [-1, -1];
if unsafe { libc::pipe(fds.as_mut_ptr()) } != 0 {
// Pipe creation failed — fall back to tempfile so we at
// least return SOMETHING.
let fifo_path = format!(
"/tmp/zshrs_psub_fallback_{}_{}",
std::process::id(),
with_executor(|e| {
let n = e.process_sub_counter;
e.process_sub_counter += 1;
n
})
);
let _ = fs::remove_file(&fifo_path);
return fifo_path;
}
let (read_end, write_end) = (fds[0], fds[1]);
let sub_for_child = sub.clone();
match unsafe { libc::fork() } {
-1 => {
unsafe {
libc::close(read_end);
libc::close(write_end);
}
return String::from("/dev/null");
}
0 => {
forked_child_subsh_levels(); // c:Src/exec.c:1221
// c:Src/exec.c:5095 entersubsh → c:1200 `zsh_subshell++`.
std::mem::forget(CmdSubstSubshellBump::enter());
// Child: close read end, dup write end to stdout,
// run the sub-chunk, exit. The exit closes the
// write end automatically, so the parent's reader
// gets EOF when the cmd finishes.
PSUB_PENDING_FILES.with(|v| v.borrow_mut().clear());
unsafe {
libc::close(read_end);
libc::dup2(write_end, libc::STDOUT_FILENO);
libc::close(write_end);
}
// c:Src/exec.c:5101/5150 — `execode(prog, 0, 1, out ?
// "outsubst" : "insubst");`. execode (c:1245-1266) APPENDS its
// context for the duration of the body, so `<(cmd)` — whose child WRITES (out=1) — runs as `…:outsubst`.
// zshrs's ported getproc carries these citations but is NOT the
// live path (established in #1062) — the VM forks here instead,
// so the push belongs in this child. No pop needed: this runs
// INSIDE the forked child and dies with it. Bug #1069 (procsub
// legs).
if let Ok(mut ctx) = crate::ported::exec::zsh_eval_context.lock() {
ctx.push("outsubst".to_string());
let joined = ctx.join(":");
if let Ok(mut tab) = crate::ported::params::paramtab().write() {
if let Some(pm) = tab.get_mut("zsh_eval_context") {
pm.u_arr = Some(ctx.clone());
pm.node.flags &= !(crate::ported::zsh_h::PM_UNSET as i32);
}
if let Some(pm) = tab.get_mut("ZSH_EVAL_CONTEXT") {
pm.u_str = Some(joined);
pm.node.flags &= !(crate::ported::zsh_h::PM_UNSET as i32);
}
}
}
crate::fusevm_disasm::maybe_print_stdout("process_subst_in", &sub_for_child);
let mut vm = fusevm::VM::new(sub_for_child);
register_builtins(&mut vm);
vm.set_shell_host(Box::new(ZshrsHost));
let _ = vm.run();
let _ = std::io::stdout().flush();
unsafe { libc::_exit(0) };
}
child_pid => {
// c:Src/exec.c:5092 `procsubstpid = pid;` — record the
// forked child's PID so `${sysparams[procsubstpid]}`
// returns it (was reading the never-updated atomic, so it
// always came back 0). p10k's gitstatus daemon reads
// `sysparams[procsubstpid]` right after `sysopen <(cmd)`
// to track its worker PID; with 0 the daemon's self-check
// failed and gitstatus fell back to re-downloading
// gitstatusd — surfacing as "no prebuilt gitstatusd".
crate::ported::exec::procsubstpid
.store(child_pid, std::sync::atomic::Ordering::Relaxed);
// Parent: close write end, keep read end open under
// the same fd value so `/dev/fd/N` resolves to the
// pipe's read side. NOTE: FD_CLOEXEC must STAY clear
// — consumers like `cat <(cmd)` and `diff <(a) <(b)`
// discover the fd via exec inheritance, so closing
// on exec defeats the whole point. C zsh's getproc
// (Src/exec.c:5045+) leaves the fd open across exec.
unsafe {
libc::close(write_end);
}
// Park read_end for close-after-consuming-command,
// exactly like process_sub_out does for its write_end
// (c:Src/exec.c addfilelist(NULL, fd) → deletefilelist).
// WITHOUT this the parent's read_end stayed open for
// the whole shell lifetime: p10k's async worker /
// realtime clock do `exec {fd}< <(cmd)` on every prompt,
// so each keystroke/redraw leaked a pipe fd until the
// ~256-fd limit was hit and the shell locked up
// (107 leaked pipes + 107 unreaped children observed).
let depth = PSUB_SCOPE_DEPTH.with(|d| d.get());
PSUB_PENDING_FDS.with(|v| v.borrow_mut().push((depth, read_end)));
// Reap the forked child so it doesn't linger as a
// zombie. `<(cmd)` children are fire-and-forget (their
// output flows through the pipe); C reaps them via the
// job machinery. A non-blocking reap here is scheduled;
// do a best-effort WNOHANG now and the rest drain on
// subsequent proc-subs / prompt cycles.
crate::fusevm_bridge::note_psub_child(child_pid);
}
}
let path = format!("{}/{}", crate::ported::config_h::PATH_DEV_FD, read_end); // c:Src/exec.c:5144
if crate::provenance::active() {
crate::provenance::on_process_subst(&prov_chunk_label(sub), &path);
}
path
}
fn process_sub_out(&mut self, sub: &fusevm::Chunk) -> String {
// c:Src/exec.c:1748 — `getproc` forks inside the enclosing
// execpline's `child_block()` span; the VM has none around a simple
// command, so take it here. See ChildBlockSpan.
#[cfg(unix)]
let _child_block = ChildBlockSpan::enter();
// c:Src/exec.c:5025 getproc, PATH_DEV_FD branch — `>(cmd)`
// (out == 0): `mpipe(pipes)`, fork; the CHILD `redup(pipes[0],
// 0)` (pipe read end onto stdin) and `closem` drops the write
// end; the PARENT closes pipes[0] and hands the consumer
// `/dev/fd/<pipes[1]>` (the write end). The previous Rust port
// used mkfifo + a child that BLOCKED in open(FIFO, O_RDONLY)
// before running cmd — with no writer the child never started,
// never exited, and kept its inherited stdout (e.g. a `$()`
// capture pipe) open forever: `a=$(print -r -- >(true))` hung.
// With the pipe shape the child runs immediately and exits,
// releasing inherited fds exactly like zsh (verified: zsh
// blocks ~2s on `a=$(print -r -- >(sleep 2))`, then EOFs).
let mut fds: [libc::c_int; 2] = [-1, -1];
if unsafe { libc::pipe(fds.as_mut_ptr()) } != 0 {
// Pipe creation failed — fall back to a plain temp file so
// the consumer at least has a writable path.
let fallback = format!(
"/tmp/zshrs_psub_out_{}_{}",
std::process::id(),
with_executor(|e| {
let n = e.process_sub_counter;
e.process_sub_counter += 1;
n
})
);
let _ = fs::write(&fallback, "");
return fallback;
}
let (read_end, write_end) = (fds[0], fds[1]);
let sub_for_child = sub.clone();
match unsafe { libc::fork() } {
-1 => {
unsafe {
libc::close(read_end);
libc::close(write_end);
}
String::from("/dev/null")
}
0 => {
forked_child_subsh_levels(); // c:Src/exec.c:1221
// c:Src/exec.c:5150 entersubsh → c:1200 `zsh_subshell++`.
std::mem::forget(CmdSubstSubshellBump::enter());
// Child: close the write end (c: closem after redup),
// dup the read end onto stdin (c: redup(pipes[0], 0)),
// run the sub-chunk, exit. Other std fds stay
// inherited — zsh's child keeps the surrounding
// command's stdout/stderr.
unsafe {
libc::close(write_end);
libc::dup2(read_end, libc::STDIN_FILENO);
libc::close(read_end);
}
// c:Src/exec.c:5101/5150 — `execode(prog, 0, 1, out ?
// "outsubst" : "insubst");`. execode (c:1245-1266) APPENDS its
// context for the duration of the body, so `>(cmd)` — whose child READS (out=0) — runs as `…:insubst`.
// zshrs's ported getproc carries these citations but is NOT the
// live path (established in #1062) — the VM forks here instead,
// so the push belongs in this child. No pop needed: this runs
// INSIDE the forked child and dies with it. Bug #1069 (procsub
// legs).
if let Ok(mut ctx) = crate::ported::exec::zsh_eval_context.lock() {
ctx.push("insubst".to_string());
let joined = ctx.join(":");
if let Ok(mut tab) = crate::ported::params::paramtab().write() {
if let Some(pm) = tab.get_mut("zsh_eval_context") {
pm.u_arr = Some(ctx.clone());
pm.node.flags &= !(crate::ported::zsh_h::PM_UNSET as i32);
}
if let Some(pm) = tab.get_mut("ZSH_EVAL_CONTEXT") {
pm.u_str = Some(joined);
pm.node.flags &= !(crate::ported::zsh_h::PM_UNSET as i32);
}
}
}
crate::fusevm_disasm::maybe_print_stdout("process_subst_out:child", &sub_for_child);
let mut vm = fusevm::VM::new(sub_for_child);
register_builtins(&mut vm);
vm.set_shell_host(Box::new(ZshrsHost));
let _ = vm.run();
unsafe { libc::_exit(0) };
}
child_pid => {
// c:Src/exec.c:5143 `procsubstpid = pid;` — same fix as
// the `<(cmd)` in-path above: record the forked child's
// PID for `${sysparams[procsubstpid]}` (was always 0).
crate::ported::exec::procsubstpid
.store(child_pid, std::sync::atomic::Ordering::Relaxed);
// Parent: close the read end, keep the write end open
// under its fd value so `/dev/fd/N` resolves to the
// pipe's write side. FD_CLOEXEC must STAY clear —
// consumers (`tee >(cmd)`) discover the fd via exec
// inheritance, matching process_sub_in above and C's
// fdtable[fd] = FDT_PROC_SUBST bookkeeping. Park the
// fd for close-after-consuming-command (c: addfilelist
// (NULL, fd) → deletefilelist) so the child's reader
// EOFs — without this `tee >(wc -c) </dev/null` left
// wc blocked until shell exit.
unsafe {
libc::close(read_end);
}
let depth = PSUB_SCOPE_DEPTH.with(|d| d.get());
PSUB_PENDING_FDS.with(|v| v.borrow_mut().push((depth, write_end)));
let path = format!("{}/{}", crate::ported::config_h::PATH_DEV_FD, write_end); // c:Src/exec.c:5144
if crate::provenance::active() {
crate::provenance::on_process_subst(&prov_chunk_label(sub), &path);
}
path
}
}
}
fn subshell_begin(&mut self) {
with_executor(|exec| {
// Special parameters whose value lives in a process GLOBAL behind a
// GSU (`Src/params.c`'s `ifs`, `wordchars`, `home`, `histsiz`, …)
// rather than in the param table. Mirrors the getfn dispatch list at
// params.rs:12548. C isolates these for free by forking `(...)`;
// zshrs's in-process subshell has to snapshot them by hand, or a
// subshell-local `IFS=,` rewrites the parent's word-splitting.
const SUBSHELL_SPECIAL_GLOBALS: &[&str] = &[
"IFS",
"HOME",
"TERM",
"USERNAME",
"WORDCHARS",
"TERMINFO",
"TERMINFO_DIRS",
"KEYBOARD_HACK",
"histchars",
"HISTSIZE",
"SAVEHIST",
];
// An UNSET special yields None and is skipped: the paramtab snapshot
// restores its PM_UNSET flag, and the getfn dispatch refuses to read
// the (stale) global while PM_UNSET is set (params.rs:12552).
let special_globals_snap: Vec<(String, String)> = SUBSHELL_SPECIAL_GLOBALS
.iter()
.filter_map(|n| crate::ported::params::getsparam(n).map(|v| ((*n).to_string(), v)))
.collect();
// Snapshot paramtab + hashed-storage too (step 1 of the
// store unification mirrors writes there; restoring only
// the HashMaps leaks subshell-scoped writes to the parent
// via paramtab readers like `paramsubst → vars_get`).
let paramtab_snap = crate::ported::params::paramtab()
.read()
.ok()
.map(|t| t.clone())
// c:Src/params.c:854 — a fresh table is 151 buckets, not
// the 17-bucket `Default`.
.unwrap_or_else(|| crate::ported::hashtable::hashtable_nodes::newhashtable(151));
let paramtab_hashed_snap = crate::ported::params::paramtab_hashed_storage()
.lock()
.ok()
.map(|m| m.clone())
.unwrap_or_default();
let loop_flags_snap = {
use std::sync::atomic::Ordering::SeqCst;
(
crate::ported::builtin::LOOPS.load(SeqCst),
crate::ported::builtin::BREAKS.load(SeqCst),
crate::ported::builtin::CONTFLAG.load(SeqCst),
)
};
exec.subshell_snapshots.push(SubshellSnapshot {
comp_globals: crate::vm_helper::CompGlobalsSnap::save(),
// c:Src/utils.c:2111 `addlockfd` — the fds carrying
// `zsystem flock` locks. Recorded so subshell_end can close
// the ones the subshell itself opened (C's fork does it for
// free). See SubshellSnapshot::flock_fds.
flock_fds: current_flock_fds(),
loop_flags: loop_flags_snap,
cmdoutval: crate::ported::exec::cmdoutval.load(std::sync::atomic::Ordering::Relaxed),
stopmsg: crate::ported::builtin::STOPMSG.load(std::sync::atomic::Ordering::Relaxed),
paramtab: paramtab_snap,
paramtab_hashed_storage: paramtab_hashed_snap,
special_globals: special_globals_snap,
positional_params: exec.pparams(),
// Snapshot canonical `traps_table` — bin_trap writes
// there (`Src/builtin.c`).
traps: crate::ported::builtin::traps_table()
.lock()
.map(|t| t.clone())
.unwrap_or_default(),
// Snapshot option store so `(set -e)` /
// `(setopt extendedglob)` don't leak to parent.
opts: crate::ported::options::opt_state_snapshot(),
// c:Src/exec.c:2880 — fork() copies the alias tables to
// the subshell. `(alias x=y)` inside the subshell dies
// with the child; the parent doesn't see x. Bug #209.
tables: crate::ported::exec::SubshForkCopy::save(),
// c:Src/exec.c::entersubsh — same fork-copy
// semantics for shfunctab. `(f() { ... })` defined
// inside the subshell dies with the child; parent's
// `type f` reports "not found". Bug #208 in
// docs/BUGS.md.
shfuncs: crate::ported::hashtable::shfunctab_lock()
.read()
.ok()
.map(|t| t.snapshot())
.unwrap_or_default(),
functions_compiled: exec.functions_compiled.clone(),
function_source: exec.function_source.clone(),
// c:Src/exec.c::entersubsh — fork-copy semantics for
// THINGYTAB (ZLE widget registry). A subshell `zle -N`
// / `zle -D` mutation dies with the child in C zsh;
// mirror via in-process snapshot. Bug #453.
thingytab: crate::ported::zle::zle_thingy::thingytab()
.lock()
.ok()
.map(|t| t.clone())
.unwrap_or_default(),
// c:Src/exec.c::entersubsh — same fork-copy for the
// KEYMAPNAMTAB (named keymap registry). `bindkey -N km`
// / `bindkey -D km` inside a subshell dies with the
// child. Bug #454.
keymapnamtab: crate::ported::zle::zle_keymap::keymapnamtab()
.lock()
.ok()
.map(|t| t.clone())
.unwrap_or_default(),
// c:Src/exec.c::entersubsh fork semantics — `$!`
// (clone::lastpid) set by a `&` INSIDE the subshell
// dies with the child: `( : & ); echo $!` -> 0.
lastpid: crate::ported::modules::clone::lastpid
.load(std::sync::atomic::Ordering::Relaxed),
// c:Src/exec.c::entersubsh fork semantics — the
// subshell gets a COPY of the job table; its disown/
// wait/`&` mutations die with it. Bug #462.
jobtab: crate::ported::jobs::JOBTAB
.get_or_init(|| std::sync::Mutex::new(Vec::new()))
.lock()
.map(|t| t.clone())
.unwrap_or_default(),
curjob: *crate::ported::jobs::CURJOB
.get_or_init(|| std::sync::Mutex::new(-1))
.lock()
.unwrap(),
prevjob: *crate::ported::jobs::PREVJOB
.get_or_init(|| std::sync::Mutex::new(-1))
.lock()
.unwrap(),
maxjob: *crate::ported::jobs::MAXJOB
.get_or_init(|| std::sync::Mutex::new(0))
.lock()
.unwrap(),
thisjob: *crate::ported::jobs::THISJOB
.get_or_init(|| std::sync::Mutex::new(-1))
.lock()
.unwrap(),
oldjobtab: crate::ported::jobs::OLDJOBTAB
.get_or_init(|| std::sync::Mutex::new(Vec::new()))
.lock()
.map(|t| t.clone())
.unwrap_or_default(),
oldmaxjob: *crate::ported::jobs::OLDMAXJOB
.get_or_init(|| std::sync::Mutex::new(0))
.lock()
.unwrap(),
// c:Src/exec.c:2880 — fork copies the fd table; the
// child's `exec >file` / `exec N<&-` die with it.
fd_frame: crate::ported::exec::SubshFdFrame::enter(),
redir_depth: exec.redirect_scope_stack.len(),
slots_mark: crate::exec_jobs::execpline_slots_mark(),
// c:Src/signals.c:39 `sigtrapped` — saved so End restores the
// parent's per-signal trap flags (see the field docs).
sigtrapped: crate::ported::signals::sigtrapped
.lock()
.map(|g| g.clone())
.unwrap_or_default(),
// c:Src/exec.c:160 `int subsh;` — saved so End can put the
// parent's value back (subshells nest).
subsh: crate::ported::exec::subsh.load(std::sync::atomic::Ordering::Relaxed),
// The parent's libc locale — see SubshellSnapshot::locale.
locale: crate::vm_helper::subsh_locale_save(),
});
// c:Src/exec.c:1192-1193 — `if (!(flags & ESUB_FAKE)) subsh = 1;`
// A `( … )` is a real subshell, so the body runs with subsh set.
// The forked child carries it in C; the in-process body needs it
// set explicitly or per-command checks that read it — notably
// PRINT_EXIT_VALUE (c:4309 `&& !subsh`) — behave as if the
// command ran in the parent.
crate::ported::exec::subsh.store(1, std::sync::atomic::Ordering::Relaxed);
// C forks for `(...)` — count the fork-equivalent so
// `time (builtin)` reports like zsh (see FORK_EVENTS).
crate::vm_helper::FORK_EVENTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
// c:Src/exec.c:1088-1092 — entersubsh resets traps in the child:
// if (!(flags & ESUB_KEEPTRAP))
// for (sig = 0; sig <= SIGCOUNT; sig++)
// if (!(sigtrapped[sig] & ZSIG_FUNC) &&
// !(isset(POSIXTRAPS) && (sigtrapped[sig] & ZSIG_IGNORED)))
// unsettrap(sig);
//
// A subshell does NOT inherit string-form traps. Two exemptions:
// FUNCTION-form traps (`TRAPUSR1() { … }`, ZSIG_FUNC) survive, and
// under POSIX_TRAPS an IGNORED trap (`trap '' SIG`) survives.
//
// The ZSIG_FUNC exemption is structural here rather than a flag
// test: zshrs keeps string-form bodies in traps_table and
// function-form ones in shfunctab as TRAPxxx, so filtering only
// traps_table leaves the function form untouched by construction.
// ZSIG_IGNORED is `trap '' SIG`, which stores an empty body.
//
// The LOOP BOUND is also part of the spec, not an implementation
// detail: `sig <= SIGCOUNT` never reaches the PSEUDO-signals,
// which zsh numbers above the real ones —
// #define SIGZERR (SIGCOUNT+1)
// #define SIGDEBUG (SIGCOUNT+2) (c:Src/signals.h:34-35)
// so ERR/ZERR and DEBUG traps SURVIVE a subshell, while SIGEXIT
// (sig 0) is inside the loop and is cleared. Verified against the
// oracle: `trap 'print e' ERR; (trap)` lists the ERR trap;
// `trap 'print u' USR1; (trap)` lists nothing.
//
// Without this a subshell kept the parent's traps: `(trap)` listed
// them where zsh lists nothing, and — the part that isn't
// cosmetic — an inherited trap FIRED inside the child, so
// `trap 'print p' USR1; (kill -USR1 $$; print after)` printed
// p before after instead of after…p (the signal is meant to reach
// the parent, whose trap runs there).
//
// The snapshot pushed above restores the parent's table at
// subshell_end, which is what makes clearing safe for zshrs's
// in-process subshell.
{
// Record the PARENT's `sigtrapped[]` BEFORE the reset below
// wipes it. C gets it from the fork: the child mutates a
// private copy (`Src/signals.c:39`) and the parent's stays
// put. (`limits[]` travels in SubshForkCopy.)
subshell_signal_enter();
entersubsh_reset_traps();
}
// c:Src/exec.c:2862 — subshell fork flags carry ESUB_PGRP,
// so entersubsh runs `clearjobtab(monitor)` (c:1219): the
// child gets an EMPTY job table plus the procless control
// job grabbed at Src/jobs.c:1828 (`thisjob = initjob()`).
// That's why zsh's `(jobs)` prints nothing and `(kill %1)`
// hits the empty control job instead of the parent's job 1.
// The snapshot pushed above restores the parent's table at
// subshell_end. Bug #462.
let monitor = crate::ported::zsh_h::isset(crate::ported::zsh_h::MONITOR) as i32;
crate::ported::jobs::clearjobtab(&mut exec.jobs, monitor);
// c:Src/exec.c:1133 + c:1245-1246 — `job_control_ok = monitor &&
// (flags & ESUB_JOB_CONTROL) && isset(POSIXJOBS)`, and a
// non-async `( … )` carries ESUB_JOB_CONTROL (c:2919-2920);
// `if (!job_control_ok) opts[MONITOR] = 0;`. With MONITOR off
// `jobs` lists the parent's oldjobtab and fg/bg refuse with
// "no job control in this shell". The option snapshot above
// restores it at subshell_end.
if !(monitor != 0 && crate::ported::zsh_h::isset(crate::ported::zsh_h::POSIXJOBS)) {
crate::ported::options::dosetopt(crate::ported::zsh_h::MONITOR, 0, 0);
}
// clearjobtab left THISJOB on the control job (Src/jobs.c:
// 1828). In C the very next pipeline's execpline reassigns
// thisjob (Src/exec.c:1700 `thisjob = newjob = initjob()`),
// so by the time any builtin runs, thisjob never aliases
// the control job. zshrs has no per-pipeline job slot —
// model the between-pipelines state (-1) so getjob's
// `jobnum != thisjob` (c:jobs.c:2107) doesn't reject %1 and
// setcurjob doesn't demote an inherited curjob that
// collides with the control slot.
*crate::ported::jobs::THISJOB
.get_or_init(|| std::sync::Mutex::new(-1))
.lock()
.unwrap() = -1;
// Subshell starts with EXIT trap cleared so the parent's
// EXIT handler doesn't fire when the subshell ends. zsh:
// each subshell has its own trap context. Other signals
// are inherited (well, parent's are still in place — but
// a trap set INSIDE the subshell shouldn't leak out).
if let Ok(mut t) = crate::ported::builtin::traps_table().lock() {
t.remove("EXIT");
}
let level = exec
.scalar("ZSH_SUBSHELL")
.and_then(|s| s.parse::<i32>().ok())
.unwrap_or(0);
// c:Src/exec.c — ZSH_SUBSHELL carries PM_READONLY (declared
// in params.rs special_params); setsparam would be rejected
// by assignstrvalue's PM_READONLY guard. Write u_val
// directly — same bypass pattern as BUILTIN_SET_LINENO at
// line 2784. C zsh's PM_SPECIAL GSU vtable handles this
// implicitly via the setfn callback.
let new_level = (level + 1) as i64;
if let Ok(mut tab) = crate::ported::params::paramtab().write() {
if let Some(pm) = tab.get_mut("ZSH_SUBSHELL") {
pm.u_val = new_level;
pm.u_str = Some(new_level.to_string());
pm.node.flags &= !(crate::ported::zsh_h::PM_UNSET as i32);
}
}
});
// Bump SUBSHELL_DEPTH so zexit defers process::exit (see
// SUBSHELL_DEPTH declaration in src/ported/builtin.rs for
// rationale).
crate::ported::builtin::SUBSHELL_DEPTH.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
// c:Src/exec.c::entersubsh — C zsh's subshell is a forked
// child process: signals sent to the parent (via `kill $$`
// inside the subshell, where `$$` is the parent's pid)
// never reach the child's signal handlers. zshrs's
// in-process subshell shares the process pid with the
// parent, so without queueing the subshell's trap handler
// fires for signals that zsh would deliver only to the
// parent. Queue signals across the subshell body so the
// parent's restored trap table sees them after
// subshell_end's unqueue drain. Bug #450.
crate::ported::signals_h::queue_signals();
}
fn subshell_end(&mut self) -> Option<i32> {
// Fire subshell's EXIT trap BEFORE restoring parent state so
// the trap body sees the subshell's vars and exit status. zsh
// forks for `(...)` so the trap runs in the child process,
// before exit. We mirror by running it here, just before the
// pop+restore. REMOVE the trap before firing so the inner
// execute_script doesn't fire it again at its own end.
let exit_trap_body = crate::ported::builtin::traps_table()
.lock()
.ok()
.and_then(|mut t| t.remove("EXIT"));
if let Some(body) = exit_trap_body {
// Execute the trap body. Errors during trap execution
// don't bubble — zsh ignores trap-body errors.
with_executor(|exec| {
let _ = exec.execute_string_without_exit_hooks(&body);
});
}
with_executor(|exec| {
// c:Src/exec.c::entersubsh — the subshell is a forked child, so a
// NOMATCH failure raised inside it (c:Src/glob.c:1877) lives and
// dies with that process. The per-command glob-failed cell is the
// in-process stand-in for that failure, and a body like `( y* )`
// ends before any command boundary consumes it: the parent's NEXT
// command then read it and returned 1 without running
// (`( y* ); print a` lost `print a`, `( y* ) || print x` lost
// the or-branch).
exec.current_command_glob_failed.set(false);
if let Some(snap) = exec.subshell_snapshots.pop() {
// c:Src/exec.c:1123 entersubsh — the forked child owns its fds, so
// redirections a body error left open (`WithRedirectsEnd` skipped)
// go with it: `(print ${a[]} 2>&1); print -u2 err` keeps fd 2.
exec.unwind_redirect_scopes_to(snap.redir_depth);
crate::exec_jobs::execpline_slots_forget_to(snap.slots_mark);
// c:Src/exec.c::entersubsh fork semantics — `loops` /
// `breaks` / `contflag` are process globals the child
// owns a private copy of, so `(break)` inside a loop
// cannot end the PARENT's loop. See
// SubshellSnapshot::loop_flags.
{
use std::sync::atomic::Ordering::SeqCst;
let (loops, breaks, contflag) = snap.loop_flags;
crate::ported::builtin::LOOPS.store(loops, SeqCst);
crate::ported::builtin::BREAKS.store(breaks, SeqCst);
crate::ported::builtin::CONTFLAG.store(contflag, SeqCst);
}
// c:Src/exec.c:225 `cmdoutval` — the child's copy dies with
// it. See SubshellSnapshot::cmdoutval.
crate::ported::exec::cmdoutval.store(snap.cmdoutval, std::sync::atomic::Ordering::Relaxed);
// See SubshellSnapshot::stopmsg.
crate::ported::builtin::STOPMSG.store(snap.stopmsg, std::sync::atomic::Ordering::Relaxed);
// c:Src/utils.c:2155-2164 `zcloselockfd` — release the
// `zsystem flock` locks the subshell itself took. Under C
// the forked child's fds close on exit; here we close the
// fds that appeared while the subshell was running.
// See SubshellSnapshot::flock_fds.
for fd in current_flock_fds() {
if !snap.flock_fds.contains(&fd) {
crate::ported::utils::zcloselockfd(fd);
}
}
// c:Src/exec.c:160 / :1192-1193 — the child's `subsh = 1`
// dies with the fork in C; restore the parent's value here.
crate::ported::exec::subsh.store(snap.subsh, std::sync::atomic::Ordering::Relaxed);
// c:Src/signals.c:39 — same fork-copy reasoning for the
// per-signal trap flags cleared at subshell entry.
//
// The `sigaction` DISPOSITIONS the body installed leak
// out too, and the flag restore alone does not undo
// them: `( trap 'echo IN' USR1 )` runs `settrap` →
// `install_handler` (c:Src/signals.c:730) on the shared
// process, so afterwards a `kill -USR1 $$` in the parent
// hit zshrs's handler, found no trap, and was swallowed
// where zsh — whose parent still had SIG_DFL, the child
// having installed the handler on its own copy — dies.
// Roll the dispositions back for exactly the signals
// whose flags differ.
let child_sigtrapped = match crate::ported::signals::sigtrapped.lock() {
Ok(mut st) => {
let prev = st.clone();
*st = snap.sigtrapped.clone();
prev
}
Err(_) => Vec::new(),
};
subshell_restore_signal_dispositions(&snap.sigtrapped, &child_sigtrapped);
// c:Src/exec.c:2880 — alias, hash-table, `environ`, cwd,
// umask, rlimit, zstyle, module, sched … writes in a
// subshell die with the forked child: the parent never sees
// `(alias x=y)` (Bug #209 in docs/BUGS.md), `(export y=sub)`
// or `(zmodload zsh/X)` (Bug #210). See SubshForkCopy.
// BEFORE the paramtab restore below: rolling a module back
// looks its parameters up in the LIVE paramtab.
snap.tables.restore();
// Restore paramtab + hashed storage so subshell-scoped
// writes via setsparam/setaparam/sethparam don't leak
// to the parent via paramtab readers.
if let Some(tab) = crate::ported::params::paramtab()
.write()
.ok()
.as_deref_mut()
{
*tab = snap.paramtab;
}
snap.comp_globals.restore();
// Restore the global-backed specials (see
// SubshellSnapshot::special_globals). MUST run after the
// paramtab restore above: setsparam writes through the GSU setfn
// to BOTH the process global and the param node, so the paramtab
// overwrite would otherwise clobber the node half of it.
// Restore parent's option store so `(set -e)` /
// `(setopt extendedglob)` don't leak. zsh forks
// subshells so child option changes die with the
// child; we run in-process and must restore. This runs
// BEFORE the special-global replay below: that replay is
// assignsparam, which honours options the body set.
crate::ported::options::opt_state_restore(snap.opts);
for (name, val) in &snap.special_globals {
crate::ported::params::setsparam(name, val);
}
// The body's `setlocale` (c:Src/params.c:4811 setlang,
// c:4877 lcsetfn) changed only the forked child in C.
crate::vm_helper::subsh_locale_restore(snap.locale.as_deref());
// c:Src/exec.c::entersubsh fork semantics — restore
// the parent's `$!`; a background job inside `(...)`
// dies with the child in C zsh.
crate::ported::modules::clone::lastpid
.store(snap.lastpid, std::sync::atomic::Ordering::Relaxed);
// c:Src/exec.c::entersubsh fork semantics — restore the
// parent's job table + curjob/prevjob/maxjob/thisjob.
// The subshell mutated only its own copy. Bug #462.
if let Ok(mut t) = crate::ported::jobs::JOBTAB
.get_or_init(|| std::sync::Mutex::new(Vec::new()))
.lock()
{
*t = snap.jobtab;
}
*crate::ported::jobs::CURJOB
.get_or_init(|| std::sync::Mutex::new(-1))
.lock()
.unwrap() = snap.curjob;
*crate::ported::jobs::PREVJOB
.get_or_init(|| std::sync::Mutex::new(-1))
.lock()
.unwrap() = snap.prevjob;
*crate::ported::jobs::MAXJOB
.get_or_init(|| std::sync::Mutex::new(0))
.lock()
.unwrap() = snap.maxjob;
*crate::ported::jobs::THISJOB
.get_or_init(|| std::sync::Mutex::new(-1))
.lock()
.unwrap() = snap.thisjob;
// c:Src/jobs.c:101/104 — the subshell's oldjobtab died with
// the child in C; put the parent's back.
*crate::ported::jobs::OLDJOBTAB
.get_or_init(|| std::sync::Mutex::new(Vec::new()))
.lock()
.unwrap() = snap.oldjobtab;
*crate::ported::jobs::OLDMAXJOB
.get_or_init(|| std::sync::Mutex::new(0))
.lock()
.unwrap() = snap.oldmaxjob;
if let Some(m) = crate::ported::params::paramtab_hashed_storage()
.lock()
.ok()
.as_deref_mut()
{
*m = snap.paramtab_hashed_storage;
}
exec.set_pparams(snap.positional_params);
// Restore parent's traps (the subshell's own traps die
// with it). zsh: `(trap "X" USR1)` doesn't leak the
// USR1 trap out of the subshell. Write back to the
// canonical `traps_table` (bin_trap writes there).
if let Ok(mut t) = crate::ported::builtin::traps_table().lock() {
*t = snap.traps;
}
// (The parent's option store was put back above, before
// the special-global replay.)
// c:Src/exec.c::entersubsh — same fork-copy
// semantics for shfunctab. Restore parent's function
// table from snapshot so `(f() { ... })` definitions
// inside the subshell don't leak to the parent.
// Bug #208 in docs/BUGS.md.
if let Ok(mut tab) = crate::ported::hashtable::shfunctab_lock().write() {
tab.restore(snap.shfuncs);
}
// Restore the runtime dispatch tables (compiled chunks
// + source). Without these, a subshell-defined
// override leaves its bytecode in place even after
// shfunctab is restored — `g` after the subshell would
// still run the override.
exec.functions_compiled = snap.functions_compiled;
exec.function_source = snap.function_source;
// c:Src/exec.c::entersubsh — restore parent's THINGYTAB
// so a subshell's `zle -N w f` / `zle -D w` doesn't
// affect the parent's widget registry. Bug #453.
if let Ok(mut t) = crate::ported::zle::zle_thingy::thingytab().lock() {
*t = snap.thingytab;
}
// Same for KEYMAPNAMTAB. Bug #454.
if let Ok(mut t) = crate::ported::zle::zle_keymap::keymapnamtab().lock() {
*t = snap.keymapnamtab;
}
// c:Src/exec.c:2880 — a bare `exec >file` / `exec N>&-`
// inside `(...)` died with the C child; put the parent's
// descriptors back (see SubshFdFrame).
drop(snap.fd_frame);
}
});
// Decrement SUBSHELL_DEPTH. If a deferred subshell exit
// landed inside (EXIT_PENDING set with depth > 0), promote
// the deferred status into the subshell's exit status now
// that we're at the boundary, then clear so the parent
// continues. Matches C zsh's "subshell-exit-via-fork"
// boundary where the child's process::exit(N) becomes
// $WAITSTATUS / $? in the parent.
crate::ported::builtin::SUBSHELL_DEPTH.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
// c:Src/exec.c — drain the signal queue against the now-
// restored parent trap table. Pairs with the
// queue_signals() call at the end of subshell_begin.
// Any `kill $$` from inside the subshell is processed
// here against OUTER's trap, matching C zsh's
// signal-delivery-to-parent semantics. Bug #450.
crate::ported::signals_h::unqueue_signals();
// Replay the signals that arrived while the body ran and that
// the PARENT traps, now that the parent's `sigtrapped[]` and
// `traps_table` are back. See `subshell_defer_signal`.
subshell_signal_leave();
// c:Src/exec.c — a `( … )` subshell is a FORK in C: an errflag
// abort inside the child ends the child with its lastval as
// the exit status, and the flag dies with the child process.
// The parent's $? picks up the status and the parent's lists
// keep running. zsh 5.9: `(readonly r=1; r=2); echo "after
// $?"` prints `after 1`. zshrs runs the subshell in-process,
// so mirror the fork isolation by clearing ERRFLAG_ERROR at
// the subshell boundary — exec.last_status() already carries
// the child's lastval (synced by ERREXIT_CHECK trigger 4).
//
// ERRFLAG_HARD must die at this boundary too: `${u:?msg}` sets
// errflag |= ERRFLAG_HARD (c:Src/subst.c:3344) and then, in a
// C forked subshell, `_exit(1)` (c:3353) — the parent never
// sees ANY errflag bit. A leaked HARD bit here made every
// subsequent zerr() take the silent arm (c:Src/utils.c:175-177
// `if (errflag || noerrs) { errflag |= ERRFLAG_ERROR; return; }`),
// so the next eval/source's parse silently "failed" and the
// D04 harness shell wedged after chunk 10's
// `(print ${unset1:?exiting1})`.
//
// !!! DASH-FAMILY GATE — see dash_mode::fatal_error_status !!!
// dash's `sh_error()` unwinds via `exraise(EXERROR)`, which sets
// `exitstatus = 2` before `exitshell()`; the `( … )` boundary IS
// one of the two places that unwind lands, so the subshell reports
// 2 rather than zsh's `lastval == ERRFLAG_ERROR == 1`. Read the
// flag BEFORE the clear below; the status is published at the
// deferred-`exit` arm uses (run_chunk otherwise restores
// `vm.last_status` over any write made here).
let dash_fatal_status = {
let ef = crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed);
let fatal = crate::ported::zsh_h::ERRFLAG_ERROR | crate::ported::zsh_h::ERRFLAG_HARD;
if ef & fatal != 0 {
crate::extensions::dash_mode::fatal_error_status()
} else {
None
}
};
crate::ported::utils::errflag.fetch_and(
!(crate::ported::zsh_h::ERRFLAG_ERROR | crate::ported::zsh_h::ERRFLAG_HARD),
std::sync::atomic::Ordering::Relaxed,
);
// c:Src/builtin.c:5834 / Src/exec.c:1443 — `retflag` dies at the
// fork boundary for the same reason `errflag` above does. In C a
// `return` inside `( … )` sets retflag in the CHILD; the child's
// execlist unwinds, the child _exit()s, and the PARENT's retflag
// was never touched. zshrs runs subshells in-process, so the flag
// survived and returned from the enclosing FUNCTION:
// f() { ( return 1 ); print IN }; f
// printed nothing where zsh prints `IN`. Storing 0 is exactly a
// restore-to-entry: a non-zero retflag unwinds its list
// immediately (c:1443's `!retflag` gate), so the parent can never
// be sitting at a subshell with the flag already set. Twin of the
// save/restore `$( … )` already does in vm_helper.rs (the
// `saved_retflag` pair around the cmd-subst sub-VM), and of the
// loops/breaks/contflag restore in SubshellSnapshot::loop_flags.
crate::ported::builtin::RETFLAG.store(0, std::sync::atomic::Ordering::Relaxed);
let exit_pending =
crate::ported::builtin::EXIT_PENDING.load(std::sync::atomic::Ordering::Relaxed);
if exit_pending != 0 {
// c:Src/builtin.c — `exit N` masks N to 8 bits because
// POSIX _exit takes the low byte as status. `(exit 256)`
// and `(exit 0)` are indistinguishable to the parent;
// `(exit 257)` exits with 1. Without the mask zshrs's
// in-process subshell propagated the full i32 (256) into
// the parent's $?, diverging from zsh.
let raw = crate::ported::builtin::EXIT_VAL.load(std::sync::atomic::Ordering::Relaxed);
// dash's `exraise(EXERROR)` assigns `exitstatus = 2` at the
// RAISE, so a fatal error wins over whatever deferred-exit
// value the unwind happened to carry. Only an errflag-driven
// unwind reaches this — a real `(exit 5)` never sets the flag,
// so `(exit 5)` still reports 5.
let val = dash_fatal_status.unwrap_or(raw & 0xFF);
with_executor(|exec| exec.set_last_status(val));
crate::ported::builtin::EXIT_PENDING.store(0, std::sync::atomic::Ordering::Relaxed);
crate::ported::builtin::RETFLAG.store(0, std::sync::atomic::Ordering::Relaxed);
crate::ported::builtin::BREAKS.store(0, std::sync::atomic::Ordering::Relaxed);
// Return the deferred-exit status so the VM updates its
// own `last_status`. Otherwise run_chunk's post-script
// `set_last_status(vm.last_status)` would clobber LASTVAL
// back to the stale pre-subshell value.
return Some(val);
}
// Same publication path for a fatal error that did NOT arm a
// deferred exit (e.g. the failed-assignment unwind).
if let Some(st) = dash_fatal_status {
with_executor(|exec| exec.set_last_status(st));
return Some(st);
}
None
}
fn redirect(&mut self, fd: u8, op: u8, target: &str) {
// Apply a redirection at the OS level for the next command/builtin.
// The host tracks saved fds in a per-executor stack so a future
// `with_redirects_end` can restore. For now, this is a thin wrapper
// that performs the dup2; pairing with explicit save/restore is
// delivered by `with_redirects_begin/end`.
with_executor(|exec| exec.host_apply_redirect(fd, op, target));
}
fn with_redirects_begin(&mut self, count: u8) {
with_executor(|exec| exec.host_redirect_scope_begin(count));
}
fn regex_match(&mut self, s: &str, regex: &str) -> bool {
// c:Src/Modules/regex.c:54 `zcond_regex_match` — POSIX ERE
// matching + populate `$MATCH` / `$MBEGIN` / `$MEND` /
// `$match[]` / `$mbegin[]` / `$mend[]` (or `$BASH_REMATCH`
// under BASHREMATCH). Direct delegation to the canonical
// port at src/ported/modules/regex.rs:58.
//
// The bridge passthru path delivers TOKEN-form bytes here
// (Inbrack \u{e191}, Outbrack \u{e192}, Star \u{e187}, Quest
// \u{e186}, etc.) since the lexer tokenizes regex meta chars
// inside `[[ ]]`. The host regex engine expects ASCII, so
// untokenize the pattern (and subject, for safety) once at
// this boundary. zsh C reaches its POSIX-ERE engine through
// the same untokenize path inside zcond_regex_match.
let s_clean = crate::lex::untokenize(s);
let regex_clean = crate::lex::untokenize(regex);
// c:Src/cond.c:113-119 — WHICH engine `=~` uses is an option:
//
// char *modname = isset(REMATCHPCRE) ? "zsh/pcre" : "zsh/regex";
//
// and the two speak different languages (POSIX ERE vs PCRE), so the
// option decides whether `\d` is a digit class or a literal `d`, and
// whether `(?<name>…)` compiles at all. This dispatch was missing:
// `=~` always used the regex module, so `setopt rematchpcre` silently
// did nothing.
if crate::ported::zsh_h::isset(crate::ported::zsh_h::REMATCHPCRE) {
// c:115 — "zsh/pcre" → the `-pcre-match` cond.
crate::ported::modules::pcre::cond_pcre_match(
&[s_clean, regex_clean],
crate::ported::modules::pcre::CPCRE_PLAIN,
) != 0
} else {
// c:115 — "zsh/regex" → the `-regex-match` cond.
crate::ported::modules::regex::zcond_regex_match(
&[s_clean.as_str(), regex_clean.as_str()],
crate::ported::modules::regex::ZREGEX_EXTENDED,
) != 0
}
}
fn with_redirects_end(&mut self) {
with_executor(|exec| exec.host_redirect_scope_end());
// c:Src/exec.c:5172 — if any redirect in this scope failed
// (noclobber-blocked, ENOENT for read, etc.), the command's
// exit status is forced to 1 regardless of what the (still-
// executed) command's own exit was. C zsh prevents the
// command from running at all when a redirect fails; the
// Rust port still runs it (sinking output to /dev/null in
// the noclobber arm at host_apply_redirect:5481) and then
// overrides $? here. Same observable effect for the common
// pattern `echo x > existing-file` under noclobber.
let failed = with_executor(|exec| {
let f = exec.redirect_failed;
exec.redirect_failed = false;
f
});
if failed {
// !!! DASH-FAMILY GATE (dash_mode::fatal_error_status) !!! dash's
// redirection failure is `sh_error` too, so it reports 2, not 1.
let st = crate::extensions::dash_mode::fatal_error_status().unwrap_or(1);
with_executor(|exec| exec.set_last_status(st));
}
}
fn heredoc(&mut self, content: &str) {
// C `Src/exec.c:4641` — `parsestr(&buf)` runs parameter +
// command substitution on the heredoc body. The lexer's
// quoted-delimiter detection (`<<'EOF'`) routes through the
// `Op::HereDoc` path in `compile_zsh.rs` which short-circuits
// before reaching here; unquoted forms route through the
// BUILTIN_EXPAND_TEXT mode-4 emit path that calls singsub.
// This handler covers the verbatim/quoted case.
if crate::provenance::active() {
crate::provenance::on_heredoc("heredoc", content);
}
with_executor(|exec| exec.host_set_pending_stdin(content.to_string()));
}
fn herestring(&mut self, content: &str) {
// Shell semantics: herestring appends a newline. `<<<` body
// substitution (`Src/exec.c:4655 getherestr` calls
// `quotesubst` + `untokenize`) lands here verbatim; the
// upstream compiler routes through `Op::HereString` after
// BUILTIN_EXPAND_TEXT for the substitution pass, so callers
// of `host.herestring` see the already-expanded form.
let mut s = content.to_string();
s.push('\n');
if crate::provenance::active() {
crate::provenance::on_heredoc("herestring", &s);
}
with_executor(|exec| exec.host_set_pending_stdin(s));
}
fn exec(&mut self, args: Vec<String>) -> i32 {
// c:Src/exec.c getproc + Src/jobs.c deletefilelist — close
// any `>(cmd)` write ends owned by this command once it
// finishes (drops on every return path below).
let _psub_fds = PsubFdGuard;
// c:Src/subst.c paramsubst — when `${var:?msg}` or `${var?msg}`
// triggered the "parameter null or not set" error, errflag
// is raised and zsh aborts the simple command without
// attempting exec. The expansion may have produced empty
// argv[0] which falls into the c:?/permission-denied path
// below, masking the real diagnostic with a spurious
// "permission denied:" line and rc=126 instead of rc=1.
// Honour errflag here so the script ends with the
// paramsubst error as the sole diagnostic. Bug #86.
//
// c:Src/exec.c — C's execlist loop clears ERRFLAG_ERROR
// between sublists when the error came from a NOMATCH-style
// command failure (glob no-match, etc.) so subsequent
// sublists run. zshrs's vm dispatch handles this at the
// post-command-boundary HERE: if THIS command has its
// `current_command_glob_failed` cell set (meaning the glob
// NOMATCH happened during this command's argv prep), surface
// status 1 and clear BOTH the cell AND ERRFLAG_ERROR so the
// NEXT exec call sees a clean state. The errflag from
// genuine script-fatal errors (parse, redirect, paramsubst
// `${:?msg}`) does NOT come paired with glob_failed, so
// those still short-circuit + propagate.
if let Some(status) = external_glob_failure_status() {
return status;
}
if (crate::ported::utils::errflag.load(std::sync::atomic::Ordering::SeqCst)
& crate::ported::zsh_h::ERRFLAG_ERROR)
!= 0
{
// c:Src/exec.c:3636-3637 — `if (errflag) { lastval = 1; … return; }`
// after prefork. The abort that follows exits with LASTVAL, so
// store it: `/bin/echo $((1/0))` exited with the previous status.
crate::ported::builtin::LASTVAL.store(1, std::sync::atomic::Ordering::Relaxed);
return 1;
}
// c:Src/exec.c — two distinct empty-command cases:
//
// 1. args=[""] — an explicit empty-string command word
// (`""`, `"\$unset"`, `\$'\$x'`). zsh attempts exec(2)
// on the empty path → EACCES → "permission denied", \$?
// = 126.
//
// 2. args=[] — the WORD LIST is empty (unquoted \$(\$cmd)
// that produced empty, or an unquoted unset \$var that
// elided). zsh: no exec is attempted; \$? becomes the
// last cmd-subst's exit status (the inner sub-VM
// already set last_status), and the line completes
// silently. Critically NOT 126.
if args.is_empty() {
// c:Src/exec.c — empty word list passes through to a
// no-op; preserve whatever the inner cmd-subst's exit
// is. Return last_status so the caller's SetStatus
// round-trips correctly.
return with_executor(|exec| exec.last_status());
}
if args[0].is_empty() {
let script_name =
crate::ported::utils::scriptname_get().unwrap_or_else(|| "zshrs".to_string());
let lineno: u64 = with_executor(|exec| {
exec.scalar("LINENO")
.and_then(|s| s.parse::<u64>().ok())
.unwrap_or(1)
});
eprintln!("{}:{}: permission denied: ", script_name, lineno);
return 126;
}
// c:Src/exec.c — when any redirect in the current scope
// failed (e.g. noclobber blocked a `>` overwrite), zsh
// refuses to execute the command and exits with status 1.
// The Rust port still applied the command (writing to the
// /dev/null sink installed by host_apply_redirect's
// noclobber arm), but the success status overwrote the
// intended `1`. Short-circuit here so the exec returns 1
// without running the body.
let redir_failed = with_executor(|exec| {
let f = exec.redirect_failed;
exec.redirect_failed = false;
f
});
if redir_failed {
return 1;
}
// c:Src/exec.c:3545-3547 — `setunderscore(lastnode(args))` for the
// command about to run. Write the canonical `zunderscore` global,
// NOT the paramtab node: `_`'s setfn is `nullstrsetfn`
// (c:Src/params.c:252-253), so a table write has no counterpart in
// C and clobbers the PM_UNSET bit that `unset _` relies on.
if let Some(last) = args.last() {
crate::ported::params::set_zunderscore(std::slice::from_ref(last)); // c:3546
}
// Provenance: record which argv slot each tracked value landed
// in, before the command consumes it.
if crate::provenance::active() {
crate::provenance::on_exec("exec", &args);
}
// Route external command spawning through `executor.execute_external`
// so intercepts (AOP before/after/around), command_hash lookups,
// pre/postexec hooks, and zsh-specific fork-then-exec all apply.
// Without this override, fusevm's default `host.exec` calls
// `Command::new` directly, bypassing zshrs's dispatch logic.
let status = with_executor(|exec| exec.host_exec_external(&args));
// c:Src/jobs.c:1748 waitonejob (no-procs else-branch). zshrs's
// exec model routes external commands through host_exec_external
// (which already waitpid'd in-line); the canonical waitonejob
// expects a Job to derive lastval, but here we already know
// it. A job index of -1 (no job-table entry) takes waitonejob's
// no-procs branch, which fires the `pipestats[0]=lastval;
// numpipestats=1;` update via the canonical port.
crate::ported::builtin::LASTVAL.store(status, std::sync::atomic::Ordering::Relaxed);
crate::ported::jobs::waitonejob(-1);
status
}
fn cmd_subst(&mut self, sub: &fusevm::Chunk) -> String {
// Run the sub-chunk on a nested VM with the same host wired up,
// capturing stdout. The current executor remains active via the
// thread-local — the nested VM uses CallBuiltin to dispatch shell
// ops back through `with_executor`.
// c:Src/exec.c:4800 getoutput — `mpipe(pipes)`: both ends are moved
// out of the script's fd range (c:Src/utils.c:2210 mpipe → movefd),
// so a closed stdout cannot hand the pipe fd 1 itself.
let (read_end, write_end) = match os_pipe::pipe() {
Ok(p) => p,
Err(_) => return String::new(),
};
let read_end = unsafe {
<os_pipe::PipeReader as std::os::fd::FromRawFd>::from_raw_fd(crate::lowfd::movefd_past_script(
std::os::fd::IntoRawFd::into_raw_fd(read_end),
))
};
// A closed fd 1 is saved as -1 and restored by closing it again
// (c:Src/utils.c:2047-2048 redup: `if (x < 0) zclose(y)`). Bailing out
// here skipped the body entirely: `{ x=$(print b >&2) } >&-` lost `b`.
// The saves exist only because the body runs in process (C's forked
// child saves nothing): keep them past the script's `{var}` range.
let saved_stdout = unsafe {
libc::fcntl(libc::STDOUT_FILENO, libc::F_DUPFD_CLOEXEC, crate::lowfd::EXTENSION_FD_FLOOR)
};
let saved_stderr = unsafe {
libc::fcntl(libc::STDERR_FILENO, libc::F_DUPFD_CLOEXEC, crate::lowfd::EXTENSION_FD_FLOOR)
};
// A job the body forks must not keep them: they belong to the
// parent C never forked the body from (see mark_saved_fd).
mark_saved_fd(saved_stdout);
mark_saved_fd(saved_stderr);
let write_fd = AsRawFd::as_raw_fd(&write_end);
unsafe {
libc::dup2(write_fd, libc::STDOUT_FILENO); // c:4840 redup(pipes[1], 1)
}
drop(write_end);
// c:Bug #56 — publish the saved outer fds so a trap firing
// during the nested VM run can route its body output to the
// PARENT's stdout instead of the cmdsub's pipe-bound fd 1.
// zsh's forked cmdsub gets this for free (trap runs in the
// parent process whose fd 1 is untouched). zshrs's
// in-process cmdsub needs this thread-local stack so the
// trap dispatcher can find the right destination fd.
CMDSUBST_OUTER_FDS.with(|s| s.borrow_mut().push((saved_stdout, saved_stderr)));
// Nested scope for `>(cmd)` fd ownership — commands inside
// the cmdsub must not drain the enclosing command's pending
// psub fds (see PSUB_SCOPE_DEPTH).
let _psub_scope = PsubScope::enter();
// c:Src/exec.c:1161 — forked cmdsub child runs entersubsh()
// which does `zsh_subshell++`; in-process equivalent.
let _subshell_bump = CmdSubstSubshellBump::enter();
let _bash_errexit = crate::dash_mode::BashCmdsubstErrexit::enter();
crate::fusevm_disasm::maybe_print_stdout("host.cmd_subst", sub);
let mut vm = fusevm::VM::new(sub.clone());
register_builtins(&mut vm);
vm.set_shell_host(Box::new(ZshrsHost));
let _ = vm.run();
let cmd_status = vm.last_status;
CMDSUBST_OUTER_FDS.with(|s| {
s.borrow_mut().pop();
});
unsafe {
libc::dup2(saved_stdout, libc::STDOUT_FILENO);
}
crate::ported::utils::zclose(saved_stdout);
if saved_stderr >= 0 {
crate::ported::utils::zclose(saved_stderr);
}
// Inner cmd's status not propagated for the same reason as
// run_command_substitution — see GAPS.md.
let _ = cmd_status;
let mut buf = String::new();
let mut reader = read_end;
let _ = reader.read_to_string(&mut buf);
// Strip trailing newlines (POSIX command substitution semantics)
while buf.ends_with('\n') {
buf.pop();
}
// Provenance: a command substitution is a lineage ORIGIN — the
// bytes did not exist in the shell before this ran.
if crate::provenance::active() {
crate::provenance::on_cmd_subst(&prov_chunk_label(sub), &buf);
}
buf
}
fn call_function(&mut self, name: &str, args: Vec<String>) -> Option<i32> {
// An alias is gone from the text by now; the compiler left its name behind.
if let Some(status) = intercept_alias_origin(name, &args) {
return Some(status);
}
// AOP intercepts (zshrs extension, no C counterpart). An external is
// intercepted where it spawns; every other command word lands here, so
// a shell function, a ported builtin or a host-registered native command
// (the fat binary's `git`) gets its advice from this one gate.
if let Some(status) = intercept_in_process_command(name, &args) {
return Some(status);
}
// c:Src/exec.c — when the command word is empty (e.g. `""`
// or `"$nonexistent"`), zsh attempts the exec(2) which
// returns EACCES ("permission denied") and exits 126. The
// Rust port silently treated empty as a no-op (status 0).
// Match zsh by emitting the diagnostic and returning 126.
if name.is_empty() {
let script_name =
crate::ported::utils::scriptname_get().unwrap_or_else(|| "zshrs".to_string());
let lineno: u64 = with_executor(|exec| {
exec.scalar("LINENO")
.and_then(|s| s.parse::<u64>().ok())
.unwrap_or(1)
});
eprintln!("{}:{}: permission denied: ", script_name, lineno);
with_executor(|exec| exec.set_last_status(126));
return Some(126);
}
// c:Src/exec.c — redirect failure in this scope means the
// command should NOT run. The Host::exec path already has
// this gate (at fn exec above); call_function takes external
// commands like `cat <&3` through a different code path, so
// gate here too. Without this, bad-fd redirects produced
// the diagnostic but the external command still ran, so $?
// came out from the command's natural exit instead of the
// forced 1.
let redir_failed = with_executor(|exec| {
let f = exec.redirect_failed;
exec.redirect_failed = false;
f
});
// c:Src/exec.c:4147-4154 — a failed prefix assignment skips the
// command with `lastval = 1` in the same way. For an external the
// assignments run in the forked child (c:4343-4350 `addvars(…); if
// (errflag) _exit(1);`), so the shell again only sees status 1:
// x=${bad?err} /bin/echo ran; print rc=$? zsh: rc=1
// while a shell function runs them in the shell, whose errflag ends
// the list.
let prefix_failed = PREFIX_ASSIGN_FAILED.with(|c| c.replace(false));
if redir_failed || prefix_failed {
// c:Src/exec.c:3719 forks an external command (execcmd_fork)
// BEFORE the redirection loop at c:3785, so a redirection that
// `zerr`s (`<&""` → "file number expected", c:Src/glob.c:2192)
// raises errflag in the CHILD, which `_exit(1)`s; the parent only
// sees status 1 and runs the next command:
// /bin/cat <&""; print after $? zsh: after 1
// zshrs applies redirections in the shell before choosing what
// runs, so the errflag landed in the shell and ended the script.
// For a name that resolves to neither a function nor a zsh
// builtin, take the error back out of the shell's errflag. A
// zshrs extension builtin counts as external here: zsh has no
// such builtin, so the same name reaches execcmd_fork there
// (an in-process stand-in for `env`, `cat`, … must fail like the
// command it stands in for: `env <&""; print after` continues).
let is_external = !with_executor(|exec| exec.function_exists(name))
&& !crate::ported::builtin::createbuiltintable().contains_key(name);
if is_external {
// A `${name?msg}` in the prefix assignments also sets
// ERRFLAG_HARD; the forked child took both bits with it.
let bits = if prefix_failed {
crate::ported::zsh_h::ERRFLAG_ERROR | crate::ported::zsh_h::ERRFLAG_HARD
} else {
crate::ported::zsh_h::ERRFLAG_ERROR
};
crate::ported::utils::errflag.fetch_and(!bits, std::sync::atomic::Ordering::Relaxed);
// A NOMATCH / NULL_GLOB failure in the redirect target's
// filename generation belongs to the same child: take its
// carrier too, or the command-boundary gate still ends the list.
let _ = external_glob_failure_status();
}
with_executor(|exec| exec.set_last_status(1));
return Some(1);
}
// c:Src/exec.c:3755-3763 — a shell function is not forked, so a
// failed argument glob is `lastval = 1; goto err;` in the shell: the
// body never runs, and errflag (left set) ends the list with status
// 1 (`f() { :; }; f *nomatch` exits 1).
if with_executor(|exec| exec.function_exists(name))
&& with_executor(|exec| exec.current_command_glob_failed.replace(false))
{
consume_tilde_globsubst_carrier();
with_executor(|exec| exec.set_last_status(1));
crate::ported::builtin::LASTVAL.store(1, std::sync::atomic::Ordering::Relaxed);
return Some(1);
}
// Provenance: same argv record as `exec`, but ONLY when the name
// really resolves to a shell function — an external command
// reaches `exec` further down and would otherwise be recorded
// twice for the same call site.
if crate::provenance::active() && with_executor(|exec| exec.function_exists(name)) {
let mut argv = Vec::with_capacity(args.len() + 1);
argv.push(name.to_string());
argv.extend(args.iter().cloned());
crate::provenance::on_exec("call", &argv);
}
// ACTUALLY A ZSH FUNCTION: zmv/zcp/zln/zcalc are zsh autoload
// functions, NOT builtins. zshrs ships fast native impls, but they
// must behave like the zsh functions — command-not-found until
// `autoload -Uz <name>` creates a function entry. When autoloaded we
// run the native impl here (short-circuiting the fpath source, which
// can hang zshrs's parser on zsh-specific syntax); when NOT autoloaded
// we fall through (return None → resolution ends in command-not-found),
// matching `zsh -f; zmv` → "command not found: zmv".
// A DEFINED zmv/zcp/zln/zcalc body (user-written, or a stub already
// loaded by `autoload +X`) is an ordinary shell function and runs as
// one through the function dispatch below. The native port stands in
// only for the fpath load of a still-PM_UNDEFINED stub
// (c:Src/exec.c:5691-5695 execautofn → loadautofn, which clears
// PM_UNDEFINED at c:5790/c:5815).
let native_autoload =
matches!(name, "zmv" | "zcp" | "zln" | "zcalc") && autoload_stub_pending(name);
if matches!(name, "zmv" | "zcp" | "zln" | "zcalc")
&& !with_executor(|exec| exec.function_exists(name))
{
return None;
}
// c:Src/exec.c:3485-3489 — `shfunctab->getnode` is consulted before
// `builtintab`: a shell function shadows every builtin of the same
// name. The zshrs-only builtins dispatched by name below (znative,
// ztest_*, the daemon z* family) are builtins too, so they sit behind
// the same function check as the builtintab arm further down.
let has_user_fn = user_fn_shadows_builtin(name);
match name {
"zmv" if native_autoload => {
return Some(crate::extensions::ext_builtins::zmv(&args, "mv"));
}
"zcp" if native_autoload => {
return Some(crate::extensions::ext_builtins::zmv(&args, "cp"));
}
"zln" if native_autoload => {
return Some(crate::extensions::ext_builtins::zmv(&args, "ln"));
}
"zcalc" if native_autoload => {
return Some(crate::extensions::ext_builtins::zcalc(&args));
}
// znative — the plugin package manager (src/extensions/pkg/). Installs
// + loads zsh script and native (Rust cdylib) plugins from a global
// content-addressed store. `znative add owner/repo`, `znative load`, ...
"znative" if !has_user_fn => {
return Some(crate::extensions::pkg::builtin::znative(&args));
}
// ztest framework (src/extensions/ztest.rs — port of
// ../strykelang's unit-test framework). All zassert_*/
// ztest_* names route through the single try_dispatch
// helper so adding/removing assertions only touches
// ztest.rs.
n if !has_user_fn && crate::extensions::ztest::try_dispatch_known(n) => {
let status = with_executor(|exec| {
crate::extensions::ztest::try_dispatch(exec, n, &args).unwrap_or(1)
});
return Some(status);
}
// Daemon-managed z* builtins — thin IPC wrappers. Short-circuit BEFORE
// the function-lookup path so a missing daemon doesn't fall through to
// "command not found". The name list is owned by the daemon crate
// (zshrs_daemon::builtins::ZSHRS_BUILTIN_NAMES); routing through
// try_dispatch keeps this site zero-touch as new z* builtins land.
n if !has_user_fn && crate::daemon::builtins::is_zshrs_builtin(n) => {
return run_daemon_builtin(n, &args);
}
_ => {}
}
// c:Src/exec.c:3050-3068 — module-provided builtins (registered
// via each module's `bintab` and folded into the canonical
// `builtintab` by `createbuiltintable`) must dispatch BEFORE
// PATH lookup. fusevm's `shell_builtins::builtin_id` doesn't
// know about per-module entries like `log`
// (Src/Modules/watch.c:693) — they reach call_function as
// CallFunction ops. Consult the merged builtintab here so
// `log` runs the canonical `bin_log` instead of falling
// through to `/usr/bin/log` on macOS. Bug #72 in docs/BUGS.md.
//
// User-defined functions still take precedence over builtins
// (zsh's `alias → function → builtin → external` resolution
// order, c:Src/exec.c:3038-3068). Check `functions_compiled`
// first so a user `log() { ... }` shadows the module bin_log.
// c:Src/exec.c — shfunctab->getnode (the DISABLED-filtering
// accessor) returns NULL for entries flipped to DISABLED via
// `disable -f NAME`. functions_compiled holds the body
// independently of the DISABLED flag, so check shfunctab first
// and mask the lookup when the entry is disabled (see
// `user_fn_shadows_builtin`; `has_user_fn` computed above). Bug #221
// in docs/BUGS.md.
if !has_user_fn {
// c:Src/exec.c:3056 — `builtintab->getnode(builtintab,
// cmdarg)` returns NULL for DISABLED entries, falling
// execcmd through to PATH lookup. Mirror by gating the
// bn_in_tab match on the BUILTINS_DISABLED set. Bug #106
// in docs/BUGS.md.
let disabled = crate::ported::builtin::BUILTINS_DISABLED
.lock()
.map(|s| s.contains(name))
.unwrap_or(false);
let bn_in_tab =
!disabled && crate::ported::builtin::createbuiltintable().contains_key(name);
if bn_in_tab {
// c:Src/exec.c:4287 — `lastval = execbuiltin(args, assigns,
// (Builtin) hn);`. The store happens BEFORE any errflag
// handling, so a builtin that BOTH raises errflag (zerr) and
// returns non-zero still publishes its status. zshrs relied on
// the VM's trailing `SetStatus` op to publish it, and that op
// is skipped once the builtin set ERRFLAG_ERROR — so
// `() { private SECONDS }` (makeprivate's zerrnam + return 1)
// reported 0 where zsh reports 1 (V10private.ztst:22).
let __ret = dispatch_builtin_raw(name, args);
// c:4289-4293 — `if (!(errflag & ERRFLAG_INT)) lastval = ret;`
// (see `dispatch_builtin`).
let __st = if (crate::ported::utils::errflag
.load(std::sync::atomic::Ordering::Relaxed)
& crate::ported::zsh_h::ERRFLAG_INT)
!= 0
{
crate::ported::builtin::LASTVAL.load(std::sync::atomic::Ordering::Relaxed)
} else {
__ret
};
crate::ported::builtin::LASTVAL.store(__st, std::sync::atomic::Ordering::Relaxed); // c:4287
with_executor(|exec| exec.set_last_status(__st)); // c:4287
return Some(__st);
}
// zshrs-original opcode builtins (async, doctor, peach, …) are not
// in builtintab, so a run-time-resolved name (`$var`) never reaches
// them. Dispatch by name here — after ported builtins, before
// external — matching the shell's function -> builtin -> external
// order (`has_user_fn` was checked above, so functions still win).
if let Some(status) = try_run_registered_builtin(name, &args) {
return Some(status);
}
}
// c:Src/lex.c:1928 — an alias is replaced by its text while the line is
// LEXED; nothing consults the alias table once the command runs. The
// dispatch-time rewrite that used to sit here (gated on INTERACTIVE)
// expanded the already-expanded command name a second time:
// `alias ls='ls -G'; ls x` ran `ls -G -G x`, and `\ls` picked it up.
// $_ pre-body bump and pending-underscore tracking are
// ZshrsHost-only concerns (prompt rendering). Apply BEFORE
// delegating to dispatch_function_call so the body sees the
// bumped value.
//
// c:Src/exec.c:3491 — `setunderscore((args && nonempty(args))
// ? ((char *) getdata(lastnode(args))) : "")`. C sets $_ to
// the LAST node of the WHOLE args list (which includes argv[0]
// == the function name). So for a no-arg `f`, $_ becomes "f"
// inside the function body. The Rust port at the CallFunction
// op-handler receives `args` WITHOUT the command name
// (compile_zsh.rs:1571 only pushes simple.words[1..]). The
// last() fallback `|| fn_name.clone()` already covers the
// no-arg case, but `exec.set_scalar("_", ...)` writes paramtab
// — the canonical `$_` read goes through `underscoregetfn`
// (params.rs:7836) which reads the `zunderscore` Mutex.
// setsparam("_") doesn't update that mutex, so the body's
// `${_}` returned empty. Bug #279 in docs/BUGS.md. Mirror the
// C `setunderscore` by writing via `set_zunderscore` directly.
let fn_name = name.to_string();
// c:Src/exec.c:5487-5488 — an ANONYMOUS function (execfuncdef, no names)
// sets `$_` from its own arguments only, `""` when it has none; the
// name pushed in front (c:5493) is not one of them.
let anon_fn = fn_name.starts_with("_zshrs_anon_");
let no_arg_underscore = if anon_fn { String::new() } else { fn_name.clone() };
{
let dollar_underscore = args.last().cloned().unwrap_or_else(|| no_arg_underscore.clone());
// c:3546 — zunderscore is the only store; the paramtab write
// that used to accompany this cleared PM_UNSET (see pop_args).
crate::ported::params::set_zunderscore(std::slice::from_ref(&dollar_underscore));
}
// Delegate the actual function dispatch to the canonical
// `dispatch_function_call` (which itself wraps the canonical
// `doshfunc` port from `Src/exec.c:5823`). Single doshfunc
// call-site keeps scope-mgmt invariants in one place.
// c:Src/exec.c:772-776 — a function runs unchanged under `-`; only a
// name that is not a function falls through to the external spawn,
// which still needs the carrier.
let exec_dash = take_exec_carrier();
let job_text = JOB_TEXT.with(|t| t.borrow_mut().take());
PREFORK_CUT.with(|c| c.set(false)); // the words are complete
// c:Src/exec.c:3674-3680 — a shell function runs in the current shell.
if with_executor(|exec| exec.function_exists(&fn_name)) {
crate::exec_jobs::mark_thisjob_cursh(false);
}
let status = with_executor(|exec| exec.dispatch_function_call(&fn_name, &args));
if status.is_none() {
EXEC_DASH.with(|c| c.set(exec_dash));
JOB_TEXT.with(|t| *t.borrow_mut() = job_text);
} else {
// c:Src/exec.c:5643-5644 execshfunc — `if (!list_pipe)
// deletefilelist(last_file_list, 0);` once doshfunc returns: the
// `=(cmd)` temp files and `>(cmd)` fds made for the call's
// arguments go with it, also when the body ran `exit` (that only
// sets exit_pending, the function still returns here first).
close_pending_psub_fds();
}
// Anonymous functions (`() { … } args`, compiled by
// parse_anon_funcdef as `_zshrs_anon_N` / `_zshrs_anon_kw_N`)
// execute exactly ONCE and must not persist. zsh runs the body and
// frees the function, so `${functions}` / `typeset -f` never show
// it. Remove every trace right after the single invocation —
// AFTER `status` is captured, so the body's exit code is preserved
// ($? — calling `unfunction` here would reset it to 0 instead).
// Without this, real plugins that use `() { … }` (fzf-tab, zinit,
// p10k, …) leaked dozens of `_zshrs_anon_N` into `$functions`,
// diverging from zsh's function table on every such config.
if fn_name.starts_with("_zshrs_anon_") {
// `${functions}` / `typeset -f` enumerate the canonical
// `shfunctab` (via scanpmfunctions); the bytecode call path
// also keeps the body in the executor's compiled-fn maps. Clear
// BOTH so no trace of the one-shot anon survives.
crate::ported::hashtable::removeshfuncnode(&fn_name);
with_executor(|exec| {
exec.functions_compiled.remove(&fn_name);
exec.function_source.remove(&fn_name);
exec.function_line_base.remove(&fn_name);
exec.function_def_file.remove(&fn_name);
});
}
// c:Src/exec.c:6207-6265 — doshfunc saves `ou = zunderscore`
// around the body and runs `setunderscore(ou)` (c:6257) on the way
// out, so a function call leaves `$_` at the CALL's last argument
// rather than at whatever the body's last command set. The value
// saved there is the one execcmd_exec installed just before the
// call (c:3546), i.e. exactly `args.last()`.
{
let last_call_arg = args.last().cloned().unwrap_or(no_arg_underscore);
crate::ported::params::set_zunderscore(std::slice::from_ref(&last_call_arg));
// c:6257
}
status
}
}
// ───────────────────────────────────────────────────────────────────────────
/// Render a failed-redirect open error the way C's `zerrmsg` `%e` format
/// code does (Src/utils.c): `strerror(errno)` with the first character
/// lowercased, except `EIO` (kept capitalized) and `EINTR` (→ "interrupt").
/// C's redirect open failures call `zwarn("%e: %s", errno, fname)`
/// (Src/exec.c:3741); zshrs's `zwarning` takes a pre-built string, so the
/// `%e` part is built here. Replaces the prior hardcoded `ErrorKind` match
/// that fell back to a generic "redirect failed" for `EROFS`/`EACCES`/etc.
/// Port of `IS_WRITE_FILE` (zsh.h:403, `REDIR_WRITE <= X <= REDIR_READWRITE`)
/// over the fusevm redirect op bytes compile_zsh lowers those types to:
/// `>`/`>|` (WRITE/CLOBBER), `>>`/`>>|` (APPEND), `>&`/`&>` and their append
/// forms (WRITE_BOTH/APPEND_BOTH, compile_zsh.rs REDIR_ERRWRITE..), `<>`.
fn redir_is_write_file(op_byte: u8) -> bool {
matches!(
op_byte,
r::WRITE | r::APPEND | r::CLOBBER | r::READ_WRITE | r::WRITE_BOTH | r::APPEND_BOTH
)
}
fn redir_errno_msg(err: &std::io::Error) -> String {
let errno = match err.raw_os_error() {
Some(n) if n != 0 => n,
_ => return "redirect failed".to_string(),
};
if errno == libc::EINTR {
return "interrupt".to_string(); // c:zerrmsg %e — EINTR special-case
}
let cptr = unsafe { libc::strerror(errno) };
if cptr.is_null() {
return "redirect failed".to_string();
}
let msg = unsafe { std::ffi::CStr::from_ptr(cptr) }.to_string_lossy();
if errno == libc::EIO {
return msg.into_owned(); // c:zerrmsg %e — EIO keeps capitalization
}
// c:zerrmsg %e — `fputc(tulower(errmsg[0])); fputs(errmsg + 1)`.
let mut chars = msg.chars();
match chars.next() {
Some(first) => first.to_lowercase().collect::<String>() + chars.as_str(),
None => "redirect failed".to_string(),
}
}
// Host-routed shell ops: ShellExecutor methods invoked by ZshrsHost from the
// fusevm VM. Not a port of Src/exec.c (see file-level docs above) — they're
// the bridge between fusevm opcodes and ShellExecutor state.
// ───────────────────────────────────────────────────────────────────────────
impl ShellExecutor {
// ─── Host-routed shell ops (called by ZshrsHost from fusevm) ────────────
/// Apply a single redirection. The current scope's saved-fd vec gets a
/// dup of the original fd so it can be restored by `host_redirect_scope_end`.
/// `op_byte` matches `fusevm::op::redirect_op::*`.
/// Park the CURRENT contents of `fd` in the enclosing redirect
/// scope so `host_redirect_scope_end` can restore them.
///
/// c:Src/exec.c:2421-2443 — `addfd`'s "starting a new multio" arm:
///
/// ```c
/// if (!forked && save[fd1] == -2) {
/// if (fd1 == fd2) save[fd1] = -1;
/// else {
/// int fdN = movefd(fd1);
/// /* fd1 may already be closed here, so
/// * ignore bad file descriptor error */
/// if (fdN < 0) { if (errno != EBADF) { … } }
/// …
/// save[fd1] = fdN;
/// }
/// }
/// ```
///
/// A `save[]` slot of -1 therefore means "fd1 was CLOSED before
/// this redirection", and `fixfds` (c:4522-4532) feeds it to
/// `redup(-1, i)`, whose first arm is `zclose(y)` (c:Src/utils.c:
/// 2047-2048). So zsh CLOSES the fd again at teardown rather than
/// leaving the redirection behind — `print x 3<file; cat <&3`
/// reports "3: bad file descriptor" in zsh.
///
/// c:Src/exec.c:3978-3986 — a bare `exec` (nullexec==1)
/// "specifically *doesn't* restore the original fd's", so nothing
/// is parked for it.
pub fn save_fd_for_scope(&mut self, fd: i32) {
if self.exec_redirs_permanent {
// Permanent — except inside an in-process subshell, whose
// fd table C forks away (see SubshFdFrame).
crate::ported::exec::SubshFdFrame::touch(fd);
return;
}
// c:2478 — `if (!forked && save[fd1] == -2)`.
if redir_scope_forked(self.redirect_scope_stack.len()) {
// A splitter already running on this scope (`>&2 2>&1`, `>f 2>&1`
// on a pipeline stage) holds its write end on every fd later
// dup'd from the stream. C's tee is a separate process that
// ends when the child exits; the in-process splitter is joined at
// scope end, so a -1 slot closes this fd there or the join
// waits forever for an EOF the dup keeps from arriving.
if self.multios_scope_stack.last().is_some_and(|s| !s.is_empty()) {
if let Some(top) = self.redirect_scope_stack.last_mut() {
top.push((fd, -1));
}
}
return;
}
// c:2425 `movefd(fd1)` — zshrs keeps the original fd open and
// dups it aside instead (the caller's dup2 overwrites it), so
// F_DUPFD stands in for movefd's dup-then-close.
let saved = unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, 10) };
// c:2422-2423 / c:2430-2436 — a closed fd1 parks -1, not a dup.
let slot = if saved >= 0 { saved } else { -1 };
if let Some(top) = self.redirect_scope_stack.last_mut() {
top.push((fd, slot));
mark_saved_fd(slot);
} else if saved >= 0 {
// No scope — leave saved fd open and let the next scope
// reclaim it. (Caller without a scope leaks the dup; this
// matches `WithRedirects` parser construction always wrapping.)
unsafe { libc::close(saved) };
}
}
/// Apply a file-open result to a redirect fd; on error, emit
/// zsh-format diagnostic, set redirect_failed, sink fd to /dev/null.
/// Shared between WRITE/APPEND/READ/CLOBBER arms in
/// host_apply_redirect to keep the error-handling identical.
fn redir_open_or_fail(
fd: i32,
result: std::io::Result<fs::File>,
target: &str,
redirect_failed: &mut bool,
) -> bool {
match result {
Ok(file) => {
let new_fd = file.into_raw_fd();
unsafe {
// When the target fd was already closed (e.g. `exec 0<&-;
// cmd < file`), open() returns the lowest free fd, which is
// `fd` itself. Then `dup2(fd, fd)` is a no-op: closing new_fd
// would CLOSE the fd we just opened, AND — since Rust's
// File::open sets O_CLOEXEC and a no-op dup2 does NOT clear
// it — an exec'd child would lose the descriptor. So in the
// reuse case, keep the fd and clear its close-on-exec flag;
// otherwise dup2 (which clears cloexec on the copy) + close.
if new_fd != fd {
libc::dup2(new_fd, fd);
libc::close(new_fd);
} else {
libc::fcntl(fd, libc::F_SETFD, 0);
}
}
true
}
Err(e) => {
// c:Src/exec.c:3741 — zwarn("%e: %s", errno, fname) with the
// real lineno prefix; redir_errno_msg builds the `%e` errno
// message for all errnos (not just the few hardcoded before).
let msg = redir_errno_msg(&e);
crate::ported::utils::zwarn(&format!("{}: {}", msg, target));
*redirect_failed = true;
// The /dev/null sink keeps a failed scoped redirect
// from leaking the aborted command's output to the
// wrong fd until scope-end restores it. For a bare
// `exec` redirect (permanent, no scope restore) C
// leaves the fd UNTOUCHED — execerr() aborts the
// statement and the original fd 1 keeps flowing
// (A04redirect: `exec >./nonexistent/x` then `echo
// output` still prints). c:Src/exec.c:3735-3742.
let permanent = with_executor(|exec| exec.exec_redirs_permanent);
if !permanent {
if let Ok(devnull) = fs::OpenOptions::new()
.read(true)
.write(true)
.open("/dev/null")
{
let new_fd = devnull.into_raw_fd();
unsafe {
if new_fd != fd {
libc::dup2(new_fd, fd);
libc::close(new_fd);
} else {
libc::fcntl(fd, libc::F_SETFD, 0);
}
}
}
}
false
}
}
}
/// REDIR_ERRWRITE / REDIR_ERRAPP (`>&word`, `>>&word`, `&>`, `&>>`):
/// one file onto BOTH fd 1 and fd 2. c:Src/exec.c:3985-3999 — the open
/// failing is `zwarn("%e: %s", errno, fn->name); execerr();`, i.e. the
/// diagnostic, status 1 and the command abandoned; an empty name fails
/// with ENOENT (`>&''` → `no such file or directory: `).
fn redir_errwrite(&mut self, result: std::io::Result<fs::File>, target: &str) {
match result {
Ok(file) => {
let new_fd = file.into_raw_fd();
unsafe {
libc::dup2(new_fd, 1);
libc::dup2(new_fd, 2);
libc::close(new_fd);
}
}
Err(e) => {
crate::ported::utils::zwarn(&format!("{}: {}", redir_errno_msg(&e), target));
self.set_last_status(1);
self.redirect_failed = true;
}
}
}
/// `host_apply_redirect` — see implementation.
pub fn host_apply_redirect(&mut self, fd: u8, op_byte: u8, target: &str) {
if redir_target_expansion_failed(self) {
return;
}
// c:Src/exec.c:3726-3729 — `if (isset(RESTRICTED) &&
// IS_WRITE_FILE(fn->type)) { zwarn("writing redirection not allowed
// in restricted mode"); execerr(); }`
if crate::ported::zsh_h::isset(crate::ported::zsh_h::RESTRICTED)
&& redir_is_write_file(op_byte)
{
crate::ported::utils::zwarn("writing redirection not allowed in restricted mode");
self.redirect_failed = true;
return;
}
// c:Src/exec.c:3775-3777 — in a pipeline stage whose input is the
// pipe, mfds[0] already holds it, so `<file` / `<&N` becomes the
// multio's second member (c:2447-2480) instead of replacing it.
if fd == 0
&& matches!(op_byte, r::READ | r::DUP_READ)
&& target.trim_start_matches('&') != "-"
{
if let Some(seed) = take_pipe_input_seed(self, 0) {
self.host_apply_redirect(0, op_byte, target);
let member = if self.redirect_failed {
-1
} else {
unsafe { libc::dup(0) }
};
if member < 0 {
let _ = crate::ported::utils::zclose(seed);
return;
}
let member = crate::ported::utils::movefd(member); // c:2465
multios_read_concat(self, 0, vec![seed, member]);
return;
}
}
// `&>` / `&>>` always target both fd 1 and fd 2 regardless of the
// fd byte the parser supplied (the lexer's tokfd clamp makes the
// raw value unreliable for these forms).
let fd: i32 = if matches!(op_byte, r::WRITE_BOTH | r::APPEND_BOTH) {
1
} else {
fd as i32
};
// c:Src/exec.c — for DUP_READ / DUP_WRITE forms (<&N / >&N),
// validate the source fd is open BEFORE the save-and-dup
// dance below. The save's `dup(fd)` reclaims the lowest free
// fd, which on closed-fd reuse would let dup2(src=N, …)
// succeed against the freshly-claimed slot — masking the
// user's "bad file descriptor" error. Check src_fd first.
if matches!(op_byte, r::DUP_READ | r::DUP_WRITE) {
let n_check = target.trim_start_matches('&');
if n_check != "-" {
if let Ok(src_fd) = n_check.parse::<i32>() {
// c:Src/exec.c:3884-3897 — a descriptor above 9 that
// the shell knows about is NOT the script's to
// duplicate:
//
// else if (fn->fd2 > 9 &&
// (fn->fd2 <= max_zsh_fd &&
// ((fdtable[fn->fd2] != FDT_UNUSED &&
// fdtable[fn->fd2] != FDT_EXTERNAL) ||
// fn->fd2 == coprocin ||
// fn->fd2 == coprocout))) {
// fil = -1;
// errno = EBADF;
//
// `FDT_EXTERNAL` is exempt because that is a
// descriptor the script itself asked for (`{v}>file`,
// c:2409) and 0/1/2 (c:Src/init.c:1900). Anything
// past `max_zsh_fd` is left alone on purpose —
// c:3886-3891: "the shell doesn't know about it. Just
// assume the user knows what they're doing."
//
// Only the open-ness of the descriptor was checked
// here, so `>&11` happily duplicated the shell's own
// history database and `>&10` its log. The `exec
// N>&-` half of this pair was already ported
// (fusevm_bridge.rs:7047, c:3830-3835); this half was
// not, and the ported copy in `ported/exec.rs:11466`
// is not on the VM's redirection path.
let shell_owned = src_fd > 9 && {
let max_fd =
crate::ported::utils::MAX_ZSH_FD.load(std::sync::atomic::Ordering::Relaxed);
let cin = crate::ported::modules::clone::coprocin
.load(std::sync::atomic::Ordering::Relaxed);
let cout = crate::ported::modules::clone::coprocout
.load(std::sync::atomic::Ordering::Relaxed);
src_fd <= max_fd && {
let kind = crate::ported::utils::fdtable_get(src_fd)
& crate::ported::zsh_h::FDT_TYPE_MASK;
(kind != crate::ported::zsh_h::FDT_UNUSED
&& kind != crate::ported::zsh_h::FDT_EXTERNAL)
// bash hands the coproc fds to the script (`>&${COPROC[1]}`).
|| (!crate::dash_mode::bash_mode() && (src_fd == cin || src_fd == cout))
}
};
if unsafe { libc::fcntl(src_fd, libc::F_GETFD) } == -1 || shell_owned {
// c:Src/exec.c — zwarn with real lineno prefix.
crate::ported::utils::zwarn(&format!("{}: bad file descriptor", src_fd));
self.set_last_status(1);
self.redirect_failed = true;
return;
}
}
}
}
// c:Src/exec.c:3978-3986 — bare `exec` redirects (nullexec==1)
// skip the save entirely: "we specifically *don't* restore the
// original fd's". C's save[] is per-execcmd, so exec's redirs
// never enter an enclosing group's save list either; pushing
// into `redirect_scope_stack.last_mut()` here (the enclosing
// group's scope) made `{ exec 1>&-; … } 2>/dev/null` restore
// stdout at group end — diverging from zsh, which keeps fd 1
// closed for the rest of the script. `save_fd_for_scope` makes
// that call (it parks nothing for a bare `exec` outside an
// in-process subshell).
self.save_fd_for_scope(fd);
// For `&>` / `&>>` also save fd 2 so the scope restores it after
// the body. Otherwise stderr stays redirected past the command.
if matches!(op_byte, r::WRITE_BOTH | r::APPEND_BOTH) {
self.save_fd_for_scope(2);
}
// c:Src/exec.c:3722-3724 + 2447-2480 — MULTIOS split when this
// command's stdout IS the pipeline output. C registers the pipe
// in mfds[1] (`addfd(forked, save, mfds, 1, output, 1, NULL)`)
// BEFORE walking the explicit redirect list, so a write-side
// redirect of fd 1 finds mfds[1] occupied and, with MULTIOS
// set, "split[s] the stream": fd 1 becomes the write end of an
// internal pipe whose reader tees every chunk to BOTH the
// pipeline pipe and the new target. That is why
// `{ echo a; echo b >&2; } 3>&1 1>&2 2>&3 3>&- | cat` sends
// `a` to the pipe (via the tee) AND to stderr — plain dup2
// replacement loses the pipe stream. The scope-depth gate
// mirrors mfds being per-execcmd: only the redirect list
// attached to the stage's own command joins the pipe; nested
// commands inside the body (`{ echo a > f; } | cat`) get a
// fresh "mfds" and replace as usual.
if fd == 1
&& self
.pipe_output_scope
.is_some_and(|d| d + 1 == self.redirect_scope_stack.len())
&& crate::ported::options::opt_state_get("multios").unwrap_or(true)
{
// Resolve the new write target exactly as the plain arms
// below would, but as a raw fd for the tee.
let new_target_fd: i32 = match op_byte {
r::DUP_WRITE => {
// Numeric `>&N` only; `-` (close) and `p` (coproc)
// fall through to the plain arms.
target
.trim_start_matches('&')
.parse::<i32>()
.map(|src| unsafe { libc::fcntl(src, libc::F_DUPFD_CLOEXEC, 10) })
.unwrap_or(-1)
}
r::WRITE | r::CLOBBER => fs::File::create(target)
.map(|f| f.into_raw_fd())
.unwrap_or(-1),
r::APPEND => fs::OpenOptions::new()
.create(true)
.append(true)
.open(target)
.map(|f| f.into_raw_fd())
.unwrap_or(-1),
_ => -1,
};
if new_target_fd >= 0 {
let pipe_dup = unsafe { libc::fcntl(1, libc::F_DUPFD_CLOEXEC, 10) };
match (pipe_dup >= 0).then(os_pipe::pipe) {
Some(Ok((read_end, write_end))) => {
// c:Src/exec.c:5222 / Src/utils.c:1990-2012 —
// `mpipe()` runs both pipe ends through
// `movefd()`, which lifts any fd below 10 out
// of the user-visible `>&N` range. Same abort
// hazard as the BUILTIN_MULTIOS_REDIRECT arm.
let read_end = unsafe {
<os_pipe::PipeReader as std::os::unix::io::FromRawFd>::from_raw_fd(
crate::extensions::fds::movefd(read_end.into_raw_fd()),
)
};
// Splitter: same read-loop shape as
// BUILTIN_MULTIOS_REDIRECT, with one ordering
// refinement. C's tee is a forked process
// (closemn → teeproc) whose wakeup latency lets
// the stage's DIRECT pipe writes land first —
// observed zsh output for `{ echo a; echo b >&2; }
// 3>&1 1>&2 2>&3 3>&- | cat` is `b` then `a`,
// 15/15 runs. A Rust thread wakes faster than
// the debug-build VM dispatches the next echo,
// inverting the order. Emulate the C timing
// observably: stream to the NEW target (file /
// stderr dup) immediately, but defer the
// pipe-bound copy until EOF (or a 64KB cap so a
// long-running stream still flows instead of
// growing memory unboundedly).
let write_now = |tfd: i32, data: &[u8]| {
let mut off = 0;
while off < data.len() {
let w = unsafe {
libc::write(
tfd,
data[off..].as_ptr() as *const libc::c_void,
data.len() - off,
)
};
if w <= 0 {
break;
}
off += w as usize;
}
};
let handle = crate::signal_thread::spawn(move || {
let mut rd = read_end;
let mut buf = [0u8; 8192];
let mut pipe_pending: Vec<u8> = Vec::new();
loop {
match std::io::Read::read(&mut rd, &mut buf) {
Ok(0) | Err(_) => break,
Ok(n) => {
write_now(new_target_fd, &buf[..n]);
pipe_pending.extend_from_slice(&buf[..n]);
if pipe_pending.len() >= 65536 {
write_now(pipe_dup, &pipe_pending);
pipe_pending.clear();
}
}
}
}
write_now(pipe_dup, &pipe_pending);
unsafe {
libc::close(pipe_dup);
libc::close(new_target_fd);
}
});
let write_raw = AsRawFd::as_raw_fd(&write_end);
unsafe { libc::dup2(write_raw, 1) };
drop(write_end);
// A forked command's scope parked no copy of fd 1
// (save_fd_for_scope), so nothing would release this
// write end at scope end and the join below would
// wait forever; a -1 slot closes it there, as the
// child's exit closes it in C.
if redir_scope_forked(self.redirect_scope_stack.len()) {
if let Some(top) = self.redirect_scope_stack.last_mut() {
top.push((1, -1));
}
}
// Scope-end closes this dup (the last writer once
// the saved fd 1 is restored) → EOF → join.
let close_on_end = unsafe { libc::fcntl(1, libc::F_DUPFD_CLOEXEC, 10) };
if let Some(top) = self.multios_scope_stack.last_mut() {
top.push((close_on_end, handle));
} else {
unsafe { libc::close(close_on_end) };
let _ = handle.join();
}
return;
}
_ => unsafe {
// pipe()/dup failure — fall through to plain replace.
if pipe_dup >= 0 {
libc::close(pipe_dup);
}
libc::close(new_target_fd);
},
}
}
}
match op_byte {
r::WRITE => {
// Honor `setopt noclobber`: refuse to overwrite an
// existing regular file unless `>!` / `>|` (CLOBBER).
// zsh internally stores the inverted-name `clobber`
// (default ON); `setopt noclobber` writes
// `clobber=false`. Honor both keys.
//
// c:Src/exec.c:2241-2245 clobber_open recover path:
// after O_EXCL fails, reopen and `if (!S_ISREG(...))
// return fd;` — non-regular targets (char/block-
// special, FIFO, socket) bypass the noclobber check.
// Bug #30 in docs/BUGS.md: this bridge-side check did
// a bare `Path::exists()` and treated `/dev/null` as
// a protected file, breaking `setopt no_clobber; echo
// hi > /dev/null` and every `2> /dev/null` idiom.
// Add a regular-file stat gate that matches the C
// semantic. The canonical clobber_open at
// src/ported/exec.rs:2123 already handles this; the
// bridge duplicates a stripped-down version here and
// must mirror the same check.
let noclobber = opt_state_get("noclobber").unwrap_or(false)
|| !opt_state_get("clobber").unwrap_or(true);
let target_meta = std::fs::metadata(target).ok();
let target_is_regular_file = target_meta
.as_ref()
.map(|m| m.file_type().is_file())
.unwrap_or(false);
// c:Src/exec.c:2313 clobber_open — CLOBBER_EMPTY permits
// re-using an EMPTY regular file under noclobber: `setopt
// noclobber clobberempty; : >f; echo hi >f` overwrites f.
// The inline bridge check ignored this and errored.
let clobber_empty_ok = opt_state_get("clobberempty").unwrap_or(false)
&& target_meta.as_ref().map(|m| m.len() == 0).unwrap_or(false);
if noclobber && target_is_regular_file && !clobber_empty_ok {
eprintln!(
"{}:{}: file exists: {}",
shname(),
crate::ported::lex::lineno(),
target
);
self.set_last_status(1);
// c:Src/exec.c — set redirect_failed so the scope-end
// hook (`with_redirects_end` in this file) forces
// $? to 1 regardless of the still-running command's
// own exit. Without this the next command (e.g.
// `echo x` writing to /dev/null below) succeeds
// and overwrites the redirect-failure status,
// making noclobber unobservable from $?.
self.redirect_failed = true;
// Sink the upcoming command's stdout to /dev/null
// so we don't leak its output to the terminal.
// zsh skips the command entirely; we approximate by
// discarding the output (the redirect target was
// the user's chosen sink, but with noclobber the
// file is protected — discarding matches the
// user's intent better than printing to terminal).
if let Ok(file) = fs::OpenOptions::new().write(true).open("/dev/null") {
let new_fd = file.into_raw_fd();
unsafe {
libc::dup2(new_fd, fd);
libc::close(new_fd);
}
}
return;
}
if !Self::redir_open_or_fail(
fd,
fs::File::create(target),
target,
&mut self.redirect_failed,
) {
self.set_last_status(1);
}
}
r::CLOBBER => {
if !Self::redir_open_or_fail(
fd,
fs::File::create(target),
target,
&mut self.redirect_failed,
) {
self.set_last_status(1);
}
}
r::APPEND => {
// c:Src/exec.c:3924-3927 — `>>` honors NO_CLOBBER+!APPENDCREATE
// by opening O_APPEND|O_WRONLY WITHOUT O_CREAT, so missing
// files yield ENOENT. zsh source:
// if (!isset(CLOBBER) && !isset(APPENDCREATE) &&
// !IS_CLOBBER_REDIR(fn->type))
// mode = O_WRONLY|O_APPEND|O_NOCTTY;
// else mode = O_WRONLY|O_APPEND|O_CREAT|O_NOCTTY;
// (IS_CLOBBER_REDIR — `>>!`/`>>|` — is currently flattened
// to plain APPEND at compile time in
// src/extensions/compile_zsh.rs:1654-1655, so the bang/pipe
// forms can't be distinguished here yet.)
let noclobber = opt_state_get("noclobber").unwrap_or(false)
|| !opt_state_get("clobber").unwrap_or(true);
let append_create = opt_state_get("appendcreate").unwrap_or(false)
|| opt_state_get("append_create").unwrap_or(false);
let open_result = if noclobber && !append_create {
fs::OpenOptions::new().append(true).open(target) // no create
} else {
fs::OpenOptions::new()
.create(true)
.append(true)
.open(target)
};
if !Self::redir_open_or_fail(fd, open_result, target, &mut self.redirect_failed) {
self.set_last_status(1);
}
}
r::READ => {
if !Self::redir_open_or_fail(
fd,
fs::File::open(target),
target,
&mut self.redirect_failed,
) {
self.set_last_status(1);
}
}
r::READ_WRITE => {
if let Ok(file) = fs::OpenOptions::new()
.create(true)
.truncate(false) // <> opens existing-or-new without truncating
.read(true)
.write(true)
.open(target)
{
let new_fd = file.into_raw_fd();
unsafe {
// See redir_open_or_fail: when the opened fd IS the
// destination (target fd was closed), keep it and clear
// O_CLOEXEC; else dup2 + close.
if new_fd != fd {
libc::dup2(new_fd, fd);
libc::close(new_fd);
} else {
libc::fcntl(fd, libc::F_SETFD, 0);
}
}
}
}
r::DUP_READ | r::DUP_WRITE => {
// Target is a numeric fd reference like `&3`. The parser
// strips the `&` prefix before we get here in some paths,
// others retain it — accept both. Also support `-` for
// close-fd (`<&-` / `>&-`) per POSIX. The src_fd
// validity check ran above before the save-and-dup.
let n = target.trim_start_matches('&');
if n == "-" {
unsafe { libc::close(fd) };
} else if n == "p" {
// c:Src/exec.c — `<&p` / `>&p` route through the
// coprocin / coprocout globals. zsh's `coproc CMD`
// launch publishes those fds; the canonical
// bin_print / bin_read `-p` arms already consume
// them. The DUP redirect form is the third
// consumer: it must dup the coproc fd onto the
// target slot so the next command's stdin/stdout
// is wired to the running coprocess. Bug #388.
let coproc_fd = if op_byte == r::DUP_READ {
crate::ported::modules::clone::coprocin
.load(std::sync::atomic::Ordering::Relaxed)
} else {
crate::ported::modules::clone::coprocout
.load(std::sync::atomic::Ordering::Relaxed)
};
if coproc_fd < 0 {
eprintln!("{}:1: no coprocess", shname());
self.set_last_status(1);
self.redirect_failed = true;
} else {
unsafe {
libc::dup2(coproc_fd, fd);
}
}
} else if let Ok(src_fd) = n.parse::<i32>() {
unsafe { libc::dup2(src_fd, fd) };
} else if op_byte == r::DUP_WRITE && crate::extensions::dash_mode::dash_faithful() {
// !!! DASH-FAITHFUL GATE (no C counterpart) !!! dash has no
// `>&file`; a non-number word is "Bad fd number" (status 2).
crate::ported::utils::zerr(&format!("Bad fd number: {n}"));
self.set_last_status(crate::extensions::dash_mode::fatal_error_status().unwrap_or(2));
self.redirect_failed = true;
} else if op_byte == r::DUP_WRITE {
// c:Src/glob.c:2184-2187 xpandredir — a MERGEOUT
// word that expands to a non-number becomes
// REDIR_ERRWRITE: `cmd >& word` opens `word` and
// routes BOTH fd 1 and fd 2 there. Reached only
// for dynamic words (`>&$var`); static filenames
// were converted at compile time.
self.redir_errwrite(fs::File::create(target), target);
} else {
// c:Src/glob.c:2185 — MERGEIN non-number:
// `zerr("file number expected")`.
crate::ported::utils::zerr("file number expected");
self.set_last_status(1);
self.redirect_failed = true;
}
}
r::WRITE_BOTH => {
self.redir_errwrite(fs::File::create(target), target);
}
r::APPEND_BOTH => {
self.redir_errwrite(
fs::OpenOptions::new().create(true).append(true).open(target),
target,
);
}
_ => {}
}
}
/// Push a fresh redirect scope. `_count` is informational — the actual
/// saved fds are appended by host_apply_redirect into the top scope.
pub fn host_redirect_scope_begin(&mut self, _count: u8) {
// c:Src/exec.c:3722-3724 — the pipeline child set
// `pipe_output_pending` right after dup2'ing its stdout onto
// the pipe; the FIRST redirect scope opened in that child is
// the stage command's own redirect list (same execcmd as the
// pipe's addfd into mfds[1]). Capture the depth so only THAT
// list's fd-1 write redirects MULTIOS-join the pipe.
if self.pipe_output_pending {
self.pipe_output_pending = false;
self.pipe_output_scope = Some(self.redirect_scope_stack.len());
}
let clean = (crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed)
& crate::ported::zsh_h::ERRFLAG_ERROR)
== 0;
let depth = self.redirect_scope_stack.len();
REDIR_SCOPE_ERRFLAG_CLEAN.with(|v| {
let mut v = v.borrow_mut();
v.truncate(depth);
v.push(clean);
});
self.redirect_scope_stack.push(Vec::new());
self.multios_scope_stack.push(Vec::new());
let serial = SUBLIST_SERIAL.with(|c| c.get());
REDIR_SCOPE_OPENED.with(|c| c.set((serial, self.redirect_scope_stack.len())));
// c:Src/exec.c:3775-3777 — only the stage command's own redirect
// list (same sublist as the pipe install) sees the seeded mfds[0].
if PIPE_INPUT_INSTALLED.with(|c| c.take()) == Some(serial) {
PIPE_INPUT_SCOPE.with(|c| c.set(Some(self.redirect_scope_stack.len())));
}
}
/// Restore every redirect scope opened above `depth`.
///
/// c:Src/exec.c:4364 — `fixfds(save)` runs on EVERY exit path out of
/// `execcmd_exec`, the one an early `return` takes out of a compound
/// command carrying redirections included (`while … done < f`,
/// `{ …; return } < f`, `if …; then return; fi < f`). zshrs compiles
/// `return` to a Jump past the body's `WithRedirectsEnd`, so that
/// scope stayed on the stack and its saved fds never came back — the
/// caller inherited the callee's redirected fd.
///
/// gitstatus hit this: `gitstatus.plugin.zsh`'s daemon sources
/// `gitstatus/install`, whose `_gitstatus_install_main` returns out of
/// `while … done <"$gitstatus_dir"/install.info`. fd 0 stayed on
/// install.info instead of reverting to the request FIFO, so
/// `gitstatusd` read EOF on startup and exited ("EOF. Exiting."),
/// `gitstatus_start` failed, `VCS_STATUS_REMOTE_URL` came back empty
/// and powerlevel10k rendered the generic git icon in place of the
/// per-forge one.
pub fn unwind_redirect_scopes_to(&mut self, depth: usize) {
while self.redirect_scope_stack.len() > depth {
self.host_redirect_scope_end();
}
}
/// Pop the top redirect scope, restoring saved fds.
pub fn host_redirect_scope_end(&mut self) {
// c:Src/exec.c — restore saved fds FIRST so the multios
// pipe-write end is released from `fd`, then close our
// tracked close_on_end (the last surviving writer dup), then
// join the splitter thread. If we closed close_on_end before
// restoring saved, `fd` would still hold a pipe writer and
// the thread would block forever waiting for EOF.
if redir_scope_forked(self.redirect_scope_stack.len()) {
FORKED_REDIR_SCOPE.with(|c| c.set(0));
}
if let Some(saved) = self.redirect_scope_stack.pop() {
for (fd, saved_fd) in saved.into_iter().rev() {
// c:Src/exec.c:4530 `redup(save[i], i)` →
// c:Src/utils.c:2047-2048 `if (x < 0) zclose(y);`.
// A -1 slot means the fd was CLOSED before the
// redirection (c:2422-2423, c:2430-2436), so the
// restore is a close, not a dup2 — otherwise the
// redirection outlives the command it was written on
// (`print x 3<file; cat <&3` printed the file instead
// of "3: bad file descriptor").
if saved_fd < 0 {
unsafe { libc::close(fd) };
continue;
}
unsafe {
libc::dup2(saved_fd, fd);
}
// c:Src/utils.c:2049 — redup's `zclose(x)`, which also
// clears the fdtable mark mark_saved_fd set.
crate::ported::utils::zclose(saved_fd);
}
}
if let Some(scope) = self.multios_scope_stack.pop() {
// Close ALL tracked writer dups BEFORE joining any
// thread. When one splitter holds a dup of another's
// pipe write-end (two multios in one scope where a later
// one duped fd 1 while an earlier splitter owned it),
// joining in push order deadlocks: splitter A's EOF
// waits on splitter B's writer dup, which only closes
// after B's thread exits — blocked behind A's join.
let mut handles = Vec::with_capacity(scope.len());
for (write_fd, handle) in scope {
if write_fd >= 0 {
unsafe {
libc::close(write_fd);
}
}
handles.push(handle);
}
for handle in handles {
let _ = handle.join();
}
}
// The scope that captured the pipeline-output marker is gone;
// deeper-nested future scopes must not re-match its depth.
if self.pipe_output_scope == Some(self.redirect_scope_stack.len()) {
self.pipe_output_scope = None;
}
if PIPE_INPUT_SCOPE.with(|c| c.get()).is_some_and(|d| d > self.redirect_scope_stack.len()) {
PIPE_INPUT_SCOPE.with(|c| c.set(None));
}
// c:Src/exec.c:4445-4452 — the command is done: drop its xtrace copy.
let depth = self.redirect_scope_stack.len();
while let Some(fd) = XTRERR_COPIES.with(|v| {
let mut v = v.borrow_mut();
if v.last().is_some_and(|&(d, _)| d > depth) { v.pop().map(|(_, fd)| fd) } else { None }
}) {
xtrerr_flush(); // c:4448 fclose(newxtrerr)
crate::ported::utils::xtrerr.store(libc::STDERR_FILENO, std::sync::atomic::Ordering::Relaxed); // c:4449
let _ = crate::ported::utils::zclose(fd); // c:4451
}
}
/// Set up `content` as stdin (fd 0) for the next command.
/// Used by `Op::HereDoc(idx)` and `Op::HereString`.
///
/// c:Src/exec.c:4655 getherestr — C writes the body to a TEMP
/// FILE (gettempfile → write_loop → close → reopen O_RDONLY →
/// unlink), NOT a pipe. The previous pipe+writer-thread shape
/// SIGPIPE'd the whole shell when the consumer never read the
/// body (`: <<< ${(F)x/y}` — D04parameter chunk 211, flaky
/// rc=141): the redirect-scope teardown closed the read end
/// while the detached thread was still in write_all, and the
/// shell's SIGPIPE disposition is SIG_DFL. A temp file has no
/// reader/writer coupling — matching C exactly, including
/// lseek-ability of fd 0, which pipes don't give.
pub fn host_set_pending_stdin(&mut self, content: String) {
// c:Src/exec.c:3775-3777 — a here-document or here-string on a
// pipeline stage fed by a pipe joins the pipe as mfds[0]'s second
// member (c:2447-2480): `cat o1 | cat <<<hs` reads o1 then hs.
if let Some(seed) = take_pipe_input_seed(self, 0) {
self.host_set_pending_stdin(content);
let member = unsafe { libc::dup(0) };
if member < 0 {
let _ = crate::ported::utils::zclose(seed);
return;
}
let member = crate::ported::utils::movefd(member); // c:2465
multios_read_concat(self, 0, vec![seed, member]);
return;
}
// c:4673 — `gettempfile(NULL, 1, &s)`.
let mut tmp = std::env::temp_dir();
tmp.push(format!(
"zshrs-herestr-{}-{:x}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0)
));
// c:Src/exec.c:4719 — `unmetafy(t, &len);` runs BEFORE
// `write_loop(fd, t, len)`: what lands in the temp file is the RAW
// byte stream, never zshrs's metafied `Meta` + `byte ^ 32` pairs.
// Writing `content.as_bytes()` leaked the metafication onto fd 0,
// so `read -d $'\xa0' <<<$'first\xa0second'` saw `c2 83 c2 80`
// where every other writer (`print`, a pipe) emits the single `a0`.
let raw = crate::ported::utils::unmetafy_str(&content); // c:4719
// c:4675 — `write_loop(fd, t, len); close(fd);`
if std::fs::write(&tmp, &raw).is_err() {
return; // c:4674 — tempfile failure → no redirect
}
// c:Src/utils.c gettempfile → mkstemp creates the temp file mode
// 0600 IGNORING the umask, so the O_RDONLY reopen below always
// succeeds. `std::fs::write` honors the umask, so under `umask
// 0777` the file landed mode 0000 and the reopen failed with
// EACCES — `cat <<<x` then read empty stdin. Force 0600 to match
// mkstemp's umask-independent permissions.
let _ = std::fs::set_permissions(
&tmp,
<std::fs::Permissions as std::os::unix::fs::PermissionsExt>::from_mode(0o600),
);
// c:4677 — `fd = open(s, O_RDONLY | O_NOCTTY);`
let file = match std::fs::File::open(&tmp) {
Ok(f) => f,
Err(_) => {
let _ = std::fs::remove_file(&tmp);
return;
}
};
// c:4678 — `unlink(s);` — fd stays valid, name disappears.
let _ = std::fs::remove_file(&tmp);
// c:Src/exec.c:2478 — `if (!forked && save[fd1] == -2)`.
let saved = if redir_scope_forked(self.redirect_scope_stack.len()) {
-1
} else {
unsafe { libc::fcntl(libc::STDIN_FILENO, libc::F_DUPFD_CLOEXEC, 10) }
};
if saved >= 0 {
if let Some(top) = self.redirect_scope_stack.last_mut() {
top.push((libc::STDIN_FILENO, saved));
mark_saved_fd(saved);
} else {
unsafe { libc::close(saved) };
}
}
// c:Src/utils.c:redup — `if (x != y) { dup2(x, y); zclose(x); }`.
// When fd 0 was already CLOSED before this heredoc runs,
// `File::open` returns the lowest free descriptor, which is 0
// itself — so `read_fd == STDIN_FILENO`. C's redup skips both the
// dup2 (a no-op for equal fds) AND the close in that case, leaving
// the just-opened temp file installed at fd 0. Unconditionally
// dropping the File here closed that fd back to nothing, so an
// external NULLCMD (`cat`) inherited a closed fd 0 and failed with
// EBADF (`cat <<EOF` inside `$(...)` when exec 0<&- closed stdin).
let read_fd = AsRawFd::as_raw_fd(&file);
if read_fd != libc::STDIN_FILENO {
// dup2 installs a fresh fd 0 with FD_CLOEXEC clear (dup2 never
// copies the flag), then we close the CLOEXEC-tagged source.
unsafe { libc::dup2(read_fd, libc::STDIN_FILENO) };
drop(file); // c:redup zclose(x)
} else {
// File::open reused fd 0. Rust opens with O_CLOEXEC, so fd 0
// now carries FD_CLOEXEC and would be auto-closed when an
// external NULLCMD (`cat`) exec's — the child then reads a
// closed fd 0 and fails with EBADF. zsh opens the heredoc temp
// via `open(s, O_RDONLY|O_NOCTTY)` (no CLOEXEC), so its child
// inherits the fd. Clear the flag to match, then keep fd 0 open
// (redup's x==y arm: no dup2, no close).
unsafe {
let flags = libc::fcntl(libc::STDIN_FILENO, libc::F_GETFD);
if flags >= 0 {
libc::fcntl(libc::STDIN_FILENO, libc::F_SETFD, flags & !libc::FD_CLOEXEC);
}
}
std::mem::forget(file);
}
}
/// Spawn an external command using zshrs's full dispatch logic
/// (intercepts, command_hash, redirect handling). Used by
/// `ZshrsHost::exec` so the bytecode VM's `Op::Exec` and
/// `Op::CallFunction` external fallback get the same semantics as
/// the tree-walker's `execute_external` rather than a plain
/// `Command::new` shortcut. Returns the exit status.
pub fn host_exec_external(&mut self, args: &[String]) -> i32 {
// c:Src/exec.c:772-776 — BINF_DASH reaches `execute()` only; every
// other route below runs the command without it.
let exec_dash = take_exec_carrier();
PREFORK_CUT.with(|c| c.set(false)); // the words are complete
// Native p10k API: the `p10k(){ zshrs-p10k-api "$@" }` stub's
// body lands here (the name is neither function nor builtin).
// Route into the engine instead of a PATH miss.
if let Some(name) = args.first() {
if let Some(status) = crate::p10k::maybe_intercept_command(name, &args[1..]) {
self.set_last_status(status);
return status;
}
}
// If a glob expansion in this command's argv triggered the
// nomatch error path, suppress the actual exec and return
// status 1 — mirrors zsh's command-aborted-on-glob-error
// behaviour. The flag is reset BEFORE returning so the next
// command starts clean.
//
// c:Src/glob.c:1876-1880 + Src/exec.c — NOMATCH sets
// ERRFLAG_ERROR but C's execlist clears the bit per-sublist
// so subsequent commands run. Symmetric with the builtin
// dispatcher's clear at fusevm_bridge.rs:299 — clear it here
// too at the external-command post-command-boundary.
consume_tilde_globsubst_carrier();
if self.current_command_glob_failed.get() {
self.current_command_glob_failed.set(false);
if take_cmd_name_glob_failed() {
self.set_last_status(1);
return 1;
}
crate::ported::utils::errflag.fetch_and(
!crate::ported::zsh_h::ERRFLAG_ERROR,
std::sync::atomic::Ordering::Relaxed,
);
self.set_last_status(1);
return 1;
}
// c:Src/subst.c:505-507 — CSH_NULL_GLOB sibling of the
// NOMATCH gate above, same external-path semantics (skip
// command, `no match`, clear ERRFLAG so the next sublist
// runs).
if consume_badcshglob() {
crate::ported::utils::errflag.fetch_and(
!crate::ported::zsh_h::ERRFLAG_ERROR,
std::sync::atomic::Ordering::Relaxed,
);
self.set_last_status(1);
return 1;
}
let Some((cmd, rest)) = args.split_first() else {
return 0;
};
// Empty command name (e.g. result of an empty `$(false)`
// command-sub being the only word) — zsh: no command runs,
// exit status preserved from prior step. Was hitting the
// "command not found: " path with empty name.
if cmd.is_empty() && rest.is_empty() {
return self.last_status();
}
let rest_vec: Vec<String> = rest.to_vec();
// Update `$_` with the just-arriving argv so the next command
// reads `_=<last_arg>`. Mirrors C zsh's writeback in
// `execcmd_exec` (Src/exec.c). Per `args.last()` semantics,
// when invoked as `cmd a b c`, `$_` becomes "c" — for a bare
// command with no args, `$_` becomes the command name itself.
crate::ported::params::set_zunderscore(args);
// Builtins not in fusevm's name→id table fall through to
// host.exec. Catch them here before the OS-level exec attempts
// to spawn a non-existent binary.
match cmd.as_str() {
"sched" => return dispatch_builtin("sched", rest_vec.clone()),
"echotc" => return dispatch_builtin("echotc", rest_vec.clone()),
"echoti" => return dispatch_builtin("echoti", rest_vec.clone()),
"zpty" => return dispatch_builtin("zpty", rest_vec.clone()),
"ztcp" => return dispatch_builtin("ztcp", rest_vec.clone()),
"zsocket" => {
// c:Src/Modules/socket.c:276 BUILTIN spec — BUILTINS["zsocket"]
// optstr "ad:ltv" parsed by execbuiltin.
return dispatch_builtin("zsocket", rest_vec.clone());
}
"private" => {
// c:Src/Modules/param_private.c:217 — bin_private via
// BUILTINS["private"]. The autoload require_module
// (exec.c:2700-2717) fires inside
// dispatch_builtin_raw, the chokepoint for all routes.
return dispatch_builtin("private", rest_vec.clone());
}
"zformat" => return dispatch_builtin("zformat", rest_vec.clone()),
"zregexparse" => return dispatch_builtin("zregexparse", rest_vec.clone()),
// `unalias`/`unhash`/`unfunction` share `bin_unhash` but
// each carries its own funcid (BIN_UNALIAS / BIN_UNHASH /
// BIN_UNFUNCTION) — dispatch_builtin handles the BUILTINS
// lookup + funcid propagation via execbuiltin.
"unalias" | "unhash" | "unfunction" => {
return dispatch_builtin(cmd.as_str(), rest_vec.clone());
}
// ACTUALLY A ZSH FUNCTION: zmv/zcp/zln/zcalc are zsh autoload
// functions — implemented natively in Rust so `autoload -Uz zmv`
// works without shipping the function source (and without the
// fpath source hanging the parser). The stub guard keeps them command-not-found until autoloaded, exactly like zsh;
// an un-guarded arm ran them for bare `zmv`, diverging from
// `zsh -f; zmv` → "command not found: zmv".
// Only a still-undefined autoload stub takes the native port; a
// defined body runs as the shell function (see
// `autoload_stub_pending`).
"zmv" if autoload_stub_pending("zmv") => {
return crate::extensions::ext_builtins::zmv(&rest_vec, "mv")
}
"zcp" if autoload_stub_pending("zcp") => {
return crate::extensions::ext_builtins::zmv(&rest_vec, "cp")
}
"zln" if autoload_stub_pending("zln") => {
return crate::extensions::ext_builtins::zmv(&rest_vec, "ln")
}
"zcalc" if autoload_stub_pending("zcalc") => {
return crate::extensions::ext_builtins::zcalc(&rest_vec)
}
"zselect" => {
// Route through canonical dispatch_builtin which goes
// via execbuiltin → BUILTINS["zselect"] (zselect.c:272).
return dispatch_builtin("zselect", rest_vec.clone());
}
"cap" => return dispatch_builtin("cap", rest_vec.clone()),
"getcap" => return dispatch_builtin("getcap", rest_vec.clone()),
"setcap" => return dispatch_builtin("setcap", rest_vec.clone()),
"yes" => return self.builtin_yes(&rest_vec),
"nl" => return self.builtin_nl(&rest_vec),
"env" => return self.builtin_env(&rest_vec),
"printenv" => return self.builtin_printenv(&rest_vec),
"tty" => return self.builtin_tty(&rest_vec),
// c:Src/Modules/files.c:806 — BUILTINS["chgrp"] with
// BIN_CHGRP funcid + "hRs" optstr.
"chgrp" => return dispatch_builtin("chgrp", rest_vec.clone()),
"nproc" => return self.builtin_nproc(&rest_vec),
"expr" => return self.builtin_expr(&rest_vec),
"sha256sum" => return self.builtin_sha256sum(&rest_vec),
"base64" => return self.builtin_base64(&rest_vec),
"tac" => return self.builtin_tac(&rest_vec),
"expand" => return self.builtin_expand(&rest_vec),
"unexpand" => return self.builtin_unexpand(&rest_vec),
"paste" => return self.builtin_paste(&rest_vec),
"fold" => return self.builtin_fold(&rest_vec),
"shuf" => return self.builtin_shuf(&rest_vec),
"comm" => return self.builtin_comm(&rest_vec),
"cksum" => return self.builtin_cksum(&rest_vec),
"factor" => return self.builtin_factor(&rest_vec),
"tsort" => return self.builtin_tsort(&rest_vec),
"sum" => return self.builtin_sum(&rest_vec),
"mkfifo" => return self.builtin_mkfifo(&rest_vec),
"link" => return self.builtin_link(&rest_vec),
"unlink" => return self.builtin_unlink(&rest_vec),
"dircolors" => return self.builtin_dircolors(&rest_vec),
"groups" => return self.builtin_groups(&rest_vec),
"arch" => return self.builtin_arch(&rest_vec),
"nice" => return self.builtin_nice(&rest_vec),
"logname" => return self.builtin_logname(&rest_vec),
"tput" => return self.builtin_tput(&rest_vec),
"users" => return self.builtin_users(&rest_vec),
// "sync" => return self.bin_sync(&rest_vec),
"zbuild" => return self.builtin_zbuild(&rest_vec),
// `zf_*` aliases from `zsh/files` (Src/Modules/files.c
// BUILTIN table at line 816-824). The C source binds
// both unprefixed (`chmod`) and prefixed (`zf_chmod`)
// names to the SAME `bin_chmod` etc. handlers — the
// prefixed forms exist so a script can portably reach
// the builtin even when a function or alias has shadowed
// the bare name. Each arm routes through the canonical
// zf_* aliases route through canonical BUILTINS entries
// (files.c:816-824) — execbuiltin parses each fn's optstr
// automatically.
"mkdir" | "zf_mkdir" | "zf_rm" | "zf_rmdir" | "zf_chmod" | "zf_chown" | "zf_chgrp"
| "zf_ln" | "zf_mv" | "zf_sync"
// `--zsh` parity gate: zsh -fc has zsh/files UNLOADED
// — bare `mkdir` is /bin/mkdir (so `command mkdir -p`
// honors the system flag set; zconvey.plugin.zsh:44
// got "File exists" from the in-process bin_mkdir
// that this arm intercepted) and `zf_*` names are
// command-not-found 127 until `zmodload zsh/files`.
// Fall through to the external/exec path in --zsh
// mode; default zshrs mode keeps the anti-fork
// intercept.
if !crate::IS_ZSH_MODE.load(std::sync::atomic::Ordering::Relaxed) =>
{
return dispatch_builtin(cmd.as_str(), rest_vec.clone());
}
// `zstat` — port of zsh/stat module (Src/Modules/stat.c
// BUILTIN("zstat", …)). Returns file metadata as
// `field value` pairs / an assoc / a plus-separated
// list depending on flags. zsh ALSO registers `stat`
// bound to the same handler, but that name conflicts
// with the system `stat(1)` binary (every script that
// calls `stat -f '%Lp' …` would break). zsh resolves
// this through opt-in `zmodload`; zshrs's modules are
// statically linked so we keep `stat` routing to the
// external command and only intercept the unambiguous
// `zstat` name.
"zstat" => {
// Canonical bin_stat per stat.c:638 via BUILTINS["zstat"].
return dispatch_builtin("zstat", rest_vec.clone());
}
_ => {}
}
// AOP intercepts: when an `intercept :before/:around/:after foo` block
// is registered, dynamic-command-name dispatch must consult it before
// spawning. Without this, `cmd=ls; $cmd` bypasses every intercept that
// a literal `ls` would trigger. The full_cmd string mirrors what the
// tree-walker era passed (cmd + args joined by space) so existing
// pattern matchers continue to work.
if !self.intercepts.is_empty() {
let full_cmd = if rest_vec.is_empty() {
cmd.clone()
} else {
format!("{} {}", cmd, rest_vec.join(" "))
};
if let Some(intercept_result) = self.run_intercepts(cmd, &full_cmd, &rest_vec) {
return intercept_result.unwrap_or(127);
}
}
// User-defined function lookup before OS-level exec. zsh's
// dynamic-command-name dispatch (`cmd=hook1; $cmd`) checks
// the function table FIRST — without this, `$f` for a
// function-name `f` was always falling through to
// `execute_external` and erroring "command not found".
// Plugin code uses this pattern constantly:
// for f in "${precmd_functions[@]}"; do "$f"; done
if self.function_exists(cmd) {
if let Some(status) = self.dispatch_function_call(cmd, &rest_vec) {
return status;
}
}
EXEC_DASH.with(|c| c.set(exec_dash));
self.execute_external(cmd, &rest_vec, &[]).unwrap_or(127)
}
}
#[cfg(test)]
mod word_assemble_tests {
use super::{word_assemble_plan9, Value};
fn arr(xs: &[&str]) -> Value {
Value::array(xs.iter().map(|s| Value::str(*s)).collect())
}
fn out(v: Value) -> Vec<String> {
match v {
Value::Array(items) => items.iter().map(|i| i.to_str()).collect(),
other => vec![other.to_str()],
}
}
// The edge-tracking fold (c:Src/subst.c:4316-4437). A naive per-segment
// operator gets s,p,p and p,s,p wrong because it forgets which trailing
// elements are still the "growing edge". These pin the exact zsh output
// (verified against zsh 5.9) for every plan9/splice permutation.
#[test]
fn plan9_then_splice() {
// "${(@)^a}${(@)b}" a=(1 2) b=(A B) -> 1A 2A B
let r = word_assemble_plan9(&[arr(&["1", "2"]), arr(&["A", "B"])], &[true, false]);
assert_eq!(out(r), vec!["1A", "2A", "B"]);
}
#[test]
fn splice_then_plan9() {
// "${(@)a}${(@)^b}" -> 1 2A 2B
let r = word_assemble_plan9(&[arr(&["1", "2"]), arr(&["A", "B"])], &[false, true]);
assert_eq!(out(r), vec!["1", "2A", "2B"]);
}
#[test]
fn plan9_then_plan9_is_full_cross() {
let r = word_assemble_plan9(&[arr(&["1", "2"]), arr(&["A", "B"])], &[true, true]);
assert_eq!(out(r), vec!["1A", "1B", "2A", "2B"]);
}
#[test]
fn splice_then_splice() {
let r = word_assemble_plan9(&[arr(&["1", "2"]), arr(&["A", "B"])], &[false, false]);
assert_eq!(out(r), vec!["1", "2A", "B"]);
}
#[test]
fn plan9_splice_plan9_growing_edge() {
// "${(@)^a}${(@)b}${(@)^c}" -> 1A 2A Bp Bq (only B, the edge, distributes)
let r = word_assemble_plan9(
&[arr(&["1", "2"]), arr(&["A", "B"]), arr(&["p", "q"])],
&[true, false, true],
);
assert_eq!(out(r), vec!["1A", "2A", "Bp", "Bq"]);
}
#[test]
fn splice_plan9_plan9_keeps_frozen_prefix() {
// "${(@)a}${(@)^b}${(@)^c}" -> 1 2Ap 2Aq 2Bp 2Bq (1 stays frozen)
let r = word_assemble_plan9(
&[arr(&["1", "2"]), arr(&["A", "B"]), arr(&["p", "q"])],
&[false, true, true],
);
assert_eq!(out(r), vec!["1", "2Ap", "2Aq", "2Bp", "2Bq"]);
}
#[test]
fn empty_plan9_array_deletes_word() {
// "${(@)^a}${(@)b}" with a=() -> word deleted
let r = word_assemble_plan9(&[Value::array(vec![]), arr(&["A", "B"])], &[true, false]);
assert!(out(r).is_empty(), "plan9 empty array deletes the word");
}
#[test]
fn leading_literal_then_mixed() {
// "X${(@)^a}${(@)b}" -> X1A X2A B
let r = word_assemble_plan9(
&[Value::str("X"), arr(&["1", "2"]), arr(&["A", "B"])],
&[false, true, false],
);
assert_eq!(out(r), vec!["X1A", "X2A", "B"]);
}
// c:Src/subst.c:4261 — a NON-plan9 empty expansion collapses to the empty
// string and the word SURVIVES; only plan9 (c:4362 `uremnode`) deletes it.
// A leading empty segment used to leave `words` empty, so every following
// segment cross-multiplied against nothing and the word vanished.
// Verified against zsh 5.9:
// n=""; a=(x y z); print -rl -- $n${^a} -> x / y / z
#[test]
fn leading_empty_splice_keeps_word_and_crosses() {
let r = word_assemble_plan9(
&[Value::array(vec![]), arr(&["x", "y", "z"])],
&[false, true],
);
assert_eq!(out(r), vec!["x", "y", "z"]);
}
// n=""; a=(x y z); print -rl -- $n"pre"${^a} -> prex / prey / prez
#[test]
fn leading_empty_then_literal_then_plan9() {
let r = word_assemble_plan9(
&[
Value::array(vec![]),
Value::str("pre"),
arr(&["x", "y", "z"]),
],
&[false, false, true],
);
assert_eq!(out(r), vec!["prex", "prey", "prez"]);
}
// n=""; a=(x y z); print -rl -- $n$a${^a} -> x / y / zx / zy / zz
// The leading empty must not consume the splice's first element.
#[test]
fn leading_empty_does_not_eat_first_splice_element() {
let r = word_assemble_plan9(
&[
Value::array(vec![]),
arr(&["x", "y", "z"]),
arr(&["x", "y", "z"]),
],
&[false, false, true],
);
assert_eq!(out(r), vec!["x", "y", "zx", "zy", "zz"]);
}
// n=""; e=(); print -rl -- $n${^e} -> nothing (plan9 empty still wins)
#[test]
fn leading_empty_then_empty_plan9_still_deletes_word() {
let r = word_assemble_plan9(
&[Value::array(vec![]), Value::array(vec![])],
&[false, true],
);
assert!(
out(r).is_empty(),
"plan9 empty array still deletes the word"
);
}
}
// ═══════════════════════════════════════════════════════════════════════
// Compiled-arithmetic value plumbing.
//
// !!! WARNING: RUST-ONLY HELPERS !!!
//
// C has no equivalent of these: `Src/math.c` keeps every operand in an
// `mnumber` on its own value stack, so an operator arm reads `a.u.l` /
// `b.u.d` directly and never converts anything. zshrs's compiled path
// keeps operands as `fusevm::Value` on the VM stack instead, so the two
// representations have to meet at each builtin boundary. `arith_div` /
// `arith_mod` / `arith_pow` below ARE line-by-line ports of their C
// arms; only the `Value` ↔ `mnumber` conversion is Rust-only.
// ═══════════════════════════════════════════════════════════════════════
/// Pop one VM value as an `mnumber`.
///
/// `Bool` appears because the comparison ops (`Op::NumLt` and friends)
/// push one; c:Src/math.c:1200 gives those operators integer 1/0, so
/// that is what a `Bool` becomes here. A `Str` reaching this point is a
/// value the compiler could not prove numeric; c:Src/math.c:337
/// `getmathparam` coerces such a string through the math evaluator,
/// which `matheval_str_operand` mirrors.
pub(crate) fn arith_pop_mnumber(vm: &mut fusevm::VM) -> crate::ported::zsh_h::mnumber {
use crate::ported::zsh_h::{mnumber, MN_FLOAT, MN_INTEGER};
match vm.pop() {
fusevm::Value::Int(n) => mnumber { l: n, d: 0.0, type_: MN_INTEGER },
fusevm::Value::Float(f) => mnumber { l: 0, d: f, type_: MN_FLOAT },
fusevm::Value::Bool(b) => mnumber { l: i64::from(b), d: 0.0, type_: MN_INTEGER },
other => {
let s = other.to_str();
if s.is_empty() {
// c:Src/math.c:345 — an unset/empty parameter is 0.
mnumber { l: 0, d: 0.0, type_: MN_INTEGER }
} else {
// c:Src/params.c:2646-2647 `matheval(getstrvalue(v))` —
// the default arm of getnumvalue, which re-lexes a
// scalar's string form. A math error reads as 0, as C's
// does after `zerr`.
crate::ported::math::matheval(&s).unwrap_or(mnumber {
l: 0,
d: 0.0,
type_: MN_INTEGER,
})
}
}
}
}
/// The inverse: an `mnumber` back onto the VM stack.
pub(crate) fn arith_push(n: crate::ported::zsh_h::mnumber) -> fusevm::Value {
if n.type_ == crate::ported::zsh_h::MN_FLOAT {
fusevm::Value::Float(n.d)
} else {
fusevm::Value::Int(n.l)
}
}
/// c:Src/math.c:1144 `notzero` — an INTEGER zero is a math error; a
/// float zero is not (it divides to an infinity).
pub(crate) fn mn_notzero(a: crate::ported::zsh_h::mnumber) -> bool {
if a.type_ & crate::ported::zsh_h::MN_INTEGER != 0 && a.l == 0 {
crate::ported::utils::zerr("division by zero"); // c:1147
return false; // c:1148
}
true // c:1150
}
/// Truthiness of an `mnumber` — c:Src/math.c:1200's `BOOL` reading,
/// where the operand is compared against zero in its own type.
pub(crate) fn mn_is_true(a: crate::ported::zsh_h::mnumber) -> bool {
if a.type_ == crate::ported::zsh_h::MN_FLOAT {
a.d != 0.0
} else {
a.l != 0
}
}
/// c:Src/math.c:1178-1183 — the two operands of an `OP_A2` operator are
/// promoted to float if EITHER is float; the result carries that type.
pub(crate) fn mn_promote(
a: crate::ported::zsh_h::mnumber,
b: crate::ported::zsh_h::mnumber,
) -> (crate::ported::zsh_h::mnumber, crate::ported::zsh_h::mnumber, u32) {
use crate::ported::zsh_h::{mnumber, MN_FLOAT};
if a.type_ == MN_FLOAT || b.type_ == MN_FLOAT {
let af = if a.type_ == MN_FLOAT { a.d } else { a.l as f64 };
let bf = if b.type_ == MN_FLOAT { b.d } else { b.l as f64 };
(
mnumber { l: 0, d: af, type_: MN_FLOAT },
mnumber { l: 0, d: bf, type_: MN_FLOAT },
MN_FLOAT,
)
} else {
(a, b, a.type_)
}
}
/// Port of the `DIV` / `DIVEQ` arm, c:Src/math.c:1237-1257.
pub(crate) fn arith_div(
a: crate::ported::zsh_h::mnumber,
b: crate::ported::zsh_h::mnumber,
) -> crate::ported::zsh_h::mnumber {
use crate::ported::zsh_h::{mnumber, MN_FLOAT};
let (a, b, ctype) = mn_promote(a, b);
let mut c = mnumber { l: 0, d: 0.0, type_: ctype };
if !mn_notzero(b) {
return c; // c:1240
}
if ctype == MN_FLOAT {
c.d = a.d / b.d; // c:1242
} else if b.l == -1 {
// c:1244-1251 — avoid the INT_MIN / -1 trap by treating it as
// multiplication, exactly as C does.
c.l = a.l.wrapping_neg(); // c:1253
} else {
c.l = a.l / b.l; // c:1255
}
c
}
/// Port of the `MOD` / `MODEQ` arm, c:Src/math.c:1258-1272.
pub(crate) fn arith_mod(
a: crate::ported::zsh_h::mnumber,
b: crate::ported::zsh_h::mnumber,
) -> crate::ported::zsh_h::mnumber {
use crate::ported::zsh_h::{mnumber, MN_FLOAT};
let (a, b, ctype) = mn_promote(a, b);
let mut c = mnumber { l: 0, d: 0.0, type_: ctype };
if !mn_notzero(b) {
return c; // c:1261
}
if ctype == MN_FLOAT {
c.d = a.d % b.d; // c:1268 fmod
} else if b.l == -1 {
c.l = 0; // c:1270
} else {
c.l = a.l % b.l; // c:1272
}
c
}
/// Port of the `POWER` / `POWEREQ` arm, c:Src/math.c:1335-1358.
pub(crate) fn arith_pow(
a: crate::ported::zsh_h::mnumber,
b: crate::ported::zsh_h::mnumber,
) -> crate::ported::zsh_h::mnumber {
use crate::ported::zsh_h::{mnumber, MN_FLOAT, MN_INTEGER};
let (mut a, mut b, mut ctype) = mn_promote(a, b);
if ctype == MN_INTEGER && b.l < 0 {
// c:1337-1342 — a negative integer exponent produces a real
// result, so both operands are cast to real first.
a = mnumber { l: 0, d: a.l as f64, type_: MN_FLOAT };
b = mnumber { l: 0, d: b.l as f64, type_: MN_FLOAT };
ctype = MN_FLOAT;
}
let mut c = mnumber { l: 0, d: 0.0, type_: ctype };
if ctype == MN_INTEGER {
// c:1344 `for (c.u.l = 1; b.u.l--; c.u.l *= a.u.l);`
c.l = 1;
let mut n = b.l;
while n > 0 {
c.l = c.l.wrapping_mul(a.l);
n -= 1;
}
} else {
if b.d <= 0.0 && !mn_notzero(a) {
return c; // c:1346-1347
}
if a.d < 0.0 {
// c:1348-1355 — a negative base to a non-integer power is
// imaginary.
let tst = b.d as i64 as f64;
if tst != b.d {
crate::ported::utils::zerr("bad math expression: imaginary power"); // c:1352
return c; // c:1353
}
}
c.d = a.d.powf(b.d); // c:1356
}
c
}
/// Body of `BUILTIN_SET_LINENO`, factored out so
/// `BUILTIN_STMT_PROLOGUE_FAST` can perform the same write without a
/// second indirect call. c:Src/exec.c:1355/1451/2056 `lineno = code - 1`.
pub(crate) fn set_lineno_impl(n: i64) -> fusevm::Value {
// A statement boundary holds no lock: reap and run any signal `zhandler` deferred
// because the previous statement was inside the parameter or job table.
if crate::ported::signals::queueing_enabled.load(std::sync::atomic::Ordering::SeqCst) == 0 {
crate::ported::signals_h::run_queued_signals();
}
// !!! DASH-FAITHFUL GATE (no C counterpart) !!! dash numbers a function body
// from the line of its definition as 1; zsh (c:Src/exec.c:1355 `lineno =
// code - 1`, function-relative) leaves that line at 0.
let n = if crate::dash_mode::dash_faithful()
&& crate::ported::modules::parameter::FUNCSTACK
.lock()
.unwrap_or_else(|e| e.into_inner())
.last()
.is_some_and(|f| f.tp == crate::ported::zsh_h::FS_FUNC)
{
n + 1
} else {
n
};
// c:Src/exec.c:1355 — `/* In evaluated traps, don't modify the
// line number. */ if (!IN_EVAL_TRAP() && !ineval && code)
// lineno = code - 1;` (same gate at c:1451 and c:2056).
// `ineval` is set by `eval()` to `!isset(EVALLINENO)`
// (Src/builtin.c:6155), so under NO_EVAL_LINENO the eval body
// must NOT renumber $LINENO — the caller's line stands.
//
// c:1354 — `/* In evaluated traps, don't modify the line number. */`
// The `IN_EVAL_TRAP()` half of the same gate was missing, so an
// eval-form trap body (`trap 'print $LINENO' DEBUG`) renumbered
// $LINENO to its own line 1 and — because nothing restores
// `lineno` on the way out (C does, via execlist's oldlineno
// save/restore at c:1429/1696) — every later statement in the
// trapped scope reported line 1 as well.
if crate::ported::zsh_h::IN_EVAL_TRAP()
|| crate::ported::builtin::ineval.load(std::sync::atomic::Ordering::Relaxed) != 0
{
return Value::Status(0);
}
// Provenance: mirror the line into the lineage ledger's own
// counter. The param-write hooks run inside the parameter
// table's lock, so they cannot read `$LINENO` back out of it.
if crate::provenance::active() {
crate::provenance::note_line(n.max(0) as usize);
}
// c:Src/exec.c:lineno = N — direct write to the param's
// u_val. Cannot go through setsparam because LINENO carries
// PM_READONLY (so `(t)LINENO` reads `integer-readonly-special`
// per zsh); setsparam → assignstrvalue's PM_READONLY guard
// would reject the internal write. C zsh handles this via the
// PM_SPECIAL GSU vtable's setfn callback which bypasses the
// generic readonly check; the Rust port writes the canonical
// field directly instead.
if let Ok(mut tab) = crate::ported::params::paramtab().write() {
if let Some(pm) = tab.get_mut("LINENO") {
// c:Src/utils.c:121 `zlong lineno` — the value lives in the C
// GLOBAL, reached through LINENO's GSU. A `typeset -h +g LINENO`
// local shadow has no PM_SPECIAL and no GSU, so C's `lineno = N`
// never touches it; skip the paramtab mirror for the same reason.
if (pm.node.flags & crate::ported::zsh_h::PM_SPECIAL as i32) != 0 {
pm.u_val = n;
pm.node.flags &= !(crate::ported::zsh_h::PM_UNSET as i32);
}
}
}
// Mirror to the file-static `lineno` (utils.c:121) that
// zerrmsg reads at utils.c:301 for the `:N: msg` prefix.
crate::ported::utils::set_lineno(n as i32);
// Also drive lex::LEX_LINENO — zerrmsg (utils.rs:376) reads
// THAT counter for the `name:N:` prefix. C zsh interleaves
// parse and execute per top-level list, so its single
// `lineno` global serves both; zshrs compiles the whole
// script before running, leaving LEX_LINENO parked at EOF.
// Without this write, every runtime zwarn/zerr reported the
// script's LAST line instead of the failing statement's.
crate::ported::lex::set_lineno(n as u64);
// DAP hook — checks breakpoints / step mode / pause-request
// for the line we just landed on. O(1) no-op when DAP is off
// (single atomic load on a OnceLock). Inside `--dap` mode
// this is the call that blocks the executor on a Condvar
// until the IDE sends `continue`. Mirrors strykelang's
// `debugger.should_stop(line) → debugger.prompt(...)` flow.
crate::extensions::dap::check_line(n as u32);
fusevm::Value::Status(0)
}
/// !!! WARNING: RUST-ONLY HELPER — NO DIRECT C COUNTERPART !!!
/// The `if (lastval) { errreturn / errexit }` half of execlist's
/// `sublist_done:` block (c:Src/exec.c:1660-1680), shared by the normal
/// check and the retflag-escape check of BUILTIN_ERREXIT_CHECK: C runs it
/// at EVERY sublist_done, including the one a `return 1` just ended.
/// Returns the builtin's result (1 = unwind this scope).
fn errexit_tail(last: i32) -> Value {
use std::sync::atomic::Ordering;
// c:Src/exec.c:1605-1610 — compute errreturn / errexit.
// errreturn = ERRRETURN && (INTERACTIVE || locallevel || sourcelevel)
// && !(noerrexit & NOERREXIT_RETURN)
// errexit = (ERREXIT || (ERRRETURN && !errreturn))
// && !(noerrexit & NOERREXIT_EXIT)
let no_err = crate::ported::exec::noerrexit.load(Ordering::Relaxed);
let locallvl = crate::ported::params::locallevel.load(Ordering::Relaxed);
let sourcelvl = crate::ported::init::sourcelevel.load(Ordering::Relaxed);
let errreturn_opt = isset(crate::ported::zsh_h::ERRRETURN);
let in_unwindable_scope =
isset(crate::ported::zsh_h::INTERACTIVE) || locallvl != 0 || sourcelvl != 0;
let errreturn = errreturn_opt
&& in_unwindable_scope
&& (no_err & crate::ported::zsh_h::NOERREXIT_RETURN) == 0;
let (errexit_on, in_subshell) = with_executor(|exec| {
let on_canonical = isset(ERREXIT) || (errreturn_opt && !errreturn); // c:1608-1609
let on_legacy = opt_state_get("errexit").unwrap_or(false);
(
(on_canonical || on_legacy) && (no_err & crate::ported::zsh_h::NOERREXIT_EXIT) == 0,
!exec.subshell_snapshots.is_empty(),
)
});
if !errexit_on {
// c:1667-1674 — `if (errexit) { … realexit(); }` comes FIRST;
// `if (errreturn) { retflag = 1; breaks = loops; }` only matters
// when the shell did not exit. With both options set inside a
// function, ERR_EXIT wins.
if errreturn {
// c:1675-1678 — unwind to the function boundary without
// exiting the shell.
crate::ported::builtin::RETFLAG.store(1, Ordering::Relaxed);
let loops = crate::ported::builtin::LOOPS.load(Ordering::Relaxed);
crate::ported::builtin::BREAKS.store(loops, Ordering::Relaxed);
return Value::Int(1);
}
return Value::Int(0);
}
// c:Src/exec.c:1611-1618 — under ERR_EXIT a failing command exits the
// whole shell via realexit() FROM THE POINT OF FAILURE, before any
// enclosing `always` arm can run. zsh 5.9.2 (the reference) has no
// `this_noerrexit` deferral, so at top-level / function scope the
// faithful behavior is to process-exit here (zexit fires the SIGEXIT
// trap and exits). This bypasses the always arm, fixing
// `setopt errexit; { false } always { print A }` which wrongly ran the
// always body: the deferred EXIT_PENDING routed the unwind through
// always_entry (compile_zsh.rs re-points it there) and
// SET_TRY_BLOCK_ERROR then cleared the pending exit so the body ran.
if crate::ported::builtin::SUBSHELL_DEPTH.load(Ordering::Relaxed) == 0 {
crate::ported::builtin::zexit(last, crate::ported::zsh_h::ZEXIT_NORMAL);
// c:1618 realexit
}
// Subshell: zshrs runs subshells in-process, so it cannot process-exit
// the whole shell here — defer to the subshell-end unwind.
crate::ported::builtin::EXIT_VAL.store(last, Ordering::Relaxed);
crate::ported::builtin::EXIT_PENDING.store(1, Ordering::Relaxed);
let _ = in_subshell;
Value::Int(1)
}
/// !!! WARNING: RUST-ONLY HELPER — NO DIRECT C COUNTERPART !!!
/// `sigtrapped[SIGZERR]` (c:Src/exec.c:1652) read through the port's
/// mutex-guarded `sigtrapped` table. C indexes the array inline.
fn zerr_sigtrapped() -> bool {
// !!! BASH-MODE (no C counterpart) !!! bash(1) `set -E`: "the ERR trap is
// inherited by shell functions, command substitutions, and commands executed
// in a subshell environment" — without it the trap is silent inside a function.
if crate::extensions::dash_mode::bash_mode()
&& crate::ported::params::locallevel.load(std::sync::atomic::Ordering::Relaxed) > 0
&& !crate::extensions::dash_mode::bash_set_o_get("errtrace")
{
return false;
}
crate::ported::signals::sigtrapped
.lock()
.ok()
.is_some_and(|st| st.get(crate::ported::signals_h::SIGZERR as usize).is_some_and(|&s| s != 0))
}
/// Body of `BUILTIN_DONETRAP_RESET`, factored out for the same reason.
/// c:Src/exec.c:1455 `donetrap = 0`.
pub(crate) fn donetrap_reset_impl() -> fusevm::Value {
// c:Src/jobs.c:651-652 — a CHLD trap update_bg_job owed while the
// shell was not in a wait loop. C runs it from the SIGCHLD handler;
// a trap body run from zshrs's handler can block on a mutex the
// interrupted statement holds, so it runs here, at the next
// statement prologue (c:Src/exec.c:1451-1455).
for _ in 0..crate::ported::jobs::CHLD_TRAP_PENDING.swap(0, std::sync::atomic::Ordering::SeqCst) {
crate::ported::signals::dotrap(libc::SIGCHLD);
}
// c:Src/jobs.c:658-678 — the trapped SIGINT/SIGQUIT pseudo-delivery
// update_job parked in PSEUDO_SIG_TRAP_PENDING (a trap body cannot
// run under the JOBTAB guard update_job holds).
let pseudo = crate::ported::jobs::PSEUDO_SIG_TRAP_PENDING.swap(0, std::sync::atomic::Ordering::SeqCst);
if pseudo != 0 {
crate::ported::signals::dotrap(pseudo); // c:663
if crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed) != 0 {
crate::ported::builtin::BREAKS.store(
crate::ported::builtin::LOOPS.load(std::sync::atomic::Ordering::Relaxed),
std::sync::atomic::Ordering::Relaxed,
); // c:671-672
}
if let Some(tab) = crate::ported::jobs::JOBTAB.get() {
crate::ported::jobs::check_cursh_sig(&tab.lock().unwrap_or_else(|e| e.into_inner()), pseudo); // c:677
}
}
// c:Src/exec.c:1455 — `donetrap = 0;` at sublist start.
// Reset before each top-level statement so the next
// sublist's ERREXIT_CHECK fires the ZERR trap on its FIRST
// non-zero command. Carries the "already fired" state
// across function-call returns within the SAME outer
// sublist (per C semantics — donetrap is process-global).
// Bug #303 in docs/BUGS.md.
crate::ported::exec::DONETRAP.store(0, std::sync::atomic::Ordering::Relaxed);
// `${~spec}` carrier: C's `globsubst` is a paramsubst-LOCAL
// int (c:Src/subst.c:1671 `int globsubst = isset(GLOBSUBST);`,
// set to 2 by `${~}` at c:2597-2603) whose only effect is the
// `shtokenize()` of THAT substitution's own result
// (c:4419-4420). It can therefore never be observed by a later
// statement. zshrs carries the flag on the global option table
// (subst.rs:5125-5136) so the compile-emitted glob ops in the
// same word pipeline can see it, and restores it at
// command-dispatch boundaries — but a `${~}` sitting in a word
// that dispatches NO command (a `for`/`select` word list, a
// loop/`case` header) had no such boundary before the NEXT
// statement's words were expanded, so GLOB_SUBST leaked into
// them. This op is emitted exactly once per sublist, in
// compile_list's prologue (compile_zsh.rs:557) — i.e. BEFORE
// the sublist's words expand — which is the same "state is
// gone by the next statement" guarantee C gets for free.
// Without it, `_parameters`' `for i in ${…:#${~pfilt}*}` loop
// globbed its `ary+=($i:"$val")` body word and died with
// "bad pattern: HISTCHARS:!^#", killing `-<TAB>` completion.
consume_tilde_globsubst_carrier();
fusevm::Value::Status(0)
}
#[cfg(test)]
mod foreground_wait_guard_tests {
use super::ForegroundWaitGuard;
/// c:Src/jobs.c:1638-1669 — the mask a foreground wait presents.
///
/// C blocks for a child inside `signal_suspend(SIGCHLD, wait_cmd)`
/// (c:1658 / c:1710), and that call's sigsuspend mask is EMPTY —
/// c:Src/signals.c:216-232 does `sigemptyset(&set)` and adds at most a
/// conditional SIGINT. SIGCHLD is held off by `child_block()` (c:1642,
/// "unblocked in signal_suspend()") rather than by userspace queueing.
/// So while the shell waits: SIGCHLD blocked, SIGWINCH deliverable.
///
/// This guard used to call `queue_signals()` and nothing else, which
/// left the standing `winch_block()` (c:Src/init.c:1458, re-armed by
/// preprompt at c:Src/utils.c:1541) in force for the whole of any
/// command — so a resize was invisible to a completion however many
/// children it forked, and `trashzle`'s repaint
/// (c:Src/Zle/compresult.c:1922 → c:Src/Zle/zle_main.c:2071-2095) never
/// saw the `resetneeded`/`winchanged` that c:Src/utils.c:1956-1958
/// raises.
#[test]
fn foreground_wait_unblocks_sigwinch_and_blocks_sigchld() {
let _g = crate::test_util::global_state_lock();
let blocked = |sig: libc::c_int| -> bool {
unsafe {
let mut cur: libc::sigset_t = std::mem::zeroed();
libc::sigemptyset(&mut cur);
libc::pthread_sigmask(libc::SIG_BLOCK, std::ptr::null(), &mut cur);
libc::sigismember(&cur, sig) == 1
}
};
let saved_winch = blocked(libc::SIGWINCH);
let saved_chld = blocked(libc::SIGCHLD);
// The standing mask between prompts (c:Src/utils.c:1541).
crate::ported::signals_h::winch_block();
crate::ported::signals_h::child_unblock();
assert!(blocked(libc::SIGWINCH), "precondition: winch_block() holds");
let (winch_in, chld_in) = {
let _w = ForegroundWaitGuard::enter();
(blocked(libc::SIGWINCH), blocked(libc::SIGCHLD))
};
let winch_out = blocked(libc::SIGWINCH);
if !saved_winch {
crate::ported::signals_h::winch_unblock();
}
if saved_chld {
crate::ported::signals_h::child_block();
} else {
crate::ported::signals_h::child_unblock();
}
assert!(
!winch_in,
"a foreground wait is C's one mid-command delivery point for \
SIGWINCH (c:Src/signals.c:216-232 — signal_suspend's mask is empty)"
);
assert!(
chld_in,
"c:Src/jobs.c:1642 — `child_block(); /* unblocked in signal_suspend() */`"
);
assert!(
winch_out,
"c:Src/utils.c:1541 — the standing winch_block() comes back after the wait"
);
}
}
#[cfg(test)]
mod builtin_completer_coverage_tests {
use super::registered_builtin;
/// Every zshrs-original builtin ships a completer in `completions/`
/// (bundled into `~/.zshrs/functions` by build.rs), so `name <TAB>` and
/// `name -<TAB>` offer its arguments instead of nothing. zsh's own
/// completion tree cannot cover these: the commands do not exist there.
///
/// The set: the in-process builtins [`registered_builtin`] dispatches
/// (taken from `EXT_BUILTIN_NAMES`), the ztest framework, and the
/// daemon-backed `z*` builtins. `pgrep` is left out: it stands in for the
/// external `pgrep`, which zsh's stock `_pgrep` already completes.
#[test]
fn every_zshrs_builtin_has_a_completer() {
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("completions");
let mut claimed = std::collections::HashSet::new();
for entry in std::fs::read_dir(&dir).expect("completions/") {
let path = entry.expect("dir entry").path();
let Ok(text) = std::fs::read_to_string(&path) else { continue };
if let Some(line) = text.lines().next().and_then(|l| l.strip_prefix("#compdef ")) {
claimed.extend(line.split_whitespace().map(str::to_string));
}
}
let names = crate::ext_builtins::EXT_BUILTIN_NAMES
.iter()
.filter(|n| registered_builtin(n).is_some() && **n != "pgrep")
.chain(crate::extensions::ztest::ZTEST_BUILTIN_NAMES)
.chain(crate::daemon::builtins::ZSHRS_BUILTIN_NAMES);
let missing: Vec<&str> = names.copied().filter(|n| !claimed.contains(*n)).collect();
assert!(
missing.is_empty(),
"zshrs builtins with no `#compdef` completer in completions/: {missing:?}"
);
}
}
#[cfg(test)]
mod function_shadows_builtin_tests {
//! c:Src/exec.c:3485-3489 — command lookup consults `shfunctab` before
//! `builtintab`, so a shell function shadows a builtin of the same name.
//! The zshrs-only builtins dispatched by name in `call_function` (daemon
//! z* family, ztest_*, znative) used to be matched before that check.
use crate::vm_helper::ShellExecutor;
fn run(script: &str) -> (ShellExecutor, i32) {
let mut exec = ShellExecutor::new();
let st = exec.execute_script(script).unwrap_or(-1);
(exec, st)
}
#[test]
fn function_shadows_daemon_z_builtin() {
let _g = crate::test_util::global_state_lock();
let (exec, _) = run("hit=; zls() { hit=fn; return 42 }; zls; st=$?");
assert_eq!(exec.scalar("hit").as_deref(), Some("fn"));
assert_eq!(exec.scalar("st").as_deref(), Some("42"));
}
#[test]
fn function_shadows_extension_builtin() {
let _g = crate::test_util::global_state_lock();
let (exec, _) =
run("hit=; basename() { hit=fn; return 43 }; basename a/b; st=$?");
assert_eq!(exec.scalar("hit").as_deref(), Some("fn"));
assert_eq!(exec.scalar("st").as_deref(), Some("43"));
}
#[test]
fn builtin_prefix_and_disable_f_bypass_the_function() {
let _g = crate::test_util::global_state_lock();
// c:Src/exec.c:3483-3487 — after `builtin`, shfunctab is skipped.
let (exec, _) = run(
"hit=; zls() { hit=fn; return 42 }; builtin zls >/dev/null 2>&1; st=$?",
);
assert_eq!(exec.scalar("hit").as_deref(), Some(""));
assert_ne!(exec.scalar("st").as_deref(), Some("42"));
// c:Src/hashtable.c:239 — getnode skips a DISABLED shfunc node.
let (exec, _) = run(
"hit=; zls() { hit=fn; return 42 }; disable -f zls; zls >/dev/null 2>&1; st=$?",
);
assert_eq!(exec.scalar("hit").as_deref(), Some(""));
assert_ne!(exec.scalar("st").as_deref(), Some("42"));
}
}
#[cfg(test)]
mod zmv_native_autoload_tests {
//! zmv/zcp/zln/zcalc are zsh autoload functions with native ports. The
//! port stands in only for loading a PM_UNDEFINED stub (c:Src/exec.c:
//! 5691-5695); a defined body is an ordinary shell function.
use crate::vm_helper::ShellExecutor;
fn run(script: &str) -> ShellExecutor {
let mut exec = ShellExecutor::new();
let _ = exec.execute_script(script);
exec
}
#[test]
fn user_defined_zmv_and_zcalc_bodies_run() {
let _g = crate::test_util::global_state_lock();
let exec = run("hit=; zmv() { hit=fn; return 44 }; zmv a b; st=$?; unfunction zmv");
assert_eq!(exec.scalar("hit").as_deref(), Some("fn"));
assert_eq!(exec.scalar("st").as_deref(), Some("44"));
let exec = run("hit=; zcalc() { hit=fn; return 45 }; zcalc; st=$?; unfunction zcalc");
assert_eq!(exec.scalar("hit").as_deref(), Some("fn"));
assert_eq!(exec.scalar("st").as_deref(), Some("45"));
}
#[test]
fn undefined_autoload_stub_uses_native_port() {
let _g = crate::test_util::global_state_lock();
// The native zmv prints its own usage and returns 1 for a missing
// pattern pair; the stub stays PM_UNDEFINED, which an fpath load
// (stock zmv body) would have cleared.
let exec = run("autoload -Uz zmv; zmv 2>/dev/null; st=$?");
assert_eq!(exec.scalar("st").as_deref(), Some("1"));
assert!(super::autoload_stub_pending("zmv"));
run("unfunction zmv 2>/dev/null");
}
#[test]
fn disabled_or_absent_zmv_is_command_not_found() {
let _g = crate::test_util::global_state_lock();
let exec = run("zmv 2>/dev/null; st=$?");
assert_eq!(exec.scalar("st").as_deref(), Some("127"));
let exec = run("autoload -Uz zmv; disable -f zmv; zmv 2>/dev/null; st=$?");
assert_eq!(exec.scalar("st").as_deref(), Some("127"));
run("unfunction zmv 2>/dev/null");
}
}
/// !!! BASH-MODE (no C counterpart) !!! Scope guard that holds `KSHGLOB` on
/// (bash `extglob`) for one `[[ … == pattern ]]` match. bash turns extglob on
/// while it parses `[[ ]]`, so `@(…)` / `+(…)` / `*(…)` / `?(…)` / `!(…)`
/// groups work in the pattern with the shopt off. Restores the prior state on
/// drop. Inert outside `--bash`, when the option is already on, or when the
/// pattern has no extended group opener.
struct BashDbracketExtglob {
armed: bool,
}
impl BashDbracketExtglob {
fn enter(pat: &str) -> Self {
use crate::ported::zsh_h::{isset, KSHGLOB};
let has_group = ["@(", "*(", "+(", "?(", "!("].iter().any(|g| pat.contains(g));
let armed = crate::dash_mode::bash_mode() && has_group && !isset(KSHGLOB);
if armed {
crate::ported::options::dosetopt(KSHGLOB, 1, 1);
}
Self { armed }
}
}
impl Drop for BashDbracketExtglob {
fn drop(&mut self) {
if self.armed {
crate::ported::options::dosetopt(crate::ported::zsh_h::KSHGLOB, 0, 1);
}
}
}