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
//! 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) };
/// 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) };
}
// 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) };
}
/// 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)
})
}
/// 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.
pub(crate) fn dispatch_builtin_raw(name: &str, args: Vec<String>) -> i32 {
let bn_idx = crate::ported::builtin::BUILTINS
.iter()
.position(|b| b.node.nam == name);
if let Some(idx) = bn_idx {
let bn_static: &'static crate::ported::zsh_h::builtin =
&crate::ported::builtin::BUILTINS[idx];
let bn_ptr = bn_static as *const _ as *mut _;
crate::ported::builtin::execbuiltin(args, Vec::new(), bn_ptr)
} else {
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 "$@"; … }`).
pub(crate) fn dispatch_builtin(name: &str, args: Vec<String>) -> i32 {
// 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 {
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.
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 {
return 1; // c:1880 — command aborted, status 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;
}
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);
status
}
/// Install the `crate::ported::exec_hooks` fn-pointer registry so
/// code under `src/ported/` can dispatch to operations owned by
/// `ShellExecutor` (array/assoc storage, script eval, function
/// dispatch, command substitution) WITHOUT a direct executor
/// reference or `with_executor` call from inside src/ported/.
///
/// Idempotent — each hook uses `OnceLock::set`, so calling this
/// multiple times (once per `ShellExecutor::new`) is safe; the second
/// and later calls are no-ops.
///
/// **Extension** — no C analog. Bridges the Rust-only `src/ported/`
/// → executor boundary that the user pinned as forbidden via memory
/// `feedback_no_exec_script_from_ported` /
/// `feedback_no_shellexecutor_in_ported`.
pub(crate) fn install_exec_hooks() {
use crate::ported::exec_hooks as h;
h::install_array_get(|name| with_executor(|exec| exec.array(name)));
h::install_assoc_get(|name| with_executor(|exec| exec.assoc(name)));
h::install_array_set(|name, val| {
with_executor(|exec| exec.set_array(name.to_string(), val));
});
h::install_assoc_set(|name, val| {
with_executor(|exec| exec.set_assoc(name.to_string(), val));
});
h::install_scalar_unset(|name| {
with_executor(|exec| exec.unset_scalar(name));
});
h::install_array_unset(|name| {
with_executor(|exec| exec.unset_array(name));
});
h::install_assoc_unset(|name| {
with_executor(|exec| exec.unset_assoc(name));
});
h::install_dispatch_function_call(|name, args| {
with_executor(|exec| exec.dispatch_function_call(name, args))
});
h::install_execute_script(|src| {
with_executor(|exec| exec.execute_script(src))
});
h::install_execute_script_zsh_pipeline(|src| {
with_executor(|exec| exec.execute_script_zsh_pipeline(src))
});
h::install_run_command_substitution(|cmd| {
with_executor(|exec| exec.run_command_substitution(cmd))
});
h::install_pparams_get(|| with_executor(|exec| exec.pparams()));
h::install_pparams_set(|v| {
with_executor(|exec| exec.set_pparams(v));
});
h::install_unregister_function(|name| {
with_executor(|exec| {
let a = exec.functions_compiled.remove(name).is_some();
let b = exec.function_source.remove(name).is_some();
a || b
})
});
}
/// Register all zsh builtins with the VM.
pub(crate) fn register_builtins(vm: &mut fusevm::VM) {
// exec_hooks fn-ptrs MUST be installed before any builtin can
// reach into src/ported/ code that consults them (e.g.
// `BUILTIN_ERREXIT_CHECK` → `dotrap` → `exec_hooks::dispatch_function_call`).
// OnceLock makes the call idempotent — repeated invocations from
// every `ShellExecutor::new` are no-ops.
install_exec_hooks();
// 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);
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");
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);
let status = dispatch_builtin("test", 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");
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 args = pop_args(vm, argc);
if args.is_empty() {
return Value::Status(0); // c:6160
}
let src = args.join(" "); // c:6166
let status = with_executor(|exec| {
// c:6175 execode
exec.execute_script(&src).unwrap_or(1)
});
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);
};
// `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.
let dash_p = args.iter().any(|a| {
a == "-p" || a == "-pv" || a == "-pV"
|| (a.starts_with('-') && a.contains('p') && !a.starts_with("--"))
});
// The post slice from execcmd_compile_head may still contain
// `-p` as the first element because precmd-modifier opt
// parsing isn't wired here. Strip it manually so the dispatch
// below sees the real command name.
let post: Vec<String> = if dash_p {
post.iter()
.filter(|a| {
let s = a.as_str();
!(s.starts_with('-') && s.len() >= 2 && s[1..].chars().all(|c| c == 'p' || c == 'v' || c == 'V'))
})
.cloned()
.collect()
} else {
post.to_vec()
};
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;
while i < args.len() {
let a = &args[i];
if a == "--" {
args.remove(i);
break;
}
if !a.starts_with('-') || a.len() < 2 {
break;
}
match a.as_str() {
"-a" => {
args.remove(i);
if i < args.len() {
argv0_override = Some(args.remove(i));
}
}
"-c" => {
clean_env = true;
args.remove(i);
}
"-l" => {
login = true;
args.remove(i);
}
_ => break,
}
}
let Some(cmd) = args.first().cloned() else {
// `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()
}
}
};
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();
let code = match err.kind() {
std::io::ErrorKind::NotFound => {
eprintln!("zshrs: exec: {}: not found", cmd);
127
}
std::io::ErrorKind::PermissionDenied => {
eprintln!("zshrs: exec: {}: permission denied", cmd);
126
}
_ => {
eprintln!("zshrs: exec: {}: {}", cmd, err);
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
reg_passthru!(vm, BUILTIN_ALIAS, "alias");
// 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);
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);
let status = with_executor(|exec| exec.builtin_complete(&args));
Value::Status(status)
});
reg_passthru!(vm, BUILTIN_COMPADD, "compadd");
reg_passthru!(vm, BUILTIN_COMPSET, "compset");
vm.register_builtin(BUILTIN_COMPDEF, |vm, argc| {
let args = pop_args(vm, argc);
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);
Value::Status(with_executor(|exec| exec.builtin_caller(&args)))
});
vm.register_builtin(BUILTIN_HELP, |vm, argc| {
let args = pop_args(vm, argc);
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).
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);
}
// 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);
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");
}
// 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);
}
// 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());
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);
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)
};
// Populate `pipestatus` (zsh) and `PIPESTATUS` (bash) arrays so
// scripts can inspect per-stage exit codes. Both names are common
// in user code; populating both removes a portability foot-gun.
with_executor(|exec| {
let strs: Vec<String> = pipestatus.iter().map(|s| s.to_string()).collect();
exec.set_array("pipestatus".to_string(), strs.clone());
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.
vm.register_builtin(BUILTIN_ARRAY_JOIN, |vm, _argc| {
let val = vm.pop();
match val {
Value::Array(items) => {
let parts: Vec<String> = items.iter().map(|v| v.to_str()).collect();
Value::str(parts.join(" "))
}
other => other,
}
});
// `cmd &` background execution. Compile_list emits this for any item
// followed by ListOp::Amp: the cmd is compiled into a sub-chunk, its index
// pushed, then this builtin pops the index, 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 returns Status(0) immediately. Job
// tracking via JobTable is deferred to Phase G6 — JobTable::add_job
// currently requires a std::process::Child, which a libc::fork doesn't
// produce. Until then, `jobs`/`fg`/`wait` can't see these pids.
//WARNING FAKE AND MUST BE DELETED
vm.register_builtin(BUILTIN_RUN_BG, |vm, _argc| {
let sub_idx = vm.pop().to_int() as usize;
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);
with_executor(|exec| {
exec.jobs
.add_pid_job(pid, String::new(), 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| {
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 {
match v {
Value::Array(items) => {
for it in items {
values.push(it.to_str());
}
}
other => values.push(other.to_str()),
}
}
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() {
if !values.len().is_multiple_of(2) {
eprintln!("zshrs:1: bad set of key/value pairs for associative array");
return true;
}
let _ = crate::ported::params::sethparam(&name, values.clone());
#[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.
//
// 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);
}
let _ = crate::ported::params::setaparam(&name, values.clone());
#[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
});
Value::Status(if blocked { 1 } else { 0 })
});
// `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 {
match v {
Value::Array(items) => {
for it in items {
values.push(it.to_str());
}
}
other => values.push(other.to_str()),
}
}
with_executor(|exec| {
// 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() {
let mut map = exec.assoc(&name).unwrap_or_default();
let mut it = values.into_iter();
while let Some(k) = it.next() {
if let Some(v) = it.next() {
map.insert(k, v);
}
}
exec.set_assoc(name, map);
return;
}
// 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.
let _ = crate::ported::params::assignaparam(
&name,
values.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, &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());
env::set_var(&scalar_name, &joined);
}
});
Value::Status(0)
});
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();
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) => break, // EOF
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);
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;
// 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.
//
// Sentinel bytes the compile path tags onto `idx` (`\u{02}` =
// compile-time DQ, `\u{05}` = outer `(@)` flag, `\u{06}` /
// `\u{07}` = outer `(v)`/`(k)` flag) are stripped here because
// paramsubst's input must be a valid zsh expression. Context
// bumps for DQ / (v) / (k) live in the callers (BUILTIN_EXPAND_TEXT
// bumps `in_dq_context`).
vm.register_builtin(BUILTIN_ARRAY_INDEX, |vm, _argc| {
let mut idx = vm.pop().to_str();
let name = vm.pop().to_str();
for sentinel in ['\u{02}', '\u{05}', '\u{06}', '\u{07}'] {
if let Some(rest) = idx.strip_prefix(sentinel) {
idx = rest.to_string();
}
}
let body = format!("${{{}[{}]}}", name, idx);
paramsubst_to_value(&body)
});
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.
//
// Sentinel bytes the compile path tags onto `flags` (`\u{02}` =
// DQ-wrapped, `\u{03}` = had `[@]`/`[*]` subscript, `\u{04}` =
// scalar-assignment context) are stripped before the
// `${(flags)name}` reconstruction so paramsubst's input is a
// valid zsh expression. Context bumps live in the caller
// (BUILTIN_EXPAND_TEXT bumps `in_dq_context` and `in_scalar_assign`).
vm.register_builtin(BUILTIN_PARAM_FLAG, |vm, _argc| {
let mut flags = vm.pop().to_str();
let name = vm.pop().to_str();
// Strip the compile-path sentinels — paramsubst doesn't
// recognize them and they'd corrupt the flag-block parse.
for sentinel in ['\u{02}', '\u{03}', '\u{04}'] {
if let Some(rest) = flags.strip_prefix(sentinel) {
flags = rest.to_string();
}
}
// Bridge is a passthru: reconstruction goes straight to
// paramsubst, which now handles the `\u{01}` literal-operand
// sentinel internally (subst.rs paramsubst pre-name-walk
// branch). No bridge-side gating.
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| {
let value = vm.pop().to_str();
let key = vm.pop().to_str();
let name = vm.pop().to_str();
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();
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_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();
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()],
};
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 — `zglob` runs per-word in the argv
// pipeline. When the upstream EXPAND_TEXT returned an array
// (e.g. `${a:e}` splat → ["txt","md"]), we must glob each
// element separately, not collapse to a sepjoin'd scalar.
// Without this, `print -l ${a:e}` saw the array stringified
// by `pop().to_str()` and emitted one joined arg.
let raw = vm.pop();
let patterns: Vec<String> = match raw {
Value::Array(items) => items.into_iter().map(|v| v.to_str()).collect(),
other => vec![other.to_str()],
};
// 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 noglob = opt_state_get("noglob").unwrap_or(false)
|| !opt_state_get("glob").unwrap_or(true);
if noglob {
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())
});
// `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)
});
vm.register_builtin(BUILTIN_ARRAY_JOIN_STAR, |vm, _argc| {
let name = vm.pop().to_str();
let result = 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 sep = match exec.scalar("IFS") {
Some(s) => s.chars().next().map(|c| c.to_string()).unwrap_or_default(),
None => " ".to_string(),
};
if name == "@" || name == "*" || name == "argv" {
return exec.pparams().join(&sep);
}
if let Some(arr) = exec.array(&name) {
arr.join(&sep)
} else {
exec.get_variable(&name)
}
});
Value::str(result)
});
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());
}
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 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),
};
// (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);
}
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()]);
});
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 == "*" {
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".
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 {
if in_dq {
let sep = with_executor(|exec| {
exec.get_variable("IFS")
.chars()
.next()
.map(|c| c.to_string())
.unwrap_or_else(|| " ".to_string())
});
return Value::str(items.join(&sep));
}
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 ($?, $#,
// $@ etc.) and pure-digit positional params always count
// as known regardless of value.
let known = !v.is_empty()
|| name.is_empty()
|| name.chars().next().map(|c|
!c.is_alphabetic() && c != '_'
).unwrap_or(true)
|| 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() {
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| {
// 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(_)));
with_executor(|exec| {
// 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));
env::set_var(&name, &value);
}
// 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.
if int_assign {
if let Some(fusevm::Value::Int(i)) = value_raw {
crate::ported::params::setiparam(&name, i);
} else {
crate::ported::params::setsparam(&name, &value);
}
} else {
crate::ported::params::setsparam(&name, &value);
}
// 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 {
env::set_var(&name, &value);
}
#[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)
});
// 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();
let body = format!("${{+{}}}", name);
let mut ret_flags: i32 = 0;
let (_full, _pos, nodes) =
crate::ported::subst::paramsubst(&body, 0, false, 0i32, &mut ret_flags);
let result = nodes.into_iter().next().unwrap_or_default();
Value::Bool(result == "1")
});
// `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;
let chunk_opt = vm.chunk.sub_chunks.get(sub_idx).cloned();
let Some(chunk) = chunk_opt else {
return Value::Status(0);
};
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();
// c:Src/exec.c — zsh's `time` keyword reads rusage from
// waitpid, which is only populated for forked external
// processes. A pure builtin (`time true`, `time echo`)
// produces zero user/system and zsh skips the print
// entirely. Mirror by suppressing when elapsed is below
// 1ms (heuristic for "no external work happened").
if elapsed.as_secs_f64() >= 0.001 {
eprintln!(
"{:.2}s user {:.2}s system {:.0}% cpu {:.3} total",
elapsed.as_secs_f64() * 0.7,
elapsed.as_secs_f64() * 0.1,
((elapsed.as_secs_f64() * 0.8) / elapsed.as_secs_f64() * 100.0).min(100.0),
elapsed.as_secs_f64()
);
}
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| {
let op_byte = vm.pop().to_int() as u8;
let varid = vm.pop().to_str();
let path = vm.pop().to_str();
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, 0o644) };
if fd < 0 {
return Value::Status(1);
}
// Re-dup to fd >= 10 so positional fds (0/1/2/etc.) stay free.
let new_fd = unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, 10) };
let final_fd = if new_fd >= 10 {
unsafe { libc::close(fd) };
new_fd
} else {
fd
};
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/exec.c WC_TRYBLOCK — TRY_BLOCK_ERROR reflects
// the errflag state at try-block exit. zsh leaves it
// at -1 (sentinel) when the block completed normally,
// and sets to last_status when errflag triggered the
// unwind. The always-arm can reset it to 0 to
// SWALLOW the error.
if errored {
exec.set_scalar(
"TRY_BLOCK_ERROR".to_string(),
vm_status.to_string(),
);
// Clear errflag so always-arm runs cleanly.
crate::ported::utils::errflag.fetch_and(
!crate::ported::zsh_h::ERRFLAG_ERROR,
Ordering::Relaxed,
);
} else {
// c:Src/Modules/parameter.c — TRY_BLOCK_ERROR reads
// as 0 inside an always-arm when no error fired
// (per zsh's PM_INTEGER default-zero). The previous
// port set -1 (the C internal "no try yet" sentinel)
// which leaked to user-visible reads.
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)
});
// 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)
});
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);
// 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!("zshrs:1: no such option: {}", name);
Value::Bool(false)
}
}
});
// 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() < 2 {
return Value::Status(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).
let len = exec.array(&name).map(|a| a.len() as i64).unwrap_or(0);
let translate = |raw: i64| -> i32 {
if raw < 0 {
(len + raw + 1).max(1) as i32
} else {
raw.max(1) as i32
}
};
let (start, end) = if let Some((s_str, e_str)) = key.split_once(',') {
let s = s_str.trim().parse::<i64>().unwrap_or(0);
let e = e_str.trim().parse::<i64>().unwrap_or(0);
(translate(s), translate(e))
} else {
let i = key.trim().parse::<i64>().unwrap_or(0);
if i == 0 {
return;
}
let n = translate(i);
(n, n)
};
// 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,
};
let mut v = crate::ported::zsh_h::value {
pm: taken,
arr: Vec::new(),
scanflags: 0,
valflags: 0,
start,
end,
};
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) => {
if la.is_empty() {
return Value::str(rhs_scalar.as_str_cow().to_string());
}
let last = la.pop().unwrap();
let l_s = last.as_str_cow();
let r_s = rhs_scalar.as_str_cow();
let mut s = String::with_capacity(l_s.len() + r_s.len());
s.push_str(&l_s);
s.push_str(&r_s);
la.push(Value::str(s));
Value::Array(la)
}
(lhs_scalar, Value::Array(mut ra)) => {
if ra.is_empty() {
return Value::str(lhs_scalar.as_str_cow().to_string());
}
let first = ra.remove(0);
let l_s = lhs_scalar.as_str_cow();
let r_s = first.as_str_cow();
let mut s = String::with_capacity(l_s.len() + r_s.len());
s.push_str(&l_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();
let rc_expand = with_executor(|exec| {
opt_state_get("rcexpandparam").unwrap_or(false)
});
let ifs_first = || -> String {
with_executor(|exec| {
exec.get_variable("IFS")
.chars()
.next()
.map(|c| c.to_string())
.unwrap_or_else(|| " ".to_string())
})
};
// Helper: join an Array to scalar via IFS-first.
let join_arr = |arr: Vec<Value>| -> String {
let sep = ifs_first();
arr.iter()
.map(|v| v.as_str_cow().into_owned())
.collect::<Vec<_>>()
.join(&sep)
};
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_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();
}
eprintln!("{}", cmd_text);
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();
let arg_strs: Vec<String> = if n_args > 0 && len >= n_args {
vm.stack[len - n_args..]
.iter()
.map(|v| quotedzputs(&v.to_str()))
.collect()
} 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);
let already_ps4 = XTRACE_DONE_PS4.with(|f| f.get());
if !already_ps4 {
printprompt4();
}
eprintln!("{}", line);
}
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);`. Emit no newline.
eprint!("{}={} ", 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 {
eprintln!();
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) {
Value::Int(1)
} else {
Value::Int(0)
}
});
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.
DEBUG_TRAP_REENTRY.with(|c| {
if c.get() {
return Value::Status(0);
}
c.set(true);
let _ = crate::ported::signals::dotrap(crate::ported::signals_h::SIGDEBUG);
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 {
return Value::Int(1);
}
let errflag_set = (crate::ported::utils::errflag.load(Ordering::Relaxed)
& crate::ported::zsh_h::ERRFLAG_ERROR)
!= 0;
if errflag_set
&& !crate::ported::zsh_h::isset(crate::ported::zsh_h::INTERACTIVE)
{
// Clear errflag so the abort doesn't keep re-triggering;
// the script-end last_status gives the caller the
// failing status. Update BOTH executor's last_status
// (LASTVAL) AND the VM's last_status so run_chunk's
// post-script sync sees the failing value.
crate::ported::utils::errflag.fetch_and(
!crate::ported::zsh_h::ERRFLAG_ERROR,
Ordering::Relaxed,
);
with_executor(|exec| exec.set_last_status(1));
vm.last_status = 1;
return Value::Int(1);
}
let last = vm.last_status;
if last == 0 {
return Value::Int(0);
}
// 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);
let (errexit_on, in_subshell) = with_executor(|exec| {
let on_canonical = isset(ERREXIT);
let on_legacy = opt_state_get("errexit").unwrap_or(false);
(
on_canonical || on_legacy,
!exec.subshell_snapshots.is_empty(),
)
});
if !errexit_on {
return Value::Int(0);
}
if in_subshell {
// c:Src/exec.c — `set -e` inside a subshell terminates
// the subshell (the forked child), and the parent shell
// sees `last` as the subshell's exit status. Set
// EXIT_PENDING + EXIT_VAL so subshell_end at the boundary
// promotes them into the parent's $?; the caller's
// JumpIfTrue will branch to the SubshellEnd landing so
// no further ops in the subshell body run.
crate::ported::builtin::EXIT_VAL.store(last, Ordering::Relaxed);
crate::ported::builtin::EXIT_PENDING.store(1, Ordering::Relaxed);
}
// 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)
});
// `${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).
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 body = if length == i64::MIN {
format!("${{{}:{}}}", name, offset)
} else {
format!("${{{}:{}:{}}}", name, 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).
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 body = if has_len {
format!("${{{}:{}:{}}}", name, off_expr, len_expr)
} else {
format!("${{{}:{}}}", name, 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 err = crate::ported::utils::errflag.load(Ordering::Relaxed)
& crate::ported::zsh_h::ERRFLAG_ERROR;
if err != 0 {
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;
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
// 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| 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.
let result_value = if mode == 5 {
let out = crate::ported::subst::singsub(&prepped);
Value::str(out)
} else {
let (_first, nodes, _ms_ws, _ret) =
crate::ported::subst::multsub(&prepped, 0);
if nodes.is_empty() {
Value::str(String::new())
} else if nodes.len() == 1 {
Value::str(nodes.into_iter().next().unwrap())
} else {
Value::Array(nodes.into_iter().map(Value::str).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);
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 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.
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);
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.
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
}
};
// Also trigger expand_glob when the word ends
// with a `(...)` qualifier suffix even without
// any other glob metachar — `/etc/hosts(mh-100)`,
// `path(.)`, etc.
let has_qual_suffix =
s.ends_with(')') && s.contains('(') && !s.contains('|');
// extendedglob `^pat` (negation) and `pat~excl`
// (exclusion). Trigger expand_glob so the runtime
// can apply the appropriate filter. Both require
// `setopt extendedglob` — runtime falls through
// to literal if that's off.
let extglob_meta = opt_state_get("extendedglob")
.unwrap_or(false)
&& (s.starts_with('^') || s.contains('~') || s.contains("/^"));
let has_numeric_range = s.contains('<')
&& s.contains('>')
&& !extract_numeric_ranges(&s).is_empty();
// Glob alternation `(a|b|c)` is a primary
// zsh feature — `/etc/(passwd|hostname)`
// should expand to file matches. Detected
// by `(` ... `|` ... `)` shape; the actual
// top-level-vs-nested check happens in
// expand_glob_alternation.
let has_alternation = s.contains('(') && s.contains('|') && s.contains(')');
if !noglob
&& !is_assignment_shape
&& (s.contains('*')
|| s.contains('?')
|| s.contains('[')
|| has_qual_suffix
|| extglob_meta
|| has_numeric_range
|| has_alternation)
{
exec.expand_glob(&s)
} 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())
}
}
})
});
// `${#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();
// 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),
};
paramsubst_to_value(&body)
});
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| {
let def_file = 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 shf = crate::ported::hashtable::shfunc_with_body(&name, &body_source);
tab.add(shf);
}
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 != '_'
}
}
/// 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));
}
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 {
if nodes.is_empty() {
Value::Array(Vec::new())
} else if nodes.len() == 1 {
Value::str(nodes.into_iter().next().unwrap())
} else {
Value::Array(nodes.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 {
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 one sub-chunk index; forks; child detaches
/// (`setsid`), runs the sub-chunk on a fresh VM, exits with last_status; parent
/// returns Status(0) immediately. Job-table registration (so `jobs`/`fg`/`wait`
/// can see the pid) is deferred to Phase G6 — fire-and-forget for now.
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;
/// `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;
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;
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;
pub const BUILTIN_BREAKS_CHECK: u16 = 601;
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;
pub const BUILTIN_PARAM_SUBSTRING_EXPR: u16 = 337;
pub const BUILTIN_XTRACE_LINE: u16 = 338;
pub const BUILTIN_ARRAY_JOIN_STAR: u16 = 339;
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;
pub const BUILTIN_RESTORE_TRY_BLOCK_STATUS: u16 = 432;
pub const BUILTIN_BEGIN_INLINE_ENV: u16 = 433;
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;
/// `${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;
/// 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;
/// 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;
/// 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. Used by `[[ x = pat ]]`,
// `case` arms, and any other point that compares against a glob pattern.
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 {
// `>(cmd)` — consumer reads stdin from a FIFO that the parent
// writes to. Create a real named pipe, fork a child that
// dup2s the read end onto stdin and runs the sub-chunk; return
// the FIFO path to the parent so it writes there.
let fifo_path = 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::remove_file(&fifo_path);
let cpath = match CString::new(fifo_path.clone()) {
Ok(c) => c,
Err(_) => return fifo_path,
};
if unsafe { libc::mkfifo(cpath.as_ptr(), 0o600) } != 0 {
// Fall back to plain file if mkfifo fails.
let _ = fs::write(&fifo_path, "");
return fifo_path;
}
let sub = sub.clone();
let fifo_for_child = fifo_path.clone();
match unsafe { libc::fork() } {
-1 => {
let _ = fs::remove_file(&fifo_path);
}
0 => {
// Child: open FIFO for read, dup onto stdin, run sub-chunk, exit.
if let Ok(f) = fs::OpenOptions::new().read(true).open(&fifo_for_child) {
let fd = f.as_raw_fd();
unsafe {
libc::dup2(fd, libc::STDIN_FILENO);
}
}
crate::fusevm_disasm::maybe_print_stdout("process_subst_out:child", &sub);
let mut vm = fusevm::VM::new(sub);
register_builtins(&mut vm);
vm.set_shell_host(Box::new(ZshrsHost));
let _ = vm.run();
unsafe { libc::_exit(0) };
}
_ => {
// Parent — return path; child handles cleanup of the FIFO
// once stdin EOFs. (The path may leak if the parent never
// writes; acceptable for common `>(cmd)` idioms.)
}
}
fifo_path
}
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(),
});
// 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);
}
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;
}
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);
}
});
// 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);
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 — 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 write_fd = AsRawFd::as_raw_fd(&write_end);
unsafe {
libc::dup2(write_fd, libc::STDOUT_FILENO);
}
drop(write_end);
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;
unsafe {
libc::dup2(saved_stdout, libc::STDOUT_FILENO);
libc::close(saved_stdout);
}
// 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 — 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));
}
// 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/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.
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());
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",
};
eprintln!("zshrs:1: {}: {}", msg, target);
*redirect_failed = true;
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
}
}
}
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 {
eprintln!(
"zshrs:1: {}: bad file descriptor",
src_fd
);
self.set_last_status(1);
self.redirect_failed = true;
return;
}
}
}
}
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) };
}
}
}
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.
let noclobber = opt_state_get("noclobber").unwrap_or(false)
|| !opt_state_get("clobber").unwrap_or(true);
if noclobber && std::path::Path::new(target).exists() {
eprintln!("zshrs:1: file exists: {}", 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 => {
if !Self::redir_open_or_fail(
fd,
fs::OpenOptions::new()
.create(true)
.append(true)
.open(target),
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 let Ok(src_fd) = n.parse::<i32>() {
unsafe { libc::dup2(src_fd, fd) };
} else {
tracing::warn!(target = %target, "DUP redir: target not parseable as fd");
}
}
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) {
self.redirect_scope_stack.push(Vec::new());
}
/// Pop the top redirect scope, restoring saved fds.
pub fn host_redirect_scope_end(&mut self) {
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);
}
}
}
}
/// Set up `content` as stdin (fd 0) for the next command via a real pipe.
/// Used by `Op::HereDoc(idx)` and `Op::HereString`.
///
/// The pattern: dup2 the read end of a fresh pipe onto fd 0, save the
/// original fd 0 into the active redirect scope so `WithRedirectsEnd`
/// restores it, and spawn a thread that writes `content` to the write end
/// and closes it (so the consumer sees EOF after the body). A thread is
/// needed because writing could block on a finite pipe buffer.
pub fn host_set_pending_stdin(&mut self, content: String) {
let (read_end, write_end) = match os_pipe::pipe() {
Ok(p) => p,
Err(_) => return,
};
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(&read_end);
unsafe { libc::dup2(read_fd, libc::STDIN_FILENO) };
drop(read_end);
std::thread::spawn(move || {
let mut w = write_end;
let _ = w.write_all(content.as_bytes());
});
}
/// 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.
if self.current_command_glob_failed.get() {
self.current_command_glob_failed.set(false);
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"].
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" => {
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)
}
}