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
//! 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) };
/// 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()) };
/// 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.
static TRY_ESCAPE_SAVE: RefCell<Vec<(i32, i32, i32, i32)>> =
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 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) };
}
/// 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() {
use std::io::Write;
let _ = std::io::stderr().write_all(buf.as_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);
}
}
/// 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() {
let depth = PSUB_SCOPE_DEPTH.with(|d| d.get());
PSUB_PENDING_FDS.with(|v| {
v.borrow_mut().retain(|&(d, fd)| {
if d >= depth {
unsafe { libc::close(fd) };
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.
pub fn cmdsubst_outer_stdout() -> Option<i32> {
CMDSUBST_OUTER_FDS.with(|s| s.borrow().last().map(|(o, _)| *o))
}
// 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) };
/// Set by subshell_end after a deferred subshell `exit N` lands.
/// Read + cleared by the next GET_VAR sync_status path so the
/// vm.last_status → LASTVAL sync doesn't clobber the deferred
/// exit status. RUST-ONLY: needed because zshrs runs subshells
/// in-process (no fork) so vm.last_status doesn't track the
/// subshell's exit; C zsh's subshell forks and the child's
/// process::exit(N) becomes $? in the parent automatically.
static SUBSHELL_EXIT_STATUS_PENDING: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// 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) };
}
/// 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
/// a global fallback inside `execute_script_zsh_pipeline`, which would
/// re-enter the executor on nested command substitution and block on
/// input.
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(),
}
}
/// 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() {
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 {
flatten_array_value(it, out);
}
}
other => out.push(other.to_str()),
}
}
/// 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)
}
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,
}
}
pub(crate) fn dispatch_builtin_raw(name: &str, args: Vec<String>) -> i32 {
// 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,
); // 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)
{
return dispatch_builtin_raw("private", args);
}
// 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::module::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.
if crate::IS_ZSH_MODE.load(std::sync::atomic::Ordering::Relaxed)
&& module_gated_files_builtin(name)
&& !crate::ported::module::MODULESTAB
.lock()
.map(|t| t.is_loaded("zsh/files"))
.unwrap_or(false)
{
// 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.
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"
)
}
pub(crate) fn dispatch_builtin(name: &str, 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/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);
}
return 1;
}
// 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.
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
});
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;
}
if let Some(status) = try_user_fn_override(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);
let mut synth = crate::ported::zsh_h::job::default();
crate::ported::jobs::waitonejob(&mut synth);
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.
let disabled = 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);
let mut synth = crate::ported::zsh_h::job::default();
crate::ported::jobs::waitonejob(&mut synth);
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 module_gated_files_builtin(name) {
if !crate::ported::module::MODULESTAB.lock().unwrap().is_loaded("zsh/files") {
// 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);
let mut synth = crate::ported::zsh_h::job::default();
crate::ported::jobs::waitonejob(&mut synth);
return status;
}
}
let status = dispatch_builtin_raw(name, args);
// c:Src/jobs.c:1748 waitonejob — canonical single-command pipestats update.
crate::ported::builtin::LASTVAL.store(status, std::sync::atomic::Ordering::Relaxed);
let mut synth = crate::ported::zsh_h::job::default();
crate::ported::jobs::waitonejob(&mut synth);
// 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)
}
// 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`.
/// Register all zsh builtins with the VM.
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
});
if redir_failed {
return Value::Status(1);
}
// `[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.
if !crate::daemon_presence::coreutils_shadows_enabled() {
return Value::Status(exec_system_command($name, &args));
}
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| {
Value::Status(dispatch_builtin($name, pop_args(vm, argc)))
});
};
}
// 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);
}
let status = dispatch_builtin("cd", args);
// c:Src/builtin.c:1258 — `callhookfunc("chpwd", NULL, 1, NULL)`
// after cd succeeds. The canonical port at
// src/ported/utils.rs:1532 handles both the `chpwd` shfunc
// dispatch AND the `chpwd_functions` array walk.
if status == 0 {
crate::ported::utils::callhookfunc("chpwd", None, 1, std::ptr::null_mut());
}
Value::Status(status)
});
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);
let status = dispatch_builtin("exit", args);
Value::Status(status)
});
vm.register_builtin(BUILTIN_RETURN, |vm, argc| {
let args = pop_args(vm, argc);
// 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);
// 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)
});
vm.register_builtin(BUILTIN_TEST, |vm, argc| {
let args = pop_args(vm, argc);
// Distinguish `[ … ]` from `test …` by sniffing the trailing
// `]` — `[` requires it (c:Src/builtin.c:7241), `test` rejects
// it. The compile path emits BUILTIN_TEST for both, so the
// dispatch name carries the `[` vs `test` semantic for
// execbuiltin's funcid (BIN_BRACKET=21 vs BIN_TEST=20). Without
// this, bin_test's `if func == BIN_BRACKET` arm (which pops
// the trailing `]`) never fired for `[` calls, so the `]`
// leaked into evalcond as a positional and silently changed
// the result. Bug surfaced via test_test_dashdash_unknown_condition.
let name = if args.last().map(|s| s.as_str()) == Some("]") {
"["
} else {
"test"
};
let status = dispatch_builtin(name, args);
Value::Status(status)
});
// 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);
// 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) get a passthru to the canonical
// dispatcher in case a future port adds a real mapfile builtin
// — until then the rc=1 unknown-command default applies.
Value::Status(dispatch_builtin("mapfile", 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);
// 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.
let oscriptname = crate::ported::utils::scriptname_get();
crate::ported::utils::set_scriptname(Some("(eval)".to_string()));
let mut status = with_executor(|exec| {
// c:6175 execode
exec.execute_script(&src).unwrap_or(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);
}
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);
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);
};
// 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();
if !tab.contains_key(name.as_str()) {
eprintln!("zshrs:1: 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.
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);
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/builtin.c:4500 — `command -p` resets PATH for the
// exec to the POSIX-defined default (`getconf PATH`), so
// standard utilities resolve even when the caller has
// emptied $PATH. zsh restores the original PATH after the
// command returns. Mirror via a scoped env::set_var.
//
// 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;
}
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();
let _path_guard = if dash_p {
let saved = env::var("PATH").ok();
let default_path = std::process::Command::new("getconf")
.arg("PATH")
.output()
.ok()
.and_then(|o| String::from_utf8(o.stdout).ok())
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.unwrap_or_else(|| "/usr/bin:/bin:/usr/sbin:/sbin".to_string());
env::set_var("PATH", &default_path);
crate::ported::params::setsparam("PATH", &default_path);
Some(saved)
} else {
None
};
struct PathGuard {
saved: Option<String>,
active: bool,
}
impl Drop for PathGuard {
fn drop(&mut self) {
if !self.active {
return;
}
match self.saved.take() {
Some(p) => {
env::set_var("PATH", &p);
crate::ported::params::setsparam("PATH", &p);
}
None => {
env::remove_var("PATH");
crate::ported::params::setsparam("PATH", "");
}
}
}
}
let _restore = PathGuard {
saved: _path_guard.unwrap_or(None),
active: dash_p,
};
if dispatch.has_command_vv {
// `-v` / `-V` → bin_whence with BIN_COMMAND funcid.
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;
let whence_args: Vec<String> = post[name_pos..].to_vec();
return Value::Status(crate::ported::builtin::bin_whence(
"command",
&whence_args,
&ops,
crate::ported::hashtable_h::BIN_COMMAND,
));
}
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())
{
return Value::Status(dispatch_builtin_raw(&n, r));
}
Value::Status(with_executor(|exec| 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 mut args = pop_args(vm, argc);
let mut argv0_override: Option<String> = None;
let mut clean_env = false;
let mut login = false;
let mut i = 0;
// c:Src/builtin.c:1075-1080 — track if any flag was consumed.
// `exec -c`, `exec -l`, `exec -a NAME` without a following
// command emit "exec requires a command to execute" rc=1.
// Bare `exec` (no args at all) is the silent-redirect-apply
// form per POSIX.
let mut saw_flag = false;
while i < args.len() {
let a = &args[i];
if a == "--" {
args.remove(i);
break;
}
// c:Src/builtin.c:42 `BIN_PREFIX("-", BINF_DASH)`. A bare
// `-` is its own BINF_PREFIX builtin (BINF_DASH flag —
// "login shell, prepend `-` to argv[0]"). In the canonical
// precmd-walk at Src/exec.c:3056-3091 a bare `-` after
// `exec` is recognized AS a builtin and stripped from
// preargs (precmd_skip++), accumulating BINF_DASH into
// cflags. The fast-path here bypasses execcmd_compile_head,
// so we mirror the strip locally: bare `-` → set login,
// remove, continue. Without this `exec -` (with no command
// following) tried to exec `-` as a literal command and
// exited the shell. Bug #252.
if a == "-" {
saw_flag = true;
login = true;
args.remove(i);
continue;
}
if !a.starts_with('-') || a.len() < 2 {
break;
}
match a.as_str() {
"-a" => {
saw_flag = true;
args.remove(i);
if i < args.len() {
argv0_override = Some(args.remove(i));
}
}
"-c" => {
saw_flag = true;
clean_env = true;
args.remove(i);
}
"-l" => {
saw_flag = true;
login = true;
args.remove(i);
}
_ => {
// c:Src/exec.c:3196-3208 — when an unrecognized
// `-X`-style arg has NO following arg, the lexer's
// IS_DASH walk hits the "no next node" branch at
// c:3199 before the unknown-flag-letter switch at
// c:3249, so the canonical message is "exec
// requires a command to execute" rc=1 (verified vs
// `/opt/homebrew/bin/zsh -fc 'exec --bad'`).
// Consume the lone flag so the post-loop check
// fires. When a following arg exists, leave the
// unknown-flag arg in place — that arg becomes
// the command name and execution proceeds.
if args.len() == 1 {
saw_flag = true;
args.remove(i);
continue;
}
break;
}
}
}
let Some(cmd) = args.first().cloned() else {
if saw_flag {
// c:Src/builtin.c:1078-1080 — flags consumed but no
// command follows → "exec requires a command to
// execute" rc=1.
eprintln!("zshrs:1: exec requires a command to execute");
return Value::Status(1);
}
// `exec` with no command + no redirects = no-op success.
return Value::Status(0);
};
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::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.
let has_user_fn = with_executor(|exec| exec.functions_compiled.contains_key(&cmd));
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 =
with_executor(|exec| !exec.subshell_snapshots.is_empty());
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 = crate::ported::builtin::createbuiltintable().contains_key(&cmd);
if bn_in_tab {
let status = dispatch_builtin_raw(&cmd, rest.clone());
let in_subshell_now =
with_executor(|exec| !exec.subshell_snapshots.is_empty());
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 = with_executor(|exec| !exec.subshell_snapshots.is_empty());
if in_subshell {
let mut command = std::process::Command::new(&cmd);
command.arg0(&display_argv0);
command.args(&rest);
if clean_env {
command.env_clear();
}
let status = match command.spawn() {
Ok(mut child) => match child.wait() {
Ok(s) => s.code().unwrap_or(127),
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: {}",
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);
}
let mut command = std::process::Command::new(&cmd);
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).
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: {}", 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.into_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);
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);
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.
if crate::IS_ZSH_MODE.load(std::sync::atomic::Ordering::Relaxed) {
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
// as BUILTIN_COMPGEN above.
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.
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 {
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);
// A compsys-defined `compdef` FUNCTION (autoload compinit →
// compinit defines compdef) wins over the extension builtin
// in every mode.
if let Some(s) = try_user_fn_override("compdef", &args) {
return Value::Status(s);
}
// c:zsh -f — compdef is a FUNCTION defined by compinit, not
// a builtin; without compinit it's command-not-found (127).
// openshift-aliases sources `<(oc completion zsh)` whose
// compdef calls must error exactly like the oracle. Same
// gate shape as BUILTIN_COMPGEN/BUILTIN_COMPLETE above.
if crate::IS_ZSH_MODE.load(std::sync::atomic::Ordering::Relaxed) {
eprintln!("zsh:1: command not found: compdef");
return Value::Status(127);
}
Value::Status(with_executor(|exec| exec.builtin_compdef(&args)))
});
vm.register_builtin(BUILTIN_COMPINIT, |vm, argc| {
let args = pop_args(vm, argc);
Value::Status(with_executor(|exec| exec.builtin_compinit(&args)))
});
vm.register_builtin(BUILTIN_CDREPLAY, |vm, argc| {
let args = pop_args(vm, argc);
Value::Status(with_executor(|exec| exec.builtin_cdreplay(&args)))
});
// 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);
// 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| {
Value::Status(crate::extensions::ext_builtins::zsleep(&pop_args(vm, argc)))
});
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
vm.register_builtin(BUILTIN_PROMPTINIT, |vm, argc| {
let args = pop_args(vm, argc);
Value::Status(crate::extensions::ext_builtins::promptinit(&args))
});
vm.register_builtin(BUILTIN_PROMPT, |vm, argc| {
let args = pop_args(vm, argc);
Value::Status(crate::extensions::ext_builtins::prompt(&args))
});
// Async / Parallel (zshrs extensions)
vm.register_builtin(BUILTIN_ASYNC, |vm, argc| {
let args = pop_args(vm, argc);
let status = with_executor(|exec| exec.builtin_async(&args));
Value::Status(status)
});
vm.register_builtin(BUILTIN_AWAIT, |vm, argc| {
let args = pop_args(vm, argc);
let status = with_executor(|exec| exec.builtin_await(&args));
Value::Status(status)
});
vm.register_builtin(BUILTIN_PMAP, |vm, argc| {
let args = pop_args(vm, argc);
let status = with_executor(|exec| exec.builtin_pmap(&args));
Value::Status(status)
});
vm.register_builtin(BUILTIN_PGREP, |vm, argc| {
let args = pop_args(vm, argc);
let status = with_executor(|exec| exec.builtin_pgrep(&args));
Value::Status(status)
});
vm.register_builtin(BUILTIN_PEACH, |vm, argc| {
let args = pop_args(vm, argc);
let status = with_executor(|exec| exec.builtin_peach(&args));
Value::Status(status)
});
vm.register_builtin(BUILTIN_BARRIER, |vm, argc| {
let args = pop_args(vm, argc);
let status = with_executor(|exec| exec.builtin_barrier(&args));
Value::Status(status)
});
// Intercept (AOP)
vm.register_builtin(BUILTIN_INTERCEPT, |vm, argc| {
let args = pop_args(vm, argc);
let status = with_executor(|exec| exec.builtin_intercept(&args));
Value::Status(status)
});
vm.register_builtin(BUILTIN_INTERCEPT_PROCEED, |vm, argc| {
let args = pop_args(vm, argc);
let status = with_executor(|exec| exec.builtin_intercept_proceed(&args));
Value::Status(status)
});
// Debug / Profile
vm.register_builtin(BUILTIN_DOCTOR, |vm, argc| {
let args = pop_args(vm, argc);
let status = with_executor(|exec| exec.builtin_doctor(&args));
Value::Status(status)
});
vm.register_builtin(BUILTIN_DBVIEW, |vm, argc| {
let args = pop_args(vm, argc);
let status = with_executor(|exec| exec.builtin_dbview(&args));
Value::Status(status)
});
vm.register_builtin(BUILTIN_PROFILE, |vm, argc| {
let args = pop_args(vm, argc);
let status = with_executor(|exec| exec.builtin_profile(&args));
Value::Status(status)
});
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);
}
// 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 => {
// 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.
if let Ok(mut t) = crate::ported::builtin::traps_table().lock() {
t.remove("EXIT");
}
// 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);
});
*crate::ported::jobs::THISJOB
.get_or_init(|| std::sync::Mutex::new(-1))
.lock()
.unwrap() = -1;
// Child: wire stdin from previous pipe's read end
if i > 0 {
unsafe {
libc::dup2(pipes[i - 1].0, libc::STDIN_FILENO);
}
}
// Wire stdout to next pipe's write end
unsafe {
libc::dup2(pipes[i].1, libc::STDOUT_FILENO);
}
// (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 all original pipe fds (keeping stdin/stdout dups)
for (r, w) in &pipes {
unsafe {
libc::close(*r);
libc::close(*w);
}
}
// 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);
}
}
}
// Parent runs the LAST stage inline. Save stdin, dup the last
// pipe's read end onto fd 0, run the chunk, restore stdin.
// Close every other pipe fd so the producer side gets EOF
// when the last upstream stage exits.
let saved_stdin = unsafe { libc::dup(libc::STDIN_FILENO) };
if last_idx > 0 {
let read_fd = pipes[last_idx - 1].0;
unsafe {
libc::dup2(read_fd, libc::STDIN_FILENO);
}
}
// Close all pipe fds in the parent now that stdin is wired.
// (Children already have their own copies. The dup2 above
// already gave us a fresh fd 0 if needed.)
for (r, w) in &pipes {
unsafe {
libc::close(*r);
libc::close(*w);
}
}
// Run the last stage's bytecode on a sub-VM with the host
// wired up. The host points back at the executor so reads
// (`read x`) update the parent's variables directly.
let last_stage_status = {
let last_chunk = stages_vec.into_iter().last().unwrap();
crate::fusevm_disasm::maybe_print_stdout("pipeline:last", &last_chunk);
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 _ = std::io::stdout().flush();
let _ = std::io::stderr().flush();
stage_vm.last_status
};
// 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 pid in child_pids {
let mut status: i32 = 0;
unsafe {
libc::waitpid(pid, &mut status, 0);
}
let s = if libc::WIFEXITED(status) {
libc::WEXITSTATUS(status)
} else if libc::WIFSIGNALED(status) {
128 + libc::WTERMSIG(status)
} else {
1
};
pipestatus.push(s);
}
// Append the in-parent last-stage status so `pipestatus` ends
// with N entries (one per stage).
pipestatus.push(last_stage_status);
// 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.
with_executor(|exec| {
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| {
let sub_idx = vm.pop().to_int() as usize;
let job_text = vm.pop().to_str();
let chunk = match vm.chunk.sub_chunks.get(sub_idx).cloned() {
Some(c) => c,
None => return Value::Status(1),
};
match unsafe { libc::fork() } {
-1 => Value::Status(1),
0 => {
// Child: detach and run.
unsafe { libc::setsid() };
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 => {
// 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;
}
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);
}
let blocked = with_executor(|exec| {
// 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)`.
if let Some((scalar_name, sep)) = exec.tied_array_to_scalar.get(&name).cloned() {
let joined = values.join(&sep);
exec.set_scalar(scalar_name, joined);
}
// 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;
let res = crate::ported::params::assignaparam(
&name,
values.clone(),
crate::ported::zsh_h::ASSPM_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;
}
#[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);
let mut synth = crate::ported::zsh_h::job::default();
crate::ported::jobs::waitonejob(&mut synth);
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);
}
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 {
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);
let mut synth = crate::ported::zsh_h::job::default();
crate::ported::jobs::waitonejob(&mut synth);
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| {
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| {
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 {
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: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;
loop {
// 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());
}
let _ = write!(std::io::stderr(), "{}", prompt);
let _ = std::io::stderr().flush();
let mut line = String::new();
match reader.read_line(&mut line) {
Ok(0) => {
// EOF — emit the final newline that zsh prints
// after the prompt-then-EOF sequence (c:Src/loop.c
// selectlist falls through to fputc('\n', stderr)
// at the end of the read failure path). Without
// this the next process's output runs directly
// after `-->>>> ` on the same line.
let _ = writeln!(std::io::stderr());
let _ = std::io::stderr().flush();
break;
}
Ok(_) => {}
Err(_) => break,
}
let trimmed = line.trim_end_matches(['\n', '\r'][..].as_ref()).to_string();
with_executor(|exec| {
exec.set_scalar("REPLY".to_string(), trimmed.clone());
});
if trimmed.is_empty() {
// Empty input → redraw menu without running body.
continue;
}
let chosen = match trimmed.parse::<usize>() {
Ok(n) if n >= 1 && n <= words.len() => words[n - 1].clone(),
_ => String::new(),
};
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.
vm.register_builtin(BUILTIN_ARRAY_INDEX, |vm, _argc| {
let idx = vm.pop().to_str();
let name = vm.pop().to_str();
array_index_lookup(&name, &idx)
});
// 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) {
let v = array_index_lookup(&name, &idx);
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 " ").
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{8c}') {
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".
match crate::ported::params::gethkparam(&name) {
Some(keys) => {
if keys.iter().any(|k| k == &key) {
Value::str(key)
} else {
Value::str("")
}
}
None => paramsubst_to_value(&format!("${{(k){}[{}]}}", name, key)),
}
});
vm.register_builtin(BUILTIN_BRIDGE_BRACE_ARRAY, |vm, _argc| {
// Inner body of `${(...)...}` (already stripped of `${`/`}` by
// the caller). The compiler optionally prefixes Qstring
// (\u{8c}) 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{8c}') {
(true, rest.to_string())
} else {
(false, body)
};
if dq {
with_executor(|exec| exec.in_dq_context += 1);
}
let v = paramsubst_to_value(&format!("${{{}}}", inner));
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| {
let flags = vm.pop().to_str();
let name = vm.pop().to_str();
let body = format!("${{({}){}}}", flags, name);
paramsubst_to_value(&body)
});
// `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.
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.
let key_is_dynamic = if _argc == 4 {
vm.pop().to_int() != 0
} else {
false
};
let value = vm.pop().to_str();
let key = vm.pop().to_str();
let name = vm.pop().to_str();
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| {
let is_indexed = exec.array(&name).is_some();
let is_assoc = exec.assoc(&name).is_some();
let is_scalar = !is_indexed && !is_assoc && exec.scalar(&name).is_some();
// 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()
}
});
let subscripted = format!("{}[{}]", name, resolved_key);
crate::ported::params::assignsparam(&subscripted, &value, crate::ported::zsh_h::ASSPM_WARN);
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();
match v {
Value::Array(items) => {
let filtered: Vec<Value> = items
.into_iter()
.filter(|x| !x.to_str().is_empty())
.collect();
Value::Array(filtered)
}
Value::Str(s) if s.is_empty() => Value::Array(Vec::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{87}` 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{a1}' {
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{84}`..`\u{a1}` range, the
// ones the lexer emits for `#$^*()…`) back to their
// source ASCII via the `ztokens` table.
let cp = c as u32;
if (0x84..=0xa1).contains(&cp) {
let idx = (cp - 0x84) 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).
if parts.len() == 1 && parts[0].is_empty() {
return Value::Array(Vec::new());
}
nodes_to_value(parts)
});
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();
// 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);
let inputs: Vec<String> = match raw {
Value::Array(items) => items.into_iter().map(|v| v.to_str()).collect(),
other => vec![other.to_str()],
};
if !brace_expand {
return nodes_to_value(inputs);
}
let mut out: Vec<String> = Vec::with_capacity(inputs.len());
for s in inputs {
for w in crate::ported::glob::xpandbraces(&s, brace_ccl) {
out.push(w);
}
}
nodes_to_value(out)
});
// `*(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_expand_word_value(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);
glob_expand_word_value(raw, noglob || !multios)
});
// 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));
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
});
if !pending {
return raw;
}
let noglob =
opt_state_get("noglob").unwrap_or(false) || !opt_state_get("glob").unwrap_or(true);
glob_expand_word_value(raw, noglob)
});
// `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)
});
// `${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();
let glob_subst =
crate::ported::zsh_h::isset(crate::ported::zsh_h::GLOBSUBST);
if !glob_subst {
return raw;
}
// Collect input strings (Str → vec![s]; Array → multiple).
let inputs: Vec<String> = match raw {
Value::Array(items) => items.into_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 {
let matches = with_executor(|exec| exec.expand_glob(&pattern));
if matches.is_empty() {
// No match: keep the literal (like nullglob off).
out.push(pattern);
} else {
for m in matches {
out.push(m);
}
}
}
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:337 — `getmathparam` for ArithCompiler pre-load.
// Pop a variable name, return its math-coerced value. Mirrors
// the routing in math::getmathparam: try i64, then f64, then
// recursive arith-eval, else 0. Bug #118 in docs/BUGS.md.
vm.register_builtin(BUILTIN_GET_MATH_VAR, |vm, _argc| {
let name = vm.pop().to_str();
let raw = crate::ported::params::getsparam(&name).unwrap_or_default();
// Empty / unset → 0.
if raw.is_empty() {
return Value::Int(0);
}
// Direct int / float parse.
if let Ok(n) = raw.parse::<i64>() {
return Value::Int(n);
}
if let Ok(f) = raw.parse::<f64>() {
return Value::Float(f);
}
// Recursive arith eval (matches getmathparam fallback at
// Src/math.c:337). If that fails too, return 0 — C's
// mathevall returns 0 with errflag set on parse failure.
match crate::ported::math::mathevali(&raw) {
Ok(n) => Value::Int(n),
Err(_) => Value::Int(0),
}
});
// 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, pass through unchanged.
// See BUILTIN_GLOB_SUBST_GUARD docs above for full rationale.
vm.register_builtin(BUILTIN_GLOB_SUBST_GUARD, |vm, _argc| {
let p = vm.pop().to_str();
let glob_subst =
crate::ported::zsh_h::isset(crate::ported::zsh_h::GLOBSUBST);
if glob_subst {
return Value::str(p);
}
let mut out = String::with_capacity(p.len() * 2);
for c in p.chars() {
match c {
'*' | '?' | '[' | ']' | '(' | ')' | '|' | '<' | '>' | '#' | '^'
| '~' | '\\' => {
out.push('\\');
out.push(c);
}
_ => out.push(c),
}
}
Value::str(out)
});
vm.register_builtin(BUILTIN_ARRAY_JOIN_STAR, |vm, _argc| {
let name = vm.pop().to_str();
let (joined, ifs_full, 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=" ".
let ifs_full = exec
.scalar("IFS")
.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;
let joined = if name == "@" || name == "*" || name == "argv" {
exec.pparams().join(&sep)
} else if let Some(assoc_map) = exec.assoc(&name) {
// c:Src/params.c — assoc-splat values for
// `"${h[@]}"` / `"${h[*]}"`. Bug #109 in
// docs/BUGS.md.
assoc_map.values().cloned().collect::<Vec<_>>().join(&sep)
} else if let Some(arr) = exec.array(&name) {
arr.join(&sep)
} else {
exec.get_variable(&name)
};
(joined, ifs_full, in_dq)
});
// c:Src/subst.c — UNQUOTED `${name[*]}` (or `$*`) goes
// through the canonical "join via IFS[0], then word-split
// via IFS" pipeline. The fast-path bypassed paramsubst
// entirely so it never word-split, producing one joined
// string instead of N argv entries. Bug #428.
//
// In QUOTED (`"${name[*]}"`) context, the result IS a
// single scalar — return it as Str without splitting.
if in_dq {
return Value::str(joined);
}
if joined.is_empty() {
return Value::Array(Vec::new());
}
// IFS word-split — every IFS char is a separator. Empty
// resulting fields are dropped (the canonical
// "remove empty unquoted words" pass from
// Src/subst.c::prefork c:184-187).
let parts: Vec<String> = joined
.split(|c: char| ifs_full.contains(c))
.filter(|s| !s.is_empty())
.map(String::from)
.collect();
if parts.is_empty() {
Value::Array(Vec::new())
} else if parts.len() == 1 {
Value::str(parts.into_iter().next().unwrap())
} else {
Value::Array(parts.into_iter().map(Value::str).collect())
}
});
vm.register_builtin(BUILTIN_ARRAY_ALL, |vm, _argc| {
let name = vm.pop().to_str();
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" {
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"
) {
// 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) => Value::Array(v.iter().map(Value::str).collect()),
None => {
// 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() {
Value::Array(vec![])
} else if opt_state_get("shwordsplit").unwrap_or(false) {
// bash-compat: under setopt sh_word_split, do
// split scalars on IFS chars.
let ifs = exec.scalar("IFS").unwrap_or_else(|| " \t\n".to_string());
let parts: Vec<Value> = val
.split(|c: char| ifs.contains(c))
.filter(|s| !s.is_empty())
.map(Value::str)
.collect();
Value::Array(parts)
} else {
Value::Array(vec![Value::str(val)])
}
}
}
})
});
// 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: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 {
return Value::Status(1);
}
if unsafe { libc::pipe(c2p.as_mut_ptr()) } < 0 {
unsafe {
libc::close(p2c[0]);
libc::close(p2c[1]);
}
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);
}
match unsafe { libc::fork() } {
-1 => {
unsafe {
libc::close(p2c[0]);
libc::close(p2c[1]);
libc::close(c2p[0]);
libc::close(c2p[1]);
}
Value::Status(1)
}
0 => {
// 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];
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 = jobs::initjob(&mut tab); // c:exec.c:1700
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| {
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),
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.
vm.register_builtin(BUILTIN_GET_VAR, |vm, argc| {
let args = pop_args(vm, argc);
let name = args.into_iter().next().unwrap_or_default();
let live_status = vm.last_status;
// Suppress sync when a deferred subshell exit just landed:
// LASTVAL holds the correct deferred status, vm.last_status
// is stale (post-subshell vm doesn't propagate status). See
// SUBSHELL_EXIT_STATUS_PENDING TLS declaration for rationale.
let suppress_sync = SUBSHELL_EXIT_STATUS_PENDING.with(|c| {
let prev = c.get();
c.set(false);
prev
});
// `$@` 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).
let sync_status = |exec: &mut ShellExecutor| {
if !suppress_sync {
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).
return with_executor(|exec| {
sync_status(exec);
Value::Array(exec.pparams().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).
let rc_expand = with_executor(|exec| opt_state_get("rcexpandparam").unwrap_or(false));
if rc_expand {
let arr_val = with_executor(|exec| {
sync_status(exec);
exec.array(&name)
});
if let Some(arr) = arr_val {
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.
let magic_vals = 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 opt_state_get("ksharrays").unwrap_or(false) {
return Value::str(vals.into_iter().next().unwrap_or_default());
}
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 = 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 = opt_state_get("ksharrays").unwrap_or(false);
if let Some(arr) = exec.array(&name) {
if ksh_arrays {
return Some((vec![arr.first().cloned().unwrap_or_default()], in_dq));
}
return Some((arr.clone(), in_dq));
}
if let Some(map) = exec.assoc(&name) {
let mut keys: Vec<&String> = map.keys().collect();
keys.sort();
let values: Vec<String> =
keys.iter().filter_map(|k| map.get(*k).cloned()).collect();
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 {
// 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
// paramsubst splat path already does this (Bug #578
// retain); this GET_VAR fast path bypassed it and leaked
// empty argv slots (visible double-space, wrong arg
// counts in `for`/`print -l`).
let items: Vec<String> = if in_dq {
items
} else {
items.into_iter().filter(|s| !s.is_empty()).collect()
};
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));
}
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, 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.
if !is_known && 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,
);
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 {
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 && opt_state_get("shwordsplit").unwrap_or(false) {
let ifs =
with_executor(|exec| exec.scalar("IFS").unwrap_or_else(|| " \t\n".to_string()));
let parts: Vec<Value> = val
.split(|c: char| ifs.contains(c))
.filter(|s| !s.is_empty())
.map(|s| Value::str(s.to_string()))
.collect();
if parts.is_empty() {
return Value::Array(Vec::new());
} else if parts.len() == 1 {
return parts.into_iter().next().unwrap();
} else {
return Value::Array(parts);
}
}
Value::str(val)
});
// `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.
if exec.array(&name).is_some() {
// 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,
);
#[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;
}
if exec.assoc(&name).is_some() {
eprintln!("zshrs: {}: cannot use += on assoc without (key val)", name);
return;
}
// 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,
);
#[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
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;
}
// Inline-assignment frame tracking (`X=foo cmd` reverts on
// command return).
if !exec.inline_env_stack.is_empty() {
let prev_var = crate::ported::params::getsparam(&name);
let prev_env = env::var(&name).ok();
exec.inline_env_stack
.last_mut()
.unwrap()
.push((name.clone(), prev_var, prev_env));
let _ = crate::ported::params::zputenv(&format!("{}={}", &name, &value)); // c:Src/params.c:5354
}
// 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::setiparam(&name, i);
} else {
assign_failed = crate::ported::params::setsparam(&name, &value).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::setiparam(&name, f as i64);
} else {
let mnval = crate::ported::math::mnumber {
l: 0,
d: f,
type_: crate::ported::math::MN_FLOAT,
};
crate::ported::params::setnparam(&name, mnval);
}
} else {
assign_failed = crate::ported::params::setsparam(&name, &value).is_none();
}
} else {
// 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.
assign_failed = crate::ported::params::setsparam(&name, &value).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 {
let _ = crate::ported::params::zputenv(&format!("{}={}", &name, &value)); // c:Src/params.c:5354
}
#[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);
}
});
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;
}
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 {
let _ = crate::ported::params::zputenv(&format!("{}={}", &name, &value)); // 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| {
let sub_idx = vm.pop().to_int() 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()
};
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);
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 _ = sub_vm.run();
let status = sub_vm.last_status;
let elapsed = start.elapsed();
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 = |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,
}
};
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/jobs.c — no job, no report (see forks_before above).
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);
}
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.
let param_flags = crate::ported::params::paramtab()
.read()
.ok()
.and_then(|t| t.get(&varid).map(|p| p.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>&-`).
if crate::ported::utils::zclose(fd1) < 0 {
crate::ported::utils::zwarn(&format!(
"failed to close file descriptor {}: {}",
fd1,
std::io::Error::last_os_error()
));
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::dup(src) };
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,
);
with_executor(|exec| {
exec.set_scalar(varid, final_fd.to_string());
});
return Value::Status(0);
}
return Value::Status(1);
}
// `{varid}<<HERE` / `{varid}<<<str` — op byte 255 (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.
if 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);
}
let body = format!("{}\n", path.trim_end_matches('\n'));
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: {}",
std::io::Error::last_os_error()
));
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);
with_executor(|exec| {
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 {
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,
std::io::Error::last_os_error()
));
return Value::Status(1);
}
crate::ported::utils::fdtable_set(final_fd, crate::ported::zsh_h::FDT_EXTERNAL);
let _ = Ordering::Relaxed;
with_executor(|exec| {
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;
let errored = (crate::ported::utils::errflag.load(Ordering::Relaxed)
& crate::ported::zsh_h::ERRFLAG_ERROR)
!= 0;
// 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);
let brk_save = crate::ported::builtin::BREAKS.swap(0, Ordering::Relaxed);
let cont_save = crate::ported::builtin::CONTFLAG.swap(0, Ordering::Relaxed);
let exit_save = crate::ported::builtin::EXIT_PENDING.swap(0, Ordering::Relaxed);
TRY_ESCAPE_SAVE.with(|s| {
s.borrow_mut()
.push((ret_save, brk_save, cont_save, exit_save));
});
with_executor(|exec| {
exec.set_scalar(
"__zshrs_try_block_saved_status".to_string(),
vm_status.to_string(),
);
// c:Src/loop.c:765-766 — `try_errflag = errflag &
// ERRFLAG_ERROR; try_interrupt = (errflag & ERRFLAG_INT) ?
// 1 : 0`. Updates the canonical loop.c globals that
// `$TRY_BLOCK_ERROR` / `$TRY_BLOCK_INTERRUPT` read from
// (port at src/ported/loop.rs::try_errflag etc.).
// Mirror into paramtab too via set_scalar so
// `${parameters[TRY_BLOCK_ERROR]}` and direct assignment
// shapes stay in sync.
let try_err = if errored { vm_status as i64 } else { 0 };
crate::ported::r#loop::try_errflag.store(try_err, Ordering::Relaxed);
crate::ported::r#loop::try_interrupt.store(0, Ordering::Relaxed);
if errored {
exec.set_scalar(
"TRY_BLOCK_ERROR".to_string(),
vm_status.to_string(),
);
// Clear errflag so always-arm runs cleanly. c:768.
crate::ported::utils::errflag.fetch_and(
!crate::ported::zsh_h::ERRFLAG_ERROR,
Ordering::Relaxed,
);
} else {
exec.set_scalar("TRY_BLOCK_ERROR".to_string(), "0".to_string());
}
});
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| {
with_executor(|exec| {
exec.inline_env_stack.push(Vec::new());
});
Value::Status(0)
});
vm.register_builtin(BUILTIN_END_INLINE_ENV, |_vm, _argc| {
with_executor(|exec| {
if let Some(frame) = exec.inline_env_stack.pop() {
for (name, prev_var, prev_env) in frame.into_iter().rev() {
match prev_var {
Some(v) => {
exec.set_scalar(name.clone(), v);
}
None => {
exec.unset_scalar(&name);
}
}
match prev_env {
Some(v) => env::set_var(&name, &v),
None => env::remove_var(&name),
}
}
}
});
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
}
for (name, prev_var, prev_env) in frame.into_iter().rev() {
match prev_var {
Some(v) => {
exec.set_scalar(name.clone(), v);
}
None => {
exec.unset_scalar(&name);
}
}
match prev_env {
Some(v) => env::set_var(&name, &v),
None => env::remove_var(&name),
}
}
}
});
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/exec.c — the entire `{try} always {…}` construct's
// exit status is the try-block's last status. Per zsh
// semantics this carries through regardless of what the
// always-arm did (including reads/writes of TRY_BLOCK_ERROR
// — those affect later commands' visible value but don't
// override the construct's exit). The "swallow" idiom in
// C is gated on errflag state at always-arm exit, not on
// TBE's literal value; full fidelity needs more state and
// is deferred.
let saved = with_executor(|exec| {
exec.scalar("__zshrs_try_block_saved_status")
.and_then(|s| s.parse::<i32>().ok())
.unwrap_or(0)
});
// 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_ESCAPE_SAVE.with(|s| s.borrow_mut().pop()) {
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)
});
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)
});
// 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();
// 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") {
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);
Value::Status(0)
});
// 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("test", &name); // c:cond.c:502
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: zwarnnam emitted by
// optison itself when POSIXBUILTINS is unset; mirror to
// stderr here for parity with the earlier diagnostic.
eprintln!("{}:1: no such option: {}", shname(), name);
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("test", &name); // c:cond.c:502
// 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| {
let pattern = vm.pop().to_str();
let name = vm.pop().to_str();
let body = format!("${{{}:#{}}}", name, pattern);
paramsubst_to_value(&body)
});
// `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.
let append = popped.pop().map_or(false, |v| v.to_str() == "1");
let key = popped.pop().unwrap().to_str();
let name = popped.pop().unwrap().to_str();
let mut values: Vec<String> = Vec::new();
for v in popped {
match v {
Value::Array(items) => {
for it in items {
values.push(it.to_str());
}
}
other => values.push(other.to_str()),
}
}
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).
let eval_bound = |s: &str| -> i64 {
let t = s.trim();
t.parse::<i64>()
.ok()
.or_else(|| crate::ported::math::mathevali(t).ok())
.unwrap_or(0)
};
let (start, end) = if let Some((s_str, e_str)) = key.split_once(',') {
let s = ksh_shift(eval_bound(s_str));
let e = ksh_shift(eval_bound(e_str));
(start_translate(s), end_translate(e))
} else {
let i = ksh_shift(eval_bound(&key));
if i == 0 {
return;
}
let n = start_translate(i);
(n, n)
};
// 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: 0,
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).
let is_scalar = taken.as_ref().map_or(false, |pm| {
crate::ported::zsh_h::PM_TYPE(pm.node.flags as u32)
== crate::ported::zsh_h::PM_SCALAR
});
let mut v = crate::ported::zsh_h::value {
pm: taken,
arr: Vec::new(),
scanflags: 0,
valflags: 0,
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);
}
}
});
Value::Status(0)
});
// BUILTIN_CONCAT_SPLICE — word-segment concat with first/last
// sticking (default zsh splice semantics for `${arr[@]}`, `$@`).
vm.register_builtin(BUILTIN_CONCAT_SPLICE, |vm, _argc| {
let rhs = vm.pop();
let lhs = vm.pop();
match (lhs, rhs) {
(Value::Array(mut 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 last_l = la.pop().unwrap();
let mut ra_iter = ra.into_iter();
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(mut la), rhs_scalar) => {
// c:Src/subst.c paramsubst splice — empty array on
// either side preserves the empty (zero words),
// doesn't collapse into a single-empty-string scalar.
// Bug #120 in docs/BUGS.md: empty array slice
// concatenated with empty literal returned
// Value::str("") which surfaced as one empty arg
// instead of zero args.
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 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(mut ra)) => {
let lhs_s = lhs_scalar.as_str_cow();
if ra.is_empty() {
// Empty-array RHS — preserve emptiness when the
// LHS is also empty (no prefix to attach). Bug
// #120 in docs/BUGS.md.
if lhs_s.is_empty() {
return Value::Array(Vec::new());
}
return Value::str(lhs_s.to_string());
}
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)
}
}
});
// 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.
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 {
let a_s = a.as_str_cow();
for b in &ra {
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
.into_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
.into_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/options.c — RC_EXPAND_PARAM applies to UNQUOTED
// expansions only; inside DQ `"$foo${arr}bar"` joins via
// $IFS[0] regardless of the option. The compiler emits
// CallBuiltin(BUILTIN_CONCAT_DISTRIBUTE, 1) when the parent
// word is DQ-wrapped (compile_zsh.rs parent_is_dq); the
// default UNQUOTED path emits argc=2 (lhs + rhs). Treat
// argc==1 as "force rc_expand off." Bug #246 in docs/BUGS.md.
let dq_suppress = argc == 1;
let rc_expand = !dq_suppress
&& with_executor(|exec| opt_state_get("rcexpandparam").unwrap_or(false));
// Helper: join an Array 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: Vec<Value>| -> String {
let strs: Vec<String> = arr
.iter()
.map(|v| v.as_str_cow().into_owned())
.collect();
crate::ported::utils::sepjoin(&strs, None)
};
if !rc_expand {
// Default: join any Array side to scalar, then concat.
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);
return Value::str(s);
}
match (lhs, rhs) {
(Value::Array(la), Value::Array(ra)) => {
// Cartesian product: [a + b for a in la for b in ra].
let mut out = Vec::with_capacity(la.len() * ra.len().max(1));
if ra.is_empty() {
return Value::Array(la);
}
if la.is_empty() {
return Value::Array(ra);
}
for a in &la {
let a_s = a.as_str_cow();
for b in &ra {
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
.into_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
.into_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) => {
// Fast path: both scalar → identical to Op::Concat.
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)
}
}
});
// `[[ 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,
_ => 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,
_ => 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 = with_executor(|_| opt_state_get("xtrace").unwrap_or(false));
Value::Int(if on { 1 } else { 0 })
});
vm.register_builtin(BUILTIN_XTRACE_LINE, |vm, _argc| {
let cmd_text = vm.pop().to_str();
// 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 = with_executor(|exec| opt_state_get("xtrace").unwrap_or(false));
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_text);
xtrerr_fputs("\n");
xtrerr_flush();
XTRACE_DONE_PS4.with(|f| f.set(false));
}
Value::Status(0)
});
// 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 = with_executor(|exec| opt_state_get("xtrace").unwrap_or(false));
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 {
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 = with_executor(|exec| opt_state_get("xtrace").unwrap_or(false));
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 = with_executor(|exec| opt_state_get("xtrace").unwrap_or(false));
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)
}
});
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.
if 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)
});
vm.register_builtin(BUILTIN_DONETRAP_RESET, |_vm, _argc| {
// 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);
Value::Status(0)
});
// `[[ -z X ]]` / `[[ -n X ]]` — pop one Value, route through
// canonical `src/ported/cond.rs::evalcond` so the actual
// empty/non-empty test reuses the C-port at `cond.rs:270-271`
// (`'n' => !arg.is_empty()`, `'z' => arg.is_empty()`).
//
// The Array→args conversion lives at the bridge because cond.rs
// expects `&[&str]` (C `cond_str` signature equivalent). 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", ""] → evalcond → 0 (true)
// - Array(1) → ["-z", word] → evalcond → 0/1
// - Array(2+) → ["-z", w1, w2, ...] → evalcond → 2 (parse
// error: too many ops)
// → coerced to false
// - Str(s) → ["-z", s] → evalcond → 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.into_iter().map(|x| x.to_str()).collect(),
Value::Str(s) => vec![s.to_string()],
other => vec![other.to_str()],
};
let mut args: Vec<&str> = vec![op];
if words.is_empty() {
args.push("");
} else {
args.extend(words.iter().map(|s| s.as_str()));
}
let opts: std::collections::HashMap<String, bool> =
std::collections::HashMap::new();
let vars: std::collections::HashMap<String, String> =
std::collections::HashMap::new();
// 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).
// `[[ ]]` dispatch — C's `evalcond(state, NULL)` calling convention.
// `None` for from_test → mathevali integer-compare coercion path.
let ret = crate::ported::cond::evalcond(&args, &opts, &vars, false, None);
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.
vm.register_builtin(BUILTIN_EXEC_HERESTR_FD, |vm, _argc| {
let fd = vm.pop().to_int() as i32;
let content = vm.pop().to_str();
// c:4671-4672 — append `\n` for "real" herestrings (not
// heredoc-derived). zshrs's bare-exec path only fires for
// the `<<<` syntax (REDIR_HERESTR), so always append.
let body = format!("{}\n", content);
// 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: {}",
std::io::Error::last_os_error()
));
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:3779 addfd → dup2 to target fd, close intermediate.
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/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 {
Value::Array(items) => {
for item in items {
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.
let saved = unsafe { libc::dup(fd) };
if saved >= 0 {
with_executor(|exec| {
if let Some(top) = exec.redirect_scope_stack.last_mut() {
top.push((fd, saved));
} else {
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::dup(fd) };
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::dup(src) };
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!("{}:1: file exists: {}", shname(), 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) => {
if i == 0 && !pipe_seed {
// c:2448-2450 — first member replaces the fd.
unsafe {
libc::dup2(tfd, fd);
}
}
target_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",
std::io::ErrorKind::IsADirectory => "is a directory",
_ => "redirect failed",
};
// c:Src/exec.c:3741 — `zwarn("%e: %s", errno, fname)`:
// zwarning supplies the `name:LINE:` prefix with the
// REAL current lineno (the old eprintln hardcoded `:1:`).
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);
}
};
let pipe_write_raw = AsRawFd::as_raw_fd(&write_end);
// 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 = std::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::dup(pipe_write_raw) };
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.
let close_on_end = unsafe { libc::dup(fd) };
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();
// 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 {
Value::Array(items) => {
for item in items {
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 {
exec.host_apply_redirect(fd as u8, *op_byte, source);
if exec.redirect_failed {
break;
}
}
});
return Value::Status(0);
}
if entries.len() == 1 {
// Single member after splicing — plain replace.
let (op_byte, source) = &entries[0];
with_executor(|exec| {
exec.host_apply_redirect(fd as u8, *op_byte, source);
});
return Value::Status(0);
}
// Save current fd state for scope-end restoration — BEFORE
// the first member's replace dup2 below.
let saved = unsafe { libc::dup(fd) };
if saved >= 0 {
with_executor(|exec| {
if let Some(top) = exec.redirect_scope_stack.last_mut() {
top.push((fd, saved));
} else {
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());
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::dup(src) };
if d >= 0 {
Ok(d)
} else {
Err(std::io::Error::last_os_error())
}
}
Err(_) => Err(std::io::Error::from_raw_os_error(libc::EBADF)),
}
}
_ => fs::File::open(source).map(|f| f.into_raw_fd()),
};
match open_result {
Ok(tfd) => {
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.
let (read_end, write_end) = match os_pipe::pipe() {
Ok(p) => p,
Err(_) => {
for f in &source_fds {
unsafe {
libc::close(*f);
}
}
return Value::Status(1);
}
};
// 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 Value::Status(1);
}
unsafe {
libc::dup2(read_dup, fd);
libc::close(read_dup);
}
// Spawn the producer.
let source_fds_for_thread = source_fds.clone();
let handle = std::thread::spawn(move || {
let mut w = write_end;
let mut buf = [0u8; 8192];
for sfd in source_fds_for_thread {
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;
}
}
unsafe {
libc::close(sfd);
}
}
// Closing w (the write_end) at scope drop signals EOF
// to the consumer.
});
with_executor(|exec| {
// 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();
}
});
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 {
return Value::Status(0);
}
// c:255 — `redir_err = lastval = 1`.
vm.last_status = 1;
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(1)
});
// c:Src/exec.c:3722-3724 — see the const's doc block. No args.
vm.register_builtin(BUILTIN_PIPE_OUTPUT_MARK, |_vm, _argc| {
with_executor(|exec| exec.pipe_output_pending = true);
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 = 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 = vm.pop().to_str();
let s = vm.pop().to_str();
let mut pat_tok = pat.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))
});
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| {
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;`
}
Value::Int(if ok { 0 } else { 1 })
});
vm.register_builtin(BUILTIN_USE_CMDOUTVAL_RESET, |_vm, _argc| {
crate::ported::exec::use_cmdoutval
.store(0, std::sync::atomic::Ordering::Relaxed);
Value::Status(0)
});
vm.register_builtin(BUILTIN_EXEC_DYNAMIC, |vm, argc| {
let raw = pop_args(vm, argc);
// 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
{
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));
}
// 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())
};
let newjob = {
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::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
);
// 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 mut tab = table.lock().unwrap_or_else(|e| e.into_inner());
if jobs::hasprocs(&tab, newjob) {
jobs::waitjobs(&mut tab, newjob); // c:1835
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.
if 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);
let mut synth = crate::ported::zsh_h::job::default();
crate::ported::jobs::waitonejob(&mut synth);
Value::Status(status)
});
// c:Src/exec.c:3340-3364 — `< file` / `> file` with no command
// word. Resolves NULLCMD/READNULLCMD at runtime then routes
// through host_exec_external. Redirects are already applied by
// the surrounding WithRedirectsBegin scope.
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);
}
let nullcmd = crate::ported::params::getsparam("NULLCMD");
let nc_str = nullcmd.as_deref().unwrap_or("");
let nc_empty = nc_str.is_empty();
// c:3340-3344 — CSHNULLCMD or no NULLCMD set → diagnostic.
if nc_empty || crate::ported::zsh_h::isset(crate::ported::zsh_h::CSHNULLCMD) {
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!("{}:{}: redirection with no command", script_name, lineno);
return Value::Status(1);
}
// 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
};
let status = 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.
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.
let cmd_text = vm.pop().to_str();
DEBUG_TRAP_REENTRY.with(|c| {
if c.get() {
return Value::Status(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::Status(0);
}
c.set(true);
// c:Src/exec.c — 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).
crate::ported::params::setsparam("ZSH_DEBUG_CMD", &cmd_text);
let _ = crate::ported::signals::dotrap(crate::ported::signals_h::SIGDEBUG);
// c:Src/exec.c::trapcmd — `unsetparam("ZSH_DEBUG_CMD")`
// after the trap returns. Mirror that.
crate::ported::params::unsetparam("ZSH_DEBUG_CMD");
c.set(false);
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);
let exit_pending = crate::ported::builtin::EXIT_PENDING.load(Ordering::Relaxed);
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:1931 — `if (errflag && !interact &&
// !isset(CONTINUEONERROR)) { errexit = 1; break; }` — with
// CONTINUE_ON_ERROR set, the top-level do-while re-enters
// loop() and the NEXT list runs instead of the shell exiting.
// Clear the flag so the next statement starts clean (the
// failed statement's lastval is already in place).
if errflag_set
&& !crate::ported::zsh_h::isset(crate::ported::zsh_h::INTERACTIVE)
&& crate::ported::zsh_h::isset(crate::ported::zsh_h::CONTINUEONERROR)
{
crate::ported::utils::errflag
.fetch_and(!crate::ported::zsh_h::ERRFLAG_ERROR, Ordering::Relaxed);
return Value::Int(0);
}
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());
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;
if !already_done {
// c:Src/signals.c:1245 dotrap(SIGZERR) — canonical ZERR
// trap dispatch. Fires whenever a command exits
// non-zero.
let _ = crate::ported::signals::dotrap(crate::ported::signals_h::SIGZERR);
// c:1602 — `donetrap = 1;` after firing.
crate::ported::exec::DONETRAP.store(1, Ordering::Relaxed);
}
// 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;
if errreturn {
// c:1620-1623 — `retflag = 1; breaks = loops;` — unwind to
// 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);
}
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 {
return Value::Int(0);
}
// c:Src/exec.c — `set -e` fires shell exit, NOT a function-only
// unwind. When LOCAL_OPTIONS restores the option mid-fn, the
// restoration would otherwise mask the trigger and let the
// outer scope continue. Setting EXIT_PENDING + EXIT_VAL here
// (for ALL scope kinds, not just subshells) makes the fn-exit
// path propagate to the shell-exit boundary at c:6135-6155.
crate::ported::builtin::EXIT_VAL.store(last, Ordering::Relaxed);
crate::ported::builtin::EXIT_PENDING.store(1, Ordering::Relaxed);
let _ = in_subshell;
// Function scope and top-level scope both branch to their
// respective return_patches; top-level lands at chunk-end,
// so execute_script returns `last` as the script's exit
// status (same observable behavior as a process::exit).
Value::Int(1)
});
// 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 status = if errflag_set || assign_failed {
1 // c:Src/exec.c:3394 `lastval = 1` / addvars cmdoutval=1
} else if had_cmd_subst {
vm.last_status // c:3396 `lastval = cmdoutval` (subst exit)
} else {
0 // c:3396 `lastval = cmdoutval` (cmdoutval = 0)
};
with_executor(|exec| exec.set_last_status(status));
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| {
let rhs = vm.pop().to_str();
let op = vm.pop().to_int() as u8;
let name = vm.pop().to_str();
// 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(&body)
});
// `${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| {
let length = vm.pop().to_int();
let offset = vm.pop().to_int();
let name = vm.pop().to_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(&body)
});
// 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| {
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(&body)
});
// `${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| {
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(&body)
});
// `$((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_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();
// 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);
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)
// 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{8c}), `\$`/`\\`/`\"`/
// `` \` `` → Bnull (\u{9f}) + 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 U+00A1 into argv.
let result_value = if mode == 5 {
let out = crate::ported::subst::singsub(&prepped);
Value::str(crate::ported::lex::untokenize(&out))
} else {
let (_first, nodes, _ms_ws, _ret) = crate::ported::subst::multsub(&prepped, 0);
// 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 nodes.is_empty() {
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;
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);
let captured = exec.run_command_substitution(inner);
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
);
}
let pf_flags = if mode == 6 {
crate::ported::zsh_h::PREFORK_ASSIGN
} 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).
let (_first, nodes, _ms_ws, _ret) =
crate::ported::subst::multsub(&prepped, pf_flags);
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.
let brace_expand = opt_state_get("braceexpand").unwrap_or(true);
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{8f}') {
crate::ported::glob::xpandbraces(&w, brace_ccl)
} 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));
let parts: Vec<String> = brace_expanded
.into_iter()
.flat_map(|s| {
// The lexer leaves glob metacharacters in their
// META-encoded form: `*` → `\u{87}`, `?` →
// `\u{86}`, `[` → `\u{91}`, 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{87}` 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);
let s = crate::lex::untokenize(&s);
// Skip glob expansion for assignment-shaped
// words (`NAME=value`). zsh doesn't expand the
// RHS of an assignment as a path glob unless
// `setopt globassign` is set, and feeding such
// words through expand_glob makes NOMATCH
// (default ON) fire spuriously on
// `integer i=2*3+1`, `path=*.rs`, etc.
let is_assignment_shape = {
let bytes = s.as_bytes();
let mut i = 0;
if !bytes.is_empty()
&& (bytes[0] == b'_' || bytes[0].is_ascii_alphabetic())
{
i += 1;
while i < bytes.len()
&& (bytes[i] == b'_' || bytes[i].is_ascii_alphanumeric())
{
i += 1;
}
i < bytes.len() && bytes[i] == b'='
} else {
false
}
};
// 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.
if is_glob_pre && !is_assignment_shape {
exec.expand_glob(&s)
} else if is_assignment_shape
&& 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 NAME=value arg runs through
// filesub(PREFORK_TYPESET): the `~`/`=` after the
// first `=` (and after each `:`) undergo filename
// expansion. `print foo=~/bar` → `foo=$HOME/bar`.
// filesubstr (subst.c:741) keys on the Tilde TOKEN,
// not literal `~`; this `s` was already untokenized
// above, so re-tokenize (as BUILTIN_MAGIC_EQUALS_PREFORK
// does) before filesub, then untokenize the result.
let mut tokd = s.clone();
crate::ported::glob::shtokenize(&mut tokd);
let exp = crate::ported::subst::filesub(
&tokd,
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.
if only.is_empty() {
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| {
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();
// 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{8c}")
} 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(&body);
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);
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);
let bytes = base64_decode(&body_b64);
let status = match bincode::deserialize::<fusevm::Chunk>(&bytes) {
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());
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);
}
// 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: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);
tab.add(shf);
}
// c:Src/exec.c:5460-5475 — `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.
if 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,
);
}
}
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.
fn array_index_lookup(name: &str, idx: &str) -> Value {
let idx_is_simple = !idx.starts_with('(') && idx != "@" && idx != "*" && !idx.contains(',');
if idx_is_simple {
if let Some(v) =
with_executor(|exec| exec.assoc(name).and_then(|m| m.get(idx).cloned()))
{
return Value::str(v);
}
}
let body = format!("${{{}[{}]}}", name, idx);
paramsubst_to_value(&body)
}
/// 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) {
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) {
// 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 {
// 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);
let mut ret_flags: i32 = 0;
let (_full, _pos, nodes) = crate::ported::subst::paramsubst(body, 0, qt, 0i32, &mut ret_flags);
if crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed) != 0 {
with_executor(|exec| 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 U+00A1 into argv.
let nodes: Vec<String> = nodes
.into_iter()
.map(|n| crate::ported::lex::untokenize(&n))
.collect();
nodes_to_value(nodes)
}
/// 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.
fn nodes_to_value(nodes: Vec<String>) -> Value {
// c:Src/glob.c:3649 remnulargs — strip the Nularg (`\u{a1}`)
// 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{a1}` had StringLen=1.
let stripped: Vec<String> = nodes
.into_iter()
.map(|mut s| {
crate::ported::glob::remnulargs(&mut s);
s
})
.collect();
if stripped.is_empty() {
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() {
let in_dq = with_executor(|exec| exec.in_dq_context > 0);
if !in_dq {
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 {
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));
}
// `$_` tracks the last argument of the PREVIOUSLY executed
// command (zsh / bash convention). Promote the deferred value
// into `$_` BEFORE this command runs (so `echo $_` reads the
// prior command's last arg) then stash THIS command's last arg
// for the next dispatch.
let new_last = args.last().cloned();
with_executor(|exec| {
if let Some(prev) = exec.pending_underscore.take() {
exec.set_scalar("_".to_string(), prev);
}
if let Some(last) = new_last {
exec.pending_underscore = Some(last);
}
});
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).
fn exec_system_command(name: &str, args: &[String]) -> i32 {
// c:Src/jobs.c — count the fork so `time` reports for an
// overridable coreutils shadow run as an external (`time sleep 0`,
// `time cat …`). This is a distinct spawn path from
// execute_external_bg; without the bump BUILTIN_TIME_SUBLIST saw no
// job and stayed silent. (Builtins that don't reach a spawn never
// hit this fn.)
crate::vm_helper::FORK_EVENTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let status = std::process::Command::new(name)
.args(args)
.stdin(std::process::Stdio::inherit())
.stdout(std::process::Stdio::inherit())
.stderr(std::process::Stdio::inherit())
.status();
match status {
Ok(s) => s.code().unwrap_or(if s.success() { 0 } else { 1 }),
Err(e) => {
eprintln!("zshrs: {}: {}", name, e);
127
}
}
}
fn try_user_fn_override(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;
/// 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 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;
/// 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;
/// 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;
/// 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;
/// 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;
/// `[[ 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:3340-3364 and exec's it through
/// host_exec_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;
/// `.` (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_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;
/// `[[ -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.
pub const BUILTIN_IS_TTY: u16 = 325;
/// `[[ -r/-w/-x file ]]` via access(2) (doaccess) — see handler.
pub const BUILTIN_COND_ACCESS: u16 = 638;
/// 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 file
/// has several other duplicate IDs — 325 has two as well — but
/// fixing those is out of scope for this port).
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;
/// 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.into_iter().map(|v| v.to_str()).collect(),
other => vec![other.to_str()],
};
if skip_glob {
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 {
let matches = with_executor(|exec| exec.expand_glob(pattern));
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;
/// `[[ -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;
/// `exec N<<<"str"` — herestring redirect to explicit fd, applied
/// permanently to the shell (no scope restoration). Pops `[content,
/// fd]` from the stack; creates a temp file, writes
/// `content + "\n"`, 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, ...)`
/// at c:3766-3780 for the bare-exec-redir code path (nullexec=1).
/// Bug #205 in docs/BUGS.md.
///
/// Stack: pushes `Value::Status(0)` on success, `Status(1)` on
/// failure. argc = 2.
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;
/// 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;
/// 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);
/// `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;
/// 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_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;
impl fusevm::ShellHost for ZshrsHost {
fn glob(&mut self, pattern: &str, _recursive: bool) -> Vec<String> {
with_executor(|exec| exec.expand_glob(pattern))
}
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 {
// 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).
let mut pat_tok = pattern.to_string();
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, pattern)
}
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();
Value::str(val_str)
}
fn process_sub_in(&mut self, sub: &fusevm::Chunk) -> String {
// 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 => {
// 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.
unsafe {
libc::close(read_end);
libc::dup2(write_end, libc::STDOUT_FILENO);
libc::close(write_end);
}
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) };
}
_ => {
// 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);
}
}
}
format!("/dev/fd/{}", read_end)
}
fn process_sub_out(&mut self, sub: &fusevm::Chunk) -> String {
// 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 => {
// 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);
}
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) };
}
_ => {
// 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)));
format!("/dev/fd/{}", write_end)
}
}
}
fn subshell_begin(&mut self) {
with_executor(|exec| {
// libc::umask returns the previous mask AND sets the new
// one; call with current value to read without changing.
let cur_umask = unsafe {
let m = libc::umask(0o022);
libc::umask(m);
m as u32
};
// 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())
.unwrap_or_default();
let paramtab_hashed_snap = crate::ported::params::paramtab_hashed_storage()
.lock()
.ok()
.map(|m| m.clone())
.unwrap_or_default();
exec.subshell_snapshots.push(SubshellSnapshot {
paramtab: paramtab_snap,
paramtab_hashed_storage: paramtab_hashed_snap,
positional_params: exec.pparams(),
env_vars: env::vars().collect(),
// Save the LOGICAL pwd ($PWD env), not `current_dir()`'s
// symlink-resolved path. zsh's subshell isolation per
// Src/exec.c at the `entersubsh` path treats `pwd` (the
// shell-tracked logical PWD) as the carrier — see
// `Src/builtin.c:1239-1242` where cd writes the logical
// dest into `pwd`. Falling back to current_dir() only
// when PWD is unset matches `setupvals` at
// `Src/init.c:1100+`.
cwd: env::var("PWD")
.ok()
.map(PathBuf::from)
.or_else(|| env::current_dir().ok()),
umask: cur_umask,
// 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 — fork() copies the alias table to
// the subshell. `(alias x=y)` inside the subshell
// dies with the child; the parent doesn't see x.
// Snapshot here so subshell_end can restore.
// Bug #209 in docs/BUGS.md.
aliases: crate::ported::hashtable::aliastab_lock()
.read()
.ok()
.map(|t| {
t.iter()
.map(|(k, v)| (k.clone(), v.text.clone()))
.collect()
})
.unwrap_or_default(),
// 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 — subshell forks its own
// modulestab. A `(zmodload zsh/X)` inside the
// subshell flips MOD_INIT_B on the CHILD's
// modulestab; when the child exits the change
// dies with it. zshrs's in-process subshell would
// otherwise leak the load to the parent.
// Bug #210 in docs/BUGS.md. Snapshot just the
// (name → flags) pairs since the only mutating
// field is the flags bitmask (MOD_INIT_B for
// loaded, MOD_UNLOAD for unloaded).
modules: crate::ported::module::MODULESTAB
.lock()
.ok()
.map(|t| {
t.modules
.iter()
.map(|(k, v)| (k.clone(), v.node.flags))
.collect()
})
.unwrap_or_default(),
// 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(),
// c:Src/exec.c entersubsh — fork copies the fd table;
// the child's `exec >file` / `exec N<&-` mutations die
// with it. Dup each user-range fd to >= 10 so
// subshell_end can restore the parent's exact table.
saved_fds: (0..10)
.map(|fd| {
let dup = unsafe { libc::fcntl(fd, libc::F_DUPFD, 10) };
(fd, dup)
})
.collect(),
});
// 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: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);
// 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_script(&body);
});
}
with_executor(|exec| {
if let Some(snap) = exec.subshell_snapshots.pop() {
// 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;
}
// 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;
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 the OS env to its pre-subshell state.
// Removes any `export` writes the subshell made, and
// restores any vars the subshell unset. Without this
// `(export y=sub)` would leak `y` to the parent shell.
let current: HashMap<String, String> = env::vars().collect();
for k in current.keys() {
if !snap.env_vars.contains_key(k) {
env::remove_var(k);
}
}
for (k, v) in &snap.env_vars {
if current.get(k) != Some(v) {
env::set_var(k, v);
}
}
if let Some(cwd) = snap.cwd {
let _ = env::set_current_dir(&cwd);
// Resync $PWD env so a parent `pwd` doesn't read
// the cwd the subshell `cd`'d into.
env::set_var("PWD", &cwd);
}
// Restore umask. zsh's `(umask 077)` doesn't leak to
// parent because the subshell forks; we run in-process
// so we manually reset.
unsafe {
libc::umask(snap.umask as libc::mode_t);
}
// 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;
}
// 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.
crate::ported::options::opt_state_restore(snap.opts);
// c:Src/exec.c — fork() means alias mutations in a
// subshell die with the child. Restore parent's
// alias table from snapshot. Clear current entries
// then re-add parent's. Bug #209 in docs/BUGS.md.
if let Ok(mut tab) = crate::ported::hashtable::aliastab_lock().write() {
tab.clear();
for (name, text) in snap.aliases {
tab.add(crate::ported::zsh_h::alias {
node: crate::ported::zsh_h::hashnode {
next: None,
nam: name,
flags: 0,
},
text,
inuse: 0,
});
}
}
// 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
// modulestab so a subshell `(zmodload zsh/X)` doesn't
// leak to the parent. Bug #210 in docs/BUGS.md.
// Restore via per-module flag write since the
// snapshot is `(name → flags)` only.
if let Ok(mut t) = crate::ported::module::MODULESTAB.lock() {
for (name, saved_flags) in &snap.modules {
if let Some(m) = t.modules.get_mut(name) {
m.node.flags = *saved_flags;
}
}
}
// 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 entersubsh fork semantics — restore the
// parent's user-range fd table. A bare `exec >file` /
// `exec N>&-` inside `(...)` died with the C child;
// the in-process subshell must undo it here. Flush
// Rust's stdout buffer FIRST so bytes the subshell
// printed drain to the SUBSHELL's fd 1, not the
// restored parent fd.
{
use std::io::Write;
let _ = std::io::stdout().flush();
}
for (fd, saved) in snap.saved_fds {
unsafe {
if saved >= 0 {
libc::dup2(saved, fd);
libc::close(saved);
} else {
// fd was closed at entry; close whatever
// the subshell opened on that slot.
libc::close(fd);
}
}
}
}
});
// 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();
// 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})`.
crate::ported::utils::errflag.fetch_and(
!(crate::ported::zsh_h::ERRFLAG_ERROR | crate::ported::zsh_h::ERRFLAG_HARD),
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);
let val = 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);
// Set the post-subshell-exit guard. The next GET_VAR
// sync_status path consults this to skip its
// vm.last_status→LASTVAL sync (which would overwrite the
// deferred-exit status we just set with stale vm state
// since SubshellEnd doesn't propagate status into the
// VM). Cleared as soon as the next sync_status sees it.
SUBSHELL_EXIT_STATUS_PENDING.with(|c| c.set(true));
// 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);
}
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{91}, Outbrack \u{92}, Star \u{87}, Quest
// \u{86}, 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);
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 {
with_executor(|exec| exec.set_last_status(1));
}
}
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.
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');
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.
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);
f
});
if glob_failed {
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 1;
}
// c:Src/subst.c:505-507 — CSH_NULL_GLOB external-path
// boundary: command skipped with `no match` but the NEXT
// sublist runs (zsh -fc 'setopt cshnullglob; ls *nope*;
// print after' prints the error then `after` — verified
// zsh 5.9.1), so clear ERRFLAG like the glob_failed arm.
if consume_badcshglob() {
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 1;
}
if (crate::ported::utils::errflag.load(std::sync::atomic::Ordering::SeqCst)
& crate::ported::zsh_h::ERRFLAG_ERROR)
!= 0
{
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;
}
// Track `$_` as the last argument of the last command (zsh /
// bash convention). Empty arglists leave it untouched.
if let Some(last) = args.last() {
with_executor(|exec| {
exec.set_scalar("_".to_string(), last.clone());
});
}
// 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. Synthesize a procs-less job so waitonejob's no-procs
// branch fires the `pipestats[0]=lastval; numpipestats=1;`
// update via the canonical port.
crate::ported::builtin::LASTVAL.store(status, std::sync::atomic::Ordering::Relaxed);
let mut synth = crate::ported::zsh_h::job::default();
crate::ported::jobs::waitonejob(&mut synth);
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`.
let (read_end, write_end) = match os_pipe::pipe() {
Ok(p) => p,
Err(_) => return String::new(),
};
let saved_stdout = unsafe { libc::dup(libc::STDOUT_FILENO) };
if saved_stdout < 0 {
return String::new();
}
let saved_stderr = unsafe { libc::dup(libc::STDERR_FILENO) };
let write_fd = AsRawFd::as_raw_fd(&write_end);
unsafe {
libc::dup2(write_fd, libc::STDOUT_FILENO);
}
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();
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);
libc::close(saved_stdout);
if saved_stderr >= 0 {
libc::close(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();
}
buf
}
fn call_function(&mut self, name: &str, args: Vec<String>) -> Option<i32> {
// 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
});
if redir_failed {
with_executor(|exec| exec.set_last_status(1));
return Some(1);
}
// zsh-bundled rename helpers + zcalc: short-circuit BEFORE the
// function/autoload lookup so the autoloaded zsh source (which
// can hang zshrs's parser on zsh-specific syntax) never runs.
// Native Rust impls live in builtin_zmv / builtin_zcalc.
match name {
"zmv" => {
return Some(crate::extensions::ext_builtins::zmv(&args, "mv"));
}
"zcp" => {
return Some(crate::extensions::ext_builtins::zmv(&args, "cp"));
}
"zln" => {
return Some(crate::extensions::ext_builtins::zmv(&args, "ln"));
}
"zcalc" => {
return Some(crate::extensions::ext_builtins::zcalc(&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 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 crate::daemon::builtins::is_zshrs_builtin(n) => {
let argv: Vec<String> = std::iter::once(name.to_string()).chain(args).collect();
return Some(crate::daemon::builtins::try_dispatch(n, &argv).unwrap_or(1));
}
_ => {}
}
// 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. Bug #221
// in docs/BUGS.md.
let user_fn_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);
let has_user_fn = !user_fn_disabled
&& with_executor(|exec| exec.functions_compiled.contains_key(name));
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 {
return Some(dispatch_builtin_raw(name, args));
}
}
// c:Src/lex.c — alias expansion is a LEXER-TIME pass, not a
// run-time lookup. zsh parses the whole `-c` argument (or
// script) before executing, so aliases defined in the same
// parse unit don't apply to commands parsed earlier. Only at
// an INTERACTIVE prompt does each line parse separately with
// the latest aliastab visible.
//
// Gate the run-time alias-rewrite path on `interactive` so
// `alias hi='echo hello'; hi` in `-c` mode falls through to
// "command not found" (matching zsh) while interactive REPL
// input still re-parses with the live aliastab.
let interactive = crate::ported::zsh_h::isset(crate::ported::zsh_h::INTERACTIVE);
let already_expanding = if interactive {
crate::ported::hashtable::aliastab_lock()
.read()
.ok()
.and_then(|tab| tab.get(name).map(|a| a.inuse != 0))
.unwrap_or(false)
} else {
true // suppress lookup entirely in non-interactive mode
};
let alias_body = if already_expanding {
None
} else {
with_executor(|exec| exec.alias(name))
};
if let Some(body) = alias_body {
let combined = if args.is_empty() {
body
} else {
let quoted: Vec<String> = args
.iter()
.map(|a| {
let escaped = a.replace('\'', "'\\''");
format!("'{}'", escaped)
})
.collect();
format!("{} {}", body, quoted.join(" "))
};
// Bump inuse → run → clear, matching C's lexer behavior.
if let Ok(mut tab) = crate::ported::hashtable::aliastab_lock().write() {
if let Some(a) = tab.get_mut(name) {
a.inuse += 1;
}
}
let status = with_executor(|exec| exec.execute_script(&combined).unwrap_or(1));
if let Ok(mut tab) = crate::ported::hashtable::aliastab_lock().write() {
if let Some(a) = tab.get_mut(name) {
a.inuse = (a.inuse - 1).max(0);
}
}
return Some(status);
}
// $_ 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();
with_executor(|exec| {
let dollar_underscore = args.last().cloned().unwrap_or_else(|| fn_name.clone());
exec.set_scalar("_".to_string(), dollar_underscore.clone());
crate::ported::params::set_zunderscore(std::slice::from_ref(&dollar_underscore));
exec.pending_underscore = Some(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.
let status = with_executor(|exec| exec.dispatch_function_call(&fn_name, &args));
// $_ post-body — last call-arg or function name. Mirrors the
// C `setunderscore` invocation after the body returns.
with_executor(|exec| {
let last_call_arg = args.last().cloned().unwrap_or_else(|| fn_name.clone());
exec.set_scalar("_".to_string(), last_call_arg.clone());
exec.pending_underscore = Some(last_call_arg);
});
status
}
}
// ───────────────────────────────────────────────────────────────────────────
// 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::*`.
/// 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 {
libc::dup2(new_fd, fd);
libc::close(new_fd);
}
true
}
Err(e) => {
let msg = match e.kind() {
std::io::ErrorKind::PermissionDenied => "permission denied",
std::io::ErrorKind::NotFound => "no such file or directory",
std::io::ErrorKind::IsADirectory => "is a directory",
_ => "redirect failed",
};
// c:Src/exec.c:3741 — zwarn with real lineno prefix.
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 {
libc::dup2(new_fd, fd);
libc::close(new_fd);
}
}
}
false
}
}
}
/// `host_apply_redirect` — see implementation.
pub fn host_apply_redirect(&mut self, fd: u8, op_byte: u8, target: &str) {
// `&>` / `&>>` 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>() {
if unsafe { libc::fcntl(src_fd, libc::F_GETFD) } == -1 {
// 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.
if !self.exec_redirs_permanent {
let saved = unsafe { libc::dup(fd) };
if saved >= 0 {
if let Some(top) = self.redirect_scope_stack.last_mut() {
top.push((fd, saved));
} else {
// 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) };
}
}
// 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) {
let saved2 = unsafe { libc::dup(2) };
if saved2 >= 0 {
if let Some(top) = self.redirect_scope_stack.last_mut() {
top.push((2, saved2));
} else {
unsafe { libc::close(saved2) };
}
}
}
}
// 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::dup(src) })
.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::dup(1) };
match (pipe_dup >= 0).then(os_pipe::pipe) {
Some(Ok((read_end, write_end))) => {
// 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 = std::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);
// Scope-end closes this dup (the last writer once
// the saved fd 1 is restored) → EOF → join.
let close_on_end = unsafe { libc::dup(1) };
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!("{}:1: file exists: {}", shname(), 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 {
libc::dup2(new_fd, fd);
libc::close(new_fd);
}
}
}
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 {
// 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.
if let Ok(file) = fs::File::create(target) {
let new_fd = file.into_raw_fd();
unsafe {
libc::dup2(new_fd, 1);
libc::dup2(new_fd, 2);
libc::close(new_fd);
}
}
} 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 => {
if let Ok(file) = fs::File::create(target) {
let new_fd = file.into_raw_fd();
unsafe {
libc::dup2(new_fd, 1);
libc::dup2(new_fd, 2);
libc::close(new_fd);
}
}
}
r::APPEND_BOTH => {
if let Ok(file) = fs::OpenOptions::new()
.create(true)
.append(true)
.open(target)
{
let new_fd = file.into_raw_fd();
unsafe {
libc::dup2(new_fd, 1);
libc::dup2(new_fd, 2);
libc::close(new_fd);
}
}
}
_ => {}
}
}
/// 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());
}
self.redirect_scope_stack.push(Vec::new());
self.multios_scope_stack.push(Vec::new());
}
/// 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 let Some(saved) = self.redirect_scope_stack.pop() {
for (fd, saved_fd) in saved.into_iter().rev() {
unsafe {
libc::dup2(saved_fd, fd);
libc::close(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;
}
}
/// 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: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:4675 — `write_loop(fd, t, len); close(fd);`
if std::fs::write(&tmp, content.as_bytes()).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);
let saved = unsafe { libc::dup(libc::STDIN_FILENO) };
if saved >= 0 {
if let Some(top) = self.redirect_scope_stack.last_mut() {
top.push((libc::STDIN_FILENO, saved));
} else {
unsafe { libc::close(saved) };
}
}
let read_fd = AsRawFd::as_raw_fd(&file);
unsafe { libc::dup2(read_fd, libc::STDIN_FILENO) };
drop(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 {
// 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);
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());
}
// zsh-bundled rename helpers — implemented natively in
// Rust so `autoload -U zmv` works without shipping the
// function source. (Without this, the autoload path hangs.)
"zmv" => return crate::extensions::ext_builtins::zmv(&rest_vec, "mv"),
"zcp" => return crate::extensions::ext_builtins::zmv(&rest_vec, "cp"),
"zln" => return crate::extensions::ext_builtins::zmv(&rest_vec, "ln"),
"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;
}
}
self.execute_external(cmd, &rest_vec, &[]).unwrap_or(127)
}
}